repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
andreagenso/java2scala
test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/security/smartcardio/SunPCSC.java
2515
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.smartcardio; import java.security.*; import javax.smartcardio.*; /** * Provider object for PC/SC. * * @since 1.6 * @author Andreas Sterbenz */ public final class SunPCSC extends Provider { private static final long serialVersionUID = 6168388284028876579L; public SunPCSC() { super("SunPCSC", 1.6d, "Sun PC/SC provider"); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { put("TerminalFactory.PC/SC", "sun.security.smartcardio.SunPCSC$Factory"); return null; } }); } public static final class Factory extends TerminalFactorySpi { public Factory(Object obj) throws PCSCException { if (obj != null) { throw new IllegalArgumentException ("SunPCSC factory does not use parameters"); } // make sure PCSC is available and that we can obtain a context PCSC.checkAvailable(); PCSCTerminals.initContext(); } /** * Returns the available readers. * This must be a new object for each call. */ protected CardTerminals engineTerminals() { return new PCSCTerminals(); } } }
apache-2.0
tananaev/traccar
src/main/java/org/traccar/protocol/TmgProtocol.java
1371
/* * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import org.traccar.BaseProtocol; import org.traccar.PipelineBuilder; import org.traccar.TrackerServer; public class TmgProtocol extends BaseProtocol { public TmgProtocol() { addServer(new TrackerServer(false, getName()) { @Override protected void addProtocolHandlers(PipelineBuilder pipeline) { pipeline.addLast(new TmgFrameDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new StringDecoder()); pipeline.addLast(new TmgProtocolDecoder(TmgProtocol.this)); } }); } }
apache-2.0
scarcher2/stripes
stripes/src/net/sourceforge/stripes/util/HtmlUtil.java
4132
/* Copyright 2005-2006 Tim Fennell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.util; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.regex.Pattern; /** * Provides simple utility methods for dealing with HTML. * * @author Tim Fennell */ public class HtmlUtil { private static final String FIELD_DELIMITER_STRING = "||"; private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\|\\|"); /** * Replaces special HTML characters from the set {@literal [<, >, ", ', &]} with their HTML * escape codes. Note that because the escape codes are multi-character that the returned * String could be longer than the one passed in. * * @param fragment a String fragment that might have HTML special characters in it * @return the fragment with special characters escaped */ public static String encode(String fragment) { // If the input is null, then the output is null if (fragment == null) return null; StringBuilder builder = new StringBuilder(fragment.length() + 10); // a little wiggle room char[] characters = fragment.toCharArray(); // This loop used to also look for and replace single ticks with &apos; but it // turns out that it's not strictly necessary since Stripes uses double-quotes // around all form fields, and stupid IE6 will render &apos; verbatim instead // of as a single quote. for (int i=0; i<characters.length; ++i) { switch (characters[i]) { case '<' : builder.append("&lt;"); break; case '>' : builder.append("&gt;"); break; case '"' : builder.append("&quot;"); break; case '&' : builder.append("&amp;"); break; default: builder.append(characters[i]); } } return builder.toString(); } /** * One of a pair of methods (the other is splitValues) that is used to combine several * un-encoded values into a single delimited, encoded value for placement into a * hidden field. * * @param values One or more values which are to be combined * @return a single HTML-encoded String that contains all the values in such a way that * they can be converted back into a Collection of Strings with splitValues(). */ public static String combineValues(Collection<String> values) { if (values == null || values.size() == 0) { return ""; } else { StringBuilder builder = new StringBuilder(values.size() * 30); for (String value : values) { builder.append(value).append(FIELD_DELIMITER_STRING); } return encode(builder.toString()); } } /** * Takes in a String produced by combineValues and returns a Collection of values that * contains the same values as originally supplied to combineValues. Note that the order * or items in the collection (and indeed the type of Collection used) are not guaranteed * to be the same. * * @param value a String value produced by * @return a Collection of zero or more Strings */ public static Collection<String> splitValues(String value) { if (value == null || value.length() == 0) { return Collections.emptyList(); } else { String[] splits = FIELD_DELIMITER_PATTERN.split(value); return Arrays.asList(splits); } } }
apache-2.0
varshavaradarajan/gocd
agent-common/src/test/java/com/thoughtworks/go/agent/common/AgentCLITest.java
4889
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.agent.common; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class AgentCLITest { private ByteArrayOutputStream errorStream; private AgentCLI agentCLI; private AgentCLI.SystemExitter exitter; @Before public void setUp() throws Exception { errorStream = new ByteArrayOutputStream(); exitter = new AgentCLI.SystemExitter() { @Override public void exit(int status) { throw new ExitException(status); } }; agentCLI = new AgentCLI(new PrintStream(errorStream), exitter); } @Test public void shouldDieIfNoArguments() { try { agentCLI.parse(); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("The following option is required: [-serverUrl]")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void serverURLMustBeAValidURL() throws Exception { try { agentCLI.parse("-serverUrl", "foobar"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("-serverUrl is not a valid url")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void serverURLMustBeSSL() throws Exception { try { agentCLI.parse("-serverUrl", "http://go.example.com:8154/go"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("serverUrl must be an HTTPS url and must begin with https://")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void shouldPassIfCorrectArgumentsAreProvided() throws Exception { AgentBootstrapperArgs agentBootstrapperArgs = agentCLI.parse("-serverUrl", "https://go.example.com:8154/go", "-sslVerificationMode", "NONE"); assertThat(agentBootstrapperArgs.getServerUrl().toString(), is("https://go.example.com:8154/go")); assertThat(agentBootstrapperArgs.getSslMode(), is(AgentBootstrapperArgs.SslMode.NONE)); } @Test public void shouldRaisExceptionWhenInvalidSslModeIsPassed() throws Exception { try { agentCLI.parse("-serverUrl", "https://go.example.com:8154/go", "-sslVerificationMode", "FOOBAR"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("Invalid value for -sslVerificationMode parameter. Allowed values:[FULL, NONE, NO_VERIFY_HOST]")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void shouldDefaultsTheSslModeToNONEWhenNotSpecified() throws Exception { AgentBootstrapperArgs agentBootstrapperArgs = agentCLI.parse("-serverUrl", "https://go.example.com/go"); assertThat(agentBootstrapperArgs.getSslMode(), is(AgentBootstrapperArgs.SslMode.NONE)); } @Test public void printsHelpAndExitsWith0() throws Exception { try { agentCLI.parse("-help"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(0)); } } class ExitException extends RuntimeException { private final int status; public ExitException(int status) { this.status = status; } public int getStatus() { return status; } } }
apache-2.0
fincatto/nfe
src/main/java/com/fincatto/documentofiscal/nfe400/utils/qrcode20/NFGeraQRCode20.java
3031
package com.fincatto.documentofiscal.nfe400.utils.qrcode20; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.lang3.StringUtils; import com.fincatto.documentofiscal.DFAmbiente; import com.fincatto.documentofiscal.nfe.NFeConfig; import com.fincatto.documentofiscal.nfe400.classes.nota.NFNota; /** * Classe abstrata para a implementação da geração do QRCode 2.0. * * Deve ser feita a implementação para emissão normal (1) e para contingência offline (9). */ public abstract class NFGeraQRCode20 { public static final String VERSAO_QRCODE = "2"; protected final NFNota nota; protected final NFeConfig config; public NFGeraQRCode20(final NFNota nota, final NFeConfig config) { this.nota = nota; this.config = config; } /** * Método responsável pela geração do qrcode. * * @return URL para consulta da nota via qrcode20. * @throws NoSuchAlgorithmException */ public abstract String getQRCode() throws NoSuchAlgorithmException; public String getUrlQRCode(){ String url = this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().getQrCodeProducao() : this.nota.getInfo().getIdentificacao().getUf().getQrCodeHomologacao(); if (StringUtils.isBlank(url)) { throw new IllegalArgumentException("URL para consulta do QRCode nao informada para uf " + this.nota.getInfo().getIdentificacao().getUf() + "!"); } if (StringUtils.isBlank(this.config.getCodigoSegurancaContribuinte())) { throw new IllegalArgumentException("CSC nao informado nas configuracoes!"); } if ((this.config.getCodigoSegurancaContribuinteID() == null) || (this.config.getCodigoSegurancaContribuinteID() == 0)) { throw new IllegalArgumentException("IdCSC nao informado nas configuracoes!"); } return url; } public static String createHash(final String campos, final String csc) throws NoSuchAlgorithmException { return sha1(campos + csc); } public static String toHex(final String arg) { return String.format("%040x", new BigInteger(1, arg.getBytes(Charset.forName("UTF-8")))); } public static String sha1(final String input) throws NoSuchAlgorithmException { final StringBuilder sb = new StringBuilder(); for (final byte element : MessageDigest.getInstance("SHA1").digest(input.getBytes(Charset.forName("UTF-8")))) { sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1)); } return sb.toString().toUpperCase(); } public String urlConsultaChaveAcesso(){ return this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().getConsultaChaveAcessoProducao() : this.nota.getInfo().getIdentificacao().getUf().getConsultaChaveAcessoHomologacao(); } }
apache-2.0
nikhilvibhav/camel
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MinaComponentBuilderFactory.java
24837
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.mina.MinaComponent; /** * Socket level networking using TCP or UDP with Apache Mina 2.x. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface MinaComponentBuilderFactory { /** * Mina (camel-mina) * Socket level networking using TCP or UDP with Apache Mina 2.x. * * Category: networking,tcp,udp * Since: 2.10 * Maven coordinates: org.apache.camel:camel-mina * * @return the dsl builder */ static MinaComponentBuilder mina() { return new MinaComponentBuilderImpl(); } /** * Builder for the Mina component. */ interface MinaComponentBuilder extends ComponentBuilder<MinaComponent> { /** * Whether or not to disconnect(close) from Mina session right after * use. Can be used for both consumer and producer. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: common * * @param disconnect the value to set * @return the dsl builder */ default MinaComponentBuilder disconnect(boolean disconnect) { doSetProperty("disconnect", disconnect); return this; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j * logging at INFO level to log all input and output. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: common * * @param minaLogger the value to set * @return the dsl builder */ default MinaComponentBuilder minaLogger(boolean minaLogger) { doSetProperty("minaLogger", minaLogger); return this; } /** * Setting to set endpoint as one-way or request-response. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: common * * @param sync the value to set * @return the dsl builder */ default MinaComponentBuilder sync(boolean sync) { doSetProperty("sync", sync); return this; } /** * You can configure the timeout that specifies how long to wait for a * response from a remote server. The timeout unit is in milliseconds, * so 60000 is 60 seconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 30000 * Group: common * * @param timeout the value to set * @return the dsl builder */ default MinaComponentBuilder timeout(long timeout) { doSetProperty("timeout", timeout); return this; } /** * Maximum amount of time it should take to send data to the MINA * session. Default is 10000 milliseconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 10000 * Group: common * * @param writeTimeout the value to set * @return the dsl builder */ default MinaComponentBuilder writeTimeout(long writeTimeout) { doSetProperty("writeTimeout", writeTimeout); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default MinaComponentBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * If the clientMode is true, mina consumer will connect the address as * a TCP client. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param clientMode the value to set * @return the dsl builder */ default MinaComponentBuilder clientMode(boolean clientMode) { doSetProperty("clientMode", clientMode); return this; } /** * If sync is enabled then this option dictates MinaConsumer if it * should disconnect where there is no reply to send back. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer (advanced) * * @param disconnectOnNoReply the value to set * @return the dsl builder */ default MinaComponentBuilder disconnectOnNoReply( boolean disconnectOnNoReply) { doSetProperty("disconnectOnNoReply", disconnectOnNoReply); return this; } /** * If sync is enabled this option dictates MinaConsumer which logging * level to use when logging a there is no reply to send back. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: WARN * Group: consumer (advanced) * * @param noReplyLogLevel the value to set * @return the dsl builder */ default MinaComponentBuilder noReplyLogLevel( org.apache.camel.LoggingLevel noReplyLogLevel) { doSetProperty("noReplyLogLevel", noReplyLogLevel); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default MinaComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether to create the InetAddress once and reuse. Setting this to * false allows to pickup DNS changes in the network. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param cachedAddress the value to set * @return the dsl builder */ default MinaComponentBuilder cachedAddress(boolean cachedAddress) { doSetProperty("cachedAddress", cachedAddress); return this; } /** * Sessions can be lazily created to avoid exceptions, if the remote * server is not up and running when the Camel producer is started. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param lazySessionCreation the value to set * @return the dsl builder */ default MinaComponentBuilder lazySessionCreation( boolean lazySessionCreation) { doSetProperty("lazySessionCreation", lazySessionCreation); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default MinaComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use the shared mina configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.mina.MinaConfiguration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default MinaComponentBuilder configuration( org.apache.camel.component.mina.MinaConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * Number of worker threads in the worker pool for TCP and UDP. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 16 * Group: advanced * * @param maximumPoolSize the value to set * @return the dsl builder */ default MinaComponentBuilder maximumPoolSize(int maximumPoolSize) { doSetProperty("maximumPoolSize", maximumPoolSize); return this; } /** * Whether to use ordered thread pool, to ensure events are processed * orderly on the same channel. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param orderedThreadPoolExecutor the value to set * @return the dsl builder */ default MinaComponentBuilder orderedThreadPoolExecutor( boolean orderedThreadPoolExecutor) { doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor); return this; } /** * Only used for TCP. You can transfer the exchange over the wire * instead of just the body. The following fields are transferred: In * body, Out body, fault body, In headers, Out headers, fault headers, * exchange properties, exchange exception. This requires that the * objects are serializable. Camel will exclude any non-serializable * objects and log it at WARN level. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param transferExchange the value to set * @return the dsl builder */ default MinaComponentBuilder transferExchange(boolean transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } /** * The mina component installs a default codec if both, codec is null * and textline is false. Setting allowDefaultCodec to false prevents * the mina component from installing a default codec as the first * element in the filter chain. This is useful in scenarios where * another filter must be the first in the filter chain, like the SSL * filter. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: codec * * @param allowDefaultCodec the value to set * @return the dsl builder */ default MinaComponentBuilder allowDefaultCodec(boolean allowDefaultCodec) { doSetProperty("allowDefaultCodec", allowDefaultCodec); return this; } /** * To use a custom minda codec implementation. * * The option is a: * &lt;code&gt;org.apache.mina.filter.codec.ProtocolCodecFactory&lt;/code&gt; type. * * Group: codec * * @param codec the value to set * @return the dsl builder */ default MinaComponentBuilder codec( org.apache.mina.filter.codec.ProtocolCodecFactory codec) { doSetProperty("codec", codec); return this; } /** * To set the textline protocol decoder max line length. By default the * default value of Mina itself is used which are 1024. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1024 * Group: codec * * @param decoderMaxLineLength the value to set * @return the dsl builder */ default MinaComponentBuilder decoderMaxLineLength( int decoderMaxLineLength) { doSetProperty("decoderMaxLineLength", decoderMaxLineLength); return this; } /** * To set the textline protocol encoder max line length. By default the * default value of Mina itself is used which are Integer.MAX_VALUE. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: -1 * Group: codec * * @param encoderMaxLineLength the value to set * @return the dsl builder */ default MinaComponentBuilder encoderMaxLineLength( int encoderMaxLineLength) { doSetProperty("encoderMaxLineLength", encoderMaxLineLength); return this; } /** * You can configure the encoding (a charset name) to use for the TCP * textline codec and the UDP protocol. If not provided, Camel will use * the JVM default Charset. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: codec * * @param encoding the value to set * @return the dsl builder */ default MinaComponentBuilder encoding(java.lang.String encoding) { doSetProperty("encoding", encoding); return this; } /** * You can set a list of Mina IoFilters to use. * * The option is a: * &lt;code&gt;java.util.List&amp;lt;org.apache.mina.core.filterchain.IoFilter&amp;gt;&lt;/code&gt; type. * * Group: codec * * @param filters the value to set * @return the dsl builder */ default MinaComponentBuilder filters( java.util.List<org.apache.mina.core.filterchain.IoFilter> filters) { doSetProperty("filters", filters); return this; } /** * Only used for TCP. If no codec is specified, you can use this flag to * indicate a text line based codec; if not specified or the value is * false, then Object Serialization is assumed over TCP. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: codec * * @param textline the value to set * @return the dsl builder */ default MinaComponentBuilder textline(boolean textline) { doSetProperty("textline", textline); return this; } /** * Only used for TCP and if textline=true. Sets the text line delimiter * to use. If none provided, Camel will use DEFAULT. This delimiter is * used to mark the end of text. * * The option is a: * &lt;code&gt;org.apache.camel.component.mina.MinaTextLineDelimiter&lt;/code&gt; type. * * Group: codec * * @param textlineDelimiter the value to set * @return the dsl builder */ default MinaComponentBuilder textlineDelimiter( org.apache.camel.component.mina.MinaTextLineDelimiter textlineDelimiter) { doSetProperty("textlineDelimiter", textlineDelimiter); return this; } /** * Whether to auto start SSL handshake. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: security * * @param autoStartTls the value to set * @return the dsl builder */ default MinaComponentBuilder autoStartTls(boolean autoStartTls) { doSetProperty("autoStartTls", autoStartTls); return this; } /** * To configure SSL security. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.SSLContextParameters&lt;/code&gt; type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default MinaComponentBuilder sslContextParameters( org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * Enable usage of global SSL context parameters. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useGlobalSslContextParameters the value to set * @return the dsl builder */ default MinaComponentBuilder useGlobalSslContextParameters( boolean useGlobalSslContextParameters) { doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters); return this; } } class MinaComponentBuilderImpl extends AbstractComponentBuilder<MinaComponent> implements MinaComponentBuilder { @Override protected MinaComponent buildConcreteComponent() { return new MinaComponent(); } private org.apache.camel.component.mina.MinaConfiguration getOrCreateConfiguration( org.apache.camel.component.mina.MinaComponent component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.mina.MinaConfiguration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "disconnect": getOrCreateConfiguration((MinaComponent) component).setDisconnect((boolean) value); return true; case "minaLogger": getOrCreateConfiguration((MinaComponent) component).setMinaLogger((boolean) value); return true; case "sync": getOrCreateConfiguration((MinaComponent) component).setSync((boolean) value); return true; case "timeout": getOrCreateConfiguration((MinaComponent) component).setTimeout((long) value); return true; case "writeTimeout": getOrCreateConfiguration((MinaComponent) component).setWriteTimeout((long) value); return true; case "bridgeErrorHandler": ((MinaComponent) component).setBridgeErrorHandler((boolean) value); return true; case "clientMode": getOrCreateConfiguration((MinaComponent) component).setClientMode((boolean) value); return true; case "disconnectOnNoReply": getOrCreateConfiguration((MinaComponent) component).setDisconnectOnNoReply((boolean) value); return true; case "noReplyLogLevel": getOrCreateConfiguration((MinaComponent) component).setNoReplyLogLevel((org.apache.camel.LoggingLevel) value); return true; case "lazyStartProducer": ((MinaComponent) component).setLazyStartProducer((boolean) value); return true; case "cachedAddress": getOrCreateConfiguration((MinaComponent) component).setCachedAddress((boolean) value); return true; case "lazySessionCreation": getOrCreateConfiguration((MinaComponent) component).setLazySessionCreation((boolean) value); return true; case "autowiredEnabled": ((MinaComponent) component).setAutowiredEnabled((boolean) value); return true; case "configuration": ((MinaComponent) component).setConfiguration((org.apache.camel.component.mina.MinaConfiguration) value); return true; case "maximumPoolSize": getOrCreateConfiguration((MinaComponent) component).setMaximumPoolSize((int) value); return true; case "orderedThreadPoolExecutor": getOrCreateConfiguration((MinaComponent) component).setOrderedThreadPoolExecutor((boolean) value); return true; case "transferExchange": getOrCreateConfiguration((MinaComponent) component).setTransferExchange((boolean) value); return true; case "allowDefaultCodec": getOrCreateConfiguration((MinaComponent) component).setAllowDefaultCodec((boolean) value); return true; case "codec": getOrCreateConfiguration((MinaComponent) component).setCodec((org.apache.mina.filter.codec.ProtocolCodecFactory) value); return true; case "decoderMaxLineLength": getOrCreateConfiguration((MinaComponent) component).setDecoderMaxLineLength((int) value); return true; case "encoderMaxLineLength": getOrCreateConfiguration((MinaComponent) component).setEncoderMaxLineLength((int) value); return true; case "encoding": getOrCreateConfiguration((MinaComponent) component).setEncoding((java.lang.String) value); return true; case "filters": getOrCreateConfiguration((MinaComponent) component).setFilters((java.util.List) value); return true; case "textline": getOrCreateConfiguration((MinaComponent) component).setTextline((boolean) value); return true; case "textlineDelimiter": getOrCreateConfiguration((MinaComponent) component).setTextlineDelimiter((org.apache.camel.component.mina.MinaTextLineDelimiter) value); return true; case "autoStartTls": getOrCreateConfiguration((MinaComponent) component).setAutoStartTls((boolean) value); return true; case "sslContextParameters": getOrCreateConfiguration((MinaComponent) component).setSslContextParameters((org.apache.camel.support.jsse.SSLContextParameters) value); return true; case "useGlobalSslContextParameters": ((MinaComponent) component).setUseGlobalSslContextParameters((boolean) value); return true; default: return false; } } } }
apache-2.0
damageboy/rundeck
rundeckapp/src/java/com/dtolabs/rundeck/server/plugins/services/StreamingLogReaderPluginProviderService.java
1978
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.server.plugins.services; import com.dtolabs.rundeck.core.plugins.BasePluggableProviderService; import com.dtolabs.rundeck.core.plugins.ServiceProviderLoader; import com.dtolabs.rundeck.plugins.ServiceNameConstants; import com.dtolabs.rundeck.plugins.logging.StreamingLogReaderPlugin; /** $INTERFACE is ... User: greg Date: 5/24/13 Time: 9:32 AM */ public class StreamingLogReaderPluginProviderService extends BasePluggableProviderService<StreamingLogReaderPlugin> { public static final String SERVICE_NAME = ServiceNameConstants.StreamingLogReader; private ServiceProviderLoader rundeckServerServiceProviderLoader; public StreamingLogReaderPluginProviderService() { super(SERVICE_NAME, StreamingLogReaderPlugin.class); } @Override public ServiceProviderLoader getPluginManager() { return getRundeckServerServiceProviderLoader(); } public ServiceProviderLoader getRundeckServerServiceProviderLoader() { return rundeckServerServiceProviderLoader; } public void setRundeckServerServiceProviderLoader(ServiceProviderLoader rundeckServerServiceProviderLoader) { this.rundeckServerServiceProviderLoader = rundeckServerServiceProviderLoader; } @Override public boolean isScriptPluggable() { //for now return false; } }
apache-2.0
objectiser/camel
examples/camel-example-cxf/src/main/java/org/apache/camel/example/cxf/jaxrs/Client.java
2440
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.example.cxf.jaxrs; import org.apache.camel.example.cxf.jaxrs.resources.Book; import org.apache.camel.example.cxf.jaxrs.resources.BookNotFoundFault; import org.apache.camel.example.cxf.jaxrs.resources.BookStore; public class Client { void invoke() throws BookNotFoundFault { // JAXWSClient invocation JAXWSClient jaxwsClient = new JAXWSClient(); BookStore bookStore = jaxwsClient.getBookStore(); bookStore.addBook(new Book("Camel User Guide", 123L)); Book book = bookStore.getBook(123L); System.out.println("Get the book with id 123. " + book); try { book = bookStore.getBook(124L); System.out.println("Get the book with id 124. " + book); } catch (Exception exception) { System.out.println("Expected exception received: " + exception); } // JAXRSClient invocation JAXRSClient jaxrsClient = new JAXRSClient(); bookStore = jaxrsClient.getBookStore(); bookStore.addBook(new Book("Karaf User Guide", 124L)); book = bookStore.getBook(124L); System.out.println("Get the book with id 124. " + book); try { book = bookStore.getBook(126L); System.out.println("Get the book with id 126. " + book); } catch (Exception exception) { System.out.println("Expected exception received: " + exception); } } public static void main(String args[]) throws Exception { Client client = new Client(); client.invoke(); } }
apache-2.0
PhaedrusTheGreek/elasticsearch
core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java
20764
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.significant; import org.apache.lucene.util.BytesRef; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.InputStreamStreamInput; import org.elasticsearch.common.io.stream.OutputStreamStreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.ChiSquare; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.GND; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.JLHScore; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.MutualInformation; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.PercentageScore; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicBuilder; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParser; import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParserMapper; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.TestSearchContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.elasticsearch.test.VersionUtils.randomVersion; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; /** * */ public class SignificanceHeuristicTests extends ESTestCase { static class SignificantTermsTestSearchContext extends TestSearchContext { @Override public int numberOfShards() { return 1; } @Override public SearchShardTarget shardTarget() { return new SearchShardTarget("no node, this is a unit test", "no index, this is a unit test", 0); } } // test that stream output can actually be read - does not replace bwc test public void testStreamResponse() throws Exception { Version version = randomVersion(random()); InternalSignificantTerms[] sigTerms = getRandomSignificantTerms(getRandomSignificanceheuristic()); // write ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer); out.setVersion(version); sigTerms[0].writeTo(out); // read ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); InputStreamStreamInput in = new InputStreamStreamInput(inBuffer); in.setVersion(version); sigTerms[1].readFrom(in); assertTrue(sigTerms[1].significanceHeuristic.equals(sigTerms[0].significanceHeuristic)); } InternalSignificantTerms[] getRandomSignificantTerms(SignificanceHeuristic heuristic) { InternalSignificantTerms[] sTerms = new InternalSignificantTerms[2]; ArrayList<InternalSignificantTerms.Bucket> buckets = new ArrayList<>(); if (randomBoolean()) { BytesRef term = new BytesRef("123.0"); buckets.add(new SignificantLongTerms.Bucket(1, 2, 3, 4, 123, InternalAggregations.EMPTY, null)); sTerms[0] = new SignificantLongTerms(10, 20, "some_name", null, 1, 1, heuristic, buckets, Collections.EMPTY_LIST, null); sTerms[1] = new SignificantLongTerms(); } else { BytesRef term = new BytesRef("someterm"); buckets.add(new SignificantStringTerms.Bucket(term, 1, 2, 3, 4, InternalAggregations.EMPTY)); sTerms[0] = new SignificantStringTerms(10, 20, "some_name", 1, 1, heuristic, buckets, Collections.EMPTY_LIST, null); sTerms[1] = new SignificantStringTerms(); } return sTerms; } SignificanceHeuristic getRandomSignificanceheuristic() { List<SignificanceHeuristic> heuristics = new ArrayList<>(); heuristics.add(JLHScore.INSTANCE); heuristics.add(new MutualInformation(randomBoolean(), randomBoolean())); heuristics.add(new GND(randomBoolean())); heuristics.add(new ChiSquare(randomBoolean(), randomBoolean())); return heuristics.get(randomInt(3)); } // test that // 1. The output of the builders can actually be parsed // 2. The parser does not swallow parameters after a significance heuristic was defined public void testBuilderAndParser() throws Exception { Set<SignificanceHeuristicParser> parsers = new HashSet<>(); SignificanceHeuristicParserMapper heuristicParserMapper = new SignificanceHeuristicParserMapper(parsers, null); SearchContext searchContext = new SignificantTermsTestSearchContext(); // test jlh with string assertTrue(parseFromString(heuristicParserMapper, searchContext, "\"jlh\":{}") instanceof JLHScore); // test gnd with string assertTrue(parseFromString(heuristicParserMapper, searchContext, "\"gnd\":{}") instanceof GND); // test mutual information with string boolean includeNegatives = randomBoolean(); boolean backgroundIsSuperset = randomBoolean(); assertThat(parseFromString(heuristicParserMapper, searchContext, "\"mutual_information\":{\"include_negatives\": " + includeNegatives + ", \"background_is_superset\":" + backgroundIsSuperset + "}"), equalTo((SignificanceHeuristic) (new MutualInformation(includeNegatives, backgroundIsSuperset)))); assertThat(parseFromString(heuristicParserMapper, searchContext, "\"chi_square\":{\"include_negatives\": " + includeNegatives + ", \"background_is_superset\":" + backgroundIsSuperset + "}"), equalTo((SignificanceHeuristic) (new ChiSquare(includeNegatives, backgroundIsSuperset)))); // test with builders assertTrue(parseFromBuilder(heuristicParserMapper, searchContext, new JLHScore.JLHScoreBuilder()) instanceof JLHScore); assertTrue(parseFromBuilder(heuristicParserMapper, searchContext, new GND.GNDBuilder(backgroundIsSuperset)) instanceof GND); assertThat(parseFromBuilder(heuristicParserMapper, searchContext, new MutualInformation.MutualInformationBuilder(includeNegatives, backgroundIsSuperset)), equalTo((SignificanceHeuristic) new MutualInformation(includeNegatives, backgroundIsSuperset))); assertThat(parseFromBuilder(heuristicParserMapper, searchContext, new ChiSquare.ChiSquareBuilder(includeNegatives, backgroundIsSuperset)), equalTo((SignificanceHeuristic) new ChiSquare(includeNegatives, backgroundIsSuperset))); // test exceptions String faultyHeuristicdefinition = "\"mutual_information\":{\"include_negatives\": false, \"some_unknown_field\": false}"; String expectedError = "unknown field [some_unknown_field]"; checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError); faultyHeuristicdefinition = "\"chi_square\":{\"unknown_field\": true}"; expectedError = "unknown field [unknown_field]"; checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError); faultyHeuristicdefinition = "\"jlh\":{\"unknown_field\": true}"; expectedError = "expected an empty object, but found "; checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError); faultyHeuristicdefinition = "\"gnd\":{\"unknown_field\": true}"; expectedError = "unknown field [unknown_field]"; checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError); } protected void checkParseException(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, String faultyHeuristicDefinition, String expectedError) throws IOException { try { XContentParser stParser = JsonXContent.jsonXContent.createParser("{\"field\":\"text\", " + faultyHeuristicDefinition + ",\"min_doc_count\":200}"); stParser.nextToken(); new SignificantTermsParser(heuristicParserMapper).parse("testagg", stParser, searchContext); fail(); } catch (ElasticsearchParseException e) { assertTrue(e.getMessage().contains(expectedError)); } } protected SignificanceHeuristic parseFromBuilder(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, SignificanceHeuristicBuilder significanceHeuristicBuilder) throws IOException { SignificantTermsBuilder stBuilder = new SignificantTermsBuilder("testagg"); stBuilder.significanceHeuristic(significanceHeuristicBuilder).field("text").minDocCount(200); XContentBuilder stXContentBuilder = XContentFactory.jsonBuilder(); stBuilder.internalXContent(stXContentBuilder, null); XContentParser stParser = JsonXContent.jsonXContent.createParser(stXContentBuilder.string()); return parseSignificanceHeuristic(heuristicParserMapper, searchContext, stParser); } private SignificanceHeuristic parseSignificanceHeuristic(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, XContentParser stParser) throws IOException { stParser.nextToken(); SignificantTermsAggregatorFactory aggregatorFactory = (SignificantTermsAggregatorFactory) new SignificantTermsParser(heuristicParserMapper).parse("testagg", stParser, searchContext); stParser.nextToken(); assertThat(aggregatorFactory.getBucketCountThresholds().getMinDocCount(), equalTo(200l)); assertThat(stParser.currentToken(), equalTo(null)); stParser.close(); return aggregatorFactory.getSignificanceHeuristic(); } protected SignificanceHeuristic parseFromString(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, String heuristicString) throws IOException { XContentParser stParser = JsonXContent.jsonXContent.createParser("{\"field\":\"text\", " + heuristicString + ", \"min_doc_count\":200}"); return parseSignificanceHeuristic(heuristicParserMapper, searchContext, stParser); } void testBackgroundAssertions(SignificanceHeuristic heuristicIsSuperset, SignificanceHeuristic heuristicNotSuperset) { try { heuristicIsSuperset.getScore(2, 3, 1, 4); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > supersetFreq")); } try { heuristicIsSuperset.getScore(1, 4, 2, 3); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("subsetSize > supersetSize")); } try { heuristicIsSuperset.getScore(2, 1, 3, 4); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize")); } try { heuristicIsSuperset.getScore(1, 2, 4, 3); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize")); } try { heuristicIsSuperset.getScore(1, 3, 4, 4); fail(); } catch (IllegalArgumentException assertionError) { assertNotNull(assertionError.getMessage()); assertTrue(assertionError.getMessage().contains("supersetFreq - subsetFreq > supersetSize - subsetSize")); } try { int idx = randomInt(3); long[] values = {1, 2, 3, 4}; values[idx] *= -1; heuristicIsSuperset.getScore(values[0], values[1], values[2], values[3]); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive")); } try { heuristicNotSuperset.getScore(2, 1, 3, 4); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize")); } try { heuristicNotSuperset.getScore(1, 2, 4, 3); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize")); } try { int idx = randomInt(3); long[] values = {1, 2, 3, 4}; values[idx] *= -1; heuristicNotSuperset.getScore(values[0], values[1], values[2], values[3]); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive")); } } void testAssertions(SignificanceHeuristic heuristic) { try { int idx = randomInt(3); long[] values = {1, 2, 3, 4}; values[idx] *= -1; heuristic.getScore(values[0], values[1], values[2], values[3]); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive")); } try { heuristic.getScore(1, 2, 4, 3); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize")); } try { heuristic.getScore(2, 1, 3, 4); fail(); } catch (IllegalArgumentException illegalArgumentException) { assertNotNull(illegalArgumentException.getMessage()); assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize")); } } public void testAssertions() throws Exception { testBackgroundAssertions(new MutualInformation(true, true), new MutualInformation(true, false)); testBackgroundAssertions(new ChiSquare(true, true), new ChiSquare(true, false)); testBackgroundAssertions(new GND(true), new GND(false)); testAssertions(PercentageScore.INSTANCE); testAssertions(JLHScore.INSTANCE); } public void testBasicScoreProperties() { basicScoreProperties(JLHScore.INSTANCE, true); basicScoreProperties(new GND(true), true); basicScoreProperties(PercentageScore.INSTANCE, true); basicScoreProperties(new MutualInformation(true, true), false); basicScoreProperties(new ChiSquare(true, true), false); } public void basicScoreProperties(SignificanceHeuristic heuristic, boolean test0) { assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0)); assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3))); assertThat(heuristic.getScore(1, 1, 3, 4), lessThan(heuristic.getScore(1, 1, 2, 4))); if (test0) { assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(0.0)); } double score = 0.0; try { long a = randomLong(); long b = randomLong(); long c = randomLong(); long d = randomLong(); score = heuristic.getScore(a, b, c, d); } catch (IllegalArgumentException e) { } assertThat(score, greaterThanOrEqualTo(0.0)); } public void testScoreMutual() throws Exception { SignificanceHeuristic heuristic = new MutualInformation(true, true); assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0)); assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3))); assertThat(heuristic.getScore(2, 2, 2, 4), equalTo(1.0)); assertThat(heuristic.getScore(0, 2, 2, 4), equalTo(1.0)); assertThat(heuristic.getScore(2, 2, 4, 4), equalTo(0.0)); assertThat(heuristic.getScore(1, 2, 2, 4), equalTo(0.0)); assertThat(heuristic.getScore(3, 6, 9, 18), equalTo(0.0)); double score = 0.0; try { long a = randomLong(); long b = randomLong(); long c = randomLong(); long d = randomLong(); score = heuristic.getScore(a, b, c, d); } catch (IllegalArgumentException e) { } assertThat(score, lessThanOrEqualTo(1.0)); assertThat(score, greaterThanOrEqualTo(0.0)); heuristic = new MutualInformation(false, true); assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(Double.NEGATIVE_INFINITY)); heuristic = new MutualInformation(true, false); score = heuristic.getScore(2, 3, 1, 4); assertThat(score, greaterThanOrEqualTo(0.0)); assertThat(score, lessThanOrEqualTo(1.0)); score = heuristic.getScore(1, 4, 2, 3); assertThat(score, greaterThanOrEqualTo(0.0)); assertThat(score, lessThanOrEqualTo(1.0)); score = heuristic.getScore(1, 3, 4, 4); assertThat(score, greaterThanOrEqualTo(0.0)); assertThat(score, lessThanOrEqualTo(1.0)); } public void testGNDCornerCases() throws Exception { GND gnd = new GND(true); //term is only in the subset, not at all in the other set but that is because the other set is empty. // this should actually not happen because only terms that are in the subset are considered now, // however, in this case the score should be 0 because a term that does not exist cannot be relevant... assertThat(gnd.getScore(0, randomIntBetween(1, 2), 0, randomIntBetween(2,3)), equalTo(0.0)); // the terms do not co-occur at all - should be 0 assertThat(gnd.getScore(0, randomIntBetween(1, 2), randomIntBetween(2, 3), randomIntBetween(5,6)), equalTo(0.0)); // comparison between two terms that do not exist - probably not relevant assertThat(gnd.getScore(0, 0, 0, randomIntBetween(1,2)), equalTo(0.0)); // terms co-occur perfectly - should be 1 assertThat(gnd.getScore(1, 1, 1, 1), equalTo(1.0)); gnd = new GND(false); assertThat(gnd.getScore(0, 0, 0, 0), equalTo(0.0)); } }
apache-2.0
jk1/intellij-community
java/java-indexing-impl/src/com/intellij/psi/impl/CompositeShortNamesCache.java
10218
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IdFilter; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Set; public class CompositeShortNamesCache extends PsiShortNamesCache { private final PsiShortNamesCache[] myCaches; public CompositeShortNamesCache(Project project) { myCaches = project.isDefault() ? new PsiShortNamesCache[0] : project.getExtensions(PsiShortNamesCache.EP_NAME); } @Override @NotNull public PsiFile[] getFilesByName(@NotNull String name) { Merger<PsiFile> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiFile[] classes = cache.getFilesByName(name); if (classes.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(classes); } } PsiFile[] result = merger == null ? null : merger.getResult(); return result != null ? result : PsiFile.EMPTY_ARRAY; } @Override @NotNull public String[] getAllFileNames() { Merger<String> merger = new Merger<>(); for (PsiShortNamesCache cache : myCaches) { merger.add(cache.getAllFileNames()); } String[] result = merger.getResult(); return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY; } @Override @NotNull public PsiClass[] getClassesByName(@NotNull String name, @NotNull GlobalSearchScope scope) { Merger<PsiClass> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiClass[] classes = cache.getClassesByName(name, scope); if (classes.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(classes); } } PsiClass[] result = merger == null ? null : merger.getResult(); return result != null ? result : PsiClass.EMPTY_ARRAY; } @Override @NotNull public String[] getAllClassNames() { Merger<String> merger = new Merger<>(); for (PsiShortNamesCache cache : myCaches) { String[] names = cache.getAllClassNames(); merger.add(names); } String[] result = merger.getResult(); return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY; } @Override public boolean processAllClassNames(@NotNull Processor<String> processor) { CommonProcessors.UniqueProcessor<String> uniqueProcessor = new CommonProcessors.UniqueProcessor<>(processor); for (PsiShortNamesCache cache : myCaches) { if (!cache.processAllClassNames(uniqueProcessor)) { return false; } } return true; } @Override public boolean processAllClassNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processAllClassNames(processor, scope, filter)) { return false; } } return true; } @Override public boolean processAllMethodNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processAllMethodNames(processor, scope, filter)) { return false; } } return true; } @Override public boolean processAllFieldNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processAllFieldNames(processor, scope, filter)) { return false; } } return true; } @Override @NotNull public PsiMethod[] getMethodsByName(@NotNull String name, @NotNull GlobalSearchScope scope) { Merger<PsiMethod> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiMethod[] methods = cache.getMethodsByName(name, scope); if (methods.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(methods); } } PsiMethod[] result = merger == null ? null : merger.getResult(); return result == null ? PsiMethod.EMPTY_ARRAY : result; } @Override @NotNull public PsiMethod[] getMethodsByNameIfNotMoreThan(@NonNls @NotNull final String name, @NotNull final GlobalSearchScope scope, final int maxCount) { Merger<PsiMethod> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(name, scope, maxCount); if (methods.length == maxCount) return methods; if (methods.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(methods); } } PsiMethod[] result = merger == null ? null : merger.getResult(); return result == null ? PsiMethod.EMPTY_ARRAY : result; } @NotNull @Override public PsiField[] getFieldsByNameIfNotMoreThan(@NonNls @NotNull String name, @NotNull GlobalSearchScope scope, int maxCount) { Merger<PsiField> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiField[] fields = cache.getFieldsByNameIfNotMoreThan(name, scope, maxCount); if (fields.length == maxCount) return fields; if (fields.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(fields); } } PsiField[] result = merger == null ? null : merger.getResult(); return result == null ? PsiField.EMPTY_ARRAY : result; } @Override public boolean processMethodsWithName(@NonNls @NotNull String name, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiMethod> processor) { return processMethodsWithName(name, processor, scope, null); } @Override public boolean processMethodsWithName(@NonNls @NotNull String name, @NotNull Processor<? super PsiMethod> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processMethodsWithName(name, processor, scope, idFilter)) return false; } return true; } @Override @NotNull public String[] getAllMethodNames() { Merger<String> merger = new Merger<>(); for (PsiShortNamesCache cache : myCaches) { merger.add(cache.getAllMethodNames()); } String[] result = merger.getResult(); return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY; } @Override @NotNull public PsiField[] getFieldsByName(@NotNull String name, @NotNull GlobalSearchScope scope) { Merger<PsiField> merger = null; for (PsiShortNamesCache cache : myCaches) { PsiField[] classes = cache.getFieldsByName(name, scope); if (classes.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(classes); } } PsiField[] result = merger == null ? null : merger.getResult(); return result == null ? PsiField.EMPTY_ARRAY : result; } @Override @NotNull public String[] getAllFieldNames() { Merger<String> merger = null; for (PsiShortNamesCache cache : myCaches) { String[] classes = cache.getAllFieldNames(); if (classes.length != 0) { if (merger == null) merger = new Merger<>(); merger.add(classes); } } String[] result = merger == null ? null : merger.getResult(); return result == null ? ArrayUtil.EMPTY_STRING_ARRAY : result; } @Override public boolean processFieldsWithName(@NotNull String key, @NotNull Processor<? super PsiField> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter filter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processFieldsWithName(key, processor, scope, filter)) return false; } return true; } @Override public boolean processClassesWithName(@NotNull String key, @NotNull Processor<? super PsiClass> processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter filter) { for (PsiShortNamesCache cache : myCaches) { if (!cache.processClassesWithName(key, processor, scope, filter)) return false; } return true; } private static class Merger<T> { private T[] mySingleItem; private Set<T> myAllItems; public void add(@NotNull T[] items) { if (items.length == 0) return; if (mySingleItem == null) { mySingleItem = items; return; } if (myAllItems == null) { T[] elements = mySingleItem; myAllItems = ContainerUtil.addAll(new THashSet<>(elements.length), elements); } ContainerUtil.addAll(myAllItems, items); } public T[] getResult() { if (myAllItems == null) return mySingleItem; return myAllItems.toArray(mySingleItem); } } @SuppressWarnings({"HardCodedStringLiteral"}) @Override public String toString() { return "Composite cache: " + Arrays.asList(myCaches); } }
apache-2.0
varshavaradarajan/gocd
domain/src/main/java/com/thoughtworks/go/domain/materials/git/GitModificationParser.java
3128
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.domain.materials.git; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.util.DateUtils; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GitModificationParser { private LinkedList<Modification> modifications = new LinkedList<>(); private static final String SPACES = "\\s+"; private static final String COMMENT_INDENT = "\\s{4}"; private static final String COMMENT_TEXT = "(.*)"; private static final String HASH = "(\\w+)"; private static final String DATE = "(.+)"; private static final String AUTHOR = "(.+)"; private static final Pattern COMMIT_PATTERN = Pattern.compile("^commit" + SPACES + HASH + "$"); private static final Pattern AUTHOR_PATTERN = Pattern.compile("^Author:"+ SPACES + AUTHOR + "$"); private static final Pattern DATE_PATTERN = Pattern.compile("^Date:" + SPACES + DATE + "$"); private static final Pattern COMMENT_PATTERN = Pattern.compile("^" + COMMENT_INDENT + COMMENT_TEXT + "$"); public List<Modification> parse(List<String> output) { for (String line : output) { processLine(line); } return modifications; } public List<Modification> getModifications() { return modifications; } public void processLine(String line) { Matcher matcher = COMMIT_PATTERN.matcher(line); if (matcher.matches()) { modifications.add(new Modification("", "", null, null, matcher.group(1))); } Matcher authorMatcher = AUTHOR_PATTERN.matcher(line); if (authorMatcher.matches()) { modifications.getLast().setUserName(authorMatcher.group(1)); } Matcher dateMatcher = DATE_PATTERN.matcher(line); if (dateMatcher.matches()) { modifications.getLast().setModifiedTime(DateUtils.parseISO8601(dateMatcher.group(1))); } Matcher commentMatcher = COMMENT_PATTERN.matcher(line); if (commentMatcher.matches()) { Modification last = modifications.getLast(); String comment = Optional.ofNullable(last.getComment()).orElse(""); if (!comment.isEmpty()) comment += "\n"; last.setComment(comment + commentMatcher.group(1)); } } }
apache-2.0
Ile2/struts2-showcase-demo
src/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/User.java
1350
/* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts2.showcase.chat; import java.io.Serializable; import java.util.Date; /** * Represends a user in the Chat example. */ public class User implements Serializable { private static final long serialVersionUID = -1434958919516089297L; private String name; private Date creationDate; public User(String name) { this.name = name; this.creationDate = new Date(System.currentTimeMillis()); } public Date getCreationDate() { return creationDate; } public String getName() { return name; } }
apache-2.0
smmribeiro/intellij-community
plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTreeConflictDataTest.java
20363
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.conflict.ConflictAction; import org.jetbrains.idea.svn.conflict.ConflictOperation; import org.jetbrains.idea.svn.conflict.ConflictVersion; import org.jetbrains.idea.svn.conflict.TreeConflictDescription; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.function.BiConsumer; import static com.intellij.testFramework.EdtTestUtil.runInEdtAndWait; import static org.junit.Assert.*; public class SvnTreeConflictDataTest extends SvnTestCase { private VirtualFile myTheirs; private SvnClientRunnerImpl mySvnClientRunner; @Override @Before public void before() throws Exception { myWcRootName = "wcRootConflictData"; myTraceClient = true; super.before(); disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); myTheirs = myTempDirFixture.findOrCreateDir("theirs"); mySvnClientRunner = new SvnClientRunnerImpl(myRunner); mySvnClientRunner.checkout(myRepoUrl, myTheirs); } @Test public void testFile2File_MINE_UNV_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_ADD, false, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); assertNull(beforeDescription.getSourceLeftVersion()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testFile2File_MINE_EDIT_THEIRS_DELETE() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_DELETE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isFile()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isNone()); }); } private String createConflict(@NotNull TreeConflictData.Data data, boolean createSubtree) throws Exception { if (createSubtree) { mySvnClientRunner.testSvnVersion(myWorkingCopyDir); createSubTree(); } runInEdtAndWait(() -> new ConflictCreator(vcs, myTheirs, myWorkingCopyDir, data, mySvnClientRunner).create()); return data.getConflictFile(); } @Test public void testFile2File_MINE_DELETE_THEIRS_EDIT() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isFile()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testFile2File_MINE_EDIT_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isFile()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isNone()); }); } @Test public void testFile2File_MINE_UNV_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testFile2File_MINE_MOVE_THEIRS_EDIT() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isFile()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testFile2File_MINE_MOVE_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); //Assert.assertEquals(NodeKind.FILE, leftVersion.getKind()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } //---------------------------------- dirs -------------------------------------------------------- @Test public void testDir2Dir_MINE_UNV_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } // not a conflict in Subversion 1.7.7. "mine" file becomes added /*@Test public void testDir2Dir_MINE_EDIT_THEIRS_DELETE() throws Exception { final String conflictFile = createConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_DELETE); VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); changeListManager.ensureUpToDate(false); VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile)); Assert.assertNotNull(vf); final Change change = changeListManager.getChange(vf); Assert.assertTrue(change instanceof ConflictedSvnChange); TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription(); Assert.assertNotNull(beforeDescription); final TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription(); Assert.assertNull(afterDescription); Assert.assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); Assert.assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); Assert.assertNotNull(leftVersion); Assert.assertEquals(NodeKind.DIR, leftVersion.getKind()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); Assert.assertNotNull(version); Assert.assertEquals(NodeKind.NONE, version.getKind()); }*/ @Test public void testDir2Dir_MINE_DELETE_THEIRS_EDIT() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isDirectory()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testDir2Dir_MINE_EDIT_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isDirectory()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isNone()); }); } @Test public void testDir2Dir_MINE_UNV_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testDir2Dir_MINE_MOVE_THEIRS_EDIT() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNotNull(leftVersion); assertTrue(leftVersion.isDirectory()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testDir2Dir_MINE_MOVE_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); //Assert.assertEquals(NodeKind.DIR, leftVersion.getKind()); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } //--------------------------------- @Test public void testFile2Dir_MINE_UNV_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testFile2Dir_MINE_ADD_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testFile2Dir_MINE_UNV_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testFile2Dir_MINE_ADD_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } @Test public void testFile2Dir_MINE_MOVE_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.FileToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isDirectory()); }); } //****************************************** // dir -> file (mine, theirs) @Test public void testDir2File_MINE_UNV_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testDir2File_MINE_ADD_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testDir2File_MINE_UNV_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testDir2File_MINE_ADD_THEIRS_MOVE() throws Exception { assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } @Test public void testDir2File_MINE_MOVE_THEIRS_ADD() throws Exception { assertConflict(TreeConflictData.DirToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> { assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation()); assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction()); ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion(); assertNull(leftVersion); final ConflictVersion version = beforeDescription.getSourceRightVersion(); assertNotNull(version); assertTrue(version.isFile()); }); } private void createSubTree() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); new SubTree(myWorkingCopyDir); mySvnClientRunner.checkin(myWorkingCopyDir); mySvnClientRunner.update(myTheirs); mySvnClientRunner.update(myWorkingCopyDir); disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); disableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); } private void assertConflict(@NotNull TreeConflictData.Data data, @NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception { assertConflict(data, true, checker); } private void assertConflict(@NotNull TreeConflictData.Data data, boolean createSubtree, @NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception { String conflictFile = createConflict(data, createSubtree); refreshChanges(); Change change; if (data == TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT || data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT || data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD) { change = changeListManager.getChange(VcsUtil.getFilePath(new File(myWorkingCopyDir.getPath(), conflictFile), true)); } else { VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile)); assertNotNull(vf); change = changeListManager.getChange(vf); } assertTrue(change instanceof ConflictedSvnChange); TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription(); TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription(); assertNotNull(beforeDescription); assertNull(afterDescription); checker.accept(beforeDescription, afterDescription); } }
apache-2.0
yongjhih/NotRetrofit
retrofit2-github-app/src/main/java/com/github/retrofit2/app/Item.java
1268
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.retrofit2.app; import auto.parcel.AutoParcel; import android.os.Parcelable; import android.support.annotation.Nullable; @AutoParcel public abstract class Item implements Parcelable { @Nullable public abstract String icon(); @Nullable public abstract String text1(); @AutoParcel.Builder public abstract static class Builder { public abstract Builder icon(String s); public abstract Builder text1(String s); public abstract Item build(); } public static Builder builder() { return new AutoParcel_Item.Builder(); } public abstract Builder toBuilder(); }
apache-2.0
psakar/Resteasy
resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java
1810
package org.jboss.resteasy.api.validation; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * * @author <a href="ron.sigal@jboss.com">Ron Sigal</a> * @version $Revision: 1.1 $ * * Copyright Jun 4, 2013 */ @XmlRootElement(name="resteasyConstraintViolation") @XmlAccessorType(XmlAccessType.FIELD) public class ResteasyConstraintViolation implements Serializable { private static final long serialVersionUID = -5441628046215135260L; private ConstraintType.Type constraintType; private String path; private String message; private String value; public ResteasyConstraintViolation(ConstraintType.Type constraintType, String path, String message, String value) { this.constraintType = constraintType; this.path = path; this.message = message; this.value = value; } public ResteasyConstraintViolation() { } /** * @return type of constraint */ public ConstraintType.Type getConstraintType() { return constraintType; } /** * @return description of element violating constraint */ public String getPath() { return path; } /** * @return description of constraint violation */ public String getMessage() { return message; } /** * @return object in violation of constraint */ public String getValue() { return value; } /** * @return String representation of violation */ public String toString() { return "[" + type() + "]\r[" + path + "]\r[" + message + "]\r[" + value + "]\r"; } /** * @return String form of violation type */ public String type() { return constraintType.toString(); } }
apache-2.0
baboune/compass
src/main/src/org/compass/core/lucene/engine/optimizer/AbstractIndexInfoOptimizer.java
2416
/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.core.lucene.engine.optimizer; import java.io.IOException; import org.apache.lucene.index.LuceneSubIndexInfo; import org.compass.core.engine.SearchEngineException; import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager; /** * @author kimchy */ public abstract class AbstractIndexInfoOptimizer extends AbstractOptimizer { protected void doOptimize(String subIndex) throws SearchEngineException { LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex); if (indexInfo == null) { return; } doOptimize(subIndex, indexInfo); } protected void doForceOptimize(String subIndex) throws SearchEngineException { LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex); if (indexInfo == null) { return; } doForceOptimize(subIndex, indexInfo); } protected LuceneSubIndexInfo doGetIndexInfo(String subIndex) { LuceneSearchEngineIndexManager indexManager = getSearchEngineFactory().getLuceneIndexManager(); LuceneSubIndexInfo indexInfo; try { indexInfo = LuceneSubIndexInfo.getIndexInfo(subIndex, indexManager); } catch (IOException e) { throw new SearchEngineException("Failed to read index info for sub index [" + subIndex + "]", e); } if (indexInfo == null) { // no index data, simply continue return null; } if (!isRunning()) { return null; } return indexInfo; } protected abstract void doOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException; protected abstract void doForceOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException; }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelFunctionFqnNameIndex.java
1887
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.stubindex; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.psi.KtNamedFunction; import java.util.Collection; /** * Stores package top level function (both extension and non-extension) full qualified names. */ public class KotlinTopLevelFunctionFqnNameIndex extends AbstractStringStubIndexExtension<KtNamedFunction> { private static final StubIndexKey<String, KtNamedFunction> KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelFunctionFqnNameIndex.class); private static final KotlinTopLevelFunctionFqnNameIndex INSTANCE = new KotlinTopLevelFunctionFqnNameIndex(); @NotNull public static KotlinTopLevelFunctionFqnNameIndex getInstance() { return INSTANCE; } private KotlinTopLevelFunctionFqnNameIndex() { super(KtNamedFunction.class); } @NotNull @Override public StubIndexKey<String, KtNamedFunction> getKey() { return KEY; } @NotNull @Override public Collection<KtNamedFunction> get(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) { return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class); } // temporary hack, see comments in findCandidateDeclarationsInIndex (findDecompiledDeclaration.kt) @NotNull public Collection<KtNamedFunction> getNoScopeWrap(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) { return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class); } }
apache-2.0
quintinali/mudrod
core/src/main/java/gov/nasa/jpl/mudrod/ssearch/ranking/TrainingImporter.java
3467
/* * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.nasa.jpl.mudrod.ssearch.ranking; import gov.nasa.jpl.mudrod.discoveryengine.MudrodAbstract; import gov.nasa.jpl.mudrod.driver.ESDriver; import gov.nasa.jpl.mudrod.driver.SparkDriver; import gov.nasa.jpl.mudrod.main.MudrodConstants; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilders; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * Supports the ability to importing training set into Elasticsearch */ public class TrainingImporter extends MudrodAbstract { /** * */ private static final long serialVersionUID = 1L; public TrainingImporter(Properties props, ESDriver es, SparkDriver spark) { super(props, es, spark); es.deleteAllByQuery(props.getProperty(MudrodConstants.ES_INDEX_NAME), "trainingranking", QueryBuilders.matchAllQuery()); addMapping(); } /** * Method of adding mapping to traning set type */ public void addMapping() { XContentBuilder Mapping; try { Mapping = jsonBuilder().startObject().startObject("trainingranking").startObject("properties").startObject("query").field("type", "string").field("index", "not_analyzed").endObject() .startObject("dataID").field("type", "string").field("index", "not_analyzed").endObject().startObject("label").field("type", "string").field("index", "not_analyzed").endObject().endObject() .endObject().endObject(); es.getClient().admin().indices().preparePutMapping(props.getProperty("indexName")).setType("trainingranking").setSource(Mapping).execute().actionGet(); } catch (IOException e) { e.printStackTrace(); } } /** * Method of importing training set in to Elasticsearch * * @param dataFolder the path to the traing set * @throws IOException IOException */ public void importTrainingSet(String dataFolder) throws IOException { es.createBulkProcessor(); File[] files = new File(dataFolder).listFiles(); for (File file : files) { BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath())); br.readLine(); String line = br.readLine(); while (line != null) { String[] list = line.split(","); String query = file.getName().replace(".csv", ""); if (list.length > 0) { IndexRequest ir = new IndexRequest(props.getProperty("indexName"), "trainingranking") .source(jsonBuilder().startObject().field("query", query).field("dataID", list[0]).field("label", list[list.length - 1]).endObject()); es.getBulkProcessor().add(ir); } line = br.readLine(); } br.close(); } es.destroyBulkProcessor(); } }
apache-2.0
ZhenyaM/veraPDF-pdfbox
pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStreamEngine.java
10595
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.text; import java.io.InputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.PDFStreamEngine; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.font.encoding.GlyphList; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDSimpleFont; import org.apache.pdfbox.pdmodel.font.PDType3Font; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import java.io.IOException; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; import org.apache.pdfbox.contentstream.operator.DrawObject; import org.apache.pdfbox.contentstream.operator.state.Concatenate; import org.apache.pdfbox.contentstream.operator.state.Restore; import org.apache.pdfbox.contentstream.operator.state.Save; import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters; import org.apache.pdfbox.contentstream.operator.state.SetMatrix; import org.apache.pdfbox.contentstream.operator.text.BeginText; import org.apache.pdfbox.contentstream.operator.text.EndText; import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize; import org.apache.pdfbox.contentstream.operator.text.SetTextHorizontalScaling; import org.apache.pdfbox.contentstream.operator.text.ShowTextAdjusted; import org.apache.pdfbox.contentstream.operator.text.ShowTextLine; import org.apache.pdfbox.contentstream.operator.text.ShowTextLineAndSpace; import org.apache.pdfbox.contentstream.operator.text.MoveText; import org.apache.pdfbox.contentstream.operator.text.MoveTextSetLeading; import org.apache.pdfbox.contentstream.operator.text.NextLine; import org.apache.pdfbox.contentstream.operator.text.SetCharSpacing; import org.apache.pdfbox.contentstream.operator.text.SetTextLeading; import org.apache.pdfbox.contentstream.operator.text.SetTextRenderingMode; import org.apache.pdfbox.contentstream.operator.text.SetTextRise; import org.apache.pdfbox.contentstream.operator.text.SetWordSpacing; import org.apache.pdfbox.contentstream.operator.text.ShowText; /** * PDFStreamEngine subclass for advanced processing of text via TextPosition. * * @see org.apache.pdfbox.text.TextPosition * @author Ben Litchfield * @author John Hewson */ class PDFTextStreamEngine extends PDFStreamEngine { private static final Log LOG = LogFactory.getLog(PDFTextStreamEngine.class); private int pageRotation; private PDRectangle pageSize; private final GlyphList glyphList; /** * Constructor. */ PDFTextStreamEngine() throws IOException { addOperator(new BeginText()); addOperator(new Concatenate()); addOperator(new DrawObject()); // special text version addOperator(new EndText()); addOperator(new SetGraphicsStateParameters()); addOperator(new Save()); addOperator(new Restore()); addOperator(new NextLine()); addOperator(new SetCharSpacing()); addOperator(new MoveText()); addOperator(new MoveTextSetLeading()); addOperator(new SetFontAndSize()); addOperator(new ShowText()); addOperator(new ShowTextAdjusted()); addOperator(new SetTextLeading()); addOperator(new SetMatrix()); addOperator(new SetTextRenderingMode()); addOperator(new SetTextRise()); addOperator(new SetWordSpacing()); addOperator(new SetTextHorizontalScaling()); addOperator(new ShowTextLine()); addOperator(new ShowTextLineAndSpace()); // load additional glyph list for Unicode mapping String path = "org/apache/pdfbox/resources/glyphlist/additional.txt"; InputStream input = GlyphList.class.getClassLoader().getResourceAsStream(path); glyphList = new GlyphList(GlyphList.getAdobeGlyphList(), input); } /** * This will initialise and process the contents of the stream. * * @param page the page to process * @throws java.io.IOException if there is an error accessing the stream. */ @Override public void processPage(PDPage page) throws IOException { this.pageRotation = page.getRotation(); this.pageSize = page.getCropBox(); super.processPage(page); } /** * This method was originally written by Ben Litchfield for PDFStreamEngine. */ @Override protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException { // // legacy calculations which were previously in PDFStreamEngine // PDGraphicsState state = getGraphicsState(); Matrix ctm = state.getCurrentTransformationMatrix(); float fontSize = state.getTextState().getFontSize(); float horizontalScaling = state.getTextState().getHorizontalScaling() / 100f; Matrix textMatrix = getTextMatrix(); // 1/2 the bbox is used as the height todo: why? float glyphHeight = font.getBoundingBox().getHeight() / 2; // transformPoint from glyph space -> text space float height = font.getFontMatrix().transformPoint(0, glyphHeight).y; // (modified) combined displacement, this is calculated *without* taking the character // spacing and word spacing into account, due to legacy code in TextStripper float tx = displacement.getX() * fontSize * horizontalScaling; float ty = 0; // todo: support vertical writing mode // (modified) combined displacement matrix Matrix td = Matrix.getTranslateInstance(tx, ty); // (modified) text rendering matrix Matrix nextTextRenderingMatrix = td.multiply(textMatrix).multiply(ctm); // text space -> device space float nextX = nextTextRenderingMatrix.getTranslateX(); float nextY = nextTextRenderingMatrix.getTranslateY(); // (modified) width and height calculations float dxDisplay = nextX - textRenderingMatrix.getTranslateX(); float dyDisplay = height * textRenderingMatrix.getScalingFactorY(); // // start of the original method // // Note on variable names. There are three different units being used in this code. // Character sizes are given in glyph units, text locations are initially given in text // units, and we want to save the data in display units. The variable names should end with // Text or Disp to represent if the values are in text or disp units (no glyph units are // saved). float fontSizeText = getGraphicsState().getTextState().getFontSize(); float horizontalScalingText = getGraphicsState().getTextState().getHorizontalScaling()/100f; //Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); float glyphSpaceToTextSpaceFactor = 1 / 1000f; if (font instanceof PDType3Font) { // This will typically be 1000 but in the case of a type3 font // this might be a different number glyphSpaceToTextSpaceFactor = 1f / font.getFontMatrix().getScaleX(); } float spaceWidthText = 0; try { // to avoid crash as described in PDFBOX-614, see what the space displacement should be spaceWidthText = font.getSpaceWidth() * glyphSpaceToTextSpaceFactor; } catch (Throwable exception) { LOG.warn(exception, exception); } if (spaceWidthText == 0) { spaceWidthText = font.getAverageFontWidth() * glyphSpaceToTextSpaceFactor; // the average space width appears to be higher than necessary so make it smaller spaceWidthText *= .80f; } if (spaceWidthText == 0) { spaceWidthText = 1.0f; // if could not find font, use a generic value } // the space width has to be transformed into display units float spaceWidthDisplay = spaceWidthText * fontSizeText * horizontalScalingText * textRenderingMatrix.getScalingFactorX() * ctm.getScalingFactorX(); // use our additional glyph list for Unicode mapping unicode = font.toUnicode(code, glyphList); // when there is no Unicode mapping available, Acrobat simply coerces the character code // into Unicode, so we do the same. Subclasses of PDFStreamEngine don't necessarily want // this, which is why we leave it until this point in PDFTextStreamEngine. if (unicode == null) { if (font instanceof PDSimpleFont) { char c = (char) code; unicode = new String(new char[] { c }); } else { // Acrobat doesn't seem to coerce composite font's character codes, instead it // skips them. See the "allah2.pdf" TestTextStripper file. return; } } processTextPosition(new TextPosition(pageRotation, pageSize.getWidth(), pageSize.getHeight(), textRenderingMatrix, nextX, nextY, dyDisplay, dxDisplay, spaceWidthDisplay, unicode, new int[] { code } , font, fontSize, (int)(fontSize * textRenderingMatrix.getScalingFactorX()))); } /** * A method provided as an event interface to allow a subclass to perform some specific * functionality when text needs to be processed. * * @param text The text to be processed. */ protected void processTextPosition(TextPosition text) { // subclasses can override to provide specific functionality } }
apache-2.0
JaredMiller/Wave
src/org/waveprotocol/wave/model/supplement/ObservablePrimitiveSupplement.java
3341
/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.model.supplement; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.wave.SourcesEvents; /** */ public interface ObservablePrimitiveSupplement extends PrimitiveSupplement, SourcesEvents<ObservablePrimitiveSupplement.Listener> { public interface Listener { /** * Notifies this listener that the last-read version of a blip has changed. */ void onLastReadBlipVersionChanged(WaveletId wid, String bid, int oldVersion, int newVersion); /** * Notifies this listener that the minimum last-read version of all wave * parts has changed. */ void onLastReadWaveletVersionChanged(WaveletId wid, int oldVersion, int newVersion); /** * Notifies this listener that the last-read version of the * participants-collection has changed. */ void onLastReadParticipantsVersionChanged(WaveletId wid, int oldVersion, int newVersion); /** * Notifies this listener that the last-read version of the tags has * changed. */ void onLastReadTagsVersionChanged(WaveletId wid, int oldVersion, int newVersion); /** * Notifies this listener that the followed state has been set to true. */ void onFollowed(); /** * Notifies this listener that the followed state has been set to false. */ void onUnfollowed(); /** * Notifies this listener that the followed state has been cleared. */ void onFollowCleared(); /** * Notifies this listener that last-archived version of a wavelet has * changed. */ void onArchiveVersionChanged(WaveletId wid, int oldVersion, int newVersion); /** * Notifies this listener that archive value has been set. */ // TODO(hearnden/fabio) remove the 'cleared' field from the primitive model void onArchiveClearChanged(boolean oldValue, boolean newValue); /** * Notifies this listener that a folder id has been added. */ void onFolderAdded(int newFolder); /** * Notifies this listener that a folder id has been removed. */ void onFolderRemoved(int oldFolder); /** * Notifies this listener that the wanted-evaluations of a wavelet has * changed. */ void onWantedEvaluationsChanged(WaveletId wid); /** * Notifies this listener that a thread's state has been changed * ThreadState values shall never be null. */ void onThreadStateChanged(WaveletId wid, String tid, ThreadState oldState, ThreadState newState); /** * Notifies this listener that gadget state has been changed. */ void onGadgetStateChanged(String gadgetId, String key, String oldValue, String newValue); } }
apache-2.0
erha19/incubator-weex
android/sdk/src/main/java/com/taobao/weex/dom/WXEvent.java
4905
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.taobao.weex.dom; import android.support.v4.util.ArrayMap; import com.alibaba.fastjson.JSONObject; import com.taobao.weex.dom.binding.ELUtils; import com.taobao.weex.dom.binding.JSONUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Store value of component event */ public class WXEvent extends ArrayList<String> implements Serializable, Cloneable { private static final long serialVersionUID = -8186587029452440107L; /** * event data format * { * type: 'appear', * params: [ * { '@binding': 'index' }, * 'static', * { '@binding': 'item.name' }, * { '@binding': '$event' } * ] * } * */ public static final String EVENT_KEY_TYPE = "type"; public static final String EVENT_KEY_ARGS = "params"; /** * dynamic binding event args, can be null, only weex use * */ private ArrayMap mEventBindingArgs; private ArrayMap<String, List<Object>> mEventBindingArgsValues; @Override public void clear() { if(mEventBindingArgs != null){ mEventBindingArgs.clear(); } if(mEventBindingArgsValues != null){ mEventBindingArgsValues.clear(); } super.clear(); } public boolean remove(String o) { if(mEventBindingArgs != null){ mEventBindingArgs.remove(o); } if(mEventBindingArgsValues != null){ mEventBindingArgsValues.remove(o); } return super.remove(o); } /** * can by null * */ public ArrayMap getEventBindingArgs() { return mEventBindingArgs; } public ArrayMap<String, List<Object>> getEventBindingArgsValues() { return mEventBindingArgsValues; } public void addEvent(Object event) { if(event instanceof CharSequence){ if(JSONUtils.isJSON(event.toString())){ addEvent(JSONUtils.toJSON(event.toString())); return; } String eventName = event.toString(); if(!contains(eventName)){ add(eventName); } }else if(event instanceof JSONObject){ JSONObject bindings = (JSONObject) event; addBindingEvent(bindings); } } public static String getEventName(Object event){ if(event instanceof CharSequence){ return event.toString(); }else if(event instanceof JSONObject){ JSONObject bindings = (JSONObject) event; String eventName = bindings.getString(WXEvent.EVENT_KEY_TYPE); return eventName; } if(event == null){ return null; } return event.toString(); } public void parseStatements() { if(!isEmpty()){ for(int i=0; i<size(); i++){ String event = get(i); if(JSONUtils.isJSON(event)){ JSONObject object = JSONUtils.toJSON(event); String eventName = addBindingEvent(object); set(i, eventName); } } } } private String addBindingEvent(JSONObject bindings){ String eventName = bindings.getString(WXEvent.EVENT_KEY_TYPE); Object args = bindings.get(WXEvent.EVENT_KEY_ARGS); if (eventName != null) { addBindingArgsEvent(eventName, args); } return eventName; } private void addBindingArgsEvent(String eventName, Object args){ if(!contains(eventName)){ add(eventName); } if(args != null){ if(mEventBindingArgs == null){ mEventBindingArgs = new ArrayMap(); } mEventBindingArgs.put(eventName, ELUtils.bindingBlock(args)); } } public void putEventBindingArgsValue(String event, List<Object> value){ if(mEventBindingArgsValues == null){ mEventBindingArgsValues = new ArrayMap(); } if(value == null){ mEventBindingArgsValues.remove(event); }else{ mEventBindingArgsValues.put(event, value); } } @Override public WXEvent clone() { WXEvent event = new WXEvent(); event.addAll(this); if(mEventBindingArgs != null) { event.mEventBindingArgs = new ArrayMap(mEventBindingArgs); } event.mEventBindingArgsValues = null; //this should not be clone, it dynamic args return event; } }
apache-2.0
JackJiang2011/beautyeye
src_all/beautyeye_v3.7_utf8/src/org/jb2011/lnf/beautyeye/winlnfutils/d/BEXPStyle.java
26390
package org.jb2011.lnf.beautyeye.winlnfutils.d; ///* // * @(#)XPStyle.java 1.28 07/01/09 // * // * Copyright 2006 Sun Microsystems, Inc. All rights reserved. // * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. // */ // ///* // * <p>These classes are designed to be used while the // * corresponding <code>LookAndFeel</code> class has been installed // * (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>). // * Using them while a different <code>LookAndFeel</code> is installed // * may produce unexpected results, including exceptions. // * Additionally, changing the <code>LookAndFeel</code> // * maintained by the <code>UIManager</code> without updating the // * corresponding <code>ComponentUI</code> of any // * <code>JComponent</code>s may also produce unexpected results, // * such as the wrong colors showing up, and is generally not // * encouraged. // * // */ // //package org.jb2011.lnf.beautyeye.winlnfutils; // //import java.awt.Color; //import java.awt.Component; //import java.awt.Dimension; //import java.awt.Graphics; //import java.awt.GraphicsConfiguration; //import java.awt.Image; //import java.awt.Insets; //import java.awt.Point; //import java.awt.Rectangle; //import java.awt.Toolkit; //import java.awt.image.BufferedImage; //import java.awt.image.DataBufferInt; //import java.awt.image.WritableRaster; //import java.security.AccessController; //import java.util.HashMap; // //import javax.swing.AbstractButton; //import javax.swing.JButton; //import javax.swing.JCheckBox; //import javax.swing.JRadioButton; //import javax.swing.JToolBar; //import javax.swing.UIManager; //import javax.swing.border.AbstractBorder; //import javax.swing.border.Border; //import javax.swing.border.EmptyBorder; //import javax.swing.border.LineBorder; //import javax.swing.plaf.ColorUIResource; //import javax.swing.plaf.InsetsUIResource; //import javax.swing.plaf.UIResource; //import javax.swing.text.JTextComponent; // //import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.Part; //import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.Prop; //import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.State; //import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.TypeEnum; // //import sun.awt.windows.ThemeReader; //import sun.security.action.GetPropertyAction; //import sun.swing.CachedPainter; // //import com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel; // ///* // * 本类实际就是XP主题包中的类,未作任何改变. // * 代码参考java源码,仅作兼容性修改 // * Add by js 2009-09-01. // */ ///** // * Implements Windows XP Styles for the Windows Look and Feel. // * // * @version 1.28 01/09/07 // * @author Leif Samuelsson // */ //public class BEXPStyle { // // Singleton instance of this class // private static BEXPStyle xp; // // // Singleton instance of SkinPainter // private static SkinPainter skinPainter = new SkinPainter(); // // private static Boolean themeActive = null; // // private HashMap<String, Border> borderMap; // private HashMap<String, Color> colorMap; // // private boolean flatMenus; // // static { // invalidateStyle(); // } // // /** Static method for clearing the hashmap and loading the // * current XP style and theme // */ // static synchronized void invalidateStyle() { // xp = null; // themeActive = null; // } // // /** Get the singleton instance of this class // * // * @return the singleton instance of this class or null if XP styles // * are not active or if this is not Windows XP // */ // public static synchronized BEXPStyle getXP() { // if (themeActive == null) { // Toolkit toolkit = Toolkit.getDefaultToolkit(); // themeActive = // (Boolean)toolkit.getDesktopProperty("win.xpstyle.themeActive"); // if (themeActive == null) { // themeActive = Boolean.FALSE; // } // if (themeActive.booleanValue()) { // GetPropertyAction propertyAction = // new GetPropertyAction("swing.noxp"); // if (AccessController.doPrivileged(propertyAction) == null && // ThemeReader.isThemed() && // !(UIManager.getLookAndFeel() // instanceof WindowsClassicLookAndFeel)) { // // xp = new BEXPStyle(); // } // } // } // return xp; // } // // // // /** Get a named <code>String</code> value from the current style // * // * @param part a <code>Part</code> // * @param state a <code>String</code> // * @param attributeKey a <code>String</code> // * @return a <code>String</code> or null if key is not found // * in the current style // * // * This is currently only used by WindowsInternalFrameTitlePane for painting // * title foregound and can be removed when no longer needed // */ // String getString(Component c, Part part, State state, Prop prop) { // return getTypeEnumName(c, part, state, prop); // } // // private static String getTypeEnumName(Component c, Part part, State state, Prop prop) { // int enumValue = ThemeReader.getEnum(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // if (enumValue == -1) { // return null; // } // return TypeEnum.getTypeEnum(prop, enumValue).getName(); // } // // // // // /** Get a named <code>int</code> value from the current style // * // * @param part a <code>Part</code> // * @return an <code>int</code> or null if key is not found // * in the current style // */ // int getInt(Component c, Part part, State state, Prop prop, int fallback) { // return ThemeReader.getInt(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // } // // /** Get a named <code>Dimension</code> value from the current style // * // * @param key a <code>String</code> // * @return a <code>Dimension</code> or null if key is not found // * in the current style // * // * This is currently only used by WindowsProgressBarUI and the value // * should probably be cached there instead of here. // */ // Dimension getDimension(Component c, Part part, State state, Prop prop) { // return ThemeReader.getPosition(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // } // // /** Get a named <code>Point</code> (e.g. a location or an offset) value // * from the current style // * // * @param key a <code>String</code> // * @return a <code>Point</code> or null if key is not found // * in the current style // * // * This is currently only used by WindowsInternalFrameTitlePane for painting // * title foregound and can be removed when no longer needed // */ // Point getPoint(Component c, Part part, State state, Prop prop) { // Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // if (d != null) { // return new Point(d.width, d.height); // } else { // return null; // } // } // // /** Get a named <code>Insets</code> value from the current style // * // * @param key a <code>String</code> // * @return an <code>Insets</code> object or null if key is not found // * in the current style // * // * This is currently only used to create borders and by // * WindowsInternalFrameTitlePane for painting title foregound. // * The return value is already cached in those places. // */ // Insets getMargin(Component c, Part part, State state, Prop prop) { // return ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // } // // // /** Get a named <code>Color</code> value from the current style // * // * @param part a <code>Part</code> // * @return a <code>Color</code> or null if key is not found // * in the current style // */ // synchronized Color getColor(Skin skin, Prop prop, Color fallback) { // String key = skin.toString() + "." + prop.name(); // Part part = skin.part; // Color color = colorMap.get(key); // if (color == null) { // color = ThemeReader.getColor(part.getControlName(null), part.getValue(), // State.getValue(part, skin.state), // prop.getValue()); // if (color != null) { // color = new ColorUIResource(color); // colorMap.put(key, color); // } // } // return (color != null) ? color : fallback; // } // // public Color getColor(Component c, Part part, State state, Prop prop, Color fallback) { // return getColor(new Skin(c, part, state), prop, fallback); // } // // // // /** Get a named <code>Border</code> value from the current style // * // * @param part a <code>Part</code> // * @return a <code>Border</code> or null if key is not found // * in the current style or if the style for the particular // * part is not defined as "borderfill". // */ // public synchronized Border getBorder(Component c, Part part) { // if (part == Part.MENU) { // // Special case because XP has no skin for menus // if (flatMenus) { // // TODO: The classic border uses this color, but we should // // create a new UI property called "PopupMenu.borderColor" // // instead. // return new XPFillBorder(UIManager.getColor("InternalFrame.borderShadow"), // 1); // } else { // return null; // Will cause L&F to use classic border // } // } // Skin skin = new Skin(c, part, null); // Border border = borderMap.get(skin.string); // if (border == null) { // String bgType = getTypeEnumName(c, part, null, Prop.BGTYPE); // if ("borderfill".equalsIgnoreCase(bgType)) { // int thickness = getInt(c, part, null, Prop.BORDERSIZE, 1); // Color color = getColor(skin, Prop.BORDERCOLOR, Color.black); // border = new XPFillBorder(color, thickness); // } else if ("imagefile".equalsIgnoreCase(bgType)) { // Insets m = getMargin(c, part, null, Prop.SIZINGMARGINS); // if (m != null) { // if (getBoolean(c, part, null, Prop.BORDERONLY)) { // border = new XPImageBorder(c, part); // } else { // if(part == Part.TP_BUTTON) { // border = new XPEmptyBorder(new Insets(3,3,3,3)); // } else { // border = new XPEmptyBorder(m); // } // } // } // } // if (border != null) { // borderMap.put(skin.string, border); // } // } // return border; // } // // private class XPFillBorder extends LineBorder implements UIResource { // XPFillBorder(Color color, int thickness) { // super(color, thickness); // } // // public Insets getBorderInsets(Component c) { // return getBorderInsets(c, new Insets(0,0,0,0)); // } // // public Insets getBorderInsets(Component c, Insets insets) { // Insets margin = null; // // // // Ideally we'd have an interface defined for classes which // // support margins (to avoid this hackery), but we've // // decided against it for simplicity // // // if (c instanceof AbstractButton) { // margin = ((AbstractButton)c).getMargin(); // } else if (c instanceof JToolBar) { // margin = ((JToolBar)c).getMargin(); // } else if (c instanceof JTextComponent) { // margin = ((JTextComponent)c).getMargin(); // } // insets.top = (margin != null? margin.top : 0) + thickness; // insets.left = (margin != null? margin.left : 0) + thickness; // insets.bottom = (margin != null? margin.bottom : 0) + thickness; // insets.right = (margin != null? margin.right : 0) + thickness; // // return insets; // } // } // // private class XPImageBorder extends AbstractBorder implements UIResource { // Skin skin; // // XPImageBorder(Component c, Part part) { // this.skin = getSkin(c, part); // } // // public void paintBorder(Component c, Graphics g, // int x, int y, int width, int height) { // skin.paintSkin(g, x, y, width, height, null); // } // // public Insets getBorderInsets(Component c) { // return getBorderInsets(c, new Insets(0,0,0,0)); // } // // public Insets getBorderInsets(Component c, Insets insets) { // Insets margin = null; // Insets borderInsets = skin.getContentMargin(); // // // // Ideally we'd have an interface defined for classes which // // support margins (to avoid this hackery), but we've // // decided against it for simplicity // // // if (c instanceof AbstractButton) { // margin = ((AbstractButton)c).getMargin(); // } else if (c instanceof JToolBar) { // margin = ((JToolBar)c).getMargin(); // } else if (c instanceof JTextComponent) { // margin = ((JTextComponent)c).getMargin(); // } // insets.top = (margin != null? margin.top : 0) + borderInsets.top; // insets.left = (margin != null? margin.left : 0) + borderInsets.left; // insets.bottom = (margin != null? margin.bottom : 0) + borderInsets.bottom; // insets.right = (margin != null? margin.right : 0) + borderInsets.right; // // return insets; // } // } // // private class XPEmptyBorder extends EmptyBorder implements UIResource { // XPEmptyBorder(Insets m) { // super(m.top+2, m.left+2, m.bottom+2, m.right+2); // } // // public Insets getBorderInsets(Component c) { // return getBorderInsets(c, getBorderInsets()); // } // // public Insets getBorderInsets(Component c, Insets insets) { // insets = super.getBorderInsets(c, insets); // // Insets margin = null; // if (c instanceof AbstractButton) { // Insets m = ((AbstractButton)c).getMargin(); // // if this is a toolbar button then ignore getMargin() // // and subtract the padding added by the constructor // if(c.getParent() instanceof JToolBar // && ! (c instanceof JRadioButton) // && ! (c instanceof JCheckBox) // && m instanceof InsetsUIResource) { // insets.top -= 2; // insets.left -= 2; // insets.bottom -= 2; // insets.right -= 2; // } else { // margin = m; // } // } else if (c instanceof JToolBar) { // margin = ((JToolBar)c).getMargin(); // } else if (c instanceof JTextComponent) { // margin = ((JTextComponent)c).getMargin(); // } // if (margin != null) { // insets.top = margin.top + 2; // insets.left = margin.left + 2; // insets.bottom = margin.bottom + 2; // insets.right = margin.right + 2; // } // return insets; // } // } // // public boolean isSkinDefined(Component c, Part part) { // return (part.getValue() == 0) // || ThemeReader.isThemePartDefined( // part.getControlName(c), part.getValue(), 0); // } // // /** Get a <code>Skin</code> object from the current style // * for a named part (component type) // * // * @param part a <code>Part</code> // * @return a <code>Skin</code> object // */ // public synchronized Skin getSkin(Component c, Part part) { // assert isSkinDefined(c, part) : "part " + part + " is not defined"; // return new Skin(c, part, null); // } // // // // // /** A class which encapsulates attributes for a given part // * (component type) and which provides methods for painting backgrounds // * and glyphs // */ // public static class Skin { // final Component component; // final Part part; // final State state; // // private final String string; // private Dimension size = null; // // Skin(Component component, Part part) { // this(component, part, null); // } // // Skin(Part part, State state) { // this(null, part, state); // } // // Skin(Component component, Part part, State state) { // this.component = component; // this.part = part; // this.state = state; // // String str = part.getControlName(component) +"." + part.name(); // if (state != null) { // str += "("+state.name()+")"; // } // string = str; // } // // public Insets getContentMargin() { // // This is only called by WindowsTableHeaderUI so far. // return ThemeReader.getThemeMargins(part.getControlName(null), part.getValue(), // 0, Prop.SIZINGMARGINS.getValue()); // } // // private int getWidth(State state) { // if (size == null) { // size = getPartSize(part, state); // } // return size.width; // } // // public int getWidth() { // return getWidth((state != null) ? state : State.NORMAL); // } // // private int getHeight(State state) { // if (size == null) { // size = getPartSize(part, state); // } // return size.height; // } // // public int getHeight() { // return getHeight((state != null) ? state : State.NORMAL); // } // // public String toString() { // return string; // } // // public boolean equals(Object obj) { // return (obj instanceof Skin && ((Skin)obj).string.equals(string)); // } // // public int hashCode() { // return string.hashCode(); // } // // /** Paint a skin at x, y. // * // * @param g the graphics context to use for painting // * @param dx the destination <i>x</i> coordinate. // * @param dy the destination <i>y</i> coordinate. // * @param state which state to paint // */ // public void paintSkin(Graphics g, int dx, int dy, State state) { // if (state == null) { // state = this.state; // } // paintSkin(g, dx, dy, getWidth(state), getHeight(state), state); // } // // /** Paint a skin in an area defined by a rectangle. // * // * @param g the graphics context to use for painting // * @param r a <code>Rectangle</code> defining the area to fill, // * may cause the image to be stretched or tiled // * @param state which state to paint // */ // void paintSkin(Graphics g, Rectangle r, State state) { // paintSkin(g, r.x, r.y, r.width, r.height, state); // } // // /** Paint a skin at a defined position and size // * // * @param g the graphics context to use for painting // * @param dx the destination <i>x</i> coordinate. // * @param dy the destination <i>y</i> coordinate. // * @param dw the width of the area to fill, may cause // * the image to be stretched or tiled // * @param dh the height of the area to fill, may cause // * the image to be stretched or tiled // * @param state which state to paint // */ // public void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state) { // skinPainter.paint(null, g, dx, dy, dw, dh, this, state); // } // /** // * Paint a skin at a defined position and size // * // * @param g the graphics context to use for painting // * @param dx the destination <i>x</i> coordinate // * @param dy the destination <i>y</i> coordinate // * @param dw the width of the area to fill, may cause // * the image to be stretched or tiled // * @param dh the height of the area to fill, may cause // * the image to be stretched or tiled // * @param state which state to paint // * @param borderFill should test if the component uses a border fill // * and skip painting if it is // */ // void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state, // boolean borderFill) { // if(borderFill && "borderfill".equals(getTypeEnumName(component, part, // state, Prop.BGTYPE))) { // return; // } // skinPainter.paint(null, g, dx, dy, dw, dh, this, state); // } // } // // private static class SkinPainter extends CachedPainter { // SkinPainter() { // super(30); // flush(); // } // // protected void paintToImage(Component c, Image image, Graphics g, // int w, int h, Object[] args) { // Skin skin = (Skin)args[0]; // Part part = skin.part; // State state = (State)args[1]; // if (state == null) { // state = skin.state; // } // if (c == null) { // c = skin.component; // } // WritableRaster raster = ((BufferedImage)image).getRaster(); // DataBufferInt buffer = (DataBufferInt)raster.getDataBuffer(); // ThemeReader.paintBackground(buffer.getData(), // part.getControlName(c), part.getValue(), // State.getValue(part, state), // 0, 0, w, h, w); // } // // protected Image createImage(Component c, int w, int h, // GraphicsConfiguration config, Object[] args) { // return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); // } // } // // static class GlyphButton extends JButton { // private Skin skin; // // public GlyphButton(Component parent, Part part) { // BEXPStyle xp = getXP(); // skin = xp.getSkin(parent, part); // setBorder(null); // setContentAreaFilled(false); // } // // public boolean isFocusTraversable() { // return false; // } // // protected State getState() { // State state = State.NORMAL; // if (!isEnabled()) { // state = State.DISABLED; // } else if (getModel().isPressed()) { // state = State.PRESSED; // } else if (getModel().isRollover()) { // state = State.HOT; // } // return state; // } // // public void paintComponent(Graphics g) { // Dimension d = getSize(); // skin.paintSkin(g, 0, 0, d.width, d.height, getState()); // } // // public void setPart(Component parent, Part part) { // BEXPStyle xp = getXP(); // skin = xp.getSkin(parent, part); // revalidate(); // repaint(); // } // // protected void paintBorder(Graphics g) { // } // // public Dimension getPreferredSize() { // return new Dimension(16, 16); // } // // public Dimension getMinimumSize() { // return new Dimension(5, 5); // } // // public Dimension getMaximumSize() { // return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); // } // } // // // Private constructor // private BEXPStyle() { // flatMenus = getSysBoolean(Prop.FLATMENUS); // // colorMap = new HashMap<String, Color>(); // borderMap = new HashMap<String, Border>(); // // Note: All further access to the maps must be synchronized // } // // // private boolean getBoolean(Component c, Part part, State state, Prop prop) { // return ThemeReader.getBoolean(part.getControlName(c), part.getValue(), // State.getValue(part, state), // prop.getValue()); // } // // private static Dimension getPartSize(Part part, State state) { // return ThemeReader.getPartSize(part.getControlName(null), part.getValue(), // State.getValue(part, state)); // } // // private static boolean getSysBoolean(Prop prop) { // // We can use any widget name here, I guess. // return ThemeReader.getSysBoolean("window", prop.getValue()); // } //}
apache-2.0
charliemblack/geode
geode-core/src/main/java/org/apache/geode/redis/internal/executor/transactions/ExecExecutor.java
2868
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.redis.internal.executor.transactions; import io.netty.buffer.ByteBuf; import java.util.Queue; import org.apache.geode.cache.CacheTransactionManager; import org.apache.geode.cache.CommitConflictException; import org.apache.geode.cache.TransactionId; import org.apache.geode.redis.internal.Coder; import org.apache.geode.redis.internal.Command; import org.apache.geode.redis.internal.ExecutionHandlerContext; import org.apache.geode.redis.internal.RedisConstants; public class ExecExecutor extends TransactionExecutor { @Override public void executeCommand(Command command, ExecutionHandlerContext context) { CacheTransactionManager txm = context.getCacheTransactionManager(); if (!context.hasTransaction()) { command.setResponse(Coder.getNilResponse(context.getByteBufAllocator())); return; } TransactionId transactionId = context.getTransactionID(); txm.resume(transactionId); boolean hasError = hasError(context.getTransactionQueue()); if (hasError) txm.rollback(); else { try { txm.commit(); } catch (CommitConflictException e) { command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), RedisConstants.ERROR_COMMIT_CONFLICT)); context.clearTransaction(); return; } } ByteBuf response = constructResponseExec(context); command.setResponse(response); context.clearTransaction(); } private ByteBuf constructResponseExec(ExecutionHandlerContext context) { Queue<Command> cQ = context.getTransactionQueue(); ByteBuf response = context.getByteBufAllocator().buffer(); response.writeByte(Coder.ARRAY_ID); response.writeBytes(Coder.intToBytes(cQ.size())); response.writeBytes(Coder.CRLFar); for (Command c : cQ) { ByteBuf r = c.getResponse(); response.writeBytes(r); } return response; } private boolean hasError(Queue<Command> queue) { for (Command c : queue) { if (c.hasError()) return true; } return false; } }
apache-2.0
gburd/wave
test/org/waveprotocol/wave/model/waveref/WaveRefTest.java
3152
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.model.waveref; import junit.framework.TestCase; import org.waveprotocol.wave.model.id.WaveId; import org.waveprotocol.wave.model.id.WaveletId; /** * Unit tests for {@link WaveRef} * * @author meade@google.com <Edwina Mead> */ public class WaveRefTest extends TestCase { public void testBasicEquals() { WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234abcd")); WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234abcd")); WaveRef different = WaveRef.of(WaveId.of("test.com", "w+1234abcd")); assertFalse(first.equals(null)); assertTrue(first.equals(first)); assertTrue(first.equals(second)); assertFalse(first.equals(different)); } public void testEqualsWithSameWaveIdDifferentOtherFields() { WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234abcd")); WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234abcd"), WaveletId.of("example.com", "conv+root")); WaveRef third = WaveRef.of(WaveId.of("example.com", "w+1234abcd"), WaveletId.of("example.com", "conv+root"), "b+12345"); assertTrue(second.equals(second)); assertTrue(third.equals(third)); assertFalse(first.equals(second)); assertFalse(first.equals(third)); assertFalse(second.equals(third)); } public void testEqualsWithDifferentWaveIdSameOtherFields() { WaveRef first = WaveRef.of(WaveId.of("test.com", "w+1234"), WaveletId.of("example.com", "conv+root"), "b+12345"); WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234"), WaveletId.of("example.com", "conv+root"), "b+12345"); assertFalse(first.equals(second)); } public void testHashCode() { WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234")); WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234"), WaveletId.of("example.com", "conv+root")); WaveRef third = WaveRef.of(WaveId.of("example.com", "w+1234"), WaveletId.of("example.com", "conv+root"), "b+12345"); WaveRef sameAsFirst = WaveRef.of(WaveId.of("example.com", "w+1234")); WaveRef sameAsThird = WaveRef.of(WaveId.of("example.com", "w+1234"), WaveletId.of("example.com", "conv+root"), "b+12345"); assertEquals(first.hashCode(), sameAsFirst.hashCode()); assertEquals(third.hashCode(), sameAsThird.hashCode()); assertFalse(first.hashCode() == second.hashCode()); assertFalse(first.hashCode() == third.hashCode()); assertFalse(second.hashCode() == third.hashCode()); } }
apache-2.0
apache/incubator-trafodion
wms/src/main/java/org/trafodion/wms/rest/ResourceConfig.java
1068
/** * @@@ START COPYRIGHT @@@ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * @@@ END COPYRIGHT @@@ **/ package org.trafodion.wms.rest; import com.sun.jersey.api.core.PackagesResourceConfig; public class ResourceConfig extends PackagesResourceConfig { public ResourceConfig() { super("org.trafodion.wms.rest"); } }
apache-2.0
niv0/isis
core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/appfeat/ApplicationFeature.java
10327
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.metamodel.services.appfeat; import java.util.SortedSet; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.apache.isis.applib.IsisApplibModule; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.services.appfeat.ApplicationFeatureRepository; import org.apache.isis.applib.services.appfeat.ApplicationMemberType; import org.apache.isis.applib.util.ObjectContracts; /** * Canonical application feature, identified by {@link ApplicationFeatureId}, * and wired together with other application features and cached by {@link ApplicationFeatureRepository}. * * <p> * Note that this is NOT a view model; instead it can be converted to a string using methods of * {@link ApplicationFeatureRepository}, eg {@link ApplicationFeatureRepository#classNamesContainedIn(String, ApplicationMemberType)}. * </p> */ public class ApplicationFeature implements Comparable<ApplicationFeature> { public static abstract class PropertyDomainEvent<T> extends IsisApplibModule.PropertyDomainEvent<ApplicationFeature, T> {} public static abstract class CollectionDomainEvent<T> extends IsisApplibModule.CollectionDomainEvent<ApplicationFeature, T> {} public static abstract class ActionDomainEvent extends IsisApplibModule.ActionDomainEvent<ApplicationFeature> {} //region > constants // using same value for all to neaten up rendering public static final int TYPICAL_LENGTH_PKG_FQN = 50; public static final int TYPICAL_LENGTH_CLS_NAME = 50; public static final int TYPICAL_LENGTH_MEMBER_NAME = 50; //endregion //region > constructors public ApplicationFeature() { this(null); } public ApplicationFeature(final ApplicationFeatureId featureId) { setFeatureId(featureId); } //endregion //region > featureId private ApplicationFeatureId featureId; @Programmatic public ApplicationFeatureId getFeatureId() { return featureId; } public void setFeatureId(final ApplicationFeatureId applicationFeatureId) { this.featureId = applicationFeatureId; } //endregion //region > memberType private ApplicationMemberType memberType; /** * Only for {@link ApplicationFeatureType#MEMBER member}s. */ @Programmatic public ApplicationMemberType getMemberType() { return memberType; } public void setMemberType(final ApplicationMemberType memberType) { this.memberType = memberType; } //endregion //region > returnTypeName (for: properties, collections, actions) private String returnTypeName; /** * Only for {@link ApplicationMemberType#ACTION action}s. */ @Programmatic public String getReturnTypeName() { return returnTypeName; } public void setReturnTypeName(final String returnTypeName) { this.returnTypeName = returnTypeName; } //endregion //region > contributed (for: properties, collections, actions) private boolean contributed; @Programmatic public boolean isContributed() { return contributed; } public void setContributed(final boolean contributed) { this.contributed = contributed; } //endregion //region > derived (properties and collections) private Boolean derived; /** * Only for {@link ApplicationMemberType#PROPERTY} and {@link ApplicationMemberType#COLLECTION} */ @Programmatic public Boolean isDerived() { return derived; } public void setDerived(final Boolean derived) { this.derived = derived; } //endregion //region > propertyMaxLength (properties only) private Integer propertyMaxLength; /** * Only for {@link ApplicationMemberType#ACTION action}s. */ @Programmatic public Integer getPropertyMaxLength() { return propertyMaxLength; } public void setPropertyMaxLength(final Integer propertyMaxLength) { this.propertyMaxLength = propertyMaxLength; } //endregion //region > propertyTypicalLength (properties only) private Integer propertyTypicalLength; /** * Only for {@link ApplicationMemberType#ACTION action}s. */ @Programmatic public Integer getPropertyTypicalLength() { return propertyTypicalLength; } public void setPropertyTypicalLength(final Integer propertyTypicalLength) { this.propertyTypicalLength = propertyTypicalLength; } //endregion //region > actionSemantics (actions only) private SemanticsOf actionSemantics; /** * Only for {@link ApplicationMemberType#ACTION action}s. */ @Programmatic public SemanticsOf getActionSemantics() { return actionSemantics; } public void setActionSemantics(final SemanticsOf actionSemantics) { this.actionSemantics = actionSemantics; } //endregion //region > packages: Contents private final SortedSet<ApplicationFeatureId> contents = Sets.newTreeSet(); @Programmatic public SortedSet<ApplicationFeatureId> getContents() { ApplicationFeatureType.ensurePackage(this.getFeatureId()); return contents; } @Programmatic public void addToContents(final ApplicationFeatureId contentId) { ApplicationFeatureType.ensurePackage(this.getFeatureId()); ApplicationFeatureType.ensurePackageOrClass(contentId); this.contents.add(contentId); } //endregion //region > classes: Properties, Collections, Actions private final SortedSet<ApplicationFeatureId> properties = Sets.newTreeSet(); @Programmatic public SortedSet<ApplicationFeatureId> getProperties() { ApplicationFeatureType.ensureClass(this.getFeatureId()); return properties; } private final SortedSet<ApplicationFeatureId> collections = Sets.newTreeSet(); @Programmatic public SortedSet<ApplicationFeatureId> getCollections() { ApplicationFeatureType.ensureClass(this.getFeatureId()); return collections; } private final SortedSet<ApplicationFeatureId> actions = Sets.newTreeSet(); @Programmatic public SortedSet<ApplicationFeatureId> getActions() { ApplicationFeatureType.ensureClass(this.getFeatureId()); return actions; } @Programmatic public void addToMembers(final ApplicationFeatureId memberId, final ApplicationMemberType memberType) { ApplicationFeatureType.ensureClass(this.getFeatureId()); ApplicationFeatureType.ensureMember(memberId); membersOf(memberType).add(memberId); } @Programmatic public SortedSet<ApplicationFeatureId> membersOf(final ApplicationMemberType memberType) { ApplicationFeatureType.ensureClass(this.getFeatureId()); switch (memberType) { case PROPERTY: return properties; case COLLECTION: return collections; default: // case ACTION: return actions; } } //endregion //region > Functions public static class Functions { private Functions(){} public static final Function<? super ApplicationFeature, ? extends String> GET_FQN = new Function<ApplicationFeature, String>() { @Override public String apply(final ApplicationFeature input) { return input.getFeatureId().getFullyQualifiedName(); } }; public static final Function<ApplicationFeature, ApplicationFeatureId> GET_ID = new Function<ApplicationFeature, ApplicationFeatureId>() { @Override public ApplicationFeatureId apply(final ApplicationFeature input) { return input.getFeatureId(); } }; } public static class Predicates { private Predicates(){} public static Predicate<ApplicationFeature> packageContainingClasses( final ApplicationMemberType memberType, final ApplicationFeatureRepositoryDefault applicationFeatures) { return new Predicate<ApplicationFeature>() { @Override public boolean apply(final ApplicationFeature input) { // all the classes in this package final Iterable<ApplicationFeatureId> classIds = Iterables.filter(input.getContents(), ApplicationFeatureId.Predicates.isClassContaining(memberType, applicationFeatures)); return classIds.iterator().hasNext(); } }; } } //endregion //region > equals, hashCode, compareTo, toString private final static String propertyNames = "featureId"; @Override public int compareTo(final ApplicationFeature other) { return ObjectContracts.compare(this, other, propertyNames); } @Override public boolean equals(final Object obj) { return ObjectContracts.equals(this, obj, propertyNames); } @Override public int hashCode() { return ObjectContracts.hashCode(this, propertyNames); } @Override public String toString() { return ObjectContracts.toString(this, propertyNames); } //endregion }
apache-2.0
niv0/isis
core/metamodel/src/main/java/org/apache/isis/core/runtime/authentication/standard/AuthenticationManagerStandardInstallerAbstract.java
2324
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.runtime.authentication.standard; import java.util.List; import org.apache.isis.core.commons.components.InstallerAbstract; import org.apache.isis.core.commons.config.IsisConfiguration; import org.apache.isis.core.runtime.authentication.AuthenticationManager; import org.apache.isis.core.runtime.authentication.AuthenticationManagerInstaller; public abstract class AuthenticationManagerStandardInstallerAbstract extends InstallerAbstract implements AuthenticationManagerInstaller { public AuthenticationManagerStandardInstallerAbstract( final String name, final IsisConfiguration isisConfiguration) { super(name, isisConfiguration); } @Override public final AuthenticationManager createAuthenticationManager() { final AuthenticationManagerStandard authenticationManager = createAuthenticationManagerStandard(); for (final Authenticator authenticator : createAuthenticators()) { authenticationManager.addAuthenticator(authenticator); } return authenticationManager; } protected AuthenticationManagerStandard createAuthenticationManagerStandard() { return new AuthenticationManagerStandard(getConfiguration()); } /** * Hook method * * @return */ protected abstract List<Authenticator> createAuthenticators(); @Override public List<Class<?>> getTypes() { return listOf(AuthenticationManager.class); } }
apache-2.0
Ant-Droid/android_frameworks_base_OLD
packages/SystemUI/src/com/android/systemui/volume/IconPulser.java
1800
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.volume; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.view.View; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; public class IconPulser { private static final float PULSE_SCALE = 1.1f; private final Interpolator mFastOutSlowInInterpolator; public IconPulser(Context context) { mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context, android.R.interpolator.fast_out_slow_in); } public void start(final View target) { if (target == null || target.getScaleX() != 1) return; // n/a, or already running target.animate().cancel(); target.animate().scaleX(PULSE_SCALE).scaleY(PULSE_SCALE) .setInterpolator(mFastOutSlowInInterpolator) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { target.animate().scaleX(1).scaleY(1).setListener(null); } }); } }
apache-2.0
guozhangwang/kafka
clients/src/main/java/org/apache/kafka/clients/RequestCompletionHandler.java
1168
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients; /** * A callback interface for attaching an action to be executed when a request is complete and the corresponding response * has been received. This handler will also be invoked if there is a disconnection while handling the request. */ public interface RequestCompletionHandler { void onComplete(ClientResponse response); }
apache-2.0
pivotal-amurmann/geode
geode-core/src/main/java/org/apache/geode/cache/query/internal/parse/ASTTypeCast.java
1274
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.query.internal.parse; import antlr.*; import org.apache.geode.cache.query.internal.QCompiler; public class ASTTypeCast extends GemFireAST { private static final long serialVersionUID = -6368577668325776355L; public ASTTypeCast() {} public ASTTypeCast(Token t) { super(t); } @Override public void compile(QCompiler compiler) { super.compile(compiler); // there's a type on the stack now compiler.typecast(); } }
apache-2.0
jswrenn/xtreemfs
java/servers/test/org/xtreemfs/test/osd/rwre/FixWrongMasterEpochDirectoryTest.java
2315
/* * Copyright (c) 2013 Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.test.osd.rwre; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.xtreemfs.osd.storage.HashStorageLayout; import org.xtreemfs.osd.storage.MetadataCache; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestHelper; public class FixWrongMasterEpochDirectoryTest { @Rule public final TestRule testLog = TestHelper.testLog; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } @Test public void testAutomaticMoveToCorrectDirectory() throws IOException { final String globalFileId = "f32b0854-91eb-44d8-adf8-65bb8baf5f60:13193"; final String correctedFileId = globalFileId; final String brokenFileId = "/" + correctedFileId; final HashStorageLayout hsl = new HashStorageLayout(SetupUtils.createOSD1Config(), new MetadataCache()); // Cleanup previous runs. hsl.deleteFile(brokenFileId, true); hsl.deleteFile(correctedFileId, true); final File brokenFileDir = new File(hsl.generateAbsoluteFilePath(brokenFileId)); final File correctedFileDir = new File(hsl.generateAbsoluteFilePath(correctedFileId)); // Set masterepoch using the wrong id. assertFalse(brokenFileDir.isDirectory()); assertFalse(correctedFileDir.isDirectory()); hsl.setMasterEpoch(brokenFileId, 1); assertTrue(brokenFileDir.isDirectory()); // Get the masterepoch with the correct id. assertEquals(1, hsl.getMasterEpoch(correctedFileId)); assertFalse(brokenFileDir.isDirectory()); assertTrue(correctedFileDir.isDirectory()); // Get the masterepoch of a file which does not exist. assertEquals(0, hsl.getMasterEpoch("fileIdDoesNotExist")); } }
bsd-3-clause
Arcnor/micromod
ibxm/src/main/java/ibxm/Data.java
4767
package ibxm; /* A data array dynamically loaded from an InputStream. */ public class Data { private int bufLen; private byte[] buffer; private java.io.InputStream stream; public Data( java.io.InputStream inputStream ) throws java.io.IOException { bufLen = 1 << 16; buffer = new byte[ bufLen ]; stream = inputStream; readFully( stream, buffer, 0, bufLen ); } public Data( byte[] data ) { bufLen = data.length; buffer = data; } public byte sByte( int offset ) throws java.io.IOException { load( offset, 1 ); return buffer[ offset ]; } public int uByte( int offset ) throws java.io.IOException { load( offset, 1 ); return buffer[ offset ] & 0xFF; } public int ubeShort( int offset ) throws java.io.IOException { load( offset, 2 ); return ( ( buffer[ offset ] & 0xFF ) << 8 ) | ( buffer[ offset + 1 ] & 0xFF ); } public int uleShort( int offset ) throws java.io.IOException { load( offset, 2 ); return ( buffer[ offset ] & 0xFF ) | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 ); } public int uleInt( int offset ) throws java.io.IOException { load( offset, 4 ); int value = buffer[ offset ] & 0xFF; value = value | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 ); value = value | ( ( buffer[ offset + 2 ] & 0xFF ) << 16 ); value = value | ( ( buffer[ offset + 3 ] & 0x7F ) << 24 ); return value; } public String strLatin1( int offset, int length ) throws java.io.IOException { load( offset, length ); char[] str = new char[ length ]; for( int idx = 0; idx < length; idx++ ) { int chr = buffer[ offset + idx ] & 0xFF; str[ idx ] = chr < 32 ? 32 : ( char ) chr; } return new String( str ); } public String strCp850( int offset, int length ) throws java.io.IOException { load( offset, length ); try { char[] str = new String( buffer, offset, length, "Cp850" ).toCharArray(); for( int idx = 0; idx < str.length; idx++ ) { str[ idx ] = str[ idx ] < 32 ? 32 : str[ idx ]; } return new String( str ); } catch( java.io.UnsupportedEncodingException e ) { return strLatin1( offset, length ); } } public short[] samS8( int offset, int length ) throws java.io.IOException { load( offset, length ); short[] sampleData = new short[ length ]; for( int idx = 0; idx < length; idx++ ) { sampleData[ idx ] = ( short ) ( buffer[ offset + idx ] << 8 ); } return sampleData; } public short[] samS8D( int offset, int length ) throws java.io.IOException { load( offset, length ); short[] sampleData = new short[ length ]; int sam = 0; for( int idx = 0; idx < length; idx++ ) { sam += buffer[ offset + idx ]; sampleData[ idx ] = ( short ) ( sam << 8 ); } return sampleData; } public short[] samU8( int offset, int length ) throws java.io.IOException { load( offset, length ); short[] sampleData = new short[ length ]; for( int idx = 0; idx < length; idx++ ) { sampleData[ idx ] = ( short ) ( ( ( buffer[ offset + idx ] & 0xFF ) - 128 ) << 8 ); } return sampleData; } public short[] samS16( int offset, int samples ) throws java.io.IOException { load( offset, samples * 2 ); short[] sampleData = new short[ samples ]; for( int idx = 0; idx < samples; idx++ ) { sampleData[ idx ] = ( short ) ( ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 ) ); } return sampleData; } public short[] samS16D( int offset, int samples ) throws java.io.IOException { load( offset, samples * 2 ); short[] sampleData = new short[ samples ]; int sam = 0; for( int idx = 0; idx < samples; idx++ ) { sam += ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 ); sampleData[ idx ] = ( short ) sam; } return sampleData; } public short[] samU16( int offset, int samples ) throws java.io.IOException { load( offset, samples * 2 ); short[] sampleData = new short[ samples ]; for( int idx = 0; idx < samples; idx++ ) { int sam = ( buffer[ offset + idx * 2 ] & 0xFF ) | ( ( buffer[ offset + idx * 2 + 1 ] & 0xFF ) << 8 ); sampleData[ idx ] = ( short ) ( sam - 32768 ); } return sampleData; } private void load( int offset, int length ) throws java.io.IOException { while( offset + length > bufLen ) { int newBufLen = bufLen << 1; byte[] newBuf = new byte[ newBufLen ]; System.arraycopy( buffer, 0, newBuf, 0, bufLen ); if( stream != null ) { readFully( stream, newBuf, bufLen, newBufLen - bufLen ); } bufLen = newBufLen; buffer = newBuf; } } private static void readFully( java.io.InputStream inputStream, byte[] buffer, int offset, int length ) throws java.io.IOException { int read = 1, end = offset + length; while( read > 0 ) { read = inputStream.read( buffer, offset, end - offset ); offset += read; } } }
bsd-3-clause
Crossy147/java-design-patterns
factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java
1281
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; public class Bow implements Weapon { @Override public String toString() { return "Bow"; } }
mit
timmolter/XChange
xchange-ripple/src/test/java/org/knowm/xchange/ripple/RippleAdaptersTest.java
24065
package org.knowm.xchange.ripple; import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.ParseException; import org.junit.Test; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.Wallet; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.ripple.dto.account.ITransferFeeSource; import org.knowm.xchange.ripple.dto.account.RippleAccountBalances; import org.knowm.xchange.ripple.dto.account.RippleAccountSettings; import org.knowm.xchange.ripple.dto.marketdata.RippleOrderBook; import org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction; import org.knowm.xchange.ripple.dto.trade.RippleAccountOrders; import org.knowm.xchange.ripple.dto.trade.RippleLimitOrder; import org.knowm.xchange.ripple.dto.trade.RippleOrderTransaction; import org.knowm.xchange.ripple.dto.trade.RipplePaymentTransaction; import org.knowm.xchange.ripple.dto.trade.RippleUserTrade; import org.knowm.xchange.ripple.service.params.RippleMarketDataParams; import org.knowm.xchange.ripple.service.params.RippleTradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParams; public class RippleAdaptersTest implements ITransferFeeSource { @Test public void adaptAccountInfoTest() throws IOException { // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/account/example-account-balances.json"); // Use Jackson to parse it final ObjectMapper mapper = new ObjectMapper(); final RippleAccountBalances rippleAccount = mapper.readValue(is, RippleAccountBalances.class); // Convert to xchange object and check field values final AccountInfo account = RippleAdapters.adaptAccountInfo(rippleAccount, "username"); assertThat(account.getWallets()).hasSize(2); assertThat(account.getUsername()).isEqualTo("username"); assertThat(account.getTradingFee()).isEqualTo(BigDecimal.ZERO); final Wallet counterWallet = account.getWallet("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(counterWallet.getId()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(counterWallet.getBalances()).hasSize(2); final Balance btcBalance = counterWallet.getBalance(Currency.BTC); assertThat(btcBalance.getTotal()).isEqualTo("0.038777349225374"); assertThat(btcBalance.getCurrency()).isEqualTo(Currency.BTC); final Balance usdBalance = counterWallet.getBalance(Currency.USD); assertThat(usdBalance.getTotal()).isEqualTo("10"); assertThat(usdBalance.getCurrency()).isEqualTo(Currency.USD); final Wallet mainWallet = account.getWallet("main"); assertThat(mainWallet.getBalances()).hasSize(1); final Balance xrpBalance = mainWallet.getBalance(Currency.XRP); assertThat(xrpBalance.getTotal()).isEqualTo("861.401578"); assertThat(xrpBalance.getCurrency()).isEqualTo(Currency.XRP); } @Test public void adaptOrderBookTest() throws IOException { // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/marketdata/example-order-book.json"); final CurrencyPair currencyPair = CurrencyPair.XRP_BTC; // Test data uses Bitstamp issued BTC final RippleMarketDataParams params = new RippleMarketDataParams(); params.setCounterCounterparty("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); // Use Jackson to parse it final ObjectMapper mapper = new ObjectMapper(); final RippleOrderBook rippleOrderBook = mapper.readValue(is, RippleOrderBook.class); // Convert to xchange object and check field values final OrderBook orderBook = RippleAdapters.adaptOrderBook(rippleOrderBook, params, currencyPair); assertThat(orderBook.getBids()).hasSize(10); assertThat(orderBook.getAsks()).hasSize(10); final LimitOrder lastBid = orderBook.getBids().get(9); assertThat(lastBid).isInstanceOf(RippleLimitOrder.class); assertThat(lastBid.getCurrencyPair()).isEqualTo(currencyPair); assertThat(((RippleLimitOrder) lastBid).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(lastBid.getType()).isEqualTo(OrderType.BID); assertThat(lastBid.getId()).isEqualTo("1303704"); assertThat(lastBid.getOriginalAmount()).isEqualTo("66314.537782"); assertThat(lastBid.getLimitPrice()).isEqualTo("0.00003317721777288062"); final LimitOrder firstAsk = orderBook.getAsks().get(0); assertThat(firstAsk).isInstanceOf(RippleLimitOrder.class); assertThat(firstAsk.getCurrencyPair()).isEqualTo(currencyPair); assertThat(((RippleLimitOrder) firstAsk).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(firstAsk.getType()).isEqualTo(OrderType.ASK); assertThat(firstAsk.getId()).isEqualTo("1011310"); assertThat(firstAsk.getOriginalAmount()).isEqualTo("35447.914936"); assertThat(firstAsk.getLimitPrice()).isEqualTo("0.00003380846624897726"); } @Test public void adaptOpenOrdersTest() throws JsonParseException, JsonMappingException, IOException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read in the JSON from the example resources final InputStream is = getClass() .getResourceAsStream("/org/knowm/xchange/ripple/dto/trade/example-account-orders.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleAccountOrders response = mapper.readValue(is, RippleAccountOrders.class); // Convert to XChange orders final OpenOrders orders = RippleAdapters.adaptOpenOrders(response, roundingScale); assertThat(orders.getOpenOrders()).hasSize(12); final LimitOrder firstOrder = orders.getOpenOrders().get(0); assertThat(firstOrder).isInstanceOf(RippleLimitOrder.class); assertThat(firstOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(((RippleLimitOrder) firstOrder).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(firstOrder.getId()).isEqualTo("5"); assertThat(firstOrder.getLimitPrice()).isEqualTo("0.00003226"); assertThat(firstOrder.getTimestamp()).isNull(); assertThat(firstOrder.getOriginalAmount()).isEqualTo("1"); assertThat(firstOrder.getType()).isEqualTo(OrderType.BID); final LimitOrder secondOrder = orders.getOpenOrders().get(1); assertThat(secondOrder).isInstanceOf(RippleLimitOrder.class); assertThat(secondOrder.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(((RippleLimitOrder) secondOrder).getCounterCounterparty()) .isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); assertThat(secondOrder.getId()).isEqualTo("7"); // Price = 15159.38551342023 / 123.123456 assertThat(secondOrder.getLimitPrice()) .isEqualTo("123.12345677999998635515884154518859509596611713043533"); assertThat(secondOrder.getTimestamp()).isNull(); assertThat(secondOrder.getOriginalAmount()).isEqualTo("123.123456"); assertThat(secondOrder.getType()).isEqualTo(OrderType.ASK); } @Override public BigDecimal getTransferFeeRate(final String address) throws IOException { final InputStream is = getClass() .getResourceAsStream( String.format( "/org/knowm/xchange/ripple/dto/account/example-account-settings-%s.json", address)); final ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, RippleAccountSettings.class).getSettings().getTransferFeeRate(); } @Test public void adaptTrade_BuyXRP_SellBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredCounterCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("0000000000000000000000000000000000000000000000000000000000000000"); assertThat(trade.getOrderId()).isEqualTo("1010"); // Price = 0.000029309526038 * 0.998 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.000029250906985924") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z")); assertThat(trade.getOriginalAmount()).isEqualTo("1"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEmpty(); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.000029309526038 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0.000000058619052076"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_SellBTC_BuyXRP() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyXRP-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredBaseCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("0000000000000000000000000000000000000000000000000000000000000000"); assertThat(trade.getOrderId()).isEqualTo("1010"); // Price = 1.0 / (0.000029309526038 * 0.998) assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("34186.97411609205306550363511634115030681332485583111528") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2000-00-00T00:00:00.000Z")); // Quantity = 0.000029309526038 * 0.998 assertThat(trade.getOriginalAmount()).isEqualTo("0.000029250906985924"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.000029309526038 * 0.002 assertThat(ripple.getBaseTransferFee()).isEqualTo("0.000000058619052076"); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEmpty(); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_SellXRP_BuyBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final IRippleTradeTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.setCurrencyPair(CurrencyPair.XRP_BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.XRP_BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("1111111111111111111111111111111111111111111111111111111111111111"); assertThat(trade.getOrderId()).isEqualTo("1111"); assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.000028572057152") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z")); assertThat(trade.getOriginalAmount()).isEqualTo("1"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEmpty(); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); // make sure that if the IRippleTradeTransaction is adapted again it returns the same values final UserTrade trade2 = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade2.getCurrencyPair()).isEqualTo(trade.getCurrencyPair()); assertThat(trade2.getFeeAmount()).isEqualTo(trade.getFeeAmount()); assertThat(trade2.getFeeCurrency()).isEqualTo(trade.getFeeCurrency()); assertThat(trade2.getId()).isEqualTo(trade.getId()); assertThat(trade2.getOrderId()).isEqualTo(trade.getOrderId()); assertThat(trade2.getPrice()).isEqualTo(trade.getPrice()); assertThat(trade2.getTimestamp()).isEqualTo(trade.getTimestamp()); assertThat(trade2.getOriginalAmount()).isEqualTo(trade.getOriginalAmount()); assertThat(trade2.getType()).isEqualTo(trade.getType()); } @Test public void adaptTrade_BuyBTC_SellXRP() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-sellXRP-buyBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final RippleTradeHistoryParams params = new RippleTradeHistoryParams(); params.addPreferredBaseCurrency(Currency.BTC); final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair()).isEqualTo(CurrencyPair.BTC_XRP); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("1111111111111111111111111111111111111111111111111111111111111111"); assertThat(trade.getOrderId()).isEqualTo("1111"); // Price = 1.0 / 0.000028572057152 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("34999.23000574012011552062010939099496310569328655387396") .setScale(roundingScale, RoundingMode.HALF_UP) .stripTrailingZeros()); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2011-11-11T11:11:11.111Z")); assertThat(trade.getOriginalAmount()).isEqualTo("0.000028572057152"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEmpty(); assertThat(ripple.getCounterTransferFee()).isZero(); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_BuyBTC_SellBTC() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-trade-buyBTC-sellBTC.json"); final ObjectMapper mapper = new ObjectMapper(); final RippleOrderTransaction response = mapper.readValue(is, RippleOrderTransaction.class); final TradeHistoryParams params = new TradeHistoryParams() {}; final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.BTC); assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("2222222222222222222222222222222222222222222222222222222222222222"); assertThat(trade.getOrderId()).isEqualTo("2222"); // Price = 0.501 * 0.998 / 0.50150835545121407952 assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.99698837430165008596385145696065600512973847422746") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2022-22-22T22:22:22.222Z")); assertThat(trade.getOriginalAmount()).isEqualTo("0.50150835545121407952"); assertThat(trade.getType()).isEqualTo(OrderType.BID); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"); // Transfer fee = 0.501 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0.001002"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } @Test public void adaptTrade_PaymentPassthrough() throws JsonParseException, JsonMappingException, IOException, ParseException { final RippleExchange exchange = new RippleExchange(); final int roundingScale = exchange.getRoundingScale(); // Read the trade JSON from the example resources final InputStream is = getClass() .getResourceAsStream( "/org/knowm/xchange/ripple/dto/trade/example-payment-passthrough.json"); final ObjectMapper mapper = new ObjectMapper(); final RipplePaymentTransaction response = mapper.readValue(is, RipplePaymentTransaction.class); final TradeHistoryParams params = new TradeHistoryParams() {}; final UserTrade trade = RippleAdapters.adaptTrade(response, params, this, roundingScale); assertThat(trade.getCurrencyPair().base).isEqualTo(Currency.XRP); assertThat(trade.getCurrencyPair().counter).isEqualTo(Currency.BTC); assertThat(trade.getFeeAmount()).isEqualTo("0.012"); assertThat(trade.getFeeCurrency()).isEqualTo(Currency.XRP); assertThat(trade.getId()) .isEqualTo("GHRE072948B95345396B2D9A364363GDE521HRT67QQRGGRTHYTRUP0RRB631107"); assertThat(trade.getOrderId()).isEqualTo("9338"); // Price = 0.009941478580724 / (349.559725 - 0.012) assertThat(trade.getPrice()) .isEqualTo( new BigDecimal("0.00002844097635229638527900589254299967193321026478") .setScale(roundingScale, RoundingMode.HALF_UP)); assertThat(trade.getTimestamp()).isEqualTo(RippleExchange.ToDate("2015-08-07T03:58:10.000Z")); assertThat(trade.getOriginalAmount()).isEqualTo("349.547725"); assertThat(trade.getType()).isEqualTo(OrderType.ASK); assertThat(trade).isInstanceOf(RippleUserTrade.class); final RippleUserTrade ripple = (RippleUserTrade) trade; assertThat(ripple.getBaseCounterparty()).isEqualTo(""); assertThat(ripple.getBaseTransferFee()).isZero(); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(Currency.XRP); assertThat(ripple.getBaseTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().base); assertThat(ripple.getCounterCounterparty()).isEqualTo("rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q"); // Transfer fee = 0.501 * 0.002 assertThat(ripple.getCounterTransferFee()).isEqualTo("0"); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(Currency.BTC); assertThat(ripple.getCounterTransferFeeCurrency()).isEqualTo(trade.getCurrencyPair().counter); } }
mit
aspose-cells/Aspose.Cells-for-Cloud
SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/cells/model/SideWall.java
210
package com.aspose.cells.model; public class SideWall { private Link link = null; public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } }
mit
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/SketchUploadState.java
173
package com.punchthrough.bean.sdk.internal.upload.sketch; public enum SketchUploadState { INACTIVE, RESETTING_REMOTE, SENDING_START_COMMAND, SENDING_BLOCKS, FINISHED }
mit
kashike/SpongeAPI
src/main/java/org/spongepowered/api/event/item/inventory/ChangeInventoryEvent.java
1942
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.event.item.inventory; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.event.Cancellable; import org.spongepowered.api.item.inventory.ItemStack; public interface ChangeInventoryEvent extends TargetInventoryEvent, AffectSlotEvent, Cancellable { /** * Fired when a {@link Living} changes it's equipment. */ interface Equipment extends ChangeInventoryEvent {} /** * Fired when a {@link Living} changes it's held {@link ItemStack}. */ interface Held extends ChangeInventoryEvent {} interface Transfer extends ChangeInventoryEvent {} interface Pickup extends ChangeInventoryEvent {} }
mit
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench/framework/source/org/eclipse/persistence/tools/workbench/framework/context/ExpandedResourceRepositoryApplicationContext.java
2433
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.framework.context; import org.eclipse.persistence.tools.workbench.framework.resources.IconResourceFileNameMap; import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepository; import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepositoryWrapper; /** * Wrap another context and expand its resource * repository with a resource repository wrapper. */ public class ExpandedResourceRepositoryApplicationContext extends ApplicationContextWrapper { private ResourceRepository expandedResourceRepository; // ********** constructor/initialization ********** /** * Construct a context with an expanded resource repository * that adds the resources in the specified resource bundle and icon map * to the original resource repository. */ public ExpandedResourceRepositoryApplicationContext(ApplicationContext delegate, Class resourceBundleClass, IconResourceFileNameMap iconResourceFileNameMap) { super(delegate); this.expandedResourceRepository = new ResourceRepositoryWrapper(this.delegateResourceRepository(), resourceBundleClass, iconResourceFileNameMap); } // ********** non-delegated behavior ********** /** * @see ApplicationContextWrapper#getResourceRepository() */ public ResourceRepository getResourceRepository() { return this.expandedResourceRepository; } // ********** additional behavior ********** /** * Return the original, unwrapped resource repository. */ public ResourceRepository delegateResourceRepository() { return this.getDelegate().getResourceRepository(); } }
epl-1.0
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/mappings/transformers/FieldTransformer.java
2097
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.mappings.transformers; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.core.mappings.transformers.CoreFieldTransformer; import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping; /** * PUBLIC: * This interface is used by the Transformation Mapping to build the value for a * specific field. The user must provide implementations of this interface to the * Transformation Mapping. * @author mmacivor * @since 10.1.3 */ public interface FieldTransformer extends CoreFieldTransformer<Session> { /** * Initialize this transformer. Only required if the user needs some special * information from the mapping in order to do the transformation * @param mapping - the mapping this transformer is associated with. */ public void initialize(AbstractTransformationMapping mapping); /** * @param instance - an instance of the domain class which contains the attribute * @param session - the current session * @param fieldName - the name of the field being transformed. Used if the user wants to use this transformer for multiple fields. * @return - The value to be written for the field associated with this transformer */ @Override public Object buildFieldValue(Object instance, String fieldName, Session session); }
epl-1.0
RallySoftware/eclipselink.runtime
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/writing/ComplexUpdateTest.java
5045
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.writing; import org.eclipse.persistence.testing.framework.*; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.sessions.*; import org.eclipse.persistence.sessions.server.ClientSession; import org.eclipse.persistence.testing.framework.WriteObjectTest; /** * Test changing private parts of an object. */ public class ComplexUpdateTest extends WriteObjectTest { /** The object which is actually changed */ public Object workingCopy; public boolean usesUnitOfWork = false; public boolean usesNestedUnitOfWork = false; public boolean shouldCommitParent = false; /** TODO: Set this to true, and fix issues from tests that fail. */ public boolean shouldCompareClone = true; public ComplexUpdateTest() { super(); } public ComplexUpdateTest(Object originalObject) { super(originalObject); } protected void changeObject() { // By default do nothing } public void commitParentUnitOfWork() { useNestedUnitOfWork(); this.shouldCommitParent = true; } public String getName() { return super.getName() + new Boolean(usesUnitOfWork) + new Boolean(usesNestedUnitOfWork); } public void reset() { if (getExecutor().getSession().isUnitOfWork()) { getExecutor().setSession(((UnitOfWork)getSession()).getParent()); // Do the same for nested units of work. if (getExecutor().getSession().isUnitOfWork()) { getExecutor().setSession(((UnitOfWork)getSession()).getParent()); } } super.reset(); } protected void setup() { super.setup(); if (this.usesUnitOfWork) { getExecutor().setSession(getSession().acquireUnitOfWork()); if (this.usesNestedUnitOfWork) { getExecutor().setSession(getSession().acquireUnitOfWork()); } this.workingCopy = ((UnitOfWork)getSession()).registerObject(this.objectToBeWritten); } else { this.workingCopy = this.objectToBeWritten; } } protected void test() { changeObject(); if (this.usesUnitOfWork) { // Ensure that the original has not been changed. if (!((UnitOfWork)getSession()).getParent().compareObjects(this.originalObject, this.objectToBeWritten)) { throw new TestErrorException("The original object was changed through changing the clone."); } ((UnitOfWork)getSession()).commit(); getExecutor().setSession(((UnitOfWork)getSession()).getParent()); if (this.usesNestedUnitOfWork) { if (this.shouldCommitParent) { ((UnitOfWork)getSession()).commit(); } getExecutor().setSession(((UnitOfWork)getSession()).getParent()); } // Ensure that the clone matches the cache. if (this.shouldCompareClone) { ClassDescriptor descriptor = getSession().getClassDescriptor(this.objectToBeWritten); if(descriptor.shouldIsolateObjectsInUnitOfWork()) { getSession().logMessage("ComplexUpdateTest: descriptor.shouldIsolateObjectsInUnitOfWork() == null. In this case object's changes are not merged back into parent's cache"); } else if (descriptor.shouldIsolateProtectedObjectsInUnitOfWork() && getSession().isClientSession()){ if (!getAbstractSession().compareObjects(this.workingCopy, ((ClientSession)getSession()).getParent().getIdentityMapAccessor().getFromIdentityMap(this.workingCopy))) { throw new TestErrorException("The clone does not match the cached object."); } } else { if (!getAbstractSession().compareObjects(this.workingCopy, this.objectToBeWritten)) { throw new TestErrorException("The clone does not match the cached object."); } } } } else { super.test(); } } public void useNestedUnitOfWork() { this.usesNestedUnitOfWork = true; this.usesUnitOfWork = true; } }
epl-1.0
RallySoftware/eclipselink.runtime
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/advanced/EntityMethodPostUpdateTest.java
1234
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.tests.jpa.advanced; import org.eclipse.persistence.testing.models.jpa.advanced.Project; /** * Tests the @PostUpdate events from an Entity. * * @author Guy Pelletier */ public class EntityMethodPostUpdateTest extends CallbackEventTest { public void test() throws Exception { m_beforeEvent = 0; // Loading a new object to update, count starts at 0. Project project = updateProject(); m_afterEvent = project.post_update_count; } }
epl-1.0
emmeryn/intellij-ocaml
OCamlSources/src/manuylov/maxim/ocaml/lang/parser/psi/element/impl/OCamlParenthesesTypeParametersImpl.java
1487
/* * OCaml Support For IntelliJ Platform. * Copyright (C) 2010 Maxim Manuylov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. */ package manuylov.maxim.ocaml.lang.parser.psi.element.impl; import com.intellij.lang.ASTNode; import manuylov.maxim.ocaml.lang.parser.psi.OCamlElementVisitor; import manuylov.maxim.ocaml.lang.parser.psi.element.OCamlParenthesesTypeParameters; import org.jetbrains.annotations.NotNull; /** * @author Maxim.Manuylov * Date: 13.05.2010 */ public class OCamlParenthesesTypeParametersImpl extends OCamlParenthesesImpl implements OCamlParenthesesTypeParameters { public OCamlParenthesesTypeParametersImpl(@NotNull final ASTNode node) { super(node); } public void visit(@NotNull final OCamlElementVisitor visitor) { visitor.visitParenthesesTypeParameters(this); } }
gpl-2.0
jballanc/openmicroscopy
components/tests/ui/library/java/src/org/openmicroscopy/shoola/keywords/ThumbnailCheckLibrary.java
9339
/* * Copyright (C) 2013 University of Dundee & Open Microscopy Environment. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.openmicroscopy.shoola.keywords; import java.awt.Component; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.util.NoSuchElementException; import javax.swing.JPanel; import org.robotframework.abbot.finder.BasicFinder; import org.robotframework.abbot.finder.ComponentNotFoundException; import org.robotframework.abbot.finder.Matcher; import org.robotframework.abbot.finder.MultipleComponentsFoundException; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; /** * Robot Framework SwingLibrary keyword library offering methods for checking thumbnails. * @author m.t.b.carroll@dundee.ac.uk * @since 4.4.9 */ public class ThumbnailCheckLibrary { /** Allow Robot Framework to instantiate this library only once. */ public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL"; /** * An iterator over the integer pixel values of a rendered image, * first increasing <em>x</em>, then <em>y</em> when <em>x</em> wraps back to 0. * This is written so as to be scalable over arbitrary image sizes * and to not cause heap allocations during the iteration. * @author m.t.b.carroll@dundee.ac.uk * @since 4.4.9 */ private static class IteratorIntPixel { final Raster raster; final int width; final int height; final int[] pixel = new int[1]; int x = 0; int y = 0; /** * Create a new pixel iterator for the given image. * The image is assumed to be of a type that packs data for each pixel into an <code>int</code>. * @param image the image over whose pixels to iterate */ IteratorIntPixel(RenderedImage image) { this.raster = image.getData(); this.width = image.getWidth(); this.height = image.getHeight(); } /** * @return if any pixels remain to be read with {@link #next()} */ boolean hasNext() { return y < height; } /** * @return the next pixel * @throws NoSuchElementException if no more pixels remain */ int next() { if (!hasNext()) { throw new NoSuchElementException(); } raster.getDataElements(x, y, pixel); if (++x == width) { x = 0; ++y; } return pixel[0]; } } /** * Find the thumbnail <code>Component</code> in the AWT hierarchy. * @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas * @param imageFilename the name of the image whose thumbnail is to be rasterized * @return the AWT <code>Component</code> for the thumbnail * @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name * @throws ComponentNotFoundException if no thumbnails are for the given image name */ private static Component componentFinder(final String panelType, final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { return new BasicFinder().find(new Matcher() { private final String soughtName = panelType + " for " + imageFilename; public boolean matches(Component component) { return component instanceof JPanel && this.soughtName.equals(component.getName()); }}); } /** * Convert the thumbnail for the image of the given filename into rasterized pixel data. * Each pixel is represented by an <code>int</code>. * @param panelType if the thumbnail should be the whole <code>"image node"</code> or just its <code>"thumbnail"</code> canvas * @param imageFilename the name of the image whose thumbnail is to be rasterized * @return the image on the thumbnail * @throws MultipleComponentsFoundException if multiple thumbnails are for the given image name * @throws ComponentNotFoundException if no thumbnails are for the given image name */ private static RenderedImage captureImage(final String panelType, final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final JPanel thumbnail = (JPanel) componentFinder(panelType, imageFilename); final int width = thumbnail.getWidth(); final int height = thumbnail.getHeight(); final BufferedImage image = new BufferedImage(width, height, StaticFieldLibrary.IMAGE_TYPE); final Graphics2D graphics = image.createGraphics(); if (graphics == null) { throw new RuntimeException("thumbnail is not displayable"); } thumbnail.paint(graphics); graphics.dispose(); return image; } /** * <table> * <td>Get Thumbnail Border Color</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the color of the thumbnail's corner pixel * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getThumbnailBorderColor(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("image node", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); if (!pixels.hasNext()) { throw new RuntimeException("image node has no pixels"); } return Integer.toHexString(pixels.next()); } /** * <table> * <td>Is Thumbnail Monochromatic</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return if the image's thumbnail canvas is solidly one color * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public boolean isThumbnailMonochromatic(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("thumbnail", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); if (!pixels.hasNext()) { throw new RuntimeException("thumbnail image has no pixels"); } final int oneColor = pixels.next(); while (pixels.hasNext()) { if (pixels.next() != oneColor) { return false; } } return true; } /** * <table> * <td>Get Thumbnail Hash</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the hash of the thumbnail canvas image * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getThumbnailHash(String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { final RenderedImage image = captureImage("thumbnail", imageFilename); final IteratorIntPixel pixels = new IteratorIntPixel(image); final Hasher hasher = Hashing.goodFastHash(128).newHasher(); while (pixels.hasNext()) { hasher.putInt(pixels.next()); } return hasher.hash().toString(); } /** * <table> * <td>Get Name Of Thumbnail For Image</td> * <td>name of image whose thumbnail is queried</td> * </table> * @param imageFilename the name of the image * @return the return value of the corresponding <code>ThumbnailCanvas.getName()</code> * @throws MultipleComponentsFoundException if multiple thumbnails exist for the given name * @throws ComponentNotFoundException if no thumbnails exist for the given name */ public String getNameOfThumbnailForImage(final String imageFilename) throws ComponentNotFoundException, MultipleComponentsFoundException { return componentFinder("thumbnail", imageFilename).getName(); } }
gpl-2.0
Murreey/CommandHelper
src/main/java/com/laytonsmith/abstraction/MCScoreboard.java
908
package com.laytonsmith.abstraction; import com.laytonsmith.abstraction.enums.MCDisplaySlot; import java.util.Set; public interface MCScoreboard { public void clearSlot(MCDisplaySlot slot); public MCObjective getObjective(MCDisplaySlot slot); public MCObjective getObjective(String name); /** * * @return Set of all objectives on this scoreboard */ public Set<MCObjective> getObjectives(); public Set<MCObjective> getObjectivesByCriteria(String criteria); /** * * @return Set of all players tracked by this scoreboard */ public Set<String> getEntries(); public MCTeam getPlayerTeam(MCOfflinePlayer player); public Set<MCScore> getScores(String entry); public MCTeam getTeam(String teamName); public Set<MCTeam> getTeams(); public MCObjective registerNewObjective(String name, String criteria); public MCTeam registerNewTeam(String name); public void resetScores(String entry); }
gpl-3.0
yescallop/Nukkit
src/main/java/cn/nukkit/block/BlockNoteblock.java
3101
package cn.nukkit.block; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.level.sound.NoteBoxSound; import cn.nukkit.network.protocol.BlockEventPacket; /** * Created by Snake1999 on 2016/1/17. * Package cn.nukkit.block in project nukkit. */ public class BlockNoteblock extends BlockSolid { public BlockNoteblock() { this(0); } public BlockNoteblock(int meta) { super(meta); } @Override public String getName() { return "Note Block"; } @Override public int getId() { return NOTEBLOCK; } @Override public int getToolType() { return ItemTool.TYPE_AXE; } @Override public double getHardness() { return 0.8D; } @Override public double getResistance() { return 4D; } public boolean canBeActivated() { return true; } public int getStrength() { return this.meta; } public void increaseStrength() { if (this.meta < 24) { this.meta++; } else { this.meta = 0; } } public int getInstrument() { Block below = this.down(); switch (below.getId()) { case WOODEN_PLANK: case NOTEBLOCK: case CRAFTING_TABLE: return NoteBoxSound.INSTRUMENT_BASS; case SAND: case SANDSTONE: case SOUL_SAND: return NoteBoxSound.INSTRUMENT_TABOUR; case GLASS: case GLASS_PANEL: case GLOWSTONE_BLOCK: return NoteBoxSound.INSTRUMENT_CLICK; case COAL_ORE: case DIAMOND_ORE: case EMERALD_ORE: case GLOWING_REDSTONE_ORE: case GOLD_ORE: case IRON_ORE: case LAPIS_ORE: case REDSTONE_ORE: return NoteBoxSound.INSTRUMENT_BASS_DRUM; default: return NoteBoxSound.INSTRUMENT_PIANO; } } public void emitSound() { BlockEventPacket pk = new BlockEventPacket(); pk.x = (int) this.x; pk.y = (int) this.y; pk.z = (int) this.z; pk.case1 = this.getInstrument(); pk.case2 = this.getStrength(); this.getLevel().addChunkPacket((int) this.x >> 4, (int) this.z >> 4, pk); this.getLevel().addSound(new NoteBoxSound(this, this.getInstrument(), this.getStrength())); } public boolean onActivate(Item item) { return this.onActivate(item, null); } public boolean onActivate(Item item, Player player) { Block up = this.up(); if (up.getId() == Block.AIR) { this.increaseStrength(); this.emitSound(); return true; } else { return false; } } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) { //TODO: redstone } return 0; } }
gpl-3.0
s20121035/rk3288_android5.1_repo
cts/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/DnsSdResponseListenerTest.java
4616
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.verifier.p2p.testcase; import java.util.ArrayList; import java.util.List; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener; import android.util.Log; /** * The utility class for testing * android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener callback function. */ public class DnsSdResponseListenerTest extends ListenerTest implements DnsSdServiceResponseListener { private static final String TAG = "DnsSdResponseListenerTest"; public static final List<ListenerArgument> NO_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> ALL_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> IPP_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> AFP_DNS_PTR = new ArrayList<ListenerArgument>(); /** * The target device address. */ private String mTargetAddr; static { initialize(); } public DnsSdResponseListenerTest(String targetAddr) { mTargetAddr = targetAddr; } @Override public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice) { Log.d(TAG, instanceName + " " + registrationType + " received from " + srcDevice.deviceAddress); /* * Check only the response from the target device. * The response from other devices are ignored. */ if (srcDevice.deviceAddress.equalsIgnoreCase(mTargetAddr)) { receiveCallback(new Argument(instanceName, registrationType)); } } private static void initialize() { String ippInstanceName = "MyPrinter"; String ippRegistrationType = "_ipp._tcp.local."; String afpInstanceName = "Example"; String afpRegistrationType = "_afpovertcp._tcp.local."; IPP_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); AFP_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); ALL_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); ALL_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); } /** * The container of the argument of {@link #onDnsSdServiceAvailable}. */ static class Argument extends ListenerArgument { private String mInstanceName; private String mRegistrationType; /** * Set the argument of {@link #onDnsSdServiceAvailable}. * * @param instanceName instance name. * @param registrationType registration type. */ Argument(String instanceName, String registrationType) { mInstanceName = instanceName; mRegistrationType = registrationType; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Argument)) { return false; } Argument arg = (Argument)obj; return equals(mInstanceName, arg.mInstanceName) && equals(mRegistrationType, arg.mRegistrationType); } private boolean equals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[type=dns_ptr instant_name="); sb.append(mInstanceName); sb.append(" registration type="); sb.append(mRegistrationType); sb.append("\n"); return "instanceName=" + mInstanceName + " registrationType=" + mRegistrationType; } } }
gpl-3.0
danielbejaranogonzalez/Mobile-Network-Designer
db/hsqldb/src/org/hsqldb/util/SqlTool.java
23912
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /* $Id: SqlTool.java,v 1.72 2007/06/29 12:23:47 unsaved Exp $ */ /** * Sql Tool. A command-line and/or interactive SQL tool. * (Note: For every Javadoc block comment, I'm using a single blank line * immediately after the description, just like's Sun's examples in * their Coding Conventions document). * * See JavaDocs for the main method for syntax of how to run. * This class is mostly used in a static (a.o.t. object) way, because most * of the work is done in the static main class. * This class should be refactored so that the main work is done in an * object method, and the static main invokes the object method. * Then programmatic users could use instances of this class in the normal * Java way. * * @see #main() * @version $Revision: 1.72 $ * @author Blaine Simpson unsaved@users */ public class SqlTool { private static final String DEFAULT_RCFILE = System.getProperty("user.home") + "/sqltool.rc"; // N.b. the following is static! private static String revnum = null; public static final int SQLTOOLERR_EXITVAL = 1; public static final int SYNTAXERR_EXITVAL = 11; public static final int RCERR_EXITVAL = 2; public static final int SQLERR_EXITVAL = 3; public static final int IOERR_EXITVAL = 4; public static final int FILEERR_EXITVAL = 5; public static final int INPUTERR_EXITVAL = 6; public static final int CONNECTERR_EXITVAL = 7; /** * The configuration identifier to use when connection parameters are * specified on the command line */ private static String CMDLINE_ID = "cmdline"; static private SqltoolRB rb = null; // Must use a shared static RB object, since we need to get messages // inside of static methods. // This means that the locale will be set the first time this class // is accessed. Subsequent calls will not update the RB if the locale // changes (could have it check and reload the RB if this becomes an // issue). static { revnum = "333"; try { rb = new SqltoolRB(); rb.validate(); rb.setMissingPosValueBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); rb.setMissingPropertyBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); } catch (RuntimeException re) { System.err.println("Failed to initialize resource bundle"); throw re; } } public static String LS = System.getProperty("line.separator"); /** Utility nested class for internal use. */ private static class BadCmdline extends Exception { static final long serialVersionUID = -2134764796788108325L; BadCmdline() {} } /** Utility object for internal use. */ private static BadCmdline bcl = new BadCmdline(); /** For trapping of exceptions inside this class. * These are always handled inside this class. */ private static class PrivateException extends Exception { static final long serialVersionUID = -7765061479594523462L; PrivateException() { super(); } PrivateException(String s) { super(s); } } public static class SqlToolException extends Exception { static final long serialVersionUID = 1424909871915188519L; int exitValue = 1; SqlToolException(String message, int exitValue) { super(message); this.exitValue = exitValue; } SqlToolException(int exitValue, String message) { this(message, exitValue); } SqlToolException(int exitValue) { super(); this.exitValue = exitValue; } } /** * Prompt the user for a password. * * @param username The user the password is for * @return The password the user entered */ private static String promptForPassword(String username) throws PrivateException { BufferedReader console; String password; password = null; try { console = new BufferedReader(new InputStreamReader(System.in)); // Prompt for password System.out.print(rb.getString(SqltoolRB.PASSWORDFOR_PROMPT, RCData.expandSysPropVars(username))); // Read the password from the command line password = console.readLine(); if (password == null) { password = ""; } else { password = password.trim(); } } catch (IOException e) { throw new PrivateException(e.getMessage()); } return password; } /** * Parses a comma delimited string of name value pairs into a * <code>Map</code> object. * * @param varString The string to parse * @param varMap The map to save the paired values into * @param lowerCaseKeys Set to <code>true</code> if the map keys should be * converted to lower case */ private static void varParser(String varString, Map varMap, boolean lowerCaseKeys) throws PrivateException { int equals; String var; String val; String[] allvars; if ((varMap == null) || (varString == null)) { throw new IllegalArgumentException( "varMap or varString are null in SqlTool.varParser call"); } allvars = varString.split("\\s*,\\s*"); for (int i = 0; i < allvars.length; i++) { equals = allvars[i].indexOf('='); if (equals < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } var = allvars[i].substring(0, equals).trim(); val = allvars[i].substring(equals + 1).trim(); if (var.length() < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } if (lowerCaseKeys) { var = var.toLowerCase(); } varMap.put(var, val); } } /** * A static wrapper for objectMain, so that that method may be executed * as a Java "program". * * Throws only RuntimExceptions or Errors, because this method is intended * to System.exit() for all but disasterous system problems, for which * the inconvenience of a a stack trace would be the least of your worries. * * If you don't want SqlTool to System.exit(), then use the method * objectMain() instead of this method. * * @see objectMain(String[]) */ public static void main(String[] args) { try { SqlTool.objectMain(args); } catch (SqlToolException fr) { if (fr.getMessage() != null) { System.err.println(fr.getMessage()); } System.exit(fr.exitValue); } System.exit(0); } /** * Connect to a JDBC Database and execute the commands given on * stdin or in SQL file(s). * * This method is changed for HSQLDB 1.8.0.8 and 1.9.0.x to never * System.exit(). * * @param arg Run "java... org.hsqldb.util.SqlTool --help" for syntax. * @throws SqlToolException Upon any fatal error, with useful * reason as the exception's message. */ static public void objectMain(String[] arg) throws SqlToolException { /* * The big picture is, we parse input args; load a RCData; * get a JDBC Connection with the RCData; instantiate and * execute as many SqlFiles as we need to. */ String rcFile = null; File tmpFile = null; String sqlText = null; String driver = null; String targetDb = null; String varSettings = null; boolean debug = false; File[] scriptFiles = null; int i = -1; boolean listMode = false; boolean interactive = false; boolean noinput = false; boolean noautoFile = false; boolean autoCommit = false; Boolean coeOverride = null; Boolean stdinputOverride = null; String rcParams = null; String rcUrl = null; String rcUsername = null; String rcPassword = null; String rcCharset = null; String rcTruststore = null; Map rcFields = null; String parameter; try { while ((i + 1 < arg.length) && arg[i + 1].startsWith("--")) { i++; if (arg[i].length() == 2) { break; // "--" } parameter = arg[i].substring(2).toLowerCase(); if (parameter.equals("help")) { System.out.println(rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); return; } if (parameter.equals("abortonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.FALSE; } else if (parameter.equals("continueonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.TRUE; } else if (parameter.equals("list")) { listMode = true; } else if (parameter.equals("rcfile")) { if (++i == arg.length) { throw bcl; } rcFile = arg[i]; } else if (parameter.equals("setvar")) { if (++i == arg.length) { throw bcl; } varSettings = arg[i]; } else if (parameter.equals("sql")) { noinput = true; // but turn back on if file "-" specd. if (++i == arg.length) { throw bcl; } sqlText = arg[i]; } else if (parameter.equals("debug")) { debug = true; } else if (parameter.equals("noautofile")) { noautoFile = true; } else if (parameter.equals("autocommit")) { autoCommit = true; } else if (parameter.equals("stdinput")) { noinput = false; stdinputOverride = Boolean.TRUE; } else if (parameter.equals("noinput")) { noinput = true; stdinputOverride = Boolean.FALSE; } else if (parameter.equals("driver")) { if (++i == arg.length) { throw bcl; } driver = arg[i]; } else if (parameter.equals("inlinerc")) { if (++i == arg.length) { throw bcl; } rcParams = arg[i]; } else { throw bcl; } } if (!listMode) { // If an inline RC file was specified, don't worry about the targetDb if (rcParams == null) { if (++i == arg.length) { throw bcl; } targetDb = arg[i]; } } int scriptIndex = 0; if (sqlText != null) { try { tmpFile = File.createTempFile("sqltool-", ".sql"); //(new java.io.FileWriter(tmpFile)).write(sqlText); java.io.FileWriter fw = new java.io.FileWriter(tmpFile); try { fw.write("/* " + (new java.util.Date()) + ". " + SqlTool.class.getName() + " command-line SQL. */" + LS + LS); fw.write(sqlText + LS); fw.flush(); } finally { fw.close(); } } catch (IOException ioe) { throw new SqlToolException(IOERR_EXITVAL, rb.getString(SqltoolRB.SQLTEMPFILE_FAIL, ioe.toString())); } } if (stdinputOverride != null) { noinput = !stdinputOverride.booleanValue(); } interactive = (!noinput) && (arg.length <= i + 1); if (arg.length == i + 2 && arg[i + 1].equals("-")) { if (stdinputOverride == null) { noinput = false; } } else if (arg.length > i + 1) { // I.e., if there are any SQL files specified. scriptFiles = new File[arg.length - i - 1 + ((stdinputOverride == null ||!stdinputOverride.booleanValue()) ? 0 : 1)]; if (debug) { System.err.println("scriptFiles has " + scriptFiles.length + " elements"); } while (i + 1 < arg.length) { scriptFiles[scriptIndex++] = new File(arg[++i]); } if (stdinputOverride != null && stdinputOverride.booleanValue()) { scriptFiles[scriptIndex++] = null; noinput = true; } } } catch (BadCmdline bcl) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); } RCData conData = null; // Use the inline RC file if it was specified if (rcParams != null) { rcFields = new HashMap(); try { varParser(rcParams, rcFields, true); } catch (PrivateException e) { throw new SqlToolException(SYNTAXERR_EXITVAL, e.getMessage()); } rcUrl = (String) rcFields.remove("url"); rcUsername = (String) rcFields.remove("user"); rcCharset = (String) rcFields.remove("charset"); rcTruststore = (String) rcFields.remove("truststore"); rcPassword = (String) rcFields.remove("password"); // Don't ask for password if what we have already is invalid! if (rcUrl == null || rcUrl.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEURL_MISSING)); if (rcUsername == null || rcUsername.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEUSERNAME_MISSING)); if (rcPassword != null && rcPassword.length() > 0) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_PASSWORD_VISIBLE)); if (rcFields.size() > 0) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.RCDATA_INLINE_EXTRAVARS, rcFields.keySet().toString())); } if (rcPassword == null) try { rcPassword = promptForPassword(rcUsername); } catch (PrivateException e) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.PASSWORD_READFAIL, e.getMessage())); } try { conData = new RCData(CMDLINE_ID, rcUrl, rcUsername, rcPassword, driver, rcCharset, rcTruststore); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_GENFROMVALUES_FAIL, e.getMessage())); } } else { try { conData = new RCData(new File((rcFile == null) ? DEFAULT_RCFILE : rcFile), targetDb); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.CONNDATA_RETRIEVAL_FAIL, targetDb, e.getMessage())); } } if (listMode) { return; } if (debug) { conData.report(); } Connection conn = null; try { conn = conData.getConnection( driver, System.getProperty("sqlfile.charset"), System.getProperty("javax.net.ssl.trustStore")); conn.setAutoCommit(autoCommit); DatabaseMetaData md = null; if (interactive && (md = conn.getMetaData()) != null) { System.out.println( rb.getString(SqltoolRB.JDBC_ESTABLISHED, md.getDatabaseProductName(), md.getDatabaseProductVersion(), md.getUserName())); } } catch (Exception e) { //e.printStackTrace(); // Let's not continue as if nothing is wrong. throw new SqlToolException(CONNECTERR_EXITVAL, rb.getString(SqltoolRB.CONNECTION_FAIL, conData.url, conData.username, e.getMessage())); } File[] emptyFileArray = {}; File[] singleNullFileArray = { null }; File autoFile = null; if (interactive &&!noautoFile) { autoFile = new File(System.getProperty("user.home") + "/auto.sql"); if ((!autoFile.isFile()) ||!autoFile.canRead()) { autoFile = null; } } if (scriptFiles == null) { // I.e., if no SQL files given on command-line. // Input file list is either nothing or {null} to read stdin. scriptFiles = (noinput ? emptyFileArray : singleNullFileArray); } int numFiles = scriptFiles.length; if (tmpFile != null) { numFiles += 1; } if (autoFile != null) { numFiles += 1; } SqlFile[] sqlFiles = new SqlFile[numFiles]; Map userVars = new HashMap(); if (varSettings != null) try { varParser(varSettings, userVars, false); } catch (PrivateException pe) { throw new SqlToolException(RCERR_EXITVAL, pe.getMessage()); } // We print version before execing this one. int interactiveFileIndex = -1; try { int fileIndex = 0; if (autoFile != null) { sqlFiles[fileIndex++] = new SqlFile(autoFile, false, userVars); } if (tmpFile != null) { sqlFiles[fileIndex++] = new SqlFile(tmpFile, false, userVars); } for (int j = 0; j < scriptFiles.length; j++) { if (interactiveFileIndex < 0 && interactive) { interactiveFileIndex = fileIndex; } sqlFiles[fileIndex++] = new SqlFile(scriptFiles[j], interactive, userVars); } } catch (IOException ioe) { try { conn.close(); } catch (Exception e) {} throw new SqlToolException(FILEERR_EXITVAL, ioe.getMessage()); } try { for (int j = 0; j < sqlFiles.length; j++) { if (j == interactiveFileIndex) { System.out.print("SqlTool v. " + revnum + ". "); } sqlFiles[j].execute(conn, coeOverride); } // Following two Exception types are handled properly inside of // SqlFile. We just need to return an appropriate error status. } catch (SqlToolError ste) { throw new SqlToolException(SQLTOOLERR_EXITVAL); } catch (SQLException se) { // SqlTool will only throw an SQLException if it is in // "\c false" mode. throw new SqlToolException(SQLERR_EXITVAL); } finally { try { conn.close(); } catch (Exception e) {} } // Taking file removal out of final block because this is good debug // info to keep around if the program aborts. if (tmpFile != null && !tmpFile.delete()) { System.err.println(conData.url + rb.getString( SqltoolRB.TEMPFILE_REMOVAL_FAIL, tmpFile.toString())); } } }
gpl-3.0
Lee-Wills/-tv
mmd/library/src/main/java/com/google/android/exoplayer/text/tx3g/Tx3gParser.java
1720
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.text.tx3g; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.Subtitle; import com.google.android.exoplayer.text.SubtitleParser; import com.google.android.exoplayer.util.MimeTypes; import com.google.android.exoplayer.util.ParsableByteArray; /** * A {@link SubtitleParser} for tx3g. * <p> * Currently only supports parsing of a single text track. */ public final class Tx3gParser implements SubtitleParser { private final ParsableByteArray parsableByteArray; public Tx3gParser() { parsableByteArray = new ParsableByteArray(); } @Override public boolean canParse(String mimeType) { return MimeTypes.APPLICATION_TX3G.equals(mimeType); } @Override public Subtitle parse(byte[] bytes, int offset, int length) { parsableByteArray.reset(bytes, length); int textLength = parsableByteArray.readUnsignedShort(); if (textLength == 0) { return Tx3gSubtitle.EMPTY; } String cueText = parsableByteArray.readString(textLength); return new Tx3gSubtitle(new Cue(cueText)); } }
gpl-3.0
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraftforge/event/terraingen/SaplingGrowTreeEvent.java
2229
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.event.terraingen; import java.util.Random; import net.minecraft.block.BlockSapling; import net.minecraft.block.state.IBlockState; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Cancelable; import net.minecraftforge.fml.common.eventhandler.Event.HasResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.world.WorldEvent; /** * SaplingGrowTreeEvent is fired when a sapling grows into a tree.<br> * This event is fired during sapling growth in * {@link BlockSapling#generateTree(World, BlockPos, IBlockState, Random)}.<br> * <br> * {@link #pos} contains the coordinates of the growing sapling. <br> * {@link #rand} contains an instance of Random for use. <br> * <br> * This event is not {@link Cancelable}.<br> * <br> * This event has a result. {@link HasResult} <br> * This result determines if the sapling is allowed to grow. <br> * <br> * This event is fired on the {@link MinecraftForge#TERRAIN_GEN_BUS}.<br> **/ @HasResult public class SaplingGrowTreeEvent extends WorldEvent { private final BlockPos pos; private final Random rand; public SaplingGrowTreeEvent(World world, Random rand, BlockPos pos) { super(world); this.rand = rand; this.pos = pos; } public BlockPos getPos() { return pos; } public Random getRand() { return rand; } }
gpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/EpworthSleepAssessmentVo.java
7901
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo; /** * Linked to core.clinical.EpworthSleepAssessment business object (ID: 1003100055). */ public class EpworthSleepAssessmentVo extends ims.core.clinical.vo.EpworthSleepAssessmentRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public EpworthSleepAssessmentVo() { } public EpworthSleepAssessmentVo(Integer id, int version) { super(id, version); } public EpworthSleepAssessmentVo(ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean = null; if(map != null) bean = (ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CHANCEOFSLEEP")) return getChanceOfSleep(); if(fieldName.equals("SLEEPSCORE")) return getSleepScore(); return super.getFieldValueByFieldName(fieldName); } public boolean getChanceOfSleepIsNotNull() { return this.chanceofsleep != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep getChanceOfSleep() { return this.chanceofsleep; } public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep value) { this.isValidated = false; this.chanceofsleep = value; } public boolean getSleepScoreIsNotNull() { return this.sleepscore != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore() { return this.sleepscore; } public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value) { this.isValidated = false; this.sleepscore = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; EpworthSleepAssessmentVo clone = new EpworthSleepAssessmentVo(this.id, this.version); if(this.chanceofsleep == null) clone.chanceofsleep = null; else clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep)this.chanceofsleep.clone(); if(this.sleepscore == null) clone.sleepscore = null; else clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(EpworthSleepAssessmentVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A EpworthSleepAssessmentVo object cannot be compared an Object of type " + obj.getClass().getName()); } EpworthSleepAssessmentVo compareObj = (EpworthSleepAssessmentVo)obj; int retVal = 0; if (retVal == 0) { if(this.getID_EpworthSleepAssessment() == null && compareObj.getID_EpworthSleepAssessment() != null) return -1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() == null) return 1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() != null) retVal = this.getID_EpworthSleepAssessment().compareTo(compareObj.getID_EpworthSleepAssessment()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.chanceofsleep != null) count++; if(this.sleepscore != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep chanceofsleep; protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/beans/MRSATreatmentVoBean.java
4677
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.beans; public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean { public MRSATreatmentVoBean() { } public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public ims.nursing.vo.MRSATreatmentVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.MRSATreatmentVo vo = null; if(map != null) vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this); if(vo == null) { vo = new ims.nursing.vo.MRSATreatmentVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getStartDate() { return this.startdate; } public void setStartDate(ims.framework.utils.beans.DateBean value) { this.startdate = value; } public ims.framework.utils.beans.DateBean getRescreenDate() { return this.rescreendate; } public void setRescreenDate(ims.framework.utils.beans.DateBean value) { this.rescreendate = value; } public Integer getTreatmentNumber() { return this.treatmentnumber; } public void setTreatmentNumber(Integer value) { this.treatmentnumber = value; } public ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] getTreatmentDetails() { return this.treatmentdetails; } public void setTreatmentDetails(ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] value) { this.treatmentdetails = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean startdate; private ims.framework.utils.beans.DateBean rescreendate; private Integer treatmentnumber; private ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] treatmentdetails; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/Transfers.java
7494
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo; /** * Linked to nursing.assessment.Transfers business object (ID: 1015100016). */ public class Transfers extends ims.nursing.assessment.vo.TransfersRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public Transfers() { } public Transfers(Integer id, int version) { super(id, version); } public Transfers(ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.TransfersBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.TransfersBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.TransfersBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PATIENTTRANSFERS")) return getPatientTransfers(); if(fieldName.equals("ASSISTANCEREQUIRED")) return getAssistanceRequired(); return super.getFieldValueByFieldName(fieldName); } public boolean getPatientTransfersIsNotNull() { return this.patienttransfers != null; } public ims.nursing.vo.lookups.Transfers getPatientTransfers() { return this.patienttransfers; } public void setPatientTransfers(ims.nursing.vo.lookups.Transfers value) { this.isValidated = false; this.patienttransfers = value; } public boolean getAssistanceRequiredIsNotNull() { return this.assistancerequired != null; } public ims.nursing.vo.lookups.Ability getAssistanceRequired() { return this.assistancerequired; } public void setAssistanceRequired(ims.nursing.vo.lookups.Ability value) { this.isValidated = false; this.assistancerequired = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; Transfers clone = new Transfers(this.id, this.version); if(this.patienttransfers == null) clone.patienttransfers = null; else clone.patienttransfers = (ims.nursing.vo.lookups.Transfers)this.patienttransfers.clone(); if(this.assistancerequired == null) clone.assistancerequired = null; else clone.assistancerequired = (ims.nursing.vo.lookups.Ability)this.assistancerequired.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(Transfers.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A Transfers object cannot be compared an Object of type " + obj.getClass().getName()); } Transfers compareObj = (Transfers)obj; int retVal = 0; if (retVal == 0) { if(this.getID_Transfers() == null && compareObj.getID_Transfers() != null) return -1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() == null) return 1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() != null) retVal = this.getID_Transfers().compareTo(compareObj.getID_Transfers()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patienttransfers != null) count++; if(this.assistancerequired != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.nursing.vo.lookups.Transfers patienttransfers; protected ims.nursing.vo.lookups.Ability assistancerequired; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/CatsReferralForSessionManagementVo.java
5952
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; /** * Linked to RefMan.CatsReferral business object (ID: 1004100035). */ public class CatsReferralForSessionManagementVo extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public CatsReferralForSessionManagementVo() { } public CatsReferralForSessionManagementVo(Integer id, int version) { super(id, version); } public CatsReferralForSessionManagementVo(ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(map); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean = null; if(map != null) bean = (ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("REFERRALDETAILS")) return getReferralDetails(); if(fieldName.equals("CURRENTSTATUS")) return getCurrentStatus(); return super.getFieldValueByFieldName(fieldName); } public boolean getReferralDetailsIsNotNull() { return this.referraldetails != null; } public ims.RefMan.vo.ReferralLetterForSessionManagementVo getReferralDetails() { return this.referraldetails; } public void setReferralDetails(ims.RefMan.vo.ReferralLetterForSessionManagementVo value) { this.isValidated = false; this.referraldetails = value; } public boolean getCurrentStatusIsNotNull() { return this.currentstatus != null; } public ims.RefMan.vo.CatsReferralStatusLiteVo getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.RefMan.vo.CatsReferralStatusLiteVo value) { this.isValidated = false; this.currentstatus = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; CatsReferralForSessionManagementVo clone = new CatsReferralForSessionManagementVo(this.id, this.version); if(this.referraldetails == null) clone.referraldetails = null; else clone.referraldetails = (ims.RefMan.vo.ReferralLetterForSessionManagementVo)this.referraldetails.clone(); if(this.currentstatus == null) clone.currentstatus = null; else clone.currentstatus = (ims.RefMan.vo.CatsReferralStatusLiteVo)this.currentstatus.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(CatsReferralForSessionManagementVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A CatsReferralForSessionManagementVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((CatsReferralForSessionManagementVo)obj).getBoId() == null) return -1; return this.id.compareTo(((CatsReferralForSessionManagementVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.referraldetails != null) count++; if(this.currentstatus != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.RefMan.vo.ReferralLetterForSessionManagementVo referraldetails; protected ims.RefMan.vo.CatsReferralStatusLiteVo currentstatus; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
opennetworkinglab/onos
core/store/serializers/src/main/java/org/onosproject/store/serializers/LinkKeySerializer.java
1671
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.serializers; import org.onosproject.net.ConnectPoint; import org.onosproject.net.LinkKey; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** * Kryo Serializer for {@link LinkKey}. */ public class LinkKeySerializer extends Serializer<LinkKey> { /** * Creates {@link LinkKey} serializer instance. */ public LinkKeySerializer() { // non-null, immutable super(false, true); } @Override public void write(Kryo kryo, Output output, LinkKey object) { kryo.writeClassAndObject(output, object.src()); kryo.writeClassAndObject(output, object.dst()); } @Override public LinkKey read(Kryo kryo, Input input, Class<LinkKey> type) { ConnectPoint src = (ConnectPoint) kryo.readClassAndObject(input); ConnectPoint dst = (ConnectPoint) kryo.readClassAndObject(input); return LinkKey.linkKey(src, dst); } }
apache-2.0
qwerty4030/elasticsearch
test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java
5796
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.rest.yaml.section; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.yaml.YamlXContent; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Holds a REST test suite loaded from a specific yaml file. * Supports a setup section and multiple test sections. */ public class ClientYamlTestSuite { public static ClientYamlTestSuite parse(String api, Path file) throws IOException { if (!Files.isRegularFile(file)) { throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file"); } String filename = file.getFileName().toString(); //remove the file extension int i = filename.lastIndexOf('.'); if (i > 0) { filename = filename.substring(0, i); } //our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break. try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.wrap(new byte[1]); if (channel.size() == 0) { throw new IllegalArgumentException("test suite file " + file.toString() + " is empty"); } channel.read(bb, channel.size() - 1); if (bb.get(0) != 10) { throw new IOException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)"); } } try (XContentParser parser = YamlXContent.yamlXContent.createParser(ExecutableSection.XCONTENT_REGISTRY, LoggingDeprecationHandler.INSTANCE, Files.newInputStream(file))) { return parse(api, filename, parser); } catch(Exception e) { throw new IOException("Error parsing " + api + "/" + filename, e); } } public static ClientYamlTestSuite parse(String api, String suiteName, XContentParser parser) throws IOException { parser.nextToken(); assert parser.currentToken() == XContentParser.Token.START_OBJECT : "expected token to be START_OBJECT but was " + parser.currentToken(); ClientYamlTestSuite restTestSuite = new ClientYamlTestSuite(api, suiteName); restTestSuite.setSetupSection(SetupSection.parseIfNext(parser)); restTestSuite.setTeardownSection(TeardownSection.parseIfNext(parser)); while(true) { //the "---" section separator is not understood by the yaml parser. null is returned, same as when the parser is closed //we need to somehow distinguish between a null in the middle of a test ("---") // and a null at the end of the file (at least two consecutive null tokens) if(parser.currentToken() == null) { if (parser.nextToken() == null) { break; } } ClientYamlTestSection testSection = ClientYamlTestSection.parse(parser); if (!restTestSuite.addTestSection(testSection)) { throw new ParsingException(testSection.getLocation(), "duplicate test section [" + testSection.getName() + "]"); } } return restTestSuite; } private final String api; private final String name; private SetupSection setupSection; private TeardownSection teardownSection; private Set<ClientYamlTestSection> testSections = new TreeSet<>(); public ClientYamlTestSuite(String api, String name) { this.api = api; this.name = name; } public String getApi() { return api; } public String getName() { return name; } public String getPath() { return api + "/" + name; } public SetupSection getSetupSection() { return setupSection; } public void setSetupSection(SetupSection setupSection) { this.setupSection = setupSection; } public TeardownSection getTeardownSection() { return teardownSection; } public void setTeardownSection(TeardownSection teardownSection) { this.teardownSection = teardownSection; } /** * Adds a {@link org.elasticsearch.test.rest.yaml.section.ClientYamlTestSection} to the REST suite * @return true if the test section was not already present, false otherwise */ public boolean addTestSection(ClientYamlTestSection testSection) { return this.testSections.add(testSection); } public List<ClientYamlTestSection> getTestSections() { return new ArrayList<>(testSections); } }
apache-2.0
milleruntime/accumulo
shell/src/main/java/org/apache/accumulo/shell/commands/ConstraintCommand.java
5893
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.shell.commands; import java.util.Map.Entry; import org.apache.accumulo.core.data.constraints.Constraint; import org.apache.accumulo.shell.Shell; import org.apache.accumulo.shell.Shell.Command; import org.apache.accumulo.shell.ShellCommandException; import org.apache.accumulo.shell.ShellCommandException.ErrorCode; import org.apache.accumulo.shell.ShellOptions; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; public class ConstraintCommand extends Command { protected Option namespaceOpt; @Override public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { final String tableName; final String namespace; if (cl.hasOption(namespaceOpt.getOpt())) { namespace = cl.getOptionValue(namespaceOpt.getOpt()); } else { namespace = null; } if (cl.hasOption(OptUtil.tableOpt().getOpt()) || !shellState.getTableName().isEmpty()) { tableName = OptUtil.getTableOpt(cl, shellState); } else { tableName = null; } int i; switch (OptUtil.getAldOpt(cl)) { case ADD: for (String constraint : cl.getArgs()) { if (namespace != null) { if (!shellState.getAccumuloClient().namespaceOperations().testClassLoad(namespace, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().namespaceOperations().addConstraint(namespace, constraint); shellState.getWriter().println("Added constraint " + constraint + " to namespace " + namespace + " with number " + i); } else if (tableName != null && !tableName.isEmpty()) { if (!shellState.getAccumuloClient().tableOperations().testClassLoad(tableName, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().tableOperations().addConstraint(tableName, constraint); shellState.getWriter().println( "Added constraint " + constraint + " to table " + tableName + " with number " + i); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case DELETE: for (String constraint : cl.getArgs()) { i = Integer.parseInt(constraint); if (namespace != null) { shellState.getAccumuloClient().namespaceOperations().removeConstraint(namespace, i); shellState.getWriter() .println("Removed constraint " + i + " from namespace " + namespace); } else if (tableName != null) { shellState.getAccumuloClient().tableOperations().removeConstraint(tableName, i); shellState.getWriter().println("Removed constraint " + i + " from table " + tableName); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case LIST: if (namespace != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().namespaceOperations() .listConstraints(namespace).entrySet()) { shellState.getWriter().println(property.toString()); } } else if (tableName != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().tableOperations() .listConstraints(tableName).entrySet()) { shellState.getWriter().println(property.toString()); } } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } return 0; } @Override public String description() { return "adds, deletes, or lists constraints for a table"; } @Override public int numArgs() { return Shell.NO_FIXED_ARG_LENGTH_CHECK; } @Override public String usage() { return getName() + " <constraint>{ <constraint>}"; } @Override public Options getOptions() { final Options o = new Options(); o.addOptionGroup(OptUtil.addListDeleteGroup("constraint")); OptionGroup grp = new OptionGroup(); grp.addOption(OptUtil.tableOpt("table to add, delete, or list constraints for")); namespaceOpt = new Option(ShellOptions.namespaceOption, "namespace", true, "name of a namespace to operate on"); namespaceOpt.setArgName("namespace"); grp.addOption(namespaceOpt); o.addOptionGroup(grp); return o; } }
apache-2.0
liveqmock/platform-tools-idea
platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java
4403
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui; import com.intellij.util.PairFunction; import com.intellij.util.containers.Convertor; import javax.swing.*; import javax.swing.table.TableModel; import java.util.ListIterator; public class TableSpeedSearch extends SpeedSearchBase<JTable> { private static final PairFunction<Object, Cell, String> TO_STRING = new PairFunction<Object, Cell, String>() { public String fun(Object o, Cell cell) { return o == null ? "" : o.toString(); } }; private final PairFunction<Object, Cell, String> myToStringConvertor; public TableSpeedSearch(JTable table) { this(table, TO_STRING); } public TableSpeedSearch(JTable table, final Convertor<Object, String> toStringConvertor) { this(table, new PairFunction<Object, Cell, String>() { @Override public String fun(Object o, Cell c) { return toStringConvertor.convert(o); } }); } public TableSpeedSearch(JTable table, final PairFunction<Object, Cell, String> toStringConvertor) { super(table); myToStringConvertor = toStringConvertor; } protected boolean isSpeedSearchEnabled() { return !getComponent().isEditing() && super.isSpeedSearchEnabled(); } @Override protected ListIterator<Object> getElementIterator(int startingIndex) { return new MyListIterator(startingIndex); } protected int getElementCount() { final TableModel tableModel = myComponent.getModel(); return tableModel.getRowCount() * tableModel.getColumnCount(); } protected void selectElement(Object element, String selectedText) { final int index = ((Integer)element).intValue(); final TableModel model = myComponent.getModel(); final int row = index / model.getColumnCount(); final int col = index % model.getColumnCount(); myComponent.getSelectionModel().setSelectionInterval(row, row); myComponent.getColumnModel().getSelectionModel().setSelectionInterval(col, col); TableUtil.scrollSelectionToVisible(myComponent); } protected int getSelectedIndex() { final int row = myComponent.getSelectedRow(); final int col = myComponent.getSelectedColumn(); // selected row is not enough as we want to select specific cell in a large multi-column table return row > -1 && col > -1 ? row * myComponent.getModel().getColumnCount() + col : -1; } protected Object[] getAllElements() { throw new UnsupportedOperationException("Not implemented"); } protected String getElementText(Object element) { final int index = ((Integer)element).intValue(); final TableModel model = myComponent.getModel(); int row = myComponent.convertRowIndexToModel(index / model.getColumnCount()); int col = myComponent.convertColumnIndexToModel(index % model.getColumnCount()); Object value = model.getValueAt(row, col); return myToStringConvertor.fun(value, new Cell(row, col)); } private class MyListIterator implements ListIterator<Object> { private int myCursor; public MyListIterator(int startingIndex) { final int total = getElementCount(); myCursor = startingIndex < 0 ? total : startingIndex; } public boolean hasNext() { return myCursor < getElementCount(); } public Object next() { return myCursor++; } public boolean hasPrevious() { return myCursor > 0; } public Object previous() { return (myCursor--) - 1; } public int nextIndex() { return myCursor; } public int previousIndex() { return myCursor - 1; } public void remove() { throw new AssertionError("Not Implemented"); } public void set(Object o) { throw new AssertionError("Not Implemented"); } public void add(Object o) { throw new AssertionError("Not Implemented"); } } }
apache-2.0
bclozel/spring-boot
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolver.java
3528
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.web; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; /** * A resolver for {@link Link links} to web endpoints. * * @author Andy Wilkinson * @since 2.0.0 */ public class EndpointLinksResolver { private static final Log logger = LogFactory.getLog(EndpointLinksResolver.class); private final Collection<? extends ExposableEndpoint<?>> endpoints; /** * Creates a new {@code EndpointLinksResolver} that will resolve links to the given * {@code endpoints}. * @param endpoints the endpoints */ public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints) { this.endpoints = endpoints; } /** * Creates a new {@code EndpointLinksResolver} that will resolve links to the given * {@code endpoints} that are exposed beneath the given {@code basePath}. * @param endpoints the endpoints * @param basePath the basePath */ public EndpointLinksResolver(Collection<? extends ExposableEndpoint<?>> endpoints, String basePath) { this.endpoints = endpoints; if (logger.isInfoEnabled()) { logger.info("Exposing " + endpoints.size() + " endpoint(s) beneath base path '" + basePath + "'"); } } /** * Resolves links to the known endpoints based on a request with the given * {@code requestUrl}. * @param requestUrl the url of the request for the endpoint links * @return the links */ public Map<String, Link> resolveLinks(String requestUrl) { String normalizedUrl = normalizeRequestUrl(requestUrl); Map<String, Link> links = new LinkedHashMap<>(); links.put("self", new Link(normalizedUrl)); for (ExposableEndpoint<?> endpoint : this.endpoints) { if (endpoint instanceof ExposableWebEndpoint) { collectLinks(links, (ExposableWebEndpoint) endpoint, normalizedUrl); } else if (endpoint instanceof PathMappedEndpoint) { links.put(endpoint.getId(), createLink(normalizedUrl, ((PathMappedEndpoint) endpoint).getRootPath())); } } return links; } private String normalizeRequestUrl(String requestUrl) { if (requestUrl.endsWith("/")) { return requestUrl.substring(0, requestUrl.length() - 1); } return requestUrl; } private void collectLinks(Map<String, Link> links, ExposableWebEndpoint endpoint, String normalizedUrl) { for (WebOperation operation : endpoint.getOperations()) { links.put(operation.getId(), createLink(normalizedUrl, operation)); } } private Link createLink(String requestUrl, WebOperation operation) { return createLink(requestUrl, operation.getRequestPredicate().getPath()); } private Link createLink(String requestUrl, String path) { return new Link(requestUrl + (path.startsWith("/") ? path : "/" + path)); } }
apache-2.0
tomatoKiller/Hadoop_Source_Learn
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
11919
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager.containermanager; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.yarn.api.ContainerManagementProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.AsyncDispatcher; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.security.NMTokenIdentifier; import org.apache.hadoop.yarn.server.api.ResourceTracker; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; import org.apache.hadoop.yarn.server.nodemanager.LocalRMInterface; import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService; import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater; import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationState; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics; import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager; import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.junit.After; import org.junit.Before; public abstract class BaseContainerManagerTest { protected static RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); protected static FileContext localFS; protected static File localDir; protected static File localLogDir; protected static File remoteLogDir; protected static File tmpDir; protected final NodeManagerMetrics metrics = NodeManagerMetrics.create(); public BaseContainerManagerTest() throws UnsupportedFileSystemException { localFS = FileContext.getLocalFSFileContext(); localDir = new File("target", this.getClass().getSimpleName() + "-localDir") .getAbsoluteFile(); localLogDir = new File("target", this.getClass().getSimpleName() + "-localLogDir") .getAbsoluteFile(); remoteLogDir = new File("target", this.getClass().getSimpleName() + "-remoteLogDir") .getAbsoluteFile(); tmpDir = new File("target", this.getClass().getSimpleName() + "-tmpDir"); } protected static Log LOG = LogFactory .getLog(BaseContainerManagerTest.class); protected static final int HTTP_PORT = 5412; protected Configuration conf = new YarnConfiguration(); protected Context context = new NMContext(new NMContainerTokenSecretManager( conf), new NMTokenSecretManagerInNM()) { public int getHttpPort() { return HTTP_PORT; }; }; protected ContainerExecutor exec; protected DeletionService delSrvc; protected String user = "nobody"; protected NodeHealthCheckerService nodeHealthChecker; protected LocalDirsHandlerService dirsHandler; protected final long DUMMY_RM_IDENTIFIER = 1234; protected NodeStatusUpdater nodeStatusUpdater = new NodeStatusUpdaterImpl( context, new AsyncDispatcher(), null, metrics) { @Override protected ResourceTracker getRMClient() { return new LocalRMInterface(); }; @Override protected void stopRMProxy() { return; } @Override protected void startStatusUpdater() { return; // Don't start any updating thread. } @Override public long getRMIdentifier() { // There is no real RM registration, simulate and set RMIdentifier return DUMMY_RM_IDENTIFIER; } }; protected ContainerManagerImpl containerManager = null; protected ContainerExecutor createContainerExecutor() { DefaultContainerExecutor exec = new DefaultContainerExecutor(); exec.setConf(conf); return exec; } @Before public void setup() throws IOException { localFS.delete(new Path(localDir.getAbsolutePath()), true); localFS.delete(new Path(tmpDir.getAbsolutePath()), true); localFS.delete(new Path(localLogDir.getAbsolutePath()), true); localFS.delete(new Path(remoteLogDir.getAbsolutePath()), true); localDir.mkdir(); tmpDir.mkdir(); localLogDir.mkdir(); remoteLogDir.mkdir(); LOG.info("Created localDir in " + localDir.getAbsolutePath()); LOG.info("Created tmpDir in " + tmpDir.getAbsolutePath()); String bindAddress = "0.0.0.0:12345"; conf.set(YarnConfiguration.NM_ADDRESS, bindAddress); conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath()); conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, remoteLogDir.getAbsolutePath()); conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1); // Default delSrvc delSrvc = createDeletionService(); delSrvc.init(conf); exec = createContainerExecutor(); nodeHealthChecker = new NodeHealthCheckerService(); nodeHealthChecker.init(conf); dirsHandler = nodeHealthChecker.getDiskHandler(); containerManager = createContainerManager(delSrvc); ((NMContext)context).setContainerManager(containerManager); nodeStatusUpdater.init(conf); containerManager.init(conf); nodeStatusUpdater.start(); } protected ContainerManagerImpl createContainerManager(DeletionService delSrvc) { return new ContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater, metrics, new ApplicationACLsManager(conf), dirsHandler) { @Override public void setBlockNewContainerRequests(boolean blockNewContainerRequests) { // do nothing } @Override protected void authorizeGetAndStopContainerRequest(ContainerId containerId, Container container, boolean stopRequest, NMTokenIdentifier identifier) throws YarnException { // do nothing } @Override protected void authorizeUser(UserGroupInformation remoteUgi, NMTokenIdentifier nmTokenIdentifier) { // do nothing } @Override protected void authorizeStartRequest( NMTokenIdentifier nmTokenIdentifier, ContainerTokenIdentifier containerTokenIdentifier) throws YarnException { // do nothing } @Override protected void updateNMTokenIdentifier( NMTokenIdentifier nmTokenIdentifier) throws InvalidToken { // Do nothing } @Override public Map<String, ByteBuffer> getAuxServiceMetaData() { Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>(); serviceData.put("AuxService1", ByteBuffer.wrap("AuxServiceMetaData1".getBytes())); serviceData.put("AuxService2", ByteBuffer.wrap("AuxServiceMetaData2".getBytes())); return serviceData; } }; } protected DeletionService createDeletionService() { return new DeletionService(exec) { @Override public void delete(String user, Path subDir, Path[] baseDirs) { // Don't do any deletions. LOG.info("Psuedo delete: user - " + user + ", subDir - " + subDir + ", baseDirs - " + baseDirs); }; }; } @After public void tearDown() throws IOException, InterruptedException { if (containerManager != null) { containerManager.stop(); } createContainerExecutor().deleteAsUser(user, new Path(localDir.getAbsolutePath()), new Path[] {}); } public static void waitForContainerState(ContainerManagementProtocol containerManager, ContainerId containerID, ContainerState finalState) throws InterruptedException, YarnException, IOException { waitForContainerState(containerManager, containerID, finalState, 20); } public static void waitForContainerState(ContainerManagementProtocol containerManager, ContainerId containerID, ContainerState finalState, int timeOutMax) throws InterruptedException, YarnException, IOException { List<ContainerId> list = new ArrayList<ContainerId>(); list.add(containerID); GetContainerStatusesRequest request = GetContainerStatusesRequest.newInstance(list); ContainerStatus containerStatus = containerManager.getContainerStatuses(request).getContainerStatuses() .get(0); int timeoutSecs = 0; while (!containerStatus.getState().equals(finalState) && timeoutSecs++ < timeOutMax) { Thread.sleep(1000); LOG.info("Waiting for container to get into state " + finalState + ". Current state is " + containerStatus.getState()); containerStatus = containerManager.getContainerStatuses(request).getContainerStatuses().get(0); } LOG.info("Container state is " + containerStatus.getState()); Assert.assertEquals("ContainerState is not correct (timedout)", finalState, containerStatus.getState()); } static void waitForApplicationState(ContainerManagerImpl containerManager, ApplicationId appID, ApplicationState finalState) throws InterruptedException { // Wait for app-finish Application app = containerManager.getContext().getApplications().get(appID); int timeout = 0; while (!(app.getApplicationState().equals(finalState)) && timeout++ < 15) { LOG.info("Waiting for app to reach " + finalState + ".. Current state is " + app.getApplicationState()); Thread.sleep(1000); } Assert.assertTrue("App is not in " + finalState + " yet!! Timedout!!", app.getApplicationState().equals(finalState)); } }
apache-2.0
electrum/presto
service/trino-proxy/src/main/java/io/trino/proxy/ProxyConfig.java
1534
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.proxy; import io.airlift.configuration.Config; import io.airlift.configuration.ConfigDescription; import io.airlift.configuration.validation.FileExists; import javax.validation.constraints.NotNull; import java.io.File; import java.net.URI; public class ProxyConfig { private URI uri; private File sharedSecretFile; @NotNull public URI getUri() { return uri; } @Config("proxy.uri") @ConfigDescription("URI of the remote Trino server") public ProxyConfig setUri(URI uri) { this.uri = uri; return this; } @NotNull @FileExists public File getSharedSecretFile() { return sharedSecretFile; } @Config("proxy.shared-secret-file") @ConfigDescription("Shared secret file used for authenticating URIs") public ProxyConfig setSharedSecretFile(File sharedSecretFile) { this.sharedSecretFile = sharedSecretFile; return this; } }
apache-2.0
tkopczynski/camel
components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpComponent.java
2487
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.mllp; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; /** * Represents the component that manages {@link MllpEndpoint}. */ public class MllpComponent extends UriEndpointComponent { public static final String MLLP_LOG_PHI_PROPERTY = "org.apache.camel.component.mllp.logPHI"; public MllpComponent() { super(MllpEndpoint.class); } public MllpComponent(CamelContext context) { super(context, MllpEndpoint.class); } protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { MllpEndpoint endpoint = new MllpEndpoint(uri, this); setProperties(endpoint, parameters); // mllp://hostname:port String hostPort; // look for options int optionsStartIndex = uri.indexOf('?'); if (-1 == optionsStartIndex) { // No options - just get the host/port stuff hostPort = uri.substring(7); } else { hostPort = uri.substring(7, optionsStartIndex); } // Make sure it has a host - may just be a port int colonIndex = hostPort.indexOf(':'); if (-1 != colonIndex) { endpoint.setHostname(hostPort.substring(0, colonIndex)); endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1))); } else { // No host specified - leave the default host and set the port endpoint.setPort(Integer.parseInt(hostPort.substring(colonIndex + 1))); } return endpoint; } }
apache-2.0
electrum/presto
core/trino-main/src/test/java/io/trino/sql/planner/assertions/ExpressionMatcher.java
3920
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.assertions; import com.google.common.collect.ImmutableList; import io.trino.Session; import io.trino.metadata.Metadata; import io.trino.sql.parser.ParsingOptions; import io.trino.sql.parser.SqlParser; import io.trino.sql.planner.Symbol; import io.trino.sql.planner.plan.ApplyNode; import io.trino.sql.planner.plan.PlanNode; import io.trino.sql.planner.plan.ProjectNode; import io.trino.sql.tree.Expression; import io.trino.sql.tree.InPredicate; import io.trino.sql.tree.SymbolReference; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkState; import static io.trino.sql.ExpressionUtils.rewriteIdentifiersToSymbolReferences; import static java.util.Objects.requireNonNull; public class ExpressionMatcher implements RvalueMatcher { private final String sql; private final Expression expression; public ExpressionMatcher(String expression) { this.sql = requireNonNull(expression, "expression is null"); this.expression = expression(expression); } public ExpressionMatcher(Expression expression) { this.expression = requireNonNull(expression, "expression is null"); this.sql = expression.toString(); } private Expression expression(String sql) { SqlParser parser = new SqlParser(); return rewriteIdentifiersToSymbolReferences(parser.createExpression(sql, new ParsingOptions())); } public static ExpressionMatcher inPredicate(SymbolReference value, SymbolReference valueList) { return new ExpressionMatcher(new InPredicate(value, valueList)); } @Override public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) { Optional<Symbol> result = Optional.empty(); ImmutableList.Builder<Expression> matchesBuilder = ImmutableList.builder(); Map<Symbol, Expression> assignments = getAssignments(node); if (assignments == null) { return result; } ExpressionVerifier verifier = new ExpressionVerifier(symbolAliases); for (Map.Entry<Symbol, Expression> assignment : assignments.entrySet()) { if (verifier.process(assignment.getValue(), expression)) { result = Optional.of(assignment.getKey()); matchesBuilder.add(assignment.getValue()); } } List<Expression> matches = matchesBuilder.build(); checkState(matches.size() < 2, "Ambiguous expression %s matches multiple assignments", expression, (matches.stream().map(Expression::toString).collect(Collectors.joining(", ")))); return result; } private static Map<Symbol, Expression> getAssignments(PlanNode node) { if (node instanceof ProjectNode) { ProjectNode projectNode = (ProjectNode) node; return projectNode.getAssignments().getMap(); } else if (node instanceof ApplyNode) { ApplyNode applyNode = (ApplyNode) node; return applyNode.getSubqueryAssignments().getMap(); } else { return null; } } @Override public String toString() { return sql; } }
apache-2.0
damienmg/bazel
src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
12016
// Copyright 2010 The Bazel Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.junit.runner.sharding.testing; import static com.google.common.truth.Truth.assertThat; import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; /** * Common base class for all sharding filter tests. */ public abstract class ShardingFilterTestCase extends TestCase { static final List<Description> TEST_DESCRIPTIONS = createGenericTestCaseDescriptions(6); /** * Returns a filter of the subclass type using the given descriptions, * shard index, and total number of shards. */ protected abstract ShardingFilterFactory createShardingFilterFactory(); public final void testShardingIsCompleteAndPartitioned_oneShard() { assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 1), TEST_DESCRIPTIONS); } public final void testShardingIsStable_oneShard() { assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 1), TEST_DESCRIPTIONS); } public final void testShardingIsCompleteAndPartitioned_moreTestsThanShards() { assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 5), TEST_DESCRIPTIONS); } public final void testShardingIsStable_moreTestsThanShards() { assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 5), TEST_DESCRIPTIONS); } public final void testShardingIsCompleteAndPartitioned_sameNumberOfTestsAndShards() { assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 6), TEST_DESCRIPTIONS); } public final void testShardingIsStable_sameNumberOfTestsAndShards() { assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 6), TEST_DESCRIPTIONS); } public final void testShardingIsCompleteAndPartitioned_moreShardsThanTests() { assertShardingIsCompleteAndPartitioned(createFilters(TEST_DESCRIPTIONS, 7), TEST_DESCRIPTIONS); } public final void testShardingIsStable_moreShardsThanTests() { assertShardingIsStable(createFilters(TEST_DESCRIPTIONS, 7), TEST_DESCRIPTIONS); } public final void testShardingIsCompleteAndPartitioned_duplicateDescriptions() { List<Description> descriptions = new ArrayList<>(); descriptions.addAll(createGenericTestCaseDescriptions(6)); descriptions.addAll(createGenericTestCaseDescriptions(6)); assertShardingIsCompleteAndPartitioned(createFilters(descriptions, 7), descriptions); } public final void testShardingIsStable_duplicateDescriptions() { List<Description> descriptions = new ArrayList<>(); descriptions.addAll(createGenericTestCaseDescriptions(6)); descriptions.addAll(createGenericTestCaseDescriptions(6)); assertShardingIsStable(createFilters(descriptions, 7), descriptions); } public final void testShouldRunTestSuite() { Description testSuiteDescription = createTestSuiteDescription(); Filter filter = createShardingFilterFactory().createFilter(TEST_DESCRIPTIONS, 0, 1); assertThat(filter.shouldRun(testSuiteDescription)).isTrue(); } /** * Creates a list of generic test case descriptions. * * @param numDescriptions the number of generic test descriptions to add to the list. */ public static List<Description> createGenericTestCaseDescriptions(int numDescriptions) { List<Description> descriptions = new ArrayList<>(); for (int i = 0; i < numDescriptions; i++) { descriptions.add(Description.createTestDescription(Test.class, "test" + i)); } return descriptions; } protected static final List<Filter> createFilters(List<Description> descriptions, int numShards, ShardingFilterFactory factory) { List<Filter> filters = new ArrayList<>(); for (int shardIndex = 0; shardIndex < numShards; shardIndex++) { filters.add(factory.createFilter(descriptions, shardIndex, numShards)); } return filters; } protected final List<Filter> createFilters(List<Description> descriptions, int numShards) { return createFilters(descriptions, numShards, createShardingFilterFactory()); } protected static void assertThrowsExceptionForUnknownDescription(Filter filter) { try { filter.shouldRun(Description.createTestDescription(Object.class, "unknown")); fail("expected thrown exception"); } catch (IllegalArgumentException expected) { } } /** * Simulates test sharding with the given filters and test descriptions. * * @param filters a list of filters, one per test shard * @param descriptions a list of test descriptions * @return a mapping from each filter to the descriptions of the tests that would be run * by the shard associated with that filter. */ protected static Map<Filter, List<Description>> simulateTestRun(List<Filter> filters, List<Description> descriptions) { Map<Filter, List<Description>> descriptionsRun = new HashMap<>(); for (Filter filter : filters) { for (Description description : descriptions) { if (filter.shouldRun(description)) { addDescriptionForFilterToMap(descriptionsRun, filter, description); } } } return descriptionsRun; } /** * Simulates test sharding with the given filters and test descriptions, for a * set of test descriptions that is in a different order in every test shard. * * @param filters a list of filters, one per test shard * @param descriptions a list of test descriptions * @return a mapping from each filter to the descriptions of the tests that would be run * by the shard associated with that filter. */ protected static Map<Filter, List<Description>> simulateSelfRandomizingTestRun( List<Filter> filters, List<Description> descriptions) { if (descriptions.isEmpty()) { return new HashMap<>(); } Deque<Description> mutatingDescriptions = new LinkedList<>(descriptions); Map<Filter, List<Description>> descriptionsRun = new HashMap<>(); for (Filter filter : filters) { // rotate the queue so that each filter gets the descriptions in a different order mutatingDescriptions.addLast(mutatingDescriptions.pollFirst()); for (Description description : descriptions) { if (filter.shouldRun(description)) { addDescriptionForFilterToMap(descriptionsRun, filter, description); } } } return descriptionsRun; } /** * Creates a test suite description (a Description that returns true * when {@link org.junit.runner.Description#isSuite()} is called.) */ protected static Description createTestSuiteDescription() { Description testSuiteDescription = Description.createSuiteDescription("testSuite"); testSuiteDescription.addChild(Description.createSuiteDescription("testCase")); return testSuiteDescription; } /** * Tests that the sharding is complete (each test is run at least once) and * partitioned (each test is run at most once) -- in other words, that * each test is run exactly once. This is a requirement of all test * sharding functions. */ protected static void assertShardingIsCompleteAndPartitioned(List<Filter> filters, List<Description> descriptions) { Map<Filter, List<Description>> run = simulateTestRun(filters, descriptions); assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions); run = simulateSelfRandomizingTestRun(filters, descriptions); assertThatCollectionContainsExactlyElementsInList(getAllValuesInMap(run), descriptions); } /** * Tests that sharding is stable for the given filters, regardless of the * ordering of the descriptions. This is useful for verifying that sharding * works with self-randomizing test suites, and a requirement of all test * sharding functions. */ protected static void assertShardingIsStable( List<Filter> filters, List<Description> descriptions) { Map<Filter, List<Description>> run1 = simulateTestRun(filters, descriptions); Map<Filter, List<Description>> run2 = simulateTestRun(filters, descriptions); assertThat(run2).isEqualTo(run1); Map<Filter, List<Description>> randomizedRun1 = simulateSelfRandomizingTestRun(filters, descriptions); Map<Filter, List<Description>> randomizedRun2 = simulateSelfRandomizingTestRun(filters, descriptions); assertThat(randomizedRun2).isEqualTo(randomizedRun1); } private static void addDescriptionForFilterToMap( Map<Filter, List<Description>> descriptionsRun, Filter filter, Description description) { List<Description> descriptions = descriptionsRun.get(filter); if (descriptions == null) { descriptions = new ArrayList<>(); descriptionsRun.put(filter, descriptions); } descriptions.add(description); } private static Collection<Description> getAllValuesInMap(Map<Filter, List<Description>> map) { Collection<Description> allDescriptions = new ArrayList<>(); for (List<Description> descriptions : map.values()) { allDescriptions.addAll(descriptions); } return allDescriptions; } /** * Returns whether the Collection and the List contain exactly the same elements with the same * frequency, ignoring the ordering. */ private static void assertThatCollectionContainsExactlyElementsInList( Collection<Description> actual, List<Description> expectedDescriptions) { String basicAssertionMessage = "Elements of collection " + actual + " are not the same as the " + "elements of expected list " + expectedDescriptions + ". "; if (actual.size() != expectedDescriptions.size()) { throw new AssertionError(basicAssertionMessage + "The number of elements is different."); } List<Description> actualDescriptions = new ArrayList<Description>(actual); // Keeps track of already reviewed descriptions, so they won't be checked again when next // encountered. // Note: this algorithm has O(n^2) time complexity and will be slow for large inputs. Set<Description> reviewedDescriptions = new HashSet<>(); for (int i = 0; i < actual.size(); i++) { Description currDescription = actualDescriptions.get(i); // If already reviewed, skip. if (reviewedDescriptions.contains(currDescription)) { continue; } int actualFreq = 0; int expectedFreq = 0; // Count the frequency of the current description in both lists. for (int j = 0; j < actual.size(); j++) { if (currDescription.equals(actualDescriptions.get(j))) { actualFreq++; } if (currDescription.equals(expectedDescriptions.get(j))) { expectedFreq++; } } if (actualFreq < expectedFreq) { throw new AssertionError(basicAssertionMessage + "There are " + (expectedFreq - actualFreq) + " missing occurrences of " + currDescription + "."); } else if (actualFreq > expectedFreq) { throw new AssertionError(basicAssertionMessage + "There are " + (actualFreq - expectedFreq) + " unexpected occurrences of " + currDescription + "."); } reviewedDescriptions.add(currDescription); } } }
apache-2.0
gkatsikas/onos
core/api/src/main/java/org/onosproject/store/service/Version.java
2369
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.service; import java.util.Objects; import com.google.common.base.MoreObjects; import com.google.common.collect.ComparisonChain; import org.onosproject.store.Timestamp; import static com.google.common.base.Preconditions.checkArgument; /** * Logical timestamp for versions. * <p> * The version is a logical timestamp that represents a point in logical time at which an event occurs. * This is used in both pessimistic and optimistic locking protocols to ensure that the state of a shared resource * has not changed at the end of a transaction. */ public class Version implements Timestamp { private final long version; public Version(long version) { this.version = version; } @Override public int compareTo(Timestamp o) { checkArgument(o instanceof Version, "Must be LockVersion", o); Version that = (Version) o; return ComparisonChain.start() .compare(this.version, that.version) .result(); } @Override public int hashCode() { return Long.hashCode(version); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Version)) { return false; } Version that = (Version) obj; return Objects.equals(this.version, that.version); } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("version", version) .toString(); } /** * Returns the lock version. * * @return the lock version */ public long value() { return this.version; } }
apache-2.0
gstevey/gradle
subprojects/platform-native/src/main/java/org/gradle/nativeplatform/internal/NativeBinarySpecInternal.java
2517
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.nativeplatform.internal; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.language.nativeplatform.DependentSourceSet; import org.gradle.nativeplatform.*; import org.gradle.nativeplatform.internal.resolve.NativeBinaryRequirementResolveResult; import org.gradle.nativeplatform.internal.resolve.NativeDependencyResolver; import org.gradle.nativeplatform.platform.NativePlatform; import org.gradle.nativeplatform.toolchain.NativeToolChain; import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider; import org.gradle.nativeplatform.toolchain.internal.PreCompiledHeader; import org.gradle.platform.base.internal.BinarySpecInternal; import java.io.File; import java.util.Collection; import java.util.Map; public interface NativeBinarySpecInternal extends NativeBinarySpec, BinarySpecInternal { void setFlavor(Flavor flavor); void setToolChain(NativeToolChain toolChain); void setTargetPlatform(NativePlatform targetPlatform); void setBuildType(BuildType buildType); Tool getToolByName(String name); PlatformToolProvider getPlatformToolProvider(); void setPlatformToolProvider(PlatformToolProvider toolProvider); void setResolver(NativeDependencyResolver resolver); void setFileCollectionFactory(FileCollectionFactory fileCollectionFactory); File getPrimaryOutput(); Collection<NativeDependencySet> getLibs(DependentSourceSet sourceSet); Collection<NativeLibraryBinary> getDependentBinaries(); /** * Adds some files to include as input to the link/assemble step of this binary. */ void binaryInputs(FileCollection files); Collection<NativeBinaryRequirementResolveResult> getAllResolutions(); Map<File, PreCompiledHeader> getPrefixFileToPCH(); void addPreCompiledHeaderFor(DependentSourceSet sourceSet); }
apache-2.0
sanyaade-g2g-repos/orientdb
core/src/main/java/com/orientechnologies/orient/core/engine/local/OEngineLocalPaginated.java
2893
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.core.engine.local; import java.util.Map; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.engine.OEngineAbstract; import com.orientechnologies.orient.core.exception.ODatabaseException; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.storage.cache.local.O2QCache; import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage; /** * @author Andrey Lomakin * @since 28.03.13 */ public class OEngineLocalPaginated extends OEngineAbstract { public static final String NAME = "plocal"; private final O2QCache readCache; public OEngineLocalPaginated() { readCache = new O2QCache( (long) (OGlobalConfiguration.DISK_CACHE_SIZE.getValueAsLong() * 1024 * 1024 * ((100 - OGlobalConfiguration.DISK_WRITE_CACHE_PART .getValueAsInteger()) / 100.0)), OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, true); try { readCache.registerMBean(); } catch (Exception e) { OLogManager.instance().error(this, "MBean for read cache cannot be registered", e); } } public OStorage createStorage(final String dbName, final Map<String, String> configuration) { try { // GET THE STORAGE return new OLocalPaginatedStorage(dbName, dbName, getMode(configuration), generateStorageId(), readCache); } catch (Throwable t) { OLogManager.instance().error(this, "Error on opening database: " + dbName + ". Current location is: " + new java.io.File(".").getAbsolutePath(), t, ODatabaseException.class); } return null; } public String getName() { return NAME; } public boolean isShared() { return true; } @Override public void shutdown() { super.shutdown(); readCache.clear(); try { readCache.unregisterMBean(); } catch (Exception e) { OLogManager.instance().error(this, "MBean for read cache cannot be unregistered", e); } } }
apache-2.0
ty1er/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-storage-am-common/src/main/java/org/apache/hyracks/storage/am/common/api/ITreeIndexMetadataFrameFactory.java
976
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.storage.am.common.api; @FunctionalInterface public interface ITreeIndexMetadataFrameFactory { ITreeIndexMetadataFrame createFrame(); }
apache-2.0
parthchandra/incubator-drill
exec/jdbc/src/test/java/org/apache/drill/jdbc/test/JdbcDataTest.java
19946
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.jdbc.test; import java.io.IOException; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.Statement; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import org.apache.calcite.rel.core.JoinRelType; import org.apache.drill.common.logical.LogicalPlan; import org.apache.drill.common.logical.PlanProperties; import org.apache.drill.common.logical.StoragePluginConfig; import org.apache.drill.common.logical.data.Filter; import org.apache.drill.common.logical.data.Join; import org.apache.drill.common.logical.data.Limit; import org.apache.drill.common.logical.data.LogicalOperator; import org.apache.drill.common.logical.data.Order; import org.apache.drill.common.logical.data.Project; import org.apache.drill.common.logical.data.Scan; import org.apache.drill.common.logical.data.Store; import org.apache.drill.common.logical.data.Union; import org.apache.drill.jdbc.JdbcTestBase; import org.apache.drill.categories.JdbcTest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.io.Resources; import org.junit.experimental.categories.Category; /** Unit tests for Drill's JDBC driver. */ @Ignore // ignore for now. @Category(JdbcTest.class) public class JdbcDataTest extends JdbcTestBase { private static String MODEL; private static String EXPECTED; @BeforeClass public static void setupFixtures() throws IOException { MODEL = Resources.toString(Resources.getResource("test-models.json"), Charsets.UTF_8); EXPECTED = Resources.toString(Resources.getResource("donuts-output-data.txt"), Charsets.UTF_8); } /** * Command-line utility to execute a logical plan. * * <p> * The forwarding method ensures that the IDE calls this method with the right classpath. * </p> */ public static void main(String[] args) throws Exception { } /** Load driver. */ @Test public void testLoadDriver() throws ClassNotFoundException { Class.forName("org.apache.drill.jdbc.Driver"); } /** * Load the driver using ServiceLoader */ @Test public void testLoadDriverServiceLoader() { ServiceLoader<Driver> sl = ServiceLoader.load(Driver.class); for(Iterator<Driver> it = sl.iterator(); it.hasNext(); ) { Driver driver = it.next(); if (driver instanceof org.apache.drill.jdbc.Driver) { return; } } Assert.fail("org.apache.drill.jdbc.Driver not found using ServiceLoader"); } /** Load driver and make a connection. */ @Test public void testConnect() throws Exception { Class.forName("org.apache.drill.jdbc.Driver"); final Connection connection = DriverManager.getConnection("jdbc:drill:zk=local"); connection.close(); } /** Load driver, make a connection, prepare a statement. */ @Test public void testPrepare() throws Exception { withModel(MODEL, "DONUTS").withConnection(new Function<Connection, Void>() { @Override public Void apply(Connection connection) { try { final Statement statement = connection.prepareStatement("select * from donuts"); statement.close(); return null; } catch (Exception e) { throw new RuntimeException(e); } } }); } /** Simple query against JSON. */ @Test public void testSelectJson() throws Exception { withModel(MODEL, "DONUTS").sql("select * from donuts").returns(EXPECTED); } /** Simple query against EMP table in HR database. */ @Test public void testSelectEmployees() throws Exception { withModel(MODEL, "HR") .sql("select * from employees") .returns( "_MAP={deptId=31, lastName=Rafferty}\n" + "_MAP={deptId=33, lastName=Jones}\n" + "_MAP={deptId=33, lastName=Steinberg}\n" + "_MAP={deptId=34, lastName=Robinson}\n" + "_MAP={deptId=34, lastName=Smith}\n" + "_MAP={lastName=John}\n"); } /** Simple query against EMP table in HR database. */ @Test public void testSelectEmpView() throws Exception { withModel(MODEL, "HR") .sql("select * from emp") .returns( "DEPTID=31; LASTNAME=Rafferty\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=null; LASTNAME=John\n"); } /** Simple query against EMP table in HR database. */ @Test public void testSelectDept() throws Exception { withModel(MODEL, "HR") .sql("select * from departments") .returns( "_MAP={deptId=31, name=Sales}\n" + "_MAP={deptId=33, name=Engineering}\n" + "_MAP={deptId=34, name=Clerical}\n" + "_MAP={deptId=35, name=Marketing}\n"); } /** Query with project list. No field references yet. */ @Test public void testProjectConstant() throws Exception { withModel(MODEL, "DONUTS").sql("select 1 + 3 as c from donuts") .returns("C=4\n" + "C=4\n" + "C=4\n" + "C=4\n" + "C=4\n"); } /** Query that projects an element from the map. */ @Test public void testProject() throws Exception { withModel(MODEL, "DONUTS").sql("select _MAP['ppu'] as ppu from donuts") .returns("PPU=0.55\n" + "PPU=0.69\n" + "PPU=0.55\n" + "PPU=0.69\n" + "PPU=1.0\n"); } /** Same logic as {@link #testProject()}, but using a subquery. */ @Test public void testProjectOnSubquery() throws Exception { withModel(MODEL, "DONUTS").sql("select d['ppu'] as ppu from (\n" + " select _MAP as d from donuts)") .returns("PPU=0.55\n" + "PPU=0.69\n" + "PPU=0.55\n" + "PPU=0.69\n" + "PPU=1.0\n"); } /** Checks the logical plan. */ @Test public void testProjectPlan() throws Exception { LogicalPlan plan = withModel(MODEL, "DONUTS") .sql("select _MAP['ppu'] as ppu from donuts") .logicalPlan(); PlanProperties planProperties = plan.getProperties(); Assert.assertEquals("optiq", planProperties.generator.type); Assert.assertEquals("na", planProperties.generator.info); Assert.assertEquals(1, planProperties.version); Assert.assertEquals(PlanProperties.PlanType.APACHE_DRILL_LOGICAL, planProperties.type); Map<String, StoragePluginConfig> seConfigs = plan.getStorageEngines(); StoragePluginConfig config = seConfigs.get("donuts-json"); // Assert.assertTrue(config != null && config instanceof ClasspathRSE.ClasspathRSEConfig); config = seConfigs.get("queue"); // Assert.assertTrue(config != null && config instanceof QueueRSE.QueueRSEConfig); Scan scan = findOnlyOperator(plan, Scan.class); Assert.assertEquals("donuts-json", scan.getStorageEngine()); Project project = findOnlyOperator(plan, Project.class); Assert.assertEquals(1, project.getSelections().size()); Assert.assertEquals(Scan.class, project.getInput().getClass()); Store store = findOnlyOperator(plan, Store.class); Assert.assertEquals("queue", store.getStorageEngine()); Assert.assertEquals("output sink", store.getMemo()); Assert.assertEquals(Project.class, store.getInput().getClass()); } /** * Query with subquery, filter, and projection of one real and one nonexistent field from a map field. */ @Test public void testProjectFilterSubquery() throws Exception { withModel(MODEL, "DONUTS") .sql( "select d['name'] as name, d['xx'] as xx from (\n" + " select _MAP as d from donuts)\n" + "where cast(d['ppu'] as double) > 0.6") .returns("NAME=Raised; XX=null\n" + "NAME=Filled; XX=null\n" + "NAME=Apple Fritter; XX=null\n"); } private static <T extends LogicalOperator> Iterable<T> findOperator(LogicalPlan plan, final Class<T> operatorClazz) { return (Iterable<T>) Iterables.filter(plan.getSortedOperators(), new Predicate<LogicalOperator>() { @Override public boolean apply(LogicalOperator input) { return input.getClass().equals(operatorClazz); } }); } private static <T extends LogicalOperator> T findOnlyOperator(LogicalPlan plan, final Class<T> operatorClazz) { return Iterables.getOnlyElement(findOperator(plan, operatorClazz)); } @Test public void testProjectFilterSubqueryPlan() throws Exception { LogicalPlan plan = withModel(MODEL, "DONUTS") .sql( "select d['name'] as name, d['xx'] as xx from (\n" + " select _MAP['donuts'] as d from donuts)\n" + "where cast(d['ppu'] as double) > 0.6") .logicalPlan(); PlanProperties planProperties = plan.getProperties(); Assert.assertEquals("optiq", planProperties.generator.type); Assert.assertEquals("na", planProperties.generator.info); Assert.assertEquals(1, planProperties.version); Assert.assertEquals(PlanProperties.PlanType.APACHE_DRILL_LOGICAL, planProperties.type); Map<String, StoragePluginConfig> seConfigs = plan.getStorageEngines(); StoragePluginConfig config = seConfigs.get("donuts-json"); // Assert.assertTrue(config != null && config instanceof ClasspathRSE.ClasspathRSEConfig); config = seConfigs.get("queue"); // Assert.assertTrue(config != null && config instanceof QueueRSE.QueueRSEConfig); Scan scan = findOnlyOperator(plan, Scan.class); Assert.assertEquals("donuts-json", scan.getStorageEngine()); Filter filter = findOnlyOperator(plan, Filter.class); Assert.assertTrue(filter.getInput() instanceof Scan); Project[] projects = Iterables.toArray(findOperator(plan, Project.class), Project.class); Assert.assertEquals(2, projects.length); Assert.assertEquals(1, projects[0].getSelections().size()); Assert.assertEquals(Filter.class, projects[0].getInput().getClass()); Assert.assertEquals(2, projects[1].getSelections().size()); Assert.assertEquals(Project.class, projects[1].getInput().getClass()); Store store = findOnlyOperator(plan, Store.class); Assert.assertEquals("queue", store.getStorageEngine()); Assert.assertEquals("output sink", store.getMemo()); Assert.assertEquals(Project.class, store.getInput().getClass()); } /** Query that projects one field. (Disabled; uses sugared syntax.) */ @Test @Ignore public void testProjectNestedFieldSugared() throws Exception { withModel(MODEL, "DONUTS").sql("select donuts.ppu from donuts") .returns("C=4\n" + "C=4\n" + "C=4\n" + "C=4\n" + "C=4\n"); } /** Query with filter. No field references yet. */ @Test public void testFilterConstantFalse() throws Exception { withModel(MODEL, "DONUTS").sql("select * from donuts where 3 > 4").returns(""); } @Test public void testFilterConstant() throws Exception { withModel(MODEL, "DONUTS").sql("select * from donuts where 3 < 4").returns(EXPECTED); } @Ignore @Test public void testValues() throws Exception { withModel(MODEL, "DONUTS").sql("values (1)").returns("EXPR$0=1\n"); // Enable when https://issues.apache.org/jira/browse/DRILL-57 fixed // .planContains("store"); } @Test public void testJoin() throws Exception { Join join = withModel(MODEL, "HR") .sql("select * from emp join dept on emp.deptId = dept.deptId") .returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales", "DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering", "DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering", "DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical", "DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical").planContains(Join.class); Assert.assertEquals(JoinRelType.INNER, join.getJoinType()); } @Test public void testLeftJoin() throws Exception { Join join = withModel(MODEL, "HR") .sql("select * from emp left join dept on emp.deptId = dept.deptId") .returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales", "DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering", "DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering", "DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical", "DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical", "DEPTID=null; LASTNAME=John; DEPTID0=null; NAME=null").planContains(Join.class); Assert.assertEquals(JoinRelType.LEFT, join.getJoinType()); } /** * Right join is tricky because Drill's "join" operator only supports "left", so we have to flip inputs. */ @Test @Ignore public void testRightJoin() throws Exception { Join join = withModel(MODEL, "HR").sql("select * from emp right join dept on emp.deptId = dept.deptId") .returnsUnordered("xx").planContains(Join.class); Assert.assertEquals(JoinRelType.LEFT, join.getJoinType()); } @Test public void testFullJoin() throws Exception { Join join = withModel(MODEL, "HR") .sql("select * from emp full join dept on emp.deptId = dept.deptId") .returnsUnordered("DEPTID=31; LASTNAME=Rafferty; DEPTID0=31; NAME=Sales", "DEPTID=33; LASTNAME=Jones; DEPTID0=33; NAME=Engineering", "DEPTID=33; LASTNAME=Steinberg; DEPTID0=33; NAME=Engineering", "DEPTID=34; LASTNAME=Robinson; DEPTID0=34; NAME=Clerical", "DEPTID=34; LASTNAME=Smith; DEPTID0=34; NAME=Clerical", "DEPTID=null; LASTNAME=John; DEPTID0=null; NAME=null", "DEPTID=null; LASTNAME=null; DEPTID0=35; NAME=Marketing").planContains(Join.class); Assert.assertEquals(JoinRelType.FULL, join.getJoinType()); } /** * Join on subquery; also tests that if a field of the same name exists in both inputs, both fields make it through * the join. */ @Test public void testJoinOnSubquery() throws Exception { Join join = withModel(MODEL, "HR") .sql( "select * from (\n" + "select deptId, lastname, 'x' as name from emp) as e\n" + " join dept on e.deptId = dept.deptId") .returnsUnordered("DEPTID=31; LASTNAME=Rafferty; NAME=x; DEPTID0=31; NAME0=Sales", "DEPTID=33; LASTNAME=Jones; NAME=x; DEPTID0=33; NAME0=Engineering", "DEPTID=33; LASTNAME=Steinberg; NAME=x; DEPTID0=33; NAME0=Engineering", "DEPTID=34; LASTNAME=Robinson; NAME=x; DEPTID0=34; NAME0=Clerical", "DEPTID=34; LASTNAME=Smith; NAME=x; DEPTID0=34; NAME0=Clerical").planContains(Join.class); Assert.assertEquals(JoinRelType.INNER, join.getJoinType()); } /** Tests that one of the FoodMart tables is present. */ @Test @Ignore public void testFoodMart() throws Exception { withModel(MODEL, "FOODMART") .sql("select * from product_class where cast(_map['product_class_id'] as integer) < 3") .returnsUnordered( "_MAP={product_category=Seafood, product_class_id=2, product_department=Seafood, product_family=Food, product_subcategory=Shellfish}", "_MAP={product_category=Specialty, product_class_id=1, product_department=Produce, product_family=Food, product_subcategory=Nuts}"); } @Test public void testUnionAll() throws Exception { Union union = withModel(MODEL, "HR") .sql("select deptId from dept\n" + "union all\n" + "select deptId from emp") .returnsUnordered("DEPTID=31", "DEPTID=33", "DEPTID=34", "DEPTID=35", "DEPTID=null") .planContains(Union.class); Assert.assertFalse(union.isDistinct()); } @Test public void testUnion() throws Exception { Union union = withModel(MODEL, "HR") .sql("select deptId from dept\n" + "union\n" + "select deptId from emp") .returnsUnordered("DEPTID=31", "DEPTID=33", "DEPTID=34", "DEPTID=35", "DEPTID=null") .planContains(Union.class); Assert.assertTrue(union.isDistinct()); } @Test public void testOrderByDescNullsFirst() throws Exception { // desc nulls last withModel(MODEL, "HR") .sql("select * from emp order by deptId desc nulls first") .returns( "DEPTID=null; LASTNAME=John\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n") .planContains(Order.class); } @Test public void testOrderByDescNullsLast() throws Exception { // desc nulls first withModel(MODEL, "HR") .sql("select * from emp order by deptId desc nulls last") .returns( "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n" + "DEPTID=null; LASTNAME=John\n") .planContains(Order.class); } @Test @Ignore public void testOrderByDesc() throws Exception { // desc is implicitly "nulls first" (i.e. null sorted as +inf) // Current behavior is to sort nulls last. This is wrong. withModel(MODEL, "HR") .sql("select * from emp order by deptId desc") .returns( "DEPTID=null; LASTNAME=John\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=31; LASTNAME=Rafferty\n") .planContains(Order.class); } @Test public void testOrderBy() throws Exception { // no sort order specified is implicitly "asc", and asc is "nulls last" withModel(MODEL, "HR") .sql("select * from emp order by deptId") .returns( "DEPTID=31; LASTNAME=Rafferty\n" + "DEPTID=33; LASTNAME=Jones\n" + "DEPTID=33; LASTNAME=Steinberg\n" + "DEPTID=34; LASTNAME=Robinson\n" + "DEPTID=34; LASTNAME=Smith\n" + "DEPTID=null; LASTNAME=John\n") .planContains(Order.class); } @Test public void testLimit() throws Exception { withModel(MODEL, "HR") .sql("select LASTNAME from emp limit 2") .returns("LASTNAME=Rafferty\n" + "LASTNAME=Jones") .planContains(Limit.class); } @Test public void testLimitOrderBy() throws Exception { TestDataConnection tdc = withModel(MODEL, "HR") .sql("select LASTNAME from emp order by LASTNAME limit 2") .returns("LASTNAME=John\n" + "LASTNAME=Jones"); tdc.planContains(Limit.class); tdc.planContains(Order.class); } @Test public void testOrderByWithOffset() throws Exception { withModel(MODEL, "HR") .sql("select LASTNAME from emp order by LASTNAME asc offset 3") .returns("LASTNAME=Robinson\n" + "LASTNAME=Smith\n" + "LASTNAME=Steinberg") .planContains(Limit.class); } @Test public void testOrderByWithOffsetAndFetch() throws Exception { withModel(MODEL, "HR") .sql("select LASTNAME from emp order by LASTNAME asc offset 3 fetch next 2 rows only") .returns("LASTNAME=Robinson\n" + "LASTNAME=Smith") .planContains(Limit.class); } }
apache-2.0
jeorme/OG-Platform
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/sabrcube/SABRCMSSpreadNoExtrapolationYCNSFunction.java
6665
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.sabrcube; import static com.opengamma.engine.value.ValueRequirementNames.SABR_SURFACES; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.interestrate.PresentValueCurveSensitivitySABRCalculator; import com.opengamma.analytics.financial.interestrate.PresentValueNodeSensitivityCalculator; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateCorrelationParameters; import com.opengamma.analytics.financial.model.option.definition.SABRInterestRateDataBundle; import com.opengamma.analytics.math.function.DoubleFunction1D; import com.opengamma.analytics.math.surface.InterpolatedDoublesSurface; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.SurfaceAndCubePropertyNames; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.financial.analytics.model.sabr.SABRDiscountingFunction; import com.opengamma.financial.analytics.model.volatility.SmileFittingPropertyNamesAndValues; import com.opengamma.financial.analytics.volatility.fittedresults.SABRFittedSurfaces; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.financial.security.FinancialSecurityUtils; import com.opengamma.util.money.Currency; /** * @deprecated Use descendants of {@link SABRDiscountingFunction} */ @Deprecated public class SABRCMSSpreadNoExtrapolationYCNSFunction extends SABRYCNSFunction { private static final PresentValueNodeSensitivityCalculator NSC = PresentValueNodeSensitivityCalculator.using(PresentValueCurveSensitivitySABRCalculator.getInstance()); @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.CAP_FLOOR_CMS_SPREAD_SECURITY; } @Override protected SABRInterestRateDataBundle getModelParameters(final ComputationTarget target, final FunctionInputs inputs, final Currency currency, final YieldCurveBundle yieldCurves, final ValueRequirement desiredValue) { final Object surfacesObject = inputs.getValue(SABR_SURFACES); if (surfacesObject == null) { throw new OpenGammaRuntimeException("Could not get SABR parameter surfaces"); } final SABRFittedSurfaces surfaces = (SABRFittedSurfaces) surfacesObject; final InterpolatedDoublesSurface alphaSurface = surfaces.getAlphaSurface(); final InterpolatedDoublesSurface betaSurface = surfaces.getBetaSurface(); final InterpolatedDoublesSurface nuSurface = surfaces.getNuSurface(); final InterpolatedDoublesSurface rhoSurface = surfaces.getRhoSurface(); final DoubleFunction1D correlationFunction = getCorrelationFunction(); final SABRInterestRateCorrelationParameters modelParameters = new SABRInterestRateCorrelationParameters(alphaSurface, betaSurface, rhoSurface, nuSurface, correlationFunction); return new SABRInterestRateDataBundle(modelParameters, yieldCurves); } @Override protected ValueProperties.Builder createValueProperties(final Currency currency) { return createValueProperties() .with(ValuePropertyNames.CURRENCY, currency.getCode()) .with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode()) .withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.CURVE) .withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION) .withAny(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION) .withAny(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD) .with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION); } @Override protected ValueProperties.Builder createValueProperties(final ComputationTarget target, final ValueRequirement desiredValue) { final String cubeDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION); final String cubeSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION); final String surfaceDefinitionName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION); final String surfaceSpecificationName = desiredValue.getConstraint(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION); final String currency = FinancialSecurityUtils.getCurrency(target.getSecurity()).getCode(); final String curveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG); final String fittingMethod = desiredValue.getConstraint(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD); final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE); return createValueProperties() .with(ValuePropertyNames.CURRENCY, currency) .with(ValuePropertyNames.CURVE_CURRENCY, currency) .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfig) .with(ValuePropertyNames.CURVE, curveName) .with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_DEFINITION, cubeDefinitionName) .with(SurfaceAndCubePropertyNames.PROPERTY_CUBE_SPECIFICATION, cubeSpecificationName) .with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_DEFINITION, surfaceDefinitionName) .with(SurfaceAndCubePropertyNames.PROPERTY_SURFACE_SPECIFICATION, surfaceSpecificationName) .with(SmileFittingPropertyNamesAndValues.PROPERTY_FITTING_METHOD, fittingMethod) .with(SmileFittingPropertyNamesAndValues.PROPERTY_VOLATILITY_MODEL, SmileFittingPropertyNamesAndValues.SABR) .with(ValuePropertyNames.CALCULATION_METHOD, SABRFunction.SABR_NO_EXTRAPOLATION); } @Override protected PresentValueNodeSensitivityCalculator getNodeSensitivityCalculator(final ValueRequirement desiredValue) { return NSC; } private static DoubleFunction1D getCorrelationFunction() { return new DoubleFunction1D() { @Override public Double evaluate(final Double x) { return 0.8; } }; } }
apache-2.0
keizer619/carbon-analytics-common
components/data-bridge/org.wso2.carbon.databridge.agent/src/main/java/org/wso2/carbon/databridge/agent/conf/DataEndpointConfiguration.java
3842
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.databridge.agent.conf; import org.apache.commons.pool.impl.GenericKeyedObjectPool; import org.wso2.carbon.databridge.agent.util.DataEndpointConstants; public class DataEndpointConfiguration { private String receiverURL; private String authURL; private String username; private String password; private GenericKeyedObjectPool transportPool; private GenericKeyedObjectPool securedTransportPool; private int batchSize; private String publisherKey; private String authKey; private String sessionId; private int corePoolSize; private int maxPoolSize; private int keepAliveTimeInPool; public enum Protocol { TCP, SSL; @Override public String toString() { return super.toString().toLowerCase(); } } public DataEndpointConfiguration(String receiverURL, String authURL, String username, String password, GenericKeyedObjectPool transportPool, GenericKeyedObjectPool securedTransportPool, int batchSize, int corePoolSize, int maxPoolSize, int keepAliveTimeInPool) { this.receiverURL = receiverURL; this.authURL = authURL; this.username = username; this.password = password; this.transportPool = transportPool; this.securedTransportPool = securedTransportPool; this.publisherKey = this.receiverURL + DataEndpointConstants.SEPARATOR + username + DataEndpointConstants.SEPARATOR + password; this.authKey = this.authURL + DataEndpointConstants.SEPARATOR + username + DataEndpointConstants.SEPARATOR + password; this.batchSize = batchSize; this.corePoolSize = corePoolSize; this.maxPoolSize = maxPoolSize; this.keepAliveTimeInPool = keepAliveTimeInPool; } public String getReceiverURL() { return receiverURL; } public String getUsername() { return username; } public String getAuthURL() { return authURL; } public String getPassword() { return password; } public String toString() { return "ReceiverURL: " + receiverURL + "," + "Authentication URL: " + authURL + "," + "Username: " + username; } public String getPublisherKey() { return publisherKey; } public String getAuthKey() { return authKey; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public GenericKeyedObjectPool getTransportPool() { return transportPool; } public GenericKeyedObjectPool getSecuredTransportPool() { return securedTransportPool; } public int getCorePoolSize() { return corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public int getKeepAliveTimeInPool() { return keepAliveTimeInPool; } public int getBatchSize() { return batchSize; } }
apache-2.0
gmrodrigues/crate
sql/src/test/java/io/crate/operation/reference/doc/IntegerColumnReferenceTest.java
3042
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.reference.doc; import io.crate.operation.reference.doc.lucene.IntegerColumnReference; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.IntField; import org.apache.lucene.document.StringField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.FieldMapper; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class IntegerColumnReferenceTest extends DocLevelExpressionsTest { @Override protected void insertValues(IndexWriter writer) throws Exception { for (int i = -10; i<10; i++) { Document doc = new Document(); doc.add(new StringField("_id", Integer.toString(i), Field.Store.NO)); doc.add(new IntField(fieldName().name(), i, Field.Store.NO)); writer.addDocument(doc); } } @Override protected FieldMapper.Names fieldName() { return new FieldMapper.Names("i"); } @Override protected FieldDataType fieldType() { return new FieldDataType("int"); } @Test public void testFieldCacheExpression() throws Exception { IntegerColumnReference integerColumn = new IntegerColumnReference(fieldName().name()); integerColumn.startCollect(ctx); integerColumn.setNextReader(readerContext); IndexSearcher searcher = new IndexSearcher(readerContext.reader()); TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), 20); int i = -10; for (ScoreDoc doc : topDocs.scoreDocs) { integerColumn.setNextDocId(doc.doc); assertThat(integerColumn.value(), is(i)); i++; } } }
apache-2.0
apache/olingo-odata2
odata2-lib/odata-core/src/main/java/org/apache/olingo/odata2/core/batch/BatchResponsePartImpl.java
2137
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ******************************************************************************/ package org.apache.olingo.odata2.core.batch; import java.util.List; import org.apache.olingo.odata2.api.batch.BatchResponsePart; import org.apache.olingo.odata2.api.processor.ODataResponse; public class BatchResponsePartImpl extends BatchResponsePart { private List<ODataResponse> responses; private boolean isChangeSet; @Override public List<ODataResponse> getResponses() { return responses; } @Override public boolean isChangeSet() { return isChangeSet; } public class BatchResponsePartBuilderImpl extends BatchResponsePartBuilder { private List<ODataResponse> responses; private boolean isChangeSet; @Override public BatchResponsePart build() { BatchResponsePartImpl.this.responses = responses; BatchResponsePartImpl.this.isChangeSet = isChangeSet; return BatchResponsePartImpl.this; } @Override public BatchResponsePartBuilder responses(final List<ODataResponse> responses) { this.responses = responses; return this; } @Override public BatchResponsePartBuilder changeSet(final boolean isChangeSet) { this.isChangeSet = isChangeSet; return this; } } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/test/java/org/apache/geode/internal/cache/diskPerf/DiskRegOverflowSyncGetInMemPerfJUnitPerformanceTest.java
3891
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.diskPerf; import java.util.Arrays; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.LogWriter; import org.apache.geode.internal.cache.DiskRegionHelperFactory; import org.apache.geode.internal.cache.DiskRegionProperties; import org.apache.geode.internal.cache.DiskRegionTestingBase; import org.apache.geode.test.junit.categories.IntegrationTest; /** * Disk region Perf test for Overflow only with Sync writes. 1) Performance of get operation for * entry in memory. */ @Category(IntegrationTest.class) public class DiskRegOverflowSyncGetInMemPerfJUnitPerformanceTest extends DiskRegionTestingBase { private static int ENTRY_SIZE = 1024; private static int OP_COUNT = 10000; private static int counter = 0; private LogWriter log = null; private DiskRegionProperties diskProps = new DiskRegionProperties(); @Override protected final void preSetUp() throws Exception { diskProps.setDiskDirs(dirs); } @Override protected final void postSetUp() throws Exception { diskProps.setOverFlowCapacity(100000); region = DiskRegionHelperFactory.getSyncOverFlowOnlyRegion(cache, diskProps); log = ds.getLogWriter(); } @Override protected final void postTearDown() throws Exception { if (cache != null) { cache.close(); } if (ds != null) { ds.disconnect(); } } @Test public void testPopulatefor1Kbwrites() { // RegionAttributes ra = region.getAttributes(); // final String key = "K"; final byte[] value = new byte[ENTRY_SIZE]; Arrays.fill(value, (byte) 77); long startTime = System.currentTimeMillis(); for (int i = 0; i < OP_COUNT; i++) { region.put("" + (i + 10000), value); } long endTime = System.currentTimeMillis(); System.out.println(" done with putting"); // Now get all the entries which are in memory. long startTimeGet = System.currentTimeMillis(); for (int i = 0; i < OP_COUNT; i++) { region.get("" + (i + 10000)); } long endTimeGet = System.currentTimeMillis(); System.out.println(" done with getting"); region.close(); // closes disk file which will flush all buffers float et = endTime - startTime; float etSecs = et / 1000f; float opPerSec = etSecs == 0 ? 0 : (OP_COUNT / (et / 1000f)); float bytesPerSec = etSecs == 0 ? 0 : ((OP_COUNT * ENTRY_SIZE) / (et / 1000f)); String stats = "et=" + et + "ms writes/sec=" + opPerSec + " bytes/sec=" + bytesPerSec; log.info(stats); System.out.println("Stats for 1 kb writes:" + stats); // Perf stats for get op float etGet = endTimeGet - startTimeGet; float etSecsGet = etGet / 1000f; float opPerSecGet = etSecsGet == 0 ? 0 : (OP_COUNT / (etGet / 1000f)); float bytesPerSecGet = etSecsGet == 0 ? 0 : ((OP_COUNT * ENTRY_SIZE) / (etGet / 1000f)); String statsGet = "et=" + etGet + "ms gets/sec=" + opPerSecGet + " bytes/sec=" + bytesPerSecGet; log.info(statsGet); System.out.println("Perf Stats of get which is in memory :" + statsGet); } }
apache-2.0
stumoodie/PathwayEditor
libs/batik-1.7/contrib/rasterizertask/sources/org/apache/tools/ant/taskdefs/optional/RasterizerTaskSVGConverterController.java
3878
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.tools.ant.taskdefs.optional; // -- Batik classes ---------------------------------------------------------- import org.apache.batik.transcoder.Transcoder; import org.apache.batik.apps.rasterizer.SVGConverterController; import org.apache.batik.apps.rasterizer.SVGConverterSource; // -- Ant classes ------------------------------------------------------------ import org.apache.tools.ant.Task; // -- Java SDK classes ------------------------------------------------------- import java.io.File; import java.util.Map; import java.util.List; /** * Implements simple controller for the <code>SVGConverter</code> operation. * * <p>This is almost the same as the * {@link org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController} * except this produces error message when the conversion fails.</p> * * <p>See {@link SVGConverterController} for the method documentation.</p> * * @see SVGConverterController SVGConverterController * @see org.apache.batik.apps.rasterizer.DefaultSVGConverterController DefaultSVGConverterController * * @author <a href="mailto:ruini@iki.fi">Henri Ruini</a> * @version $Id: RasterizerTaskSVGConverterController.java 479617 2006-11-27 13:43:51Z dvholten $ */ public class RasterizerTaskSVGConverterController implements SVGConverterController { // -- Variables ---------------------------------------------------------- /** Ant task that is used to log messages. */ protected Task executingTask = null; // -- Constructors ------------------------------------------------------- /** * Don't allow public usage. */ protected RasterizerTaskSVGConverterController() { } /** * Sets the given Ant task to receive log messages. * * @param task Ant task. The value can be <code>null</code> when log messages won't be written. */ public RasterizerTaskSVGConverterController(Task task) { executingTask = task; } // -- Public interface --------------------------------------------------- public boolean proceedWithComputedTask(Transcoder transcoder, Map hints, List sources, List dest){ return true; } public boolean proceedWithSourceTranscoding(SVGConverterSource source, File dest) { return true; } public boolean proceedOnSourceTranscodingFailure(SVGConverterSource source, File dest, String errorCode){ if(executingTask != null) { executingTask.log("Unable to rasterize image '" + source.getName() + "' to '" + dest.getAbsolutePath() + "': " + errorCode); } return true; } public void onSourceTranscodingSuccess(SVGConverterSource source, File dest){ } }
apache-2.0
salyh/geronimo-specs
geronimo-javamail_1.5_spec/src/main/java/javax/mail/MessageAware.java
952
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.mail; /** * @version $Rev$ $Date$ */ public interface MessageAware { public abstract MessageContext getMessageContext(); }
apache-2.0
mbiarnes/kie-wb-common
kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/editors/expressions/types/function/supplementary/pmml/PMMLDocumentMetadataProviderTest.java
10034
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.dmn.client.editors.expressions.types.function.supplementary.pmml; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.soup.commons.util.Sets; import org.kie.workbench.common.dmn.api.definition.model.Definitions; import org.kie.workbench.common.dmn.api.definition.model.Import; import org.kie.workbench.common.dmn.api.definition.model.ImportDMN; import org.kie.workbench.common.dmn.api.definition.model.ImportPMML; import org.kie.workbench.common.dmn.api.editors.included.DMNImportTypes; import org.kie.workbench.common.dmn.api.editors.included.PMMLDocumentMetadata; import org.kie.workbench.common.dmn.api.editors.included.PMMLIncludedModel; import org.kie.workbench.common.dmn.api.editors.included.PMMLModelMetadata; import org.kie.workbench.common.dmn.api.editors.included.PMMLParameterMetadata; import org.kie.workbench.common.dmn.api.property.dmn.LocationURI; import org.kie.workbench.common.dmn.client.editors.included.imports.IncludedModelsPageStateProviderImpl; import org.kie.workbench.common.dmn.client.graph.DMNGraphUtils; import org.kie.workbench.common.dmn.client.service.DMNClientServicesProxy; import org.kie.workbench.common.stunner.core.client.service.ServiceCallback; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.uberfire.backend.vfs.Path; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyListOf; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class PMMLDocumentMetadataProviderTest { @Mock private DMNGraphUtils graphUtils; @Mock private DMNClientServicesProxy clientServicesProxy; @Mock private IncludedModelsPageStateProviderImpl stateProvider; @Mock private Path dmnModelPath; @Captor private ArgumentCaptor<List<PMMLIncludedModel>> pmmlIncludedModelsArgumentCaptor; @Captor private ArgumentCaptor<ServiceCallback<List<PMMLDocumentMetadata>>> callbackArgumentCaptor; private Definitions definitions; private PMMLDocumentMetadataProvider provider; @Before public void setup() { this.definitions = new Definitions(); this.provider = new PMMLDocumentMetadataProvider(graphUtils, clientServicesProxy, stateProvider); final Diagram diagram = mock(Diagram.class); final Metadata metadata = mock(Metadata.class); when(stateProvider.getDiagram()).thenReturn(Optional.of(diagram)); when(diagram.getMetadata()).thenReturn(metadata); when(metadata.getPath()).thenReturn(dmnModelPath); when(graphUtils.getDefinitions(diagram)).thenReturn(definitions); } @Test @SuppressWarnings("unchecked") public void testLoadPMMLIncludedDocumentsDMNModelPath() { provider.loadPMMLIncludedDocuments(); verify(clientServicesProxy).loadPMMLDocumentsFromImports(eq(dmnModelPath), anyListOf(PMMLIncludedModel.class), any(ServiceCallback.class)); } @Test @SuppressWarnings("unchecked") public void testLoadPMMLIncludedDocumentsPMMLIncludedModels() { final Import dmn = new ImportDMN("dmn", new LocationURI("dmn-location"), DMNImportTypes.DMN.getDefaultNamespace()); final Import pmml = new ImportPMML("pmml", new LocationURI("pmml-location"), DMNImportTypes.PMML.getDefaultNamespace()); dmn.getName().setValue("dmn"); pmml.getName().setValue("pmml"); definitions.getImport().add(dmn); definitions.getImport().add(pmml); provider.loadPMMLIncludedDocuments(); verify(clientServicesProxy).loadPMMLDocumentsFromImports(any(Path.class), pmmlIncludedModelsArgumentCaptor.capture(), any(ServiceCallback.class)); final List<PMMLIncludedModel> actualIncludedModels = pmmlIncludedModelsArgumentCaptor.getValue(); assertThat(actualIncludedModels).hasSize(1); final PMMLIncludedModel pmmlIncludedModel = actualIncludedModels.get(0); assertThat(pmmlIncludedModel.getModelName()).isEqualTo("pmml"); assertThat(pmmlIncludedModel.getPath()).isEqualTo("pmml-location"); assertThat(pmmlIncludedModel.getImportType()).isEqualTo(DMNImportTypes.PMML.getDefaultNamespace()); } @Test public void testGetPMMLDocumentNames() { final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>(); pmmlDocuments.add(new PMMLDocumentMetadata("path1", "zDocument1", DMNImportTypes.PMML.getDefaultNamespace(), Collections.emptyList())); pmmlDocuments.add(new PMMLDocumentMetadata("path2", "aDocument2", DMNImportTypes.PMML.getDefaultNamespace(), Collections.emptyList())); final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments(); callback.onSuccess(pmmlDocuments); final List<String> documentNames = provider.getPMMLDocumentNames(); assertThat(documentNames).containsSequence("aDocument2", "zDocument1"); } private ServiceCallback<List<PMMLDocumentMetadata>> loadPMMLIncludedDocuments() { provider.loadPMMLIncludedDocuments(); verify(clientServicesProxy).loadPMMLDocumentsFromImports(any(Path.class), anyListOf(PMMLIncludedModel.class), callbackArgumentCaptor.capture()); return callbackArgumentCaptor.getValue(); } @Test public void testGetPMMLDocumentModelNames() { final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>(); pmmlDocuments.add(new PMMLDocumentMetadata("path", "document", DMNImportTypes.PMML.getDefaultNamespace(), asList(new PMMLModelMetadata("zModel1", Collections.emptySet()), new PMMLModelMetadata("aModel2", Collections.emptySet())))); final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments(); callback.onSuccess(pmmlDocuments); final List<String> modelNames = provider.getPMMLDocumentModels("document"); assertThat(modelNames).containsSequence("aModel2", "zModel1"); assertThat(provider.getPMMLDocumentModels("unknown")).isEmpty(); } @Test public void testGetPMMLDocumentModelParameterNames() { final List<PMMLDocumentMetadata> pmmlDocuments = new ArrayList<>(); pmmlDocuments.add(new PMMLDocumentMetadata("path", "document", DMNImportTypes.PMML.getDefaultNamespace(), singletonList(new PMMLModelMetadata("model", new Sets.Builder<PMMLParameterMetadata>() .add(new PMMLParameterMetadata("zParameter1")) .add(new PMMLParameterMetadata("aParameter2")) .build())))); final ServiceCallback<List<PMMLDocumentMetadata>> callback = loadPMMLIncludedDocuments(); callback.onSuccess(pmmlDocuments); final List<String> modelNames = provider.getPMMLDocumentModelParameterNames("document", "model"); assertThat(modelNames).containsSequence("aParameter2", "zParameter1"); assertThat(provider.getPMMLDocumentModelParameterNames("unknown", "unknown")).isEmpty(); } }
apache-2.0
ollie314/docker-java
src/main/java/com/github/dockerjava/core/command/ListImagesCmdImpl.java
2238
package com.github.dockerjava.core.command; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.model.Image; import com.github.dockerjava.core.util.FiltersBuilder; /** * List images */ public class ListImagesCmdImpl extends AbstrDockerCmd<ListImagesCmd, List<Image>> implements ListImagesCmd { private String imageNameFilter; private Boolean showAll = false; private FiltersBuilder filters = new FiltersBuilder(); public ListImagesCmdImpl(ListImagesCmd.Exec exec) { super(exec); } @Override public Map<String, List<String>> getFilters() { return filters.build(); } @Override public Boolean hasShowAllEnabled() { return showAll; } @Override public ListImagesCmd withShowAll(Boolean showAll) { this.showAll = showAll; return this; } @Override public ListImagesCmd withDanglingFilter(Boolean dangling) { checkNotNull(dangling, "dangling have not been specified"); filters.withFilter("dangling", dangling.toString()); return this; } @Override public ListImagesCmd withLabelFilter(String... labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withLabelFilter(Map<String, String> labels) { checkNotNull(labels, "labels have not been specified"); filters.withLabels(labels); return this; } @Override public ListImagesCmd withImageNameFilter(String imageNameFilter) { checkNotNull(imageNameFilter, "image name filter not specified"); this.imageNameFilter = imageNameFilter; return this; } @Override public String getImageNameFilter() { return this.imageNameFilter; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
apache-2.0
shun634501730/java_source_cn
src_en/java/rmi/server/SocketSecurityException.java
1223
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.rmi.server; /** * An obsolete subclass of {@link ExportException}. * * @author Ann Wollrath * @since JDK1.1 * @deprecated This class is obsolete. Use {@link ExportException} instead. */ @Deprecated public class SocketSecurityException extends ExportException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7622072999407781979L; /** * Constructs an <code>SocketSecurityException</code> with the specified * detail message. * * @param s the detail message. * @since JDK1.1 */ public SocketSecurityException(String s) { super(s); } /** * Constructs an <code>SocketSecurityException</code> with the specified * detail message and nested exception. * * @param s the detail message. * @param ex the nested exception * @since JDK1.1 */ public SocketSecurityException(String s, Exception ex) { super(s, ex); } }
apache-2.0
MikeThomsen/nifi
nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java
5613
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.registry.client; import org.apache.nifi.registry.flow.VersionedFlowSnapshot; import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; import java.io.IOException; import java.util.List; /** * Client for interacting with snapshots. */ public interface FlowSnapshotClient { /** * Creates a new snapshot/version for the given flow. * * The snapshot object must have the version populated, and will receive an error if the submitted version is * not the next one-up version. * * @param snapshot the new snapshot * @return the created snapshot * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshot create(VersionedFlowSnapshot snapshot) throws NiFiRegistryException, IOException; /** * Gets the snapshot for the given bucket, flow, and version. * * @param bucketId the bucket id * @param flowId the flow id * @param version the version * @return the snapshot with the given version of the given flow in the given bucket * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshot get(String bucketId, String flowId, int version) throws NiFiRegistryException, IOException; /** * Gets the snapshot for the given flow and version. * * @param flowId the flow id * @param version the version * @return the snapshot with the given version of the given flow * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshot get(String flowId, int version) throws NiFiRegistryException, IOException; /** * Gets the latest snapshot for the given flow. * * @param bucketId the bucket id * @param flowId the flow id * @return the snapshot with the latest version for the given flow * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshot getLatest(String bucketId, String flowId) throws NiFiRegistryException, IOException; /** * Gets the latest snapshot for the given flow. * * @param flowId the flow id * @return the snapshot with the latest version for the given flow * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshot getLatest(String flowId) throws NiFiRegistryException, IOException; /** * Gets the latest snapshot metadata for the given flow. * * @param bucketId the bucket id * @param flowId the flow id * @return the snapshot metadata for the latest version of the given flow * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshotMetadata getLatestMetadata(String bucketId, String flowId) throws NiFiRegistryException, IOException; /** * Gets the latest snapshot metadata for the given flow. * * @param flowId the flow id * @return the snapshot metadata for the latest version of the given flow * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ VersionedFlowSnapshotMetadata getLatestMetadata(String flowId) throws NiFiRegistryException, IOException; /** * Gets a list of the metadata for all snapshots of a given flow. * * The contents of each snapshot are not part of the response. * * @param bucketId the bucket id * @param flowId the flow id * @return the list of snapshot metadata * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ List<VersionedFlowSnapshotMetadata> getSnapshotMetadata(String bucketId, String flowId) throws NiFiRegistryException, IOException; /** * Gets a list of the metadata for all snapshots of a given flow. * * The contents of each snapshot are not part of the response. * * @param flowId the flow id * @return the list of snapshot metadata * @throws NiFiRegistryException if an error is encountered other than IOException * @throws IOException if an I/O error is encountered */ List<VersionedFlowSnapshotMetadata> getSnapshotMetadata(String flowId) throws NiFiRegistryException, IOException; }
apache-2.0
emanoelxavier/osc-core
osc-server/src/main/java/org/osc/core/broker/service/tasks/conformance/openstack/UploadImageToGlanceTask.java
4272
/******************************************************************************* * Copyright (c) Intel Corporation * Copyright (c) 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.osc.core.broker.service.tasks.conformance.openstack; import java.io.File; import java.util.Set; import javax.persistence.EntityManager; import org.osc.core.broker.job.lock.LockObjectReference; import org.osc.core.broker.model.entities.appliance.ApplianceSoftwareVersion; import org.osc.core.broker.model.entities.appliance.VirtualSystem; import org.osc.core.broker.model.entities.virtualization.openstack.OsImageReference; import org.osc.core.broker.rest.client.openstack.openstack4j.Endpoint; import org.osc.core.broker.rest.client.openstack.openstack4j.Openstack4jGlance; import org.osc.core.broker.service.appliance.UploadConfig; import org.osc.core.broker.service.persistence.OSCEntityManager; import org.osc.core.broker.service.tasks.TransactionalTask; import org.slf4j.LoggerFactory; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.slf4j.Logger; @Component(service = UploadImageToGlanceTask.class, configurationPid = "org.osc.core.broker.upload", configurationPolicy = ConfigurationPolicy.REQUIRE) public class UploadImageToGlanceTask extends TransactionalTask { private final Logger log = LoggerFactory.getLogger(UploadImageToGlanceTask.class); private String region; private VirtualSystem vs; private String glanceImageName; private ApplianceSoftwareVersion applianceSoftwareVersion; private Endpoint osEndPoint; private String uploadPath; @Activate void activate(UploadConfig config) { this.uploadPath = config.upload_path(); } public UploadImageToGlanceTask create(VirtualSystem vs, String region, String glanceImageName, ApplianceSoftwareVersion applianceSoftwareVersion, Endpoint osEndPoint) { UploadImageToGlanceTask task = new UploadImageToGlanceTask(); task.vs = vs; task.region = region; task.applianceSoftwareVersion = applianceSoftwareVersion; task.osEndPoint = osEndPoint; task.glanceImageName = glanceImageName; task.name = task.getName(); task.uploadPath = this.uploadPath; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } @Override public void executeTransaction(EntityManager em) throws Exception { OSCEntityManager<VirtualSystem> emgr = new OSCEntityManager<>(VirtualSystem.class, em, this.txBroadcastUtil); this.vs = emgr.findByPrimaryKey(this.vs.getId()); this.log.info("Uploading image " + this.glanceImageName + " to region + " + this.region); File imageFile = new File(this.uploadPath + this.applianceSoftwareVersion.getImageUrl()); try (Openstack4jGlance glance = new Openstack4jGlance(this.osEndPoint)) { String imageId = glance.uploadImage(this.region, this.glanceImageName, imageFile, this.applianceSoftwareVersion.getImageProperties()); this.vs.addOsImageReference(new OsImageReference(this.vs, this.region, imageId)); } OSCEntityManager.update(em, this.vs, this.txBroadcastUtil); } @Override public String getName() { return String.format("Uploading image '%s' to region '%s'", this.glanceImageName, this.region); } @Override public Set<LockObjectReference> getObjects() { return LockObjectReference.getObjectReferences(this.vs); } }
apache-2.0
gkatsikas/onos
drivers/default/src/test/java/org/onosproject/driver/extensions/NiciraTunGpeNpTest.java
1762
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.driver.extensions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import org.junit.Test; import com.google.common.testing.EqualsTester; /** * Unit tests for NiciraTunGpeNp class. */ public class NiciraTunGpeNpTest { final byte np1 = (byte) 1; final byte np2 = (byte) 2; /** * Checks the operation of equals() methods. */ @Test public void testEquals() { final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1); final NiciraTunGpeNp sameAsTunGpeNp1 = new NiciraTunGpeNp(np1); final NiciraTunGpeNp tunGpeNp2 = new NiciraTunGpeNp(np2); new EqualsTester().addEqualityGroup(tunGpeNp1, sameAsTunGpeNp1).addEqualityGroup(tunGpeNp2) .testEquals(); } /** * Checks the construction of a NiciraTunGpeNp object. */ @Test public void testConstruction() { final NiciraTunGpeNp tunGpeNp1 = new NiciraTunGpeNp(np1); assertThat(tunGpeNp1, is(notNullValue())); assertThat(tunGpeNp1.tunGpeNp(), is(np1)); } }
apache-2.0
goodwinnk/intellij-community
java/java-impl/src/com/intellij/codeInsight/navigation/JavaGotoSuperHandler.java
5139
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.navigation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator; import com.intellij.codeInsight.generation.actions.PresentableCodeInsightActionHandler; import com.intellij.codeInsight.navigation.actions.GotoSuperAction; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.util.MethodCellRenderer; import com.intellij.ide.util.PsiNavigationSupport; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.impl.FindSuperElementsHelper; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; public class JavaGotoSuperHandler implements PresentableCodeInsightActionHandler { @Override public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID); int offset = editor.getCaretModel().getOffset(); PsiElement[] superElements = findSuperElements(file, offset); if (superElements.length == 0) return; if (superElements.length == 1) { PsiElement superElement = superElements[0].getNavigationElement(); final PsiFile containingFile = superElement.getContainingFile(); if (containingFile == null) return; final VirtualFile virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) return; Navigatable descriptor = PsiNavigationSupport.getInstance().createNavigatable(project, virtualFile, superElement.getTextOffset()); descriptor.navigate(true); } else if (superElements[0] instanceof PsiMethod) { boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature((PsiMethod[])superElements); PsiElementListNavigator.openTargets(editor, (PsiMethod[])superElements, CodeInsightBundle.message("goto.super.method.chooser.title"), CodeInsightBundle .message("goto.super.method.findUsages.title", ((PsiMethod)superElements[0]).getName()), new MethodCellRenderer(showMethodNames)); } else { NavigationUtil.getPsiElementPopup(superElements, CodeInsightBundle.message("goto.super.class.chooser.title")) .showInBestPositionFor(editor); } } @NotNull private PsiElement[] findSuperElements(@NotNull PsiFile file, int offset) { PsiElement element = getElement(file, offset); if (element == null) return PsiElement.EMPTY_ARRAY; final PsiElement psiElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class); if (psiElement instanceof PsiFunctionalExpression) { final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(psiElement); if (interfaceMethod != null) { return ArrayUtil.prepend(interfaceMethod, interfaceMethod.findSuperMethods(false)); } } final PsiNameIdentifierOwner parent = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class, PsiClass.class); if (parent == null) { return PsiElement.EMPTY_ARRAY; } return FindSuperElementsHelper.findSuperElements(parent); } protected PsiElement getElement(@NotNull PsiFile file, int offset) { return file.findElementAt(offset); } @Override public boolean startInWriteAction() { return false; } @Override public void update(@NotNull Editor editor, @NotNull PsiFile file, Presentation presentation) { final PsiElement element = getElement(file, editor.getCaretModel().getOffset()); final PsiElement containingElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class); if (containingElement instanceof PsiClass) { presentation.setText(ActionsBundle.actionText("GotoSuperClass")); presentation.setDescription(ActionsBundle.actionDescription("GotoSuperClass")); } else { presentation.setText(ActionsBundle.actionText("GotoSuperMethod")); presentation.setDescription(ActionsBundle.actionDescription("GotoSuperMethod")); } } }
apache-2.0
chanakaudaya/developer-studio
esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/MediatorFlow11CreateCommand.java
2841
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.CloneTargetContainer; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; /** * @generated */ public class MediatorFlow11CreateCommand extends EditElementCommand { /** * @generated */ public MediatorFlow11CreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { CloneTargetContainer container = (CloneTargetContainer) getElementToEdit(); if (container.getMediatorFlow() != null) { return false; } return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { MediatorFlow newElement = EsbFactory.eINSTANCE.createMediatorFlow(); CloneTargetContainer owner = (CloneTargetContainer) getElementToEdit(); owner.setMediatorFlow(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(MediatorFlow newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
apache-2.0
bmwshop/brooklyn
locations/jclouds/src/main/java/brooklyn/location/jclouds/pool/MachinePoolPredicates.java
5001
package brooklyn.location.jclouds.pool; import java.util.Map; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Processor; import org.jclouds.domain.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; public class MachinePoolPredicates { private static final Logger log = LoggerFactory.getLogger(MachinePoolPredicates.class); public static Predicate<NodeMetadata> except(final MachineSet removedItems) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return !removedItems.contains(input); } }; } public static Predicate<NodeMetadata> except(final Predicate<NodeMetadata> predicateToExclude) { return Predicates.not(predicateToExclude); } public static Predicate<NodeMetadata> matching(final ReusableMachineTemplate template) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return matches(template, input); } }; } public static Predicate<NodeMetadata> withTag(final String tag) { return new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata input) { return input.getTags().contains(tag); } }; } public static Predicate<NodeMetadata> compose(final Predicate<NodeMetadata> ...predicates) { return Predicates.and(predicates); } /** True iff the node matches the criteria specified in this template. * <p> * NB: This only checks some of the most common fields, * plus a hashcode (in strict mode). * In strict mode you're practically guaranteed to match only machines created by this template. * (Add a tag(uid) and you _will_ be guaranteed, strict mode or not.) * <p> * Outside strict mode, some things (OS and hypervisor) can fall through the gaps. * But if that is a problem we can easily add them in. * <p> * (Caveat: If explicit Hardware, Image, and/or Template were specified in the template, * then the hash code probably will not detect it.) **/ public static boolean matches(ReusableMachineTemplate template, NodeMetadata m) { try { // tags and user metadata if (! m.getTags().containsAll( template.getTags(false) )) return false; if (! isSubMapOf(template.getUserMetadata(false), m.getUserMetadata())) return false; // common hardware parameters if (template.getMinRam()!=null && m.getHardware().getRam() < template.getMinRam()) return false; if (template.getMinCores()!=null) { double numCores = 0; for (Processor p: m.getHardware().getProcessors()) numCores += p.getCores(); if (numCores+0.001 < template.getMinCores()) return false; } if (template.getIs64bit()!=null) { if (m.getOperatingSystem().is64Bit() != template.getIs64bit()) return false; } if (template.getOsFamily()!=null) { if (m.getOperatingSystem() == null || !template.getOsFamily().equals(m.getOperatingSystem().getFamily())) return false; } if (template.getOsNameMatchesRegex()!=null) { if (m.getOperatingSystem() == null || m.getOperatingSystem().getName()==null || !m.getOperatingSystem().getName().matches(template.getOsNameMatchesRegex())) return false; } if (template.getLocationId()!=null) { if (!isLocationContainedIn(m.getLocation(), template.getLocationId())) return false; } // TODO other TemplateBuilder fields and TemplateOptions return true; } catch (Exception e) { log.warn("Error (rethrowing) trying to match "+m+" against "+template+": "+e, e); throw Throwables.propagate(e); } } private static boolean isLocationContainedIn(Location location, String locationId) { if (location==null) return false; if (locationId.equals(location.getId())) return true; return isLocationContainedIn(location.getParent(), locationId); } public static boolean isSubMapOf(Map<String, String> sub, Map<String, String> bigger) { for (Map.Entry<String, String> e: sub.entrySet()) { if (e.getValue()==null) { if (!bigger.containsKey(e.getKey())) return false; if (bigger.get(e.getKey())!=null) return false; } else { if (!e.getValue().equals(bigger.get(e.getKey()))) return false; } } return true; } }
apache-2.0
kishorejangid/manifoldcf
connectors/documentum/build-stub/src/main/java/com/documentum/fc/client/DfIdentityException.java
954
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.documentum.fc.client; /** Stub interface to allow the connector to build fully. */ public class DfIdentityException extends DfServiceException { }
apache-2.0
electrum/presto
testing/trino-server-dev/src/main/java/io/trino/server/DevelopmentLoaderConfig.java
2534
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.server; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import io.airlift.configuration.Config; import io.airlift.resolver.ArtifactResolver; import javax.validation.constraints.NotNull; import java.util.List; public class DevelopmentLoaderConfig { private static final Splitter SPLITTER = Splitter.on(',').omitEmptyStrings().trimResults(); private List<String> plugins = ImmutableList.of(); private String mavenLocalRepository = ArtifactResolver.USER_LOCAL_REPO; private List<String> mavenRemoteRepository = ImmutableList.of(ArtifactResolver.MAVEN_CENTRAL_URI); public List<String> getPlugins() { return plugins; } public DevelopmentLoaderConfig setPlugins(List<String> plugins) { this.plugins = ImmutableList.copyOf(plugins); return this; } @Config("plugin.bundles") public DevelopmentLoaderConfig setPlugins(String plugins) { this.plugins = SPLITTER.splitToList(plugins); return this; } @NotNull public String getMavenLocalRepository() { return mavenLocalRepository; } @Config("maven.repo.local") public DevelopmentLoaderConfig setMavenLocalRepository(String mavenLocalRepository) { this.mavenLocalRepository = mavenLocalRepository; return this; } @NotNull public List<String> getMavenRemoteRepository() { return mavenRemoteRepository; } public DevelopmentLoaderConfig setMavenRemoteRepository(List<String> mavenRemoteRepository) { this.mavenRemoteRepository = mavenRemoteRepository; return this; } @Config("maven.repo.remote") public DevelopmentLoaderConfig setMavenRemoteRepository(String mavenRemoteRepository) { this.mavenRemoteRepository = ImmutableList.copyOf(Splitter.on(',').omitEmptyStrings().trimResults().split(mavenRemoteRepository)); return this; } }
apache-2.0
pspaude/uPortal
uportal-war/src/main/java/org/jasig/portal/portlets/statistics/PortletMoveStatisticsController.java
2682
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.portlets.statistics; import java.util.Collections; import java.util.List; import org.jasig.portal.events.aggr.portletlayout.PortletLayoutAggregation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.annotation.RenderMapping; import org.springframework.web.portlet.bind.annotation.ResourceMapping; import com.google.visualization.datasource.base.TypeMismatchException; import com.google.visualization.datasource.datatable.value.NumberValue; import com.google.visualization.datasource.datatable.value.Value; /** * @author Chris Waymire <cwaymire@unicon.net> */ @Controller @RequestMapping(value="VIEW") public class PortletMoveStatisticsController extends BasePortletLayoutStatisticsController<PortletMoveReportForm> { private static final String DATA_TABLE_RESOURCE_ID = "portletMoveData"; private static final String REPORT_NAME = "portletMove.totals"; @RenderMapping(value="MAXIMIZED", params="report=" + REPORT_NAME) public String getLoginView() throws TypeMismatchException { return super.getLoginView(); } @ResourceMapping(DATA_TABLE_RESOURCE_ID) public ModelAndView renderPortletAddAggregationReport(PortletMoveReportForm form) throws TypeMismatchException { return super.renderPortletAddAggregationReport(form); } @Override public String getReportName() { return REPORT_NAME; } @Override public String getReportDataResourceId() { return DATA_TABLE_RESOURCE_ID; } @Override protected List<Value> createRowValues(PortletLayoutAggregation aggr, PortletMoveReportForm form) { int count = aggr != null ? aggr.getMoveCount() : 0; return Collections.<Value>singletonList(new NumberValue(count)); } }
apache-2.0
immortius/Terasology
engine/src/main/java/org/terasology/entitySystem/prefab/internal/PojoPrefab.java
2855
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.entitySystem.prefab.internal; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.terasology.assets.AssetType; import org.terasology.assets.ResourceUrn; import org.terasology.entitySystem.Component; import org.terasology.entitySystem.prefab.Prefab; import org.terasology.entitySystem.prefab.PrefabData; import java.util.List; import java.util.Map; /** * @author Immortius */ public class PojoPrefab extends Prefab { private Prefab parent; private Map<Class<? extends Component>, Component> componentMap; private List<Prefab> children = Lists.newArrayList(); private boolean persisted; private boolean alwaysRelevant = true; public PojoPrefab(ResourceUrn urn, AssetType<?, PrefabData> assetType, PrefabData data) { super(urn, assetType); reload(data); } @Override public Prefab getParent() { return parent; } @Override public List<Prefab> getChildren() { return ImmutableList.copyOf(children); } @Override public boolean isPersisted() { return persisted; } @Override public boolean isAlwaysRelevant() { return alwaysRelevant; } @Override public boolean exists() { return true; } @Override public boolean hasComponent(Class<? extends Component> component) { return componentMap.containsKey(component); } @Override public <T extends Component> T getComponent(Class<T> componentClass) { return componentClass.cast(componentMap.get(componentClass)); } @Override public Iterable<Component> iterateComponents() { return ImmutableList.copyOf(componentMap.values()); } @Override protected void doDispose() { } @Override protected void doReload(PrefabData data) { this.componentMap = ImmutableMap.copyOf(data.getComponents()); this.persisted = data.isPersisted(); this.alwaysRelevant = data.isAlwaysRelevant(); this.parent = data.getParent(); if (parent != null && parent instanceof PojoPrefab) { ((PojoPrefab) parent).children.add(this); } } }
apache-2.0
briandwyer/cas-hudson
cas-server-core/src/main/java/org/jasig/cas/services/jmx/AbstractServicesManagerMBean.java
3919
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.services.jmx; import org.jasig.cas.services.RegisteredService; import org.jasig.cas.services.RegisteredServiceImpl; import org.jasig.cas.services.ServicesManager; import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperationParameter; import org.springframework.util.Assert; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; /** * Abstract base class to support both the {@link org.jasig.cas.services.ServicesManager} and the * {@link org.jasig.cas.services.ReloadableServicesManager}. * * @author <a href="mailto:tobias.trelle@proximity.de">Tobias Trelle</a> * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.4.4 */ public abstract class AbstractServicesManagerMBean<T extends ServicesManager> { @NotNull private T servicesManager; protected AbstractServicesManagerMBean(final T servicesManager) { this.servicesManager = servicesManager; } protected final T getServicesManager() { return this.servicesManager; } @ManagedAttribute(description = "Retrieves the list of Registered Services in a slightly friendlier output.") public final List<String> getRegisteredServicesAsStrings() { final List<String> services = new ArrayList<String>(); for (final RegisteredService r : this.servicesManager.getAllServices()) { services.add(new StringBuilder().append("id: ").append(r.getId()) .append(" name: ").append(r.getName()) .append(" enabled: ").append(r.isEnabled()) .append(" ssoEnabled: ").append(r.isSsoEnabled()) .append(" serviceId: ").append(r.getServiceId()) .toString()); } return services; } @ManagedOperation(description = "Can remove a service based on its identifier.") @ManagedOperationParameter(name="id", description = "the identifier to remove") public final RegisteredService removeService(final long id) { return this.servicesManager.delete(id); } @ManagedOperation(description = "Disable a service by id.") @ManagedOperationParameter(name="id", description = "the identifier to disable") public final void disableService(final long id) { changeEnabledState(id, false); } @ManagedOperation(description = "Enable a service by its id.") @ManagedOperationParameter(name="id", description = "the identifier to enable.") public final void enableService(final long id) { changeEnabledState(id, true); } private void changeEnabledState(final long id, final boolean newState) { final RegisteredService r = this.servicesManager.findServiceBy(id); Assert.notNull(r, "invalid RegisteredService id"); // we screwed up our APIs in older versions of CAS, so we need to CAST this to do anything useful. ((RegisteredServiceImpl) r).setEnabled(newState); this.servicesManager.save(r); } }
apache-2.0
kaulkie/jline2
src/main/java/jline/internal/ShutdownHooks.java
3503
/* * Copyright (c) 2002-2015, the original author or authors. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. * * http://www.opensource.org/licenses/bsd-license.php */ package jline.internal; import java.util.ArrayList; import java.util.List; import static jline.internal.Preconditions.checkNotNull; /** * Manages the JLine shutdown-hook thread and tasks to execute on shutdown. * * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> * @since 2.7 */ public class ShutdownHooks { public static final String JLINE_SHUTDOWNHOOK = "jline.shutdownhook"; private static final boolean enabled = Configuration.getBoolean(JLINE_SHUTDOWNHOOK, true); private static final List<Task> tasks = new ArrayList<Task>(); private static Thread hook; public static synchronized <T extends Task> T add(final T task) { checkNotNull(task); // If not enabled ignore if (!enabled) { Log.debug("Shutdown-hook is disabled; not installing: ", task); return task; } // Install the hook thread if needed if (hook == null) { hook = addHook(new Thread("JLine Shutdown Hook") { @Override public void run() { runTasks(); } }); } // Track the task Log.debug("Adding shutdown-hook task: ", task); tasks.add(task); return task; } private static synchronized void runTasks() { Log.debug("Running all shutdown-hook tasks"); // Iterate through copy of tasks list for (Task task : tasks.toArray(new Task[tasks.size()])) { Log.debug("Running task: ", task); try { task.run(); } catch (Throwable e) { Log.warn("Task failed", e); } } tasks.clear(); } private static Thread addHook(final Thread thread) { Log.debug("Registering shutdown-hook: ", thread); try { Runtime.getRuntime().addShutdownHook(thread); } catch (AbstractMethodError e) { // JDK 1.3+ only method. Bummer. Log.debug("Failed to register shutdown-hook", e); } return thread; } public static synchronized void remove(final Task task) { checkNotNull(task); // ignore if not enabled or hook never installed if (!enabled || hook == null) { return; } // Drop the task tasks.remove(task); // If there are no more tasks, then remove the hook thread if (tasks.isEmpty()) { removeHook(hook); hook = null; } } private static void removeHook(final Thread thread) { Log.debug("Removing shutdown-hook: ", thread); try { Runtime.getRuntime().removeShutdownHook(thread); } catch (AbstractMethodError e) { // JDK 1.3+ only method. Bummer. Log.debug("Failed to remove shutdown-hook", e); } catch (IllegalStateException e) { // The VM is shutting down, not a big deal; ignore } } /** * Essentially a {@link Runnable} which allows running to throw an exception. */ public static interface Task { void run() throws Exception; } }
bsd-3-clause
chrisrico/XChange
xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/trade/DSXOrderHistoryReturn.java
517
package org.knowm.xchange.dsx.dto.trade; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import org.knowm.xchange.dsx.dto.DSXReturn; /** @author Mikhail Wall */ public class DSXOrderHistoryReturn extends DSXReturn<Map<Long, DSXOrderHistoryResult>> { public DSXOrderHistoryReturn( @JsonProperty("success") boolean success, @JsonProperty("return") Map<Long, DSXOrderHistoryResult> value, @JsonProperty("error") String error) { super(success, value, error); } }
mit
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/java/time/Year.java
47803
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package java.time; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; import static java.time.temporal.ChronoUnit.CENTURIES; import static java.time.temporal.ChronoUnit.DECADES; import static java.time.temporal.ChronoUnit.ERAS; import static java.time.temporal.ChronoUnit.MILLENNIA; import static java.time.temporal.ChronoUnit.YEARS; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.time.chrono.Chronology; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.SignStyle; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; import java.util.Objects; /** * A year in the ISO-8601 calendar system, such as {@code 2007}. * <p> * {@code Year} is an immutable date-time object that represents a year. * Any field that can be derived from a year can be obtained. * <p> * <b>Note that years in the ISO chronology only align with years in the * Gregorian-Julian system for modern years. Parts of Russia did not switch to the * modern Gregorian/ISO rules until 1920. * As such, historical years must be treated with caution.</b> * <p> * This class does not store or represent a month, day, time or time-zone. * For example, the value "2007" can be stored in a {@code Year}. * <p> * Years represented by this class follow the ISO-8601 standard and use * the proleptic numbering system. Year 1 is preceded by year 0, then by year -1. * <p> * The ISO-8601 calendar system is the modern civil calendar system used today * in most of the world. It is equivalent to the proleptic Gregorian calendar * system, in which today's rules for leap years are applied for all time. * For most applications written today, the ISO-8601 rules are entirely suitable. * However, any application that makes use of historical dates, and requires them * to be accurate will find the ISO-8601 approach unsuitable. * * <p> * This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a> * class; use of identity-sensitive operations (including reference equality * ({@code ==}), identity hash code, or synchronization) on instances of * {@code Year} may have unpredictable results and should be avoided. * The {@code equals} method should be used for comparisons. * * @implSpec * This class is immutable and thread-safe. * * @since 1.8 */ public final class Year implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable { /** * The minimum supported year, '-999,999,999'. */ public static final int MIN_VALUE = -999_999_999; /** * The maximum supported year, '+999,999,999'. */ public static final int MAX_VALUE = 999_999_999; /** * Serialization version. */ private static final long serialVersionUID = -23038383694477807L; /** * Parser. */ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder() .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .toFormatter(); /** * The year being represented. */ private final int year; //----------------------------------------------------------------------- /** * Obtains the current year from the system clock in the default time-zone. * <p> * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default * time-zone to obtain the current year. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * * @return the current year using the system clock and default time-zone, not null */ public static Year now() { return now(Clock.systemDefaultZone()); } /** * Obtains the current year from the system clock in the specified time-zone. * <p> * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year. * Specifying the time-zone avoids dependence on the default time-zone. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * * @param zone the zone ID to use, not null * @return the current year using the system clock, not null */ public static Year now(ZoneId zone) { return now(Clock.system(zone)); } /** * Obtains the current year from the specified clock. * <p> * This will query the specified clock to obtain the current year. * Using this method allows the use of an alternate clock for testing. * The alternate clock may be introduced using {@link Clock dependency injection}. * * @param clock the clock to use, not null * @return the current year, not null */ public static Year now(Clock clock) { final LocalDate now = LocalDate.now(clock); // called once return Year.of(now.getYear()); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Year}. * <p> * This method accepts a year value from the proleptic ISO calendar system. * <p> * The year 2AD/CE is represented by 2.<br> * The year 1AD/CE is represented by 1.<br> * The year 1BC/BCE is represented by 0.<br> * The year 2BC/BCE is represented by -1.<br> * * @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE} * @return the year, not null * @throws DateTimeException if the field is invalid */ public static Year of(int isoYear) { YEAR.checkValidValue(isoYear); return new Year(isoYear); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Year} from a temporal object. * <p> * This obtains a year based on the specified temporal. * A {@code TemporalAccessor} represents an arbitrary set of date and time information, * which this factory converts to an instance of {@code Year}. * <p> * The conversion extracts the {@link ChronoField#YEAR year} field. * The extraction is only permitted if the temporal object has an ISO * chronology, or can be converted to a {@code LocalDate}. * <p> * This method matches the signature of the functional interface {@link TemporalQuery} * allowing it to be used in queries via method reference, {@code Year::from}. * * @param temporal the temporal object to convert, not null * @return the year, not null * @throws DateTimeException if unable to convert to a {@code Year} */ public static Year from(TemporalAccessor temporal) { if (temporal instanceof Year) { return (Year) temporal; } Objects.requireNonNull(temporal, "temporal"); try { if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) { temporal = LocalDate.from(temporal); } return of(temporal.get(YEAR)); } catch (DateTimeException ex) { throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " + temporal + " of type " + temporal.getClass().getName(), ex); } } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Year} from a text string such as {@code 2007}. * <p> * The string must represent a valid year. * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol. * * @param text the text to parse such as "2007", not null * @return the parsed year, not null * @throws DateTimeParseException if the text cannot be parsed */ public static Year parse(CharSequence text) { return parse(text, PARSER); } /** * Obtains an instance of {@code Year} from a text string using a specific formatter. * <p> * The text is parsed using the formatter, returning a year. * * @param text the text to parse, not null * @param formatter the formatter to use, not null * @return the parsed year, not null * @throws DateTimeParseException if the text cannot be parsed */ public static Year parse(CharSequence text, DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.parse(text, Year::from); } //------------------------------------------------------------------------- /** * Checks if the year is a leap year, according to the ISO proleptic * calendar system rules. * <p> * This method applies the current rules for leap years across the whole time-line. * In general, a year is a leap year if it is divisible by four without * remainder. However, years divisible by 100, are not leap years, with * the exception of years divisible by 400 which are. * <p> * For example, 1904 is a leap year it is divisible by 4. * 1900 was not a leap year as it is divisible by 100, however 2000 was a * leap year as it is divisible by 400. * <p> * The calculation is proleptic - applying the same rules into the far future and far past. * This is historically inaccurate, but is correct for the ISO-8601 standard. * * @param year the year to check * @return true if the year is leap, false otherwise */ public static boolean isLeap(long year) { return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0); } //----------------------------------------------------------------------- /** * Constructor. * * @param year the year to represent */ private Year(int year) { this.year = year; } //----------------------------------------------------------------------- /** * Gets the year value. * <p> * The year returned by this method is proleptic as per {@code get(YEAR)}. * * @return the year, {@code MIN_VALUE} to {@code MAX_VALUE} */ public int getValue() { return year; } //----------------------------------------------------------------------- /** * Checks if the specified field is supported. * <p> * This checks if this year can be queried for the specified field. * If false, then calling the {@link #range(TemporalField) range}, * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} * methods will throw an exception. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The supported fields are: * <ul> * <li>{@code YEAR_OF_ERA} * <li>{@code YEAR} * <li>{@code ERA} * </ul> * All other {@code ChronoField} instances will return false. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the field is supported is determined by the field. * * @param field the field to check, null returns false * @return true if the field is supported on this year, false if not */ @Override public boolean isSupported(TemporalField field) { if (field instanceof ChronoField) { return field == YEAR || field == YEAR_OF_ERA || field == ERA; } return field != null && field.isSupportedBy(this); } /** * Checks if the specified unit is supported. * <p> * This checks if the specified unit can be added to, or subtracted from, this date-time. * If false, then calling the {@link #plus(long, TemporalUnit)} and * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. * <p> * If the unit is a {@link ChronoUnit} then the query is implemented here. * The supported units are: * <ul> * <li>{@code YEARS} * <li>{@code DECADES} * <li>{@code CENTURIES} * <li>{@code MILLENNIA} * <li>{@code ERAS} * </ul> * All other {@code ChronoUnit} instances will return false. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} * passing {@code this} as the argument. * Whether the unit is supported is determined by the unit. * * @param unit the unit to check, null returns false * @return true if the unit can be added/subtracted, false if not */ @Override public boolean isSupported(TemporalUnit unit) { if (unit instanceof ChronoUnit) { return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS; } return unit != null && unit.isSupportedBy(this); } //----------------------------------------------------------------------- /** * Gets the range of valid values for the specified field. * <p> * The range object expresses the minimum and maximum valid values for a field. * This year is used to enhance the accuracy of the returned range. * If it is not possible to return the range, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return * appropriate range instances. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the range can be obtained is determined by the field. * * @param field the field to query the range for, not null * @return the range of valid values for the field, not null * @throws DateTimeException if the range for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported */ @Override public ValueRange range(TemporalField field) { if (field == YEAR_OF_ERA) { return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE)); } return Temporal.super.range(field); } /** * Gets the value of the specified field from this year as an {@code int}. * <p> * This queries this year for the value for the specified field. * The returned value will always be within the valid range of values for the field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this year. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained or * the value is outside the range of valid values for the field * @throws UnsupportedTemporalTypeException if the field is not supported or * the range of values exceeds an {@code int} * @throws ArithmeticException if numeric overflow occurs */ @Override // override for Javadoc public int get(TemporalField field) { return range(field).checkValidIntValue(getLong(field), field); } /** * Gets the value of the specified field from this year as a {@code long}. * <p> * This queries this year for the value for the specified field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this year. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long getLong(TemporalField field) { if (field instanceof ChronoField) { switch ((ChronoField) field) { case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); case YEAR: return year; case ERA: return (year < 1 ? 0 : 1); } throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } return field.getFrom(this); } //----------------------------------------------------------------------- /** * Checks if the year is a leap year, according to the ISO proleptic * calendar system rules. * <p> * This method applies the current rules for leap years across the whole time-line. * In general, a year is a leap year if it is divisible by four without * remainder. However, years divisible by 100, are not leap years, with * the exception of years divisible by 400 which are. * <p> * For example, 1904 is a leap year it is divisible by 4. * 1900 was not a leap year as it is divisible by 100, however 2000 was a * leap year as it is divisible by 400. * <p> * The calculation is proleptic - applying the same rules into the far future and far past. * This is historically inaccurate, but is correct for the ISO-8601 standard. * * @return true if the year is leap, false otherwise */ public boolean isLeap() { return Year.isLeap(year); } /** * Checks if the month-day is valid for this year. * <p> * This method checks whether this year and the input month and day form * a valid date. * * @param monthDay the month-day to validate, null returns false * @return true if the month and day are valid for this year */ public boolean isValidMonthDay(MonthDay monthDay) { return monthDay != null && monthDay.isValidYear(year); } /** * Gets the length of this year in days. * * @return the length of this year in days, 365 or 366 */ public int length() { return isLeap() ? 366 : 365; } //----------------------------------------------------------------------- /** * Returns an adjusted copy of this year. * <p> * This returns a {@code Year}, based on this one, with the year adjusted. * The adjustment takes place using the specified adjuster strategy object. * Read the documentation of the adjuster to understand what adjustment will be made. * <p> * The result of this method is obtained by invoking the * {@link TemporalAdjuster#adjustInto(Temporal)} method on the * specified adjuster passing {@code this} as the argument. * <p> * This instance is immutable and unaffected by this method call. * * @param adjuster the adjuster to use, not null * @return a {@code Year} based on {@code this} with the adjustment made, not null * @throws DateTimeException if the adjustment cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Year with(TemporalAdjuster adjuster) { return (Year) adjuster.adjustInto(this); } /** * Returns a copy of this year with the specified field set to a new value. * <p> * This returns a {@code Year}, based on this one, with the value * for the specified field changed. * If it is not possible to set the value, because the field is not supported or for * some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the adjustment is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code YEAR_OF_ERA} - * Returns a {@code Year} with the specified year-of-era * The era will be unchanged. * <li>{@code YEAR} - * Returns a {@code Year} with the specified year. * This completely replaces the date and is equivalent to {@link #of(int)}. * <li>{@code ERA} - * Returns a {@code Year} with the specified era. * The year-of-era will be unchanged. * </ul> * <p> * In all cases, if the new value is outside the valid range of values for the field * then a {@code DateTimeException} will be thrown. * <p> * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} * passing {@code this} as the argument. In this case, the field determines * whether and how to adjust the instant. * <p> * This instance is immutable and unaffected by this method call. * * @param field the field to set in the result, not null * @param newValue the new value of the field in the result * @return a {@code Year} based on {@code this} with the specified field set, not null * @throws DateTimeException if the field cannot be set * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Year with(TemporalField field, long newValue) { if (field instanceof ChronoField) { ChronoField f = (ChronoField) field; f.checkValidValue(newValue); switch (f) { case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue)); case YEAR: return Year.of((int) newValue); case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year)); } throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } return field.adjustInto(this, newValue); } //----------------------------------------------------------------------- /** * Returns a copy of this year with the specified amount added. * <p> * This returns a {@code Year}, based on this one, with the specified amount added. * The amount is typically {@link Period} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free * to implement the addition in any way it wishes, however it typically * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully added. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount to add, not null * @return a {@code Year} based on this year with the addition made, not null * @throws DateTimeException if the addition cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Year plus(TemporalAmount amountToAdd) { return (Year) amountToAdd.addTo(this); } /** * Returns a copy of this year with the specified amount added. * <p> * This returns a {@code Year}, based on this one, with the amount * in terms of the unit added. If it is not possible to add the amount, because the * unit is not supported or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoUnit} then the addition is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code YEARS} - * Returns a {@code Year} with the specified number of years added. * This is equivalent to {@link #plusYears(long)}. * <li>{@code DECADES} - * Returns a {@code Year} with the specified number of decades added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 10. * <li>{@code CENTURIES} - * Returns a {@code Year} with the specified number of centuries added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 100. * <li>{@code MILLENNIA} - * Returns a {@code Year} with the specified number of millennia added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 1,000. * <li>{@code ERAS} - * Returns a {@code Year} with the specified number of eras added. * Only two eras are supported so the amount must be one, zero or minus one. * If the amount is non-zero then the year is changed such that the year-of-era * is unchanged. * </ul> * <p> * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} * passing {@code this} as the argument. In this case, the unit determines * whether and how to perform the addition. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount of the unit to add to the result, may be negative * @param unit the unit of the amount to add, not null * @return a {@code Year} based on this year with the specified amount added, not null * @throws DateTimeException if the addition cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Year plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return plusYears(amountToAdd); case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); } throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } return unit.addTo(this, amountToAdd); } /** * Returns a copy of this year with the specified number of years added. * <p> * This instance is immutable and unaffected by this method call. * * @param yearsToAdd the years to add, may be negative * @return a {@code Year} based on this year with the period added, not null * @throws DateTimeException if the result exceeds the supported year range */ public Year plusYears(long yearsToAdd) { if (yearsToAdd == 0) { return this; } return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe } //----------------------------------------------------------------------- /** * Returns a copy of this year with the specified amount subtracted. * <p> * This returns a {@code Year}, based on this one, with the specified amount subtracted. * The amount is typically {@link Period} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free * to implement the subtraction in any way it wishes, however it typically * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount to subtract, not null * @return a {@code Year} based on this year with the subtraction made, not null * @throws DateTimeException if the subtraction cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Year minus(TemporalAmount amountToSubtract) { return (Year) amountToSubtract.subtractFrom(this); } /** * Returns a copy of this year with the specified amount subtracted. * <p> * This returns a {@code Year}, based on this one, with the amount * in terms of the unit subtracted. If it is not possible to subtract the amount, * because the unit is not supported or for some other reason, an exception is thrown. * <p> * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. * See that method for a full description of how addition, and thus subtraction, works. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount of the unit to subtract from the result, may be negative * @param unit the unit of the amount to subtract, not null * @return a {@code Year} based on this year with the specified amount subtracted, not null * @throws DateTimeException if the subtraction cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Year minus(long amountToSubtract, TemporalUnit unit) { return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); } /** * Returns a copy of this year with the specified number of years subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param yearsToSubtract the years to subtract, may be negative * @return a {@code Year} based on this year with the period subtracted, not null * @throws DateTimeException if the result exceeds the supported year range */ public Year minusYears(long yearsToSubtract) { return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); } //----------------------------------------------------------------------- /** * Queries this year using the specified query. * <p> * This queries this year using the specified query strategy object. * The {@code TemporalQuery} object defines the logic to be used to * obtain the result. Read the documentation of the query to understand * what the result of this method will be. * <p> * The result of this method is obtained by invoking the * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the * specified query passing {@code this} as the argument. * * @param <R> the type of the result * @param query the query to invoke, not null * @return the query result, null may be returned (defined by the query) * @throws DateTimeException if unable to query (defined by the query) * @throws ArithmeticException if numeric overflow occurs (defined by the query) */ @SuppressWarnings("unchecked") @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.chronology()) { return (R) IsoChronology.INSTANCE; } else if (query == TemporalQueries.precision()) { return (R) YEARS; } return Temporal.super.query(query); } /** * Adjusts the specified temporal object to have this year. * <p> * This returns a temporal object of the same observable type as the input * with the year changed to be the same as this. * <p> * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} * passing {@link ChronoField#YEAR} as the field. * If the specified temporal object does not use the ISO calendar system then * a {@code DateTimeException} is thrown. * <p> * In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#with(TemporalAdjuster)}: * <pre> * // these two lines are equivalent, but the second approach is recommended * temporal = thisYear.adjustInto(temporal); * temporal = temporal.with(thisYear); * </pre> * <p> * This instance is immutable and unaffected by this method call. * * @param temporal the target object to be adjusted, not null * @return the adjusted object, not null * @throws DateTimeException if unable to make the adjustment * @throws ArithmeticException if numeric overflow occurs */ @Override public Temporal adjustInto(Temporal temporal) { if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) { throw new DateTimeException("Adjustment only supported on ISO date-time"); } return temporal.with(YEAR, year); } /** * Calculates the amount of time until another year in terms of the specified unit. * <p> * This calculates the amount of time between two {@code Year} * objects in terms of a single {@code TemporalUnit}. * The start and end points are {@code this} and the specified year. * The result will be negative if the end is before the start. * The {@code Temporal} passed to this method is converted to a * {@code Year} using {@link #from(TemporalAccessor)}. * For example, the period in decades between two year can be calculated * using {@code startYear.until(endYear, DECADES)}. * <p> * The calculation returns a whole number, representing the number of * complete units between the two years. * For example, the period in decades between 2012 and 2031 * will only be one decade as it is one year short of two decades. * <p> * There are two equivalent ways of using this method. * The first is to invoke this method. * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: * <pre> * // these two lines are equivalent * amount = start.until(end, YEARS); * amount = YEARS.between(start, end); * </pre> * The choice should be made based on which makes the code more readable. * <p> * The calculation is implemented in this method for {@link ChronoUnit}. * The units {@code YEARS}, {@code DECADES}, {@code CENTURIES}, * {@code MILLENNIA} and {@code ERAS} are supported. * Other {@code ChronoUnit} values will throw an exception. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} * passing {@code this} as the first argument and the converted input temporal * as the second argument. * <p> * This instance is immutable and unaffected by this method call. * * @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null * @param unit the unit to measure the amount in, not null * @return the amount of time between this year and the end year * @throws DateTimeException if the amount cannot be calculated, or the end * temporal cannot be converted to a {@code Year} * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long until(Temporal endExclusive, TemporalUnit unit) { Year end = Year.from(endExclusive); if (unit instanceof ChronoUnit) { long yearsUntil = ((long) end.year) - year; // no overflow switch ((ChronoUnit) unit) { case YEARS: return yearsUntil; case DECADES: return yearsUntil / 10; case CENTURIES: return yearsUntil / 100; case MILLENNIA: return yearsUntil / 1000; case ERAS: return end.getLong(ERA) - getLong(ERA); } throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } return unit.between(this, end); } /** * Formats this year using the specified formatter. * <p> * This year will be passed to the formatter to produce a string. * * @param formatter the formatter to use, not null * @return the formatted year string, not null * @throws DateTimeException if an error occurs during printing */ public String format(DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.format(this); } //----------------------------------------------------------------------- /** * Combines this year with a day-of-year to create a {@code LocalDate}. * <p> * This returns a {@code LocalDate} formed from this year and the specified day-of-year. * <p> * The day-of-year value 366 is only valid in a leap year. * * @param dayOfYear the day-of-year to use, not null * @return the local date formed from this year and the specified date of year, not null * @throws DateTimeException if the day of year is zero or less, 366 or greater or equal * to 366 and this is not a leap year */ public LocalDate atDay(int dayOfYear) { return LocalDate.ofYearDay(year, dayOfYear); } /** * Combines this year with a month to create a {@code YearMonth}. * <p> * This returns a {@code YearMonth} formed from this year and the specified month. * All possible combinations of year and month are valid. * <p> * This method can be used as part of a chain to produce a date: * <pre> * LocalDate date = year.atMonth(month).atDay(day); * </pre> * * @param month the month-of-year to use, not null * @return the year-month formed from this year and the specified month, not null */ public YearMonth atMonth(Month month) { return YearMonth.of(year, month); } /** * Combines this year with a month to create a {@code YearMonth}. * <p> * This returns a {@code YearMonth} formed from this year and the specified month. * All possible combinations of year and month are valid. * <p> * This method can be used as part of a chain to produce a date: * <pre> * LocalDate date = year.atMonth(month).atDay(day); * </pre> * * @param month the month-of-year to use, from 1 (January) to 12 (December) * @return the year-month formed from this year and the specified month, not null * @throws DateTimeException if the month is invalid */ public YearMonth atMonth(int month) { return YearMonth.of(year, month); } /** * Combines this year with a month-day to create a {@code LocalDate}. * <p> * This returns a {@code LocalDate} formed from this year and the specified month-day. * <p> * A month-day of February 29th will be adjusted to February 28th in the resulting * date if the year is not a leap year. * * @param monthDay the month-day to use, not null * @return the local date formed from this year and the specified month-day, not null */ public LocalDate atMonthDay(MonthDay monthDay) { return monthDay.atYear(year); } //----------------------------------------------------------------------- /** * Compares this year to another year. * <p> * The comparison is based on the value of the year. * It is "consistent with equals", as defined by {@link Comparable}. * * @param other the other year to compare to, not null * @return the comparator value, negative if less, positive if greater */ @Override public int compareTo(Year other) { return year - other.year; } /** * Is this year after the specified year. * * @param other the other year to compare to, not null * @return true if this is after the specified year */ public boolean isAfter(Year other) { return year > other.year; } /** * Is this year before the specified year. * * @param other the other year to compare to, not null * @return true if this point is before the specified year */ public boolean isBefore(Year other) { return year < other.year; } //----------------------------------------------------------------------- /** * Checks if this year is equal to another year. * <p> * The comparison is based on the time-line position of the years. * * @param obj the object to check, null returns false * @return true if this is equal to the other year */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Year) { return year == ((Year) obj).year; } return false; } /** * A hash code for this year. * * @return a suitable hash code */ @Override public int hashCode() { return year; } //----------------------------------------------------------------------- /** * Outputs this year as a {@code String}. * * @return a string representation of this year, not null */ @Override public String toString() { return Integer.toString(year); } //----------------------------------------------------------------------- /** * Writes the object using a * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. * @serialData * <pre> * out.writeByte(11); // identifies a Year * out.writeInt(year); * </pre> * * @return the instance of {@code Ser}, not null */ private Object writeReplace() { return new Ser(Ser.YEAR_TYPE, this); } /** * Defend against malicious streams. * * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } void writeExternal(DataOutput out) throws IOException { out.writeInt(year); } static Year readExternal(DataInput in) throws IOException { return Year.of(in.readInt()); } }
mit
gazarenkov/che-sketch
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/UnixProcessManager.java
5909
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core.util; import com.sun.jna.Library; import com.sun.jna.Native; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * Process manager for *nix like system. * * @author andrew00x */ class UnixProcessManager extends ProcessManager { /* At the moment tested on linux only. */ private static final Logger LOG = LoggerFactory.getLogger(UnixProcessManager.class); private static final CLibrary C_LIBRARY; private static final Field PID_FIELD; static { CLibrary lib = null; Field pidField = null; if (SystemInfo.isUnix()) { try { lib = ((CLibrary)Native.loadLibrary("c", CLibrary.class)); } catch (Exception e) { LOG.error("Cannot load native library", e); } try { pidField = Thread.currentThread().getContextClassLoader().loadClass("java.lang.UNIXProcess").getDeclaredField("pid"); pidField.setAccessible(true); } catch (Exception e) { LOG.error(e.getMessage(), e); } } C_LIBRARY = lib; PID_FIELD = pidField; } private static interface CLibrary extends Library { // kill -l int SIGKILL = 9; int SIGTERM = 15; int kill(int pid, int signal); String strerror(int errno); int system(String cmd); } private static final Pattern UNIX_PS_TABLE_PATTERN = Pattern.compile("\\s+"); @Override public void kill(Process process) { if (C_LIBRARY != null) { killTree(getPid(process)); } else { throw new IllegalStateException("Can't kill process. Not unix system?"); } } private void killTree(int pid) { final int[] children = getChildProcesses(pid); LOG.debug("PID: {}, child PIDs: {}", pid, children); if (children.length > 0) { for (int cpid : children) { killTree(cpid); // kill process tree recursively } } int r = C_LIBRARY.kill(pid, CLibrary.SIGKILL); // kill origin process LOG.debug("kill {}", pid); if (r != 0) { if (LOG.isDebugEnabled()) { LOG.debug("kill for {} returns {}, strerror '{}'", pid, r, C_LIBRARY.strerror(r)); } } } private int[] getChildProcesses(final int myPid) { final String ps = "ps -e -o ppid,pid,comm"; /* PPID, PID, COMMAND */ final List<Integer> children = new ArrayList<>(); final StringBuilder error = new StringBuilder(); final LineConsumer stdout = new LineConsumer() { @Override public void writeLine(String line) throws IOException { if (line != null && !line.isEmpty()) { final String[] tokens = UNIX_PS_TABLE_PATTERN.split(line.trim()); if (tokens.length == 3 /* PPID, PID, COMMAND */) { int ppid; try { ppid = Integer.parseInt(tokens[0]); } catch (NumberFormatException e) { // May be first line from process table: 'PPID PID COMMAND'. Skip it. return; } if (ppid == myPid) { int pid = Integer.parseInt(tokens[1]); children.add(pid); } } } } @Override public void close() throws IOException { } }; final LineConsumer stderr = new LineConsumer() { @Override public void writeLine(String line) throws IOException { if (error.length() > 0) { error.append('\n'); } error.append(line); } @Override public void close() throws IOException { } }; try { ProcessUtil.process(Runtime.getRuntime().exec(ps), stdout, stderr); } catch (IOException e) { throw new IllegalStateException(e); } if (error.length() > 0) { throw new IllegalStateException("can't get child processes: " + error.toString()); } final int size = children.size(); final int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = children.get(i); } return result; } @Override public boolean isAlive(Process process) { return process.isAlive(); } int getPid(Process process) { if (PID_FIELD != null) { try { return ((Number)PID_FIELD.get(process)).intValue(); } catch (IllegalAccessException e) { throw new IllegalStateException("Can't get process' pid. Not unix system?", e); } } else { throw new IllegalStateException("Can't get process' pid. Not unix system?"); } } @Override int system(String command) { return C_LIBRARY.system(command); } }
epl-1.0
gazarenkov/che-sketch
ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/toolbar/MenuLockLayer.java
3234
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ui.toolbar; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.RootPanel; /** * This Lock Layer for Popup Menu uses as root for for Popup Menus and uses for closing all visible popups when user clicked outside one of * them. * * @author Vitaliy Guliy */ public class MenuLockLayer extends AbsolutePanel { /** Lock Layer uses for locking of screen. Uses for hiding popups. */ private class LockLayer extends AbsolutePanel { public LockLayer() { sinkEvents(Event.ONMOUSEDOWN); } @Override public void onBrowserEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: close(); break; } } } /** Callback which is uses for closing Popup menu. */ private CloseMenuHandler closeMenuCallback; private int topOffset = 20; /** Create Menu Lock Layer. */ public MenuLockLayer() { this(null, 0); } /** * Create Menu Lock Layer. * * @param closeMenuCallback * - callback which is uses for */ public MenuLockLayer(CloseMenuHandler closeMenuCallback) { this(closeMenuCallback, 0); } public MenuLockLayer(CloseMenuHandler closeMenuCallback, int topOffset) { this.closeMenuCallback = closeMenuCallback; this.topOffset = topOffset; getElement().setId("menu-lock-layer-id"); RootPanel.get().add(this, 0, topOffset); getElement().getStyle().setProperty("right", "0px"); getElement().getStyle().setProperty("bottom", "0px"); getElement().getStyle().setProperty("zIndex", (Integer.MAX_VALUE - 5) + ""); AbsolutePanel blockMouseEventsPanel = new LockLayer(); blockMouseEventsPanel.setStyleName("exo-lockLayer"); blockMouseEventsPanel.getElement().getStyle().setProperty("position", "absolute"); blockMouseEventsPanel.getElement().getStyle().setProperty("left", "0px"); blockMouseEventsPanel.getElement().getStyle().setProperty("top", "0px"); blockMouseEventsPanel.getElement().getStyle().setProperty("right", "0px"); blockMouseEventsPanel.getElement().getStyle().setProperty("bottom", "0px"); add(blockMouseEventsPanel); } public void close() { removeFromParent(); if (closeMenuCallback != null) { closeMenuCallback.onCloseMenu(); } } public int getTopOffset() { return topOffset; } }
epl-1.0
revans2/storm
storm-core/src/jvm/backtype/storm/state/ISynchronizeOutputCollector.java
167
package backtype.storm.state; import java.util.List; public interface ISynchronizeOutputCollector { void add(int streamId, Object id, List<Object> tuple); }
epl-1.0
gazarenkov/che-sketch
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ServiceContext.java
1098
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core.rest; import javax.ws.rs.core.UriBuilder; /** * Helps to deliver context of RESTful request to components. * * @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a> */ public interface ServiceContext { /** * Get UriBuilder which already contains base URI of RESTful application and URL pattern of RESTful service that produces this * instance. */ UriBuilder getServiceUriBuilder(); /** Get UriBuilder which already contains base URI of RESTful application. */ UriBuilder getBaseUriBuilder(); }
epl-1.0
tarzanking/javacpp
src/main/java/com/googlecode/javacpp/Generator.java
138100
/* * Copyright (C) 2011,2012,2013,2014 Samuel Audet * * This file is part of JavaCPP. * * JavaCPP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version (subject to the "Classpath" exception * as provided in the LICENSE.txt file that accompanied this code). * * JavaCPP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JavaCPP. If not, see <http://www.gnu.org/licenses/>. */ package com.googlecode.javacpp; import com.googlecode.javacpp.annotation.Adapter; import com.googlecode.javacpp.annotation.Allocator; import com.googlecode.javacpp.annotation.ArrayAllocator; import com.googlecode.javacpp.annotation.ByPtr; import com.googlecode.javacpp.annotation.ByPtrPtr; import com.googlecode.javacpp.annotation.ByPtrRef; import com.googlecode.javacpp.annotation.ByRef; import com.googlecode.javacpp.annotation.ByVal; import com.googlecode.javacpp.annotation.Cast; import com.googlecode.javacpp.annotation.Const; import com.googlecode.javacpp.annotation.Convention; import com.googlecode.javacpp.annotation.Function; import com.googlecode.javacpp.annotation.Index; import com.googlecode.javacpp.annotation.MemberGetter; import com.googlecode.javacpp.annotation.MemberSetter; import com.googlecode.javacpp.annotation.Name; import com.googlecode.javacpp.annotation.Namespace; import com.googlecode.javacpp.annotation.NoDeallocator; import com.googlecode.javacpp.annotation.NoException; import com.googlecode.javacpp.annotation.NoOffset; import com.googlecode.javacpp.annotation.Opaque; import com.googlecode.javacpp.annotation.Platform; import com.googlecode.javacpp.annotation.Raw; import com.googlecode.javacpp.annotation.ValueGetter; import com.googlecode.javacpp.annotation.ValueSetter; import java.io.Closeable; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; /** * The Generator is where all the C++ source code that we need gets generated. * It has not been designed in any meaningful way since the requirements were * not well understood. It is basically a prototype and is really quite a mess. * Now that we understand better what we need, it could use some refactoring. * <p> * When attempting to understand what the Generator does, try to run experiments * and inspect the generated code: It is quite readable. * <p> * Moreover, although Generator is the one ultimately doing something with the * various annotations it relies on, it was easier to describe the behavior its * meant to have with them as part of the documentation of the annotations, so * we can refer to them to understand more about how Generator should work: * * @see Adapter * @see Allocator * @see ArrayAllocator * @see ByPtr * @see ByPtrPtr * @see ByPtrRef * @see ByRef * @see ByVal * @see Cast * @see Const * @see Convention * @see Function * @see Index * @see MemberGetter * @see MemberSetter * @see Name * @see Namespace * @see NoDeallocator * @see NoException * @see NoOffset * @see Opaque * @see Platform * @see Raw * @see ValueGetter * @see ValueSetter * * @author Samuel Audet */ public class Generator implements Closeable { public Generator(Logger logger, Loader.ClassProperties properties) { this.logger = logger; this.properties = properties; } static class IndexedSet<E> extends LinkedHashMap<E,Integer> implements Iterable<E> { public int index(E e) { Integer i = get(e); if (i == null) { put(e, i = size()); } return i; } public Iterator<E> iterator() { return keySet().iterator(); } } static final String JNI_VERSION = "JNI_VERSION_1_4"; static final List<Class> baseClasses = Arrays.asList(new Class[] { Pointer.class, //FunctionPointer.class, BytePointer.class, ShortPointer.class, IntPointer.class, LongPointer.class, FloatPointer.class, DoublePointer.class, CharPointer.class, PointerPointer.class, BoolPointer.class, CLongPointer.class, SizeTPointer.class }); final Logger logger; final Loader.ClassProperties properties; PrintWriter out, out2; IndexedSet<String> callbacks; IndexedSet<Class> functions, deallocators, arrayDeallocators, jclasses, jclassesInit; HashMap<Class,LinkedList<String>> members; boolean mayThrowExceptions, usesAdapters; public boolean generate(String sourceFilename, String headerFilename, String classPath, Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the IndexedSet objects out = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }); out2 = null; callbacks = new IndexedSet<String>(); functions = new IndexedSet<Class>(); deallocators = new IndexedSet<Class>(); arrayDeallocators = new IndexedSet<Class>(); jclasses = new IndexedSet<Class>(); jclassesInit = new IndexedSet<Class>(); members = new HashMap<Class,LinkedList<String>>(); mayThrowExceptions = false; usesAdapters = false; if (classes(true, true, classPath, classes)) { // second pass with a real writer out = new PrintWriter(sourceFilename); if (headerFilename != null) { out2 = new PrintWriter(headerFilename); } return classes(mayThrowExceptions, usesAdapters, classPath, classes); } else { return false; } } public void close() { if (out != null) { out.close(); } if (out2 != null) { out2.close(); } } boolean classes(boolean handleExceptions, boolean defineAdapters, String classPath, Class<?> ... classes) { String version = Generator.class.getPackage().getImplementationVersion(); if (version == null) { version = "unknown"; } String warning = "// Generated by JavaCPP version " + version; out.println(warning); out.println(); if (out2 != null) { out2.println(warning); out2.println(); } for (String s : properties.get("platform.define")) { out.println("#define " + s); } out.println(); out.println("#ifdef __APPLE__"); out.println(" #define _JAVASOFT_JNI_MD_H_"); out.println(); out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))"); out.println(" #define JNIIMPORT"); out.println(" #define JNICALL"); out.println(); out.println(" typedef int jint;"); out.println(" typedef long long jlong;"); out.println(" typedef signed char jbyte;"); out.println("#endif"); out.println("#ifdef _WIN32"); out.println(" #define _JAVASOFT_JNI_MD_H_"); out.println(); out.println(" #define JNIEXPORT __declspec(dllexport)"); out.println(" #define JNIIMPORT __declspec(dllimport)"); out.println(" #define JNICALL __stdcall"); out.println(); out.println(" typedef int jint;"); out.println(" typedef long long jlong;"); out.println(" typedef signed char jbyte;"); out.println("#endif"); out.println("#include <jni.h>"); if (out2 != null) { out2.println("#include <jni.h>"); } out.println("#ifdef ANDROID"); out.println(" #include <android/log.h>"); out.println("#elif defined(__APPLE__) && defined(__OBJC__)"); out.println(" #include <TargetConditionals.h>"); out.println(" #include <Foundation/Foundation.h>"); out.println("#endif"); out.println("#if defined(ANDROID) || TARGET_OS_IPHONE"); out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)"); out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)"); out.println("#endif"); out.println(); out.println("#include <stddef.h>"); out.println("#ifndef _WIN32"); out.println(" #include <stdint.h>"); out.println("#endif"); out.println("#include <stdio.h>"); out.println("#include <stdlib.h>"); out.println("#include <string.h>"); out.println("#include <exception>"); out.println("#include <new>"); out.println(); out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))"); out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))"); out.println(); out.println("#if defined(_MSC_VER)"); out.println(" #define JavaCPP_noinline __declspec(noinline)"); out.println(" #define JavaCPP_hidden /* hidden by default */"); out.println("#elif defined(__GNUC__)"); out.println(" #define JavaCPP_noinline __attribute__((noinline))"); out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\")))"); out.println("#else"); out.println(" #define JavaCPP_noinline"); out.println(" #define JavaCPP_hidden"); out.println("#endif"); out.println(); List[] include = { properties.get("platform.include"), properties.get("platform.cinclude") }; for (int i = 0; i < include.length; i++) { if (include[i] != null && include[i].size() > 0) { if (i == 1) { out.println("extern \"C\" {"); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("extern \"C\" {"); out2.println("#endif"); } } for (String s : (List<String>)include[i]) { String line = "#include "; if (!s.startsWith("<") && !s.startsWith("\"")) { line += '"'; } line += s; if (!s.endsWith(">") && !s.endsWith("\"")) { line += '"'; } out.println(line); if (out2 != null) { out2.println(line); } } if (i == 1) { out.println("}"); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("}"); out2.println("#endif"); } } out.println(); } } out.println("static JavaVM* JavaCPP_vm = NULL;"); out.println("static bool JavaCPP_haveAllocObject = false;"); out.println("static bool JavaCPP_haveNonvirtual = false;"); out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {"); Iterator<Class> classIterator = jclasses.iterator(); int maxMemberSize = 0; while (classIterator.hasNext()) { Class c = classIterator.next(); out.print(" \"" + c.getName().replace('.','/') + "\""); if (classIterator.hasNext()) { out.println(","); } LinkedList<String> m = members.get(c); if (m != null && m.size() > maxMemberSize) { maxMemberSize = m.size(); } } out.println(" };"); out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };"); out.println("static jfieldID JavaCPP_addressFID = NULL;"); out.println("static jfieldID JavaCPP_positionFID = NULL;"); out.println("static jfieldID JavaCPP_limitFID = NULL;"); out.println("static jfieldID JavaCPP_capacityFID = NULL;"); out.println("static jmethodID JavaCPP_initMID = NULL;"); out.println("static jmethodID JavaCPP_toStringMID = NULL;"); out.println(); out.println("static inline void JavaCPP_log(const char* fmt, ...) {"); out.println(" va_list ap;"); out.println(" va_start(ap, fmt);"); out.println("#ifdef ANDROID"); out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);"); out.println("#elif defined(__APPLE__) && defined(__OBJC__)"); out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);"); out.println("#else"); out.println(" vfprintf(stderr, fmt, ap);"); out.println(" fprintf(stderr, \"\\n\");"); out.println("#endif"); out.println(" va_end(ap);"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {"); out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {"); out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);"); out.println(" if (cls == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);"); out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" env->PopLocalFrame(NULL);"); out.println(" }"); out.println(" return JavaCPP_classes[i];"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);"); out.println(" if (fid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return fid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return mid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return mid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {"); out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" if (JavaCPP_haveAllocObject) {"); out.println(" return env->AllocObject(cls);"); out.println(" } else {"); out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting default constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" return env->NewObject(cls, mid);"); out.println(" }"); out.println("}"); out.println(); out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, int size, void (*deallocator)(void*)) {"); out.println(" if (deallocator != NULL) {"); out.println(" jvalue args[3];"); out.println(" args[0].j = ptr_to_jlong(ptr);"); out.println(" args[1].i = size;"); out.println(" args[2].j = ptr_to_jlong(deallocator);"); out.println(" if (JavaCPP_haveNonvirtual) {"); out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, " + jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);"); out.println(" } else {"); out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);"); out.println(" }"); out.println(" } else {"); out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));"); out.println(" env->SetIntField(obj, JavaCPP_limitFID, size);"); out.println(" env->SetIntField(obj, JavaCPP_capacityFID, size);"); out.println(" }"); out.println("}"); out.println(); out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {"); out.println("public:"); out.println(" JavaCPP_exception(const char* str) throw() {"); out.println(" if (str == NULL) {"); out.println(" strcpy(msg, \"Unknown exception.\");"); out.println(" } else {"); out.println(" strncpy(msg, str, sizeof(msg));"); out.println(" msg[sizeof(msg) - 1] = 0;"); out.println(" }"); out.println(" }"); out.println(" virtual const char* what() const throw() { return msg; }"); out.println(" char msg[1024];"); out.println("};"); out.println(); if (handleExceptions) { out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {"); out.println(" jstring str = NULL;"); out.println(" try {"); out.println(" throw;"); out.println(" } catch (std::exception& e) {"); out.println(" str = env->NewStringUTF(e.what());"); out.println(" } catch (...) {"); out.println(" str = env->NewStringUTF(\"Unknown exception.\");"); out.println(" }"); out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");"); out.println(" if (mid == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);"); out.println("}"); out.println(); } if (defineAdapters) { out.println("#include <vector>"); out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {"); out.println("public:"); out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size) : ptr((P*)ptr), size(size),"); out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }"); out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), vec2(vec), vec(vec2) { }"); out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), vec(vec) { }"); out.println(" void assign(P* ptr, typename std::vector<T>::size_type size) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" vec.assign(ptr, ptr + size);"); out.println(" }"); out.println(" static void deallocate(void* ptr) { delete[] (P*)ptr; }"); out.println(" operator P*() {"); out.println(" if (vec.size() > size) {"); out.println(" ptr = new (std::nothrow) P[vec.size()];"); out.println(" }"); out.println(" if (ptr) {"); out.println(" std::copy(vec.begin(), vec.end(), ptr);"); out.println(" }"); out.println(" size = vec.size();"); out.println(" return ptr;"); out.println(" }"); out.println(" operator const P*() { return &vec[0]; }"); out.println(" operator std::vector<T>&() { return vec; }"); out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }"); out.println(" P* ptr;"); out.println(" typename std::vector<T>::size_type size;"); out.println(" std::vector<T> vec2;"); out.println(" std::vector<T>& vec;"); out.println("};"); out.println(); out.println("#include <string>"); out.println("class JavaCPP_hidden StringAdapter {"); out.println("public:"); out.println(" StringAdapter(const char* ptr, size_t size) : ptr((char*)ptr), size(size),"); out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }"); out.println(" StringAdapter(const signed char* ptr, size_t size) : ptr((char*)ptr), size(size),"); out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }"); out.println(" StringAdapter(const unsigned char* ptr, size_t size) : ptr((char*)ptr), size(size),"); out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }"); out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), str2(str), str(str2) { }"); out.println(" StringAdapter( std::string& str) : ptr(0), size(0), str(str) { }"); out.println(" void assign(char* ptr, size_t size) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" str.assign(ptr ? ptr : \"\");"); out.println(" }"); out.println(" static void deallocate(void* ptr) { free(ptr); }"); out.println(" operator char*() {"); out.println(" const char* c_str = str.c_str();"); out.println(" if (ptr == NULL || strcmp(c_str, ptr) != 0) {"); out.println(" ptr = strdup(c_str);"); out.println(" }"); out.println(" size = strlen(c_str) + 1;"); out.println(" return ptr;"); out.println(" }"); out.println(" operator signed char*() { return (signed char*)(operator char*)(); }"); out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }"); out.println(" operator const char*() { return str.c_str(); }"); out.println(" operator const signed char*() { return (signed char*)str.c_str(); }"); out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }"); out.println(" operator std::string&() { return str; }"); out.println(" operator std::string*() { return ptr ? &str : 0; }"); out.println(" char* ptr;"); out.println(" size_t size;"); out.println(" std::string str2;"); out.println(" std::string& str;"); out.println("};"); out.println(); } if (!functions.isEmpty()) { out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {"); out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");"); out.println(" }"); out.println("}"); out.println(); out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {"); out.println(" bool attached = false;"); out.println(" JavaVM *vm = JavaCPP_vm;"); out.println(" if (vm == NULL) {"); if (out2 != null) { out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE"); out.println(" int size = 1;"); out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {"); out.println("#endif"); } out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");"); out.println(" *env = NULL;"); out.println(" return false;"); if (out2 != null) { out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE"); out.println(" }"); out.println("#endif"); } out.println(" }"); out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" struct {"); out.println(" JNIEnv **env;"); out.println(" operator JNIEnv**() { return env; } // Android JNI"); out.println(" operator void**() { return (void**)env; } // standard JNI"); out.println(" } env2 = { env };"); out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");"); out.println(" *env = NULL;"); out.println(" return false;"); out.println(" }"); out.println(" attached = true;"); out.println(" }"); out.println(" if (JavaCPP_vm == NULL) {"); out.println(" if (JNI_OnLoad(vm, NULL) < 0) {"); out.println(" JavaCPP_detach(attached);"); out.println(" *env = NULL;"); out.println(" return false;"); out.println(" }"); out.println(" }"); out.println(" return attached;"); out.println("}"); out.println(); } for (Class c : functions) { String[] typeName = cppTypeName(c); String[] returnConvention = typeName[0].split("\\("); returnConvention[1] = constValueTypeName(returnConvention[1]); String parameterDeclaration = typeName[1].substring(1); String instanceTypeName = functionClassName(c); out.println("struct JavaCPP_hidden " + instanceTypeName + " {"); out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }"); out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";"); out.println(" " + typeName[0] + "ptr" + typeName[1] + ";"); out.println(" jobject obj; static jmethodID mid;"); out.println("};"); out.println("jmethodID " + instanceTypeName + "::mid = NULL;"); } out.println(); for (String s : callbacks) { out.println(s); } out.println(); for (Class c : deallocators) { String name = "JavaCPP_" + mangle(c.getName()); out.print("static void " + name + "_deallocate(void *p) { "); if (FunctionPointer.class.isAssignableFrom(c)) { String typeName = functionClassName(c) + "*"; out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef(((" + typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }"); } else { String[] typeName = cppTypeName(c); out.println("delete (" + typeName[0] + typeName[1] + ")p; }"); } } for (Class c : arrayDeallocators) { String name = "JavaCPP_" + mangle(c.getName()); String[] typeName = cppTypeName(c); out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }"); } out.println(); out.println("extern \"C\" {"); if (out2 != null) { out2.println(); out2.println("#ifdef __cplusplus"); out2.println("extern \"C\" {"); out2.println("#endif"); out2.println("JNIIMPORT int JavaCPP_init(int argc, const char *argv[]);"); out.println(); out.println("JNIEXPORT int JavaCPP_init(int argc, const char *argv[]) {"); out.println("#if defined(ANDROID) || TARGET_OS_IPHONE"); out.println(" return JNI_OK;"); out.println("#else"); out.println(" if (JavaCPP_vm != NULL) {"); out.println(" return JNI_OK;"); out.println(" }"); out.println(" int err;"); out.println(" JavaVM *vm;"); out.println(" JNIEnv *env;"); out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);"); out.println(" JavaVMOption options[256] = { { NULL } };"); out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";"); out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {"); out.println(" options[i].optionString = (char*)argv[i - 1];"); out.println(" }"); out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };"); out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad(vm, NULL)) >= 0 ? JNI_OK : err;"); out.println("#endif"); out.println("}"); } out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex out.println("JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {"); out.println(" JNIEnv* env;"); out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad().\");"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" if (JavaCPP_vm == vm) {"); out.println(" return env->GetVersion();"); out.println(" }"); out.println(" JavaCPP_vm = vm;"); out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;"); out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;"); out.println(" const char* members[" + jclasses.size() + "][" + maxMemberSize + "] = {"); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { out.print(" { "); LinkedList<String> m = members.get(classIterator.next()); Iterator<String> memberIterator = m == null ? null : m.iterator(); while (memberIterator != null && memberIterator.hasNext()) { out.print("\"" + memberIterator.next() + "\""); if (memberIterator.hasNext()) { out.print(", "); } } out.print(" }"); if (classIterator.hasNext()) { out.println(","); } } out.println(" };"); out.println(" int offsets[" + jclasses.size() + "][" + maxMemberSize + "] = {"); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { out.print(" { "); Class c = classIterator.next(); LinkedList<String> m = members.get(c); Iterator<String> memberIterator = m == null ? null : m.iterator(); while (memberIterator != null && memberIterator.hasNext()) { String[] typeName = cppTypeName(c); String valueTypeName = valueTypeName(typeName); String memberName = memberIterator.next(); if ("sizeof".equals(memberName)) { if ("void".equals(valueTypeName)) { valueTypeName = "void*"; } out.print("sizeof(" + valueTypeName + ")"); } else { out.print("offsetof(" + valueTypeName + ", " + memberName + ")"); } if (memberIterator.hasNext()) { out.print(", "); } } out.print(" }"); if (classIterator.hasNext()) { out.println(","); } } out.println(" };"); out.print(" int memberOffsetSizes[" + jclasses.size() + "] = { "); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { LinkedList<String> m = members.get(classIterator.next()); out.print(m == null ? 0 : m.size()); if (classIterator.hasNext()) { out.print(", "); } } out.println(" };"); out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " + jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)V\");"); out.println(" if (putMemberOffsetMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {"); out.println(" for (int j = 0; j < memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {"); out.println(" if (env->PushLocalFrame(2) == 0) {"); out.println(" jvalue args[3];"); out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);"); out.println(" args[1].l = env->NewStringUTF(members[i][j]);"); out.println(" args[2].i = offsets[i][j];"); out.println(" env->CallStaticVoidMethodA(JavaCPP_getClass(env, " + jclasses.index(Loader.class) + "), putMemberOffsetMID, args);"); out.println(" env->PopLocalFrame(NULL);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"address\", \"J\");"); out.println(" if (JavaCPP_addressFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"position\", \"I\");"); out.println(" if (JavaCPP_positionFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"limit\", \"I\");"); out.println(" if (JavaCPP_limitFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"capacity\", \"I\");"); out.println(" if (JavaCPP_capacityFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " + jclasses.index(Pointer.class) + ", \"init\", \"(JIJ)V\");"); out.println(" if (JavaCPP_initMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " + jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");"); out.println(" if (JavaCPP_toStringMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); classIterator = jclassesInit.iterator(); while (classIterator.hasNext()) { Class c = classIterator.next(); if (c == Pointer.class) { continue; } out.println(" if (JavaCPP_getClass(env, " + jclasses.index(c) + ") == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); } out.println(" return env->GetVersion();"); out.println("}"); out.println(); if (out2 != null) { out2.println("JNIIMPORT int JavaCPP_uninit();"); out2.println(); out.println("JNIEXPORT int JavaCPP_uninit() {"); out.println("#if defined(ANDROID) || TARGET_OS_IPHONE"); out.println(" return JNI_OK;"); out.println("#else"); out.println(" JavaVM *vm = JavaCPP_vm;"); out.println(" JNI_OnUnload(JavaCPP_vm, NULL);"); out.println(" return vm->DestroyJavaVM();"); out.println("#endif"); out.println("}"); } out.println(); out.println("JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {"); out.println(" JNIEnv* env;"); out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad().\");"); out.println(" return;"); out.println(" }"); out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {"); out.println(" env->DeleteWeakGlobalRef(JavaCPP_classes[i]);"); out.println(" JavaCPP_classes[i] = NULL;"); out.println(" }"); out.println(" JavaCPP_vm = NULL;"); out.println("}"); out.println(); for (Class<?> cls : baseClasses) { methods(cls); } boolean didSomethingUseful = false; for (Class<?> cls : classes) { try { didSomethingUseful |= methods(cls); } catch (NoClassDefFoundError e) { logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e); } } out.println("}"); out.println(); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("}"); out2.println("#endif"); } return didSomethingUseful; } boolean methods(Class<?> cls) { if (!checkPlatform(cls)) { return false; } LinkedList<String> memberList = members.get(cls); if (!cls.isAnnotationPresent(Opaque.class) && !FunctionPointer.class.isAssignableFrom(cls)) { if (memberList == null) { members.put(cls, memberList = new LinkedList<String>()); } if (!memberList.contains("sizeof")) { memberList.add("sizeof"); } } boolean didSomething = false; for (Class<?> c : cls.getDeclaredClasses()) { if (Pointer.class.isAssignableFrom(c) || Pointer.Deallocator.class.isAssignableFrom(c)) { didSomething |= methods(c); } } Method[] methods = cls.getDeclaredMethods(); boolean[] callbackAllocators = new boolean[methods.length]; Method functionMethod = functionMethod(cls, callbackAllocators); boolean firstCallback = true; for (int i = 0; i < methods.length; i++) { String nativeName = mangle(cls.getName()) + "_" + mangle(methods[i].getName()); if (!checkPlatform(methods[i].getAnnotation(Platform.class))) { continue; } MethodInformation methodInfo = methodInformation(methods[i]); String callbackName = "JavaCPP_" + nativeName + "_callback"; if (callbackAllocators[i] && functionMethod == null) { logger.warn("No callback method call() or apply() has been not declared in \"" + cls.getCanonicalName() + "\". No code will be generated for callback allocator."); continue; } else if (callbackAllocators[i] || (methods[i].equals(functionMethod) && methodInfo == null)) { functions.index(cls); Name name = methods[i].getAnnotation(Name.class); if (name != null && name.value().length > 0 && name.value()[0].length() > 0) { callbackName = name.value()[0]; } callback(cls, functionMethod, callbackName, firstCallback); firstCallback = false; didSomething = true; } if (methodInfo == null) { continue; } if ((methodInfo.memberGetter || methodInfo.memberSetter) && !methodInfo.noOffset && memberList != null && !Modifier.isStatic(methodInfo.modifiers)) { if (!memberList.contains(methodInfo.memberName[0])) { memberList.add(methodInfo.memberName[0]); } } didSomething = true; out.print("JNIEXPORT " + jniTypeName(methodInfo.returnType) + " JNICALL Java_" + nativeName); if (methodInfo.overloaded) { out.print("__" + mangle(signature(methodInfo.parameterTypes))); } if (Modifier.isStatic(methodInfo.modifiers)) { out.print("(JNIEnv* env, jclass cls"); } else { out.print("(JNIEnv* env, jobject obj"); } for (int j = 0; j < methodInfo.parameterTypes.length; j++) { out.print(", " + jniTypeName(methodInfo.parameterTypes[j]) + " arg" + j); } out.println(") {"); if (callbackAllocators[i]) { callbackAllocator(cls, callbackName); continue; } else if (!Modifier.isStatic(methodInfo.modifiers) && !methodInfo.allocator && !methodInfo.arrayAllocator && !methodInfo.deallocator) { // get our "this" pointer String[] typeName = cppTypeName(cls); if ("void*".equals(typeName[0])) { typeName[0] = "char*"; } else if (FunctionPointer.class.isAssignableFrom(cls)) { functions.index(cls); typeName[0] = functionClassName(cls) + "*"; typeName[1] = ""; } out.println(" " + typeName[0] + " ptr" + typeName[1] + " = (" + typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(obj, JavaCPP_addressFID));"); out.println(" if (ptr == NULL) {"); out.println(" env->ThrowNew(JavaCPP_getClass(env, " + jclasses.index(NullPointerException.class) + "), \"This pointer address is NULL.\");"); out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;")); out.println(" }"); if (FunctionPointer.class.isAssignableFrom(cls)) { out.println(" if (ptr->ptr == NULL) {"); out.println(" env->ThrowNew(JavaCPP_getClass(env, " + jclasses.index(NullPointerException.class) + "), \"This function pointer address is NULL.\");"); out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;")); out.println(" }"); } if (!cls.isAnnotationPresent(Opaque.class)) { out.println(" jint position = env->GetIntField(obj, JavaCPP_positionFID);"); out.println(" ptr += position;"); if (methodInfo.bufferGetter) { out.println(" jint size = env->GetIntField(obj, JavaCPP_limitFID);"); out.println(" size -= position;"); } } } parametersBefore(methodInfo); String returnPrefix = returnBefore(methodInfo); call(methodInfo, returnPrefix); returnAfter(methodInfo); parametersAfter(methodInfo); if (methodInfo.throwsException != null) { out.println(" if (exc != NULL) {"); out.println(" env->Throw(exc);"); out.println(" }"); } if (methodInfo.returnType != void.class) { out.println(" return rarg;"); } out.println("}"); } out.println(); return didSomething; } void parametersBefore(MethodInformation methodInfo) { String adapterLine = ""; AdapterInformation prevAdapterInfo = null; int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0; for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) { if (!methodInfo.parameterTypes[j].isPrimitive()) { Annotation passBy = by(methodInfo, j); String cast = cast(methodInfo, j); String[] typeName = cppTypeName(methodInfo.parameterTypes[j]); AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j); if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) { functions.index(methodInfo.parameterTypes[j]); if (methodInfo.parameterTypes[j] == FunctionPointer.class) { logger.warn("Method \"" + methodInfo.method + "\" has an abstract FunctionPointer parameter, " + "but a concrete subclass is required. Compilation will most likely fail."); } typeName[0] = functionClassName(methodInfo.parameterTypes[j]) + "*"; typeName[1] = ""; } if (typeName[0].length() == 0 || methodInfo.parameterRaw[j]) { methodInfo.parameterRaw[j] = true; typeName[0] = jniTypeName(methodInfo.parameterTypes[j]); out.println(" " + typeName[0] + " ptr" + j + " = arg" + j + ";"); continue; } if ("void*".equals(typeName[0])) { typeName[0] = "char*"; } out.print(" " + typeName[0] + " ptr" + j + typeName[1] + " = "); if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) { out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(arg" + j + ", JavaCPP_addressFID));"); if ((j == 0 && FunctionPointer.class.isAssignableFrom(methodInfo.cls) && methodInfo.cls.isAnnotationPresent(Namespace.class)) || passBy instanceof ByVal || passBy instanceof ByRef) { // in the case of member ptr, ptr0 is our object pointer, which cannot be NULL out.println(" if (ptr" + j + " == NULL) {"); out.println(" env->ThrowNew(JavaCPP_getClass(env, " + jclasses.index(NullPointerException.class) + "), \"Pointer address of argument " + j + " is NULL.\");"); out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;")); out.println(" }"); } if (adapterInfo != null || prevAdapterInfo != null) { out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j + ", JavaCPP_limitFID);"); } if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) { out.println(" jint position" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j + ", JavaCPP_positionFID);"); out.println(" ptr" + j + " += position" + j + ";"); if (adapterInfo != null || prevAdapterInfo != null) { out.println(" size" + j + " -= position" + j + ";"); } } } else if (methodInfo.parameterTypes[j] == String.class) { out.println("arg" + j + " == NULL ? NULL : env->GetStringUTFChars(arg" + j + ", NULL);"); if (adapterInfo != null || prevAdapterInfo != null) { out.println(" jint size" + j + " = 0;"); } } else if (methodInfo.parameterTypes[j].isArray() && methodInfo.parameterTypes[j].getComponentType().isPrimitive()) { out.print("arg" + j + " == NULL ? NULL : "); String s = methodInfo.parameterTypes[j].getComponentType().getName(); if (methodInfo.valueGetter || methodInfo.valueSetter || methodInfo.memberGetter || methodInfo.memberSetter) { out.println("(j" + s + "*)env->GetPrimitiveArrayCritical(arg" + j + ", NULL);"); } else { s = Character.toUpperCase(s.charAt(0)) + s.substring(1); out.println("env->Get" + s + "ArrayElements(arg" + j + ", NULL);"); } if (adapterInfo != null || prevAdapterInfo != null) { out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetArrayLength(arg" + j + ");"); } } else if (Buffer.class.isAssignableFrom(methodInfo.parameterTypes[j])) { out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] + ")env->GetDirectBufferAddress(arg" + j + ");"); if (adapterInfo != null || prevAdapterInfo != null) { out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetDirectBufferCapacity(arg" + j + ");"); } } else { out.println("arg" + j + ";"); logger.warn("Method \"" + methodInfo.method + "\" has an unsupported parameter of type \"" + methodInfo.parameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail."); } if (adapterInfo != null) { usesAdapters = true; adapterLine = " " + adapterInfo.name + " adapter" + j + "("; prevAdapterInfo = adapterInfo; } if (prevAdapterInfo != null) { if (!FunctionPointer.class.isAssignableFrom(methodInfo.cls)) { // sometimes we need to use the Cast annotation for declaring functions only adapterLine += cast; } adapterLine += "ptr" + j + ", size" + j; if (--prevAdapterInfo.argc > 0) { adapterLine += ", "; } } if (prevAdapterInfo != null && prevAdapterInfo.argc <= 0) { out.println(adapterLine + ");"); prevAdapterInfo = null; } } } } String returnBefore(MethodInformation methodInfo) { String returnPrefix = ""; if (methodInfo.returnType == void.class) { if (methodInfo.allocator || methodInfo.arrayAllocator) { if (methodInfo.cls != Pointer.class) { out.println(" if (!env->IsSameObject(env->GetObjectClass(obj), JavaCPP_getClass(env, " + jclasses.index(methodInfo.cls) + "))) {"); out.println(" return;"); out.println(" }"); } String[] typeName = cppTypeName(methodInfo.cls); returnPrefix = typeName[0] + " rptr" + typeName[1] + " = "; } } else { String cast = cast(methodInfo.returnType, methodInfo.annotations); String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations); if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) { out.println(" jobject rarg = obj;"); } else if (methodInfo.returnType.isPrimitive()) { out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = 0;"); returnPrefix = typeName[0] + " rvalue" + typeName[1] + " = " + cast; } else { Annotation returnBy = by(methodInfo.annotations); String valueTypeName = valueTypeName(typeName); returnPrefix = "rptr = " + cast; if (typeName[0].length() == 0 || methodInfo.returnRaw) { methodInfo.returnRaw = true; typeName[0] = jniTypeName(methodInfo.returnType); out.println(" " + typeName[0] + " rarg = NULL;"); out.println(" " + typeName[0] + " rptr;"); } else if (Pointer.class.isAssignableFrom(methodInfo.returnType) || Buffer.class.isAssignableFrom(methodInfo.returnType) || (methodInfo.returnType.isArray() && methodInfo.returnType.getComponentType().isPrimitive())) { if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) { functions.index(methodInfo.returnType); typeName[0] = functionClassName(methodInfo.returnType) + "*"; typeName[1] = ""; valueTypeName = valueTypeName(typeName); returnPrefix = "if (rptr != NULL) rptr->ptr = "; } if (returnBy instanceof ByVal) { returnPrefix += (noException(methodInfo.returnType, methodInfo.method) ? "new (std::nothrow) " : "new ") + valueTypeName + typeName[1] + "("; } else if (returnBy instanceof ByRef) { returnPrefix += "&"; } else if (returnBy instanceof ByPtrPtr) { if (cast.length() > 0) { typeName[0] = typeName[0].substring(0, typeName[0].length()-1); } returnPrefix = "rptr = NULL; " + typeName[0] + "* rptrptr" + typeName[1] + " = " + cast; } // else ByPtr || ByPtrRef if (methodInfo.bufferGetter) { out.println(" jobject rarg = NULL;"); out.println(" char* rptr;"); } else { out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = NULL;"); out.println(" " + typeName[0] + " rptr" + typeName[1] + ";"); } if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) { out.println(" rptr = new (std::nothrow) " + valueTypeName + ";"); } } else if (methodInfo.returnType == String.class) { out.println(" jstring rarg = NULL;"); out.println(" const char* rptr;"); if (returnBy instanceof ByRef) { returnPrefix = "std::string rstr("; } else { returnPrefix += "(const char*)"; } } else { logger.warn("Method \"" + methodInfo.method + "\" has unsupported return type \"" + methodInfo.returnType.getCanonicalName() + "\". Compilation will most likely fail."); } AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations); if (adapterInfo != null) { usesAdapters = true; returnPrefix = adapterInfo.name + " radapter("; } } } if (methodInfo.throwsException != null) { out.println(" jthrowable exc = NULL;"); out.println(" try {"); } return returnPrefix; } void call(MethodInformation methodInfo, String returnPrefix) { String indent = methodInfo.throwsException != null ? " " : " "; String prefix = "("; String suffix = ")"; int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0; boolean index = methodInfo.method.isAnnotationPresent(Index.class) || (methodInfo.pairedMethod != null && methodInfo.pairedMethod.isAnnotationPresent(Index.class)); if (methodInfo.deallocator) { out.println(indent + "void* allocatedAddress = jlong_to_ptr(arg0);"); out.println(indent + "void (*deallocatorAddress)(void*) = (void(*)(void*))jlong_to_ptr(arg1);"); out.println(indent + "if (deallocatorAddress != NULL && allocatedAddress != NULL) {"); out.println(indent + " (*deallocatorAddress)(allocatedAddress);"); out.println(indent + "}"); return; // nothing else should be appended here for deallocator } else if (methodInfo.valueGetter || methodInfo.valueSetter || methodInfo.memberGetter || methodInfo.memberSetter) { boolean wantsPointer = false; int k = methodInfo.parameterTypes.length-1; if ((methodInfo.valueSetter || methodInfo.memberSetter) && !(by(methodInfo, k) instanceof ByRef) && adapterInformation(false, methodInfo, k) == null && methodInfo.parameterTypes[k] == String.class) { // special considerations for char arrays as strings out.print(indent + "strcpy((char*)"); wantsPointer = true; prefix = ", "; } else if (k >= 1 && methodInfo.parameterTypes[0].isArray() && methodInfo.parameterTypes[0].getComponentType().isPrimitive() && (methodInfo.parameterTypes[1] == int.class || methodInfo.parameterTypes[1] == long.class)) { // special considerations for primitive arrays out.print(indent + "memcpy("); wantsPointer = true; prefix = ", "; if (methodInfo.memberGetter || methodInfo.valueGetter) { out.print("ptr0 + arg1, "); } else { // methodInfo.memberSetter || methodInfo.valueSetter prefix += "ptr0 + arg1, "; } skipParameters = 2; suffix = " * sizeof(*ptr0)" + suffix; } else { out.print(indent + returnPrefix); prefix = methodInfo.valueGetter || methodInfo.memberGetter ? "" : " = "; suffix = ""; } if (Modifier.isStatic(methodInfo.modifiers)) { out.print(cppScopeName(methodInfo)); } else if (methodInfo.memberGetter || methodInfo.memberSetter) { if (index) { out.print("(*ptr)"); prefix = "." + methodInfo.memberName[0] + prefix; } else { out.print("ptr->" + methodInfo.memberName[0]); } } else { // methodInfo.valueGetter || methodInfo.valueSetter out.print(index ? "(*ptr)" : methodInfo.dim > 0 || wantsPointer ? "ptr" : "*ptr"); } } else if (methodInfo.bufferGetter) { out.print(indent + returnPrefix + "ptr"); prefix = ""; suffix = ""; } else { // function call out.print(indent + returnPrefix); if (FunctionPointer.class.isAssignableFrom(methodInfo.cls)) { if (methodInfo.cls.isAnnotationPresent(Namespace.class)) { out.print("(ptr0->*(ptr->ptr))"); skipParameters = 1; } else { out.print("(*ptr->ptr)"); } } else if (methodInfo.allocator) { String[] typeName = cppTypeName(methodInfo.cls); String valueTypeName = valueTypeName(typeName); if (methodInfo.cls == Pointer.class) { // can't allocate a "void", so simply assign the argument instead prefix = ""; suffix = ""; } else { out.print((noException(methodInfo.cls, methodInfo.method) ? "new (std::nothrow) " : "new ") + valueTypeName + typeName[1]); if (methodInfo.arrayAllocator) { prefix = "["; suffix = "]"; } } } else if (Modifier.isStatic(methodInfo.modifiers)) { out.print(cppScopeName(methodInfo)); } else { if (index) { out.print("(*ptr)"); prefix = "." + methodInfo.memberName[0] + prefix; } else { out.print("ptr->" + methodInfo.memberName[0]); } } } for (int j = skipParameters; j <= methodInfo.parameterTypes.length; j++) { if (j == skipParameters + methodInfo.dim) { if (methodInfo.memberName.length > 1) { out.print(methodInfo.memberName[1]); } out.print(prefix); if (methodInfo.withEnv) { out.print(Modifier.isStatic(methodInfo.modifiers) ? "env, cls" : "env, obj"); if (methodInfo.parameterTypes.length - skipParameters - methodInfo.dim > 0) { out.print(", "); } } } if (j == methodInfo.parameterTypes.length) { break; } if (j < skipParameters + methodInfo.dim) { // print array indices to access array members, or whatever // the C++ operator does with them when the Index annotation is present out.print("["); } Annotation passBy = by(methodInfo, j); String cast = cast(methodInfo, j); AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j); if (("(void*)".equals(cast) || "(void *)".equals(cast)) && methodInfo.parameterTypes[j] == long.class) { out.print("jlong_to_ptr(arg" + j + ")"); } else if (methodInfo.parameterTypes[j].isPrimitive()) { out.print(cast + "arg" + j); } else if (adapterInfo != null) { cast = adapterInfo.cast.trim(); if (cast.length() > 0 && !cast.startsWith("(") && !cast.endsWith(")")) { cast = "(" + cast + ")"; } out.print(cast + "adapter" + j); j += adapterInfo.argc - 1; } else if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j]) && passBy == null) { out.print(cast + "(ptr" + j + " == NULL ? NULL : ptr" + j + "->ptr)"); } else if (passBy instanceof ByVal || (passBy instanceof ByRef && methodInfo.parameterTypes[j] != String.class)) { out.print("*" + cast + "ptr" + j); } else if (passBy instanceof ByPtrPtr) { out.print(cast + "(arg" + j + " == NULL ? NULL : &ptr" + j + ")"); } else { // ByPtr || ByPtrRef || (ByRef && std::string) out.print(cast + "ptr" + j); } if (j < skipParameters + methodInfo.dim) { out.print("]"); } else if (j < methodInfo.parameterTypes.length - 1) { out.print(", "); } } out.print(suffix); if (methodInfo.memberName.length > 2) { out.print(methodInfo.memberName[2]); } if (by(methodInfo.annotations) instanceof ByRef && methodInfo.returnType == String.class) { // special considerations for std::string out.print(");\n" + indent + "rptr = rstr.c_str()"); } } void returnAfter(MethodInformation methodInfo) { String indent = methodInfo.throwsException != null ? " " : " "; String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations); Annotation returnBy = by(methodInfo.annotations); String valueTypeName = valueTypeName(typeName); AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations); String suffix = methodInfo.deallocator ? "" : ";"; if (!methodInfo.returnType.isPrimitive() && adapterInfo != null) { suffix = ")" + suffix; } if ((Pointer.class.isAssignableFrom(methodInfo.returnType) || (methodInfo.returnType.isArray() && methodInfo.returnType.getComponentType().isPrimitive()) || Buffer.class.isAssignableFrom(methodInfo.returnType))) { if (returnBy instanceof ByVal) { suffix = ")" + suffix; } else if (returnBy instanceof ByPtrPtr) { out.println(suffix); suffix = ""; out.println(indent + "if (rptrptr == NULL) {"); out.println(indent + " env->ThrowNew(JavaCPP_getClass(env, " + jclasses.index(NullPointerException.class) + "), \"Return pointer address is NULL.\");"); out.println(indent + "} else {"); out.println(indent + " rptr = *rptrptr;"); out.println(indent + "}"); } } out.println(suffix); if (methodInfo.returnType == void.class) { if (methodInfo.allocator || methodInfo.arrayAllocator) { out.println(indent + "jint rcapacity = " + (methodInfo.arrayAllocator ? "arg0;" : "1;")); boolean noDeallocator = methodInfo.cls == Pointer.class || methodInfo.cls.isAnnotationPresent(NoDeallocator.class); for (Annotation a : methodInfo.annotations) { if (a instanceof NoDeallocator) { noDeallocator = true; break; } } out.print(indent + "JavaCPP_initPointer(env, obj, rptr, rcapacity, "); if (noDeallocator) { out.println("NULL);"); } else if (methodInfo.arrayAllocator) { out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocateArray);"); arrayDeallocators.index(methodInfo.cls); } else { out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocate);"); deallocators.index(methodInfo.cls); } } } else { if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) { // nothing } else if (methodInfo.returnType.isPrimitive()) { out.println(indent + "rarg = (" + jniTypeName(methodInfo.returnType) + ")rvalue;"); } else if (methodInfo.returnRaw) { out.println(indent + "rarg = rptr;"); } else { boolean needInit = false; if (adapterInfo != null) { out.println(indent + "rptr = radapter;"); if (methodInfo.returnType != String.class) { out.println(indent + "jint rcapacity = (jint)radapter.size;"); out.println(indent + "void (*deallocator)(void*) = " + (adapterInfo.constant ? "NULL;" : "&" + adapterInfo.name + "::deallocate;")); } needInit = true; } else if (returnBy instanceof ByVal || FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) { out.println(indent + "jint rcapacity = 1;"); out.println(indent + "void (*deallocator)(void*) = &JavaCPP_" + mangle(methodInfo.returnType.getName()) + "_deallocate;"); deallocators.index(methodInfo.returnType); needInit = true; } if (Pointer.class.isAssignableFrom(methodInfo.returnType)) { out.print(indent); if (!(returnBy instanceof ByVal)) { // check if we can reuse one of the Pointer objects from the arguments if (Modifier.isStatic(methodInfo.modifiers) && methodInfo.parameterTypes.length > 0) { for (int i = 0; i < methodInfo.parameterTypes.length; i++) { String cast = cast(methodInfo, i); if (Arrays.equals(methodInfo.parameterAnnotations[i], methodInfo.annotations) && methodInfo.parameterTypes[i] == methodInfo.returnType) { out.println( "if (rptr == " + cast + "ptr" + i + ") {"); out.println(indent + " rarg = arg" + i + ";"); out.print(indent + "} else "); } } } else if (!Modifier.isStatic(methodInfo.modifiers) && methodInfo.cls == methodInfo.returnType) { out.println( "if (rptr == ptr) {"); out.println(indent + " rarg = obj;"); out.print(indent + "} else "); } } out.println( "if (rptr != NULL) {"); out.println(indent + " rarg = JavaCPP_createPointer(env, " + jclasses.index(methodInfo.returnType) + (methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? ", arg0);" : ");")); if (needInit) { out.println(indent + " JavaCPP_initPointer(env, rarg, rptr, rcapacity, deallocator);"); } else { out.println(indent + " env->SetLongField(rarg, JavaCPP_addressFID, ptr_to_jlong(rptr));"); } out.println(indent + "}"); } else if (methodInfo.returnType == String.class) { out.println(indent + "if (rptr != NULL) {"); out.println(indent + " rarg = env->NewStringUTF(rptr);"); out.println(indent + "}"); } else if (methodInfo.returnType.isArray() && methodInfo.returnType.getComponentType().isPrimitive()) { if (adapterInfo == null && !(returnBy instanceof ByVal)) { out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;"); } String s = methodInfo.returnType.getComponentType().getName(); String S = Character.toUpperCase(s.charAt(0)) + s.substring(1); out.println(indent + "if (rptr != NULL) {"); out.println(indent + " rarg = env->New" + S + "Array(rcapacity);"); out.println(indent + " env->Set" + S + "ArrayRegion(rarg, 0, rcapacity, (j" + s + "*)rptr);"); out.println(indent + "}"); if (adapterInfo != null) { out.println(indent + "if (deallocator != 0 && rptr != NULL) {"); out.println(indent + " (*(void(*)(void*))jlong_to_ptr(deallocator))((void*)rptr);"); out.println(indent + "}"); } } else if (Buffer.class.isAssignableFrom(methodInfo.returnType)) { if (methodInfo.bufferGetter) { out.println(indent + "jint rcapacity = size;"); } else if (adapterInfo == null && !(returnBy instanceof ByVal)) { out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;"); } out.println(indent + "if (rptr != NULL) {"); out.println(indent + " rarg = env->NewDirectByteBuffer((void*)rptr, rcapacity);"); out.println(indent + "}"); } } } } void parametersAfter(MethodInformation methodInfo) { if (methodInfo.throwsException != null) { mayThrowExceptions = true; out.println(" } catch (...) {"); out.println(" exc = JavaCPP_handleException(env, " + jclasses.index(methodInfo.throwsException) + ");"); out.println(" }"); out.println(); } int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0; for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) { if (methodInfo.parameterRaw[j]) { continue; } Annotation passBy = by(methodInfo, j); String cast = cast(methodInfo, j); String[] typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]); AdapterInformation adapterInfo = adapterInformation(true, methodInfo, j); if ("void*".equals(typeName[0])) { typeName[0] = "char*"; } if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) { if (adapterInfo != null) { for (int k = 0; k < adapterInfo.argc; k++) { out.println(" " + typeName[0] + " rptr" + (j+k) + typeName[1] + " = " + cast + "adapter" + j + ";"); out.println(" jint rsize" + (j+k) + " = (jint)adapter" + j + ".size" + (k > 0 ? (k+1) + ";" : ";")); out.println(" if (rptr" + (j+k) + " != " + cast + "ptr" + (j+k) + ") {"); out.println(" JavaCPP_initPointer(env, arg" + j + ", rptr" + (j+k) + ", rsize" + (j+k) + ", &" + adapterInfo.name + "::deallocate);"); out.println(" } else {"); out.println(" env->SetIntField(arg" + j + ", JavaCPP_limitFID, rsize" + (j+k) + " + position" + (j+k) + ");"); out.println(" }"); } } else if ((passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) && !methodInfo.valueSetter && !methodInfo.memberSetter) { if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) { out.println(" ptr" + j + " -= position" + j + ";"); } out.println(" if (arg" + j + " != NULL) env->SetLongField(arg" + j + ", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));"); } } else if (methodInfo.parameterTypes[j] == String.class) { out.println(" if (arg" + j + " != NULL) env->ReleaseStringUTFChars(arg" + j + ", ptr" + j + ");"); } else if (methodInfo.parameterTypes[j].isArray() && methodInfo.parameterTypes[j].getComponentType().isPrimitive()) { out.print(" if (arg" + j + " != NULL) "); if (methodInfo.valueGetter || methodInfo.valueSetter || methodInfo.memberGetter || methodInfo.memberSetter) { out.println("env->ReleasePrimitiveArrayCritical(arg" + j + ", ptr" + j + ", 0);"); } else { String s = methodInfo.parameterTypes[j].getComponentType().getName(); String S = Character.toUpperCase(s.charAt(0)) + s.substring(1); out.println("env->Release" + S + "ArrayElements(arg" + j + ", (j" + s + "*)ptr" + j + ", 0);"); } } } } void callback(Class<?> cls, Method callbackMethod, String callbackName, boolean needFunctor) { Class<?> callbackReturnType = callbackMethod.getReturnType(); Class<?>[] callbackParameterTypes = callbackMethod.getParameterTypes(); Annotation[] callbackAnnotations = callbackMethod.getAnnotations(); Annotation[][] callbackParameterAnnotations = callbackMethod.getParameterAnnotations(); String instanceTypeName = functionClassName(cls); String[] callbackTypeName = cppTypeName(cls); String[] returnConvention = callbackTypeName[0].split("\\("); returnConvention[1] = constValueTypeName(returnConvention[1]); String parameterDeclaration = callbackTypeName[1].substring(1); callbacks.index("static " + instanceTypeName + " " + callbackName + "_instance;"); jclassesInit.index(cls); // for custom class loaders if (out2 != null) { out2.println("JNIIMPORT " + returnConvention[0] + (returnConvention.length > 1 ? returnConvention[1] : "") + callbackName + parameterDeclaration + ";"); } out.println("JNIEXPORT " + returnConvention[0] + (returnConvention.length > 1 ? returnConvention[1] : "") + callbackName + parameterDeclaration + " {"); out.print((callbackReturnType != void.class ? " return " : " ") + callbackName + "_instance("); for (int j = 0; j < callbackParameterTypes.length; j++) { out.print("arg" + j); if (j < callbackParameterTypes.length - 1) { out.print(", "); } } out.println(");"); out.println("}"); if (!needFunctor) { return; } out.println(returnConvention[0] + instanceTypeName + "::operator()" + parameterDeclaration + " {"); String returnPrefix = ""; if (callbackReturnType != void.class) { out.println(" " + jniTypeName(callbackReturnType) + " rarg = 0;"); returnPrefix = "rarg = "; if (callbackReturnType == String.class) { returnPrefix += "(jstring)"; } } String callbackReturnCast = cast(callbackReturnType, callbackAnnotations); Annotation returnBy = by(callbackAnnotations); String[] returnTypeName = cppTypeName(callbackReturnType); String returnValueTypeName = valueTypeName(returnTypeName); AdapterInformation returnAdapterInfo = adapterInformation(false, returnValueTypeName, callbackAnnotations); out.println(" jthrowable exc = NULL;"); out.println(" JNIEnv* env;"); out.println(" bool attached = JavaCPP_getEnv(&env);"); out.println(" if (env == NULL) {"); out.println(" goto end;"); out.println(" }"); out.println("{"); if (callbackParameterTypes.length > 0) { out.println(" jvalue args[" + callbackParameterTypes.length + "];"); for (int j = 0; j < callbackParameterTypes.length; j++) { if (callbackParameterTypes[j].isPrimitive()) { out.println(" args[" + j + "]." + signature(callbackParameterTypes[j]).toLowerCase() + " = (" + jniTypeName(callbackParameterTypes[j]) + ")arg" + j + ";"); } else { Annotation passBy = by(callbackParameterAnnotations[j]); String[] typeName = cppTypeName(callbackParameterTypes[j]); String valueTypeName = valueTypeName(typeName); AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, callbackParameterAnnotations[j]); boolean needInit = false; if (adapterInfo != null) { usesAdapters = true; out.println(" " + adapterInfo.name + " adapter" + j + "(arg" + j + ");"); if (callbackParameterTypes[j] != String.class) { out.println(" jint size" + j + " = (jint)adapter" + j + ".size;"); out.println(" void (*deallocator" + j + ")(void*) = &" + adapterInfo.name + "::deallocate;"); } needInit = true; } else if ((passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) || FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) { out.println(" jint size" + j + " = 1;"); out.println(" void (*deallocator" + j + ")(void*) = &JavaCPP_" + mangle(callbackParameterTypes[j].getName()) + "_deallocate;"); deallocators.index(callbackParameterTypes[j]); needInit = true; } if (Pointer.class.isAssignableFrom(callbackParameterTypes[j]) || Buffer.class.isAssignableFrom(callbackParameterTypes[j]) || (callbackParameterTypes[j].isArray() && callbackParameterTypes[j].getComponentType().isPrimitive())) { if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) { functions.index(callbackParameterTypes[j]); typeName[0] = functionClassName(callbackParameterTypes[j]) + "*"; typeName[1] = ""; valueTypeName = valueTypeName(typeName); } out.println(" " + jniTypeName(callbackParameterTypes[j]) + " obj" + j + " = NULL;"); out.println(" " + typeName[0] + " ptr" + j + typeName[1] + " = NULL;"); if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) { out.println(" ptr" + j + " = new (std::nothrow) " + valueTypeName + ";"); out.println(" if (ptr" + j + " != NULL) {"); out.println(" ptr" + j + "->ptr = arg" + j + ";"); out.println(" }"); } else if (adapterInfo != null) { out.println(" ptr" + j + " = adapter" + j + ";"); } else if (passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) { out.println(" ptr" + j + (noException(callbackParameterTypes[j], callbackMethod) ? " = new (std::nothrow) " : " = new ") + valueTypeName + typeName[1] + "(*(" + typeName[0] + typeName[1] + ")&arg" + j + ");"); } else if (passBy instanceof ByVal || passBy instanceof ByRef) { out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")&arg" + j + ";"); } else if (passBy instanceof ByPtrPtr) { out.println(" if (arg" + j + " == NULL) {"); out.println(" JavaCPP_log(\"Pointer address of argument " + j + " is NULL in callback for " + cls.getCanonicalName() + ".\");"); out.println(" } else {"); out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")*arg" + j + ";"); out.println(" }"); } else { // ByPtr || ByPtrRef out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")arg" + j + ";"); } } if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) { String s = " obj" + j + " = JavaCPP_createPointer(env, " + jclasses.index(callbackParameterTypes[j]) + ");"; jclassesInit.index(callbackParameterTypes[j]); // for custom class loaders adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]); if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) { out.println(s); } else { out.println(" if (ptr" + j + " != NULL) { "); out.println(" " + s); out.println(" }"); } out.println(" if (obj" + j + " != NULL) { "); if (needInit) { out.println(" JavaCPP_initPointer(env, obj" + j + ", ptr" + j + ", size" + j + ", deallocator" + j + ");"); } else { out.println(" env->SetLongField(obj" + j + ", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));"); } out.println(" }"); out.println(" args[" + j + "].l = obj" + j + ";"); } else if (callbackParameterTypes[j] == String.class) { out.println(" jstring obj" + j + " = (const char*)" + (adapterInfo != null ? "adapter" : "arg") + j + " == NULL ? NULL : env->NewStringUTF((const char*)" + (adapterInfo != null ? "adapter" : "arg") + j + ");"); out.println(" args[" + j + "].l = obj" + j + ";"); } else if (callbackParameterTypes[j].isArray() && callbackParameterTypes[j].getComponentType().isPrimitive()) { if (adapterInfo == null) { out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;"); } String s = callbackParameterTypes[j].getComponentType().getName(); String S = Character.toUpperCase(s.charAt(0)) + s.substring(1); out.println(" if (ptr" + j + " != NULL) {"); out.println(" obj" + j + " = env->New" + S + "Array(size"+ j + ");"); out.println(" env->Set" + S + "ArrayRegion(obj" + j + ", 0, size" + j + ", (j" + s + "*)ptr" + j + ");"); out.println(" }"); if (adapterInfo != null) { out.println(" if (deallocator" + j + " != 0 && ptr" + j + " != NULL) {"); out.println(" (*(void(*)(void*))jlong_to_ptr(deallocator" + j + "))((void*)ptr" + j + ");"); out.println(" }"); } } else if (Buffer.class.isAssignableFrom(callbackParameterTypes[j])) { if (adapterInfo == null) { out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;"); } out.println(" if (ptr" + j + " != NULL) {"); out.println(" obj" + j + " = env->NewDirectByteBuffer((void*)ptr" + j + ", size" + j + ");"); out.println(" }"); } else { logger.warn("Callback \"" + callbackMethod + "\" has unsupported parameter type \"" + callbackParameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail."); } } } } out.println(" if (obj == NULL) {"); out.println(" obj = env->NewGlobalRef(JavaCPP_createPointer(env, " + jclasses.index(cls) + "));"); out.println(" if (obj == NULL) {"); out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");"); out.println(" } else {"); out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(this));"); out.println(" }"); out.println(" ptr = &" + callbackName + ";"); out.println(" }"); out.println(" if (mid == NULL) {"); out.println(" mid = JavaCPP_getMethodID(env, " + jclasses.index(cls) + ", \"" + callbackMethod.getName() + "\", \"(" + signature(callbackMethod.getParameterTypes()) + ")" + signature(callbackMethod.getReturnType()) + "\");"); out.println(" }"); out.println(" if (env->IsSameObject(obj, NULL)) {"); out.println(" JavaCPP_log(\"Function pointer object is NULL in callback for " + cls.getCanonicalName() + ".\");"); out.println(" } else if (mid == NULL) {"); out.println(" JavaCPP_log(\"Error getting method ID of function caller \\\"" + callbackMethod + "\\\" for callback.\");"); out.println(" } else {"); String s = "Object"; if (callbackReturnType.isPrimitive()) { s = callbackReturnType.getName(); s = Character.toUpperCase(s.charAt(0)) + s.substring(1); } out.println(" " + returnPrefix + "env->Call" + s + "MethodA(obj, mid, " + (callbackParameterTypes.length == 0 ? "NULL);" : "args);")); out.println(" if ((exc = env->ExceptionOccurred()) != NULL) {"); out.println(" env->ExceptionClear();"); out.println(" }"); out.println(" }"); for (int j = 0; j < callbackParameterTypes.length; j++) { if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) { String[] typeName = cppTypeName(callbackParameterTypes[j]); Annotation passBy = by(callbackParameterAnnotations[j]); String cast = cast(callbackParameterTypes[j], callbackParameterAnnotations[j]); String valueTypeName = valueTypeName(typeName); AdapterInformation adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]); if ("void*".equals(typeName[0])) { typeName[0] = "char*"; } if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) { out.println(" " + typeName[0] + " rptr" + j + typeName[1] + " = (" + typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(obj" + j + ", JavaCPP_addressFID));"); if (adapterInfo != null) { out.println(" jint rsize" + j + " = env->GetIntField(obj" + j + ", JavaCPP_limitFID);"); } if (!callbackParameterTypes[j].isAnnotationPresent(Opaque.class)) { out.println(" jint rposition" + j + " = env->GetIntField(obj" + j + ", JavaCPP_positionFID);"); out.println(" rptr" + j + " += rposition" + j + ";"); if (adapterInfo != null) { out.println(" rsize" + j + " -= rposition" + j + ";"); } } if (adapterInfo != null) { out.println(" adapter" + j + ".assign(rptr" + j + ", rsize" + j + ");"); } else if (passBy instanceof ByPtrPtr) { out.println(" if (arg" + j + " != NULL) {"); out.println(" *arg" + j + " = *" + cast + "&rptr" + j + ";"); out.println(" }"); } else if (passBy instanceof ByPtrRef) { out.println(" arg" + j + " = " + cast + "rptr" + j + ";"); } } } if (!callbackParameterTypes[j].isPrimitive()) { out.println(" env->DeleteLocalRef(obj" + j + ");"); } } out.println("}"); out.println("end:"); if (callbackReturnType != void.class) { if ("void*".equals(returnTypeName[0])) { returnTypeName[0] = "char*"; } if (Pointer.class.isAssignableFrom(callbackReturnType)) { out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : (" + returnTypeName[0] + returnTypeName[1] + ")jlong_to_ptr(env->GetLongField(rarg, JavaCPP_addressFID));"); if (returnAdapterInfo != null) { out.println(" jint rsize = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_limitFID);"); } if (!callbackReturnType.isAnnotationPresent(Opaque.class)) { out.println(" jint rposition = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_positionFID);"); out.println(" rptr += rposition;"); if (returnAdapterInfo != null) { out.println(" rsize -= rposition;"); } } } else if (callbackReturnType == String.class) { out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetStringUTFChars(rarg, NULL);"); if (returnAdapterInfo != null) { out.println(" jint rsize = 0;"); } } else if (Buffer.class.isAssignableFrom(callbackReturnType)) { out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetDirectBufferAddress(rarg);"); if (returnAdapterInfo != null) { out.println(" jint rsize = rarg == NULL ? 0 : env->GetDirectBufferCapacity(rarg);"); } } else if (!callbackReturnType.isPrimitive()) { logger.warn("Callback \"" + callbackMethod + "\" has unsupported return type \"" + callbackReturnType.getCanonicalName() + "\". Compilation will most likely fail."); } } out.println(" if (exc != NULL) {"); out.println(" jstring str = (jstring)env->CallObjectMethod(exc, JavaCPP_toStringMID);"); out.println(" env->DeleteLocalRef(exc);"); out.println(" const char *msg = env->GetStringUTFChars(str, NULL);"); out.println(" JavaCPP_exception e(msg);"); out.println(" env->ReleaseStringUTFChars(str, msg);"); out.println(" env->DeleteLocalRef(str);"); out.println(" JavaCPP_detach(attached);"); out.println(" throw e;"); out.println(" } else {"); out.println(" JavaCPP_detach(attached);"); out.println(" }"); if (callbackReturnType != void.class) { if (callbackReturnType.isPrimitive()) { out.println(" return " + callbackReturnCast + "rarg;"); } else if (returnAdapterInfo != null) { usesAdapters = true; out.println(" return " + returnAdapterInfo.name + "(" + callbackReturnCast + "rptr, rsize);"); } else if (FunctionPointer.class.isAssignableFrom(callbackReturnType)) { functions.index(callbackReturnType); out.println(" return " + callbackReturnCast + "(rptr == NULL ? NULL : rptr->ptr);"); } else if (returnBy instanceof ByVal || returnBy instanceof ByRef) { out.println(" if (rptr == NULL) {"); out.println(" JavaCPP_log(\"Return pointer address is NULL in callback for " + cls.getCanonicalName() + ".\");"); out.println(" static " + returnValueTypeName + " empty" + returnTypeName[1] + ";"); out.println(" return empty;"); out.println(" } else {"); out.println(" return *" + callbackReturnCast + "rptr;"); out.println(" }"); } else if (returnBy instanceof ByPtrPtr) { out.println(" return " + callbackReturnCast + "&rptr;"); } else { // ByPtr || ByPtrRef out.println(" return " + callbackReturnCast + "rptr;"); } } out.println("}"); } void callbackAllocator(Class cls, String callbackName) { // XXX: Here, we should actually allocate new trampolines on the heap somehow... // For now it just bumps out from the global variable the last object that called this method String instanceTypeName = functionClassName(cls); out.println(" obj = env->NewWeakGlobalRef(obj);"); out.println(" if (obj == NULL) {"); out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");"); out.println(" return;"); out.println(" }"); out.println(" " + instanceTypeName + "* rptr = new (std::nothrow) " + instanceTypeName + ";"); out.println(" if (rptr != NULL) {"); out.println(" rptr->ptr = &" + callbackName + ";"); out.println(" rptr->obj = obj;"); out.println(" JavaCPP_initPointer(env, obj, rptr, 1, &JavaCPP_" + mangle(cls.getName()) + "_deallocate);"); deallocators.index(cls); out.println(" " + callbackName + "_instance = *rptr;"); out.println(" }"); out.println("}"); } boolean checkPlatform(Class<?> cls) { com.googlecode.javacpp.annotation.Properties classProperties = cls.getAnnotation(com.googlecode.javacpp.annotation.Properties.class); if (classProperties != null) { Class[] classes = classProperties.inherit(); if (classes != null) { for (Class c : classes) { if (checkPlatform(c)) { return true; } } } Platform[] platforms = classProperties.value(); if (platforms != null) { for (Platform p : platforms) { if (checkPlatform(p)) { return true; } } } } else if (checkPlatform(cls.getAnnotation(Platform.class))) { return true; } return false; } boolean checkPlatform(Platform platform) { if (platform == null) { return true; } String platform2 = properties.getProperty("platform"); String[][] names = { platform.value(), platform.not() }; boolean[] matches = { false, false }; for (int i = 0; i < names.length; i++) { for (String s : names[i]) { if (platform2.startsWith(s)) { matches[i] = true; break; } } } if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) { return true; } return false; } static String functionClassName(Class<?> cls) { Name name = cls.getAnnotation(Name.class); return name != null ? name.value()[0] : "JavaCPP_" + mangle(cls.getName()); } static Method functionMethod(Class<?> cls, boolean[] callbackAllocators) { if (!FunctionPointer.class.isAssignableFrom(cls)) { return null; } Method[] methods = cls.getDeclaredMethods(); Method functionMethod = null; for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); int modifiers = methods[i].getModifiers(); Class[] parameterTypes = methods[i].getParameterTypes(); Class returnType = methods[i].getReturnType(); if (Modifier.isStatic(modifiers)) { continue; } if (callbackAllocators != null && methodName.startsWith("allocate") && Modifier.isNative(modifiers) && returnType == void.class && parameterTypes.length == 0) { // found a callback allocator method callbackAllocators[i] = true; } else if (methodName.startsWith("call") || methodName.startsWith("apply")) { // found a function caller method and/or callback method functionMethod = methods[i]; } } return functionMethod; } static class MethodInformation { Class<?> cls; Method method; Annotation[] annotations; int modifiers; Class<?> returnType; String name, memberName[]; int dim; boolean[] parameterRaw; Class<?>[] parameterTypes; Annotation[][] parameterAnnotations; boolean returnRaw, withEnv, overloaded, noOffset, deallocator, allocator, arrayAllocator, bufferGetter, valueGetter, valueSetter, memberGetter, memberSetter, noReturnGetter; Method pairedMethod; Class<?> throwsException; } MethodInformation methodInformation(Method method) { if (!Modifier.isNative(method.getModifiers())) { return null; } MethodInformation info = new MethodInformation(); info.cls = method.getDeclaringClass(); info.method = method; info.annotations = method.getAnnotations(); info.modifiers = method.getModifiers(); info.returnType = method.getReturnType(); info.name = method.getName(); Name name = method.getAnnotation(Name.class); info.memberName = name != null ? name.value() : new String[] { info.name }; Index index = method.getAnnotation(Index.class); info.dim = index != null ? index.value() : 0; info.parameterTypes = method.getParameterTypes(); info.parameterAnnotations = method.getParameterAnnotations(); info.returnRaw = method.isAnnotationPresent(Raw.class); info.withEnv = info.returnRaw ? method.getAnnotation(Raw.class).withEnv() : false; info.parameterRaw = new boolean[info.parameterAnnotations.length]; for (int i = 0; i < info.parameterAnnotations.length; i++) { for (int j = 0; j < info.parameterAnnotations[i].length; j++) { if (info.parameterAnnotations[i][j] instanceof Raw) { info.parameterRaw[i] = true; info.withEnv |= ((Raw)info.parameterAnnotations[i][j]).withEnv(); } } } boolean canBeGetter = info.returnType != void.class || (info.parameterTypes.length > 0 && info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive()); boolean canBeSetter = (info.returnType == void.class || info.returnType == info.cls) && info.parameterTypes.length > 0; boolean canBeAllocator = !Modifier.isStatic(info.modifiers) && info.returnType == void.class; boolean canBeArrayAllocator = canBeAllocator && info.parameterTypes.length == 1 && (info.parameterTypes[0] == int.class || info.parameterTypes[0] == long.class); boolean valueGetter = false; boolean valueSetter = false; boolean memberGetter = false; boolean memberSetter = false; boolean noReturnGetter = false; Method pairedMethod = null; for (Method method2 : info.cls.getDeclaredMethods()) { int modifiers2 = method2.getModifiers(); Class returnType2 = method2.getReturnType(); String methodName2 = method2.getName(); Class[] parameterTypes2 = method2.getParameterTypes(); Annotation[] annotations2 = method2.getAnnotations(); Annotation[][] parameterAnnotations2 = method2.getParameterAnnotations(); int skipParameters = info.parameterTypes.length > 0 && info.parameterTypes[0] == Class.class ? 1 : 0; int skipParameters2 = parameterTypes2.length > 0 && parameterTypes2[0] == Class.class ? 1 : 0; if (method.equals(method2) || !Modifier.isNative(modifiers2)) { continue; } boolean canBeValueGetter = false; boolean canBeValueSetter = false; boolean canBeMemberGetter = false; boolean canBeMemberSetter = false; if (canBeGetter && "get".equals(info.name) && "put".equals(methodName2)) { canBeValueGetter = true; } else if (canBeSetter && "put".equals(info.name) && "get".equals(methodName2)) { canBeValueSetter = true; } else if (methodName2.equals(info.name)) { info.overloaded = true; canBeMemberGetter = canBeGetter; canBeMemberSetter = canBeSetter; for (int j = skipParameters; j < info.parameterTypes.length; j++) { if (info.parameterTypes[j] != int.class && info.parameterTypes[j] != long.class) { canBeMemberGetter = false; if (j < info.parameterTypes.length - 1) { canBeMemberSetter = false; } } } } else { continue; } boolean sameIndexParameters = true; for (int j = 0; j < info.parameterTypes.length - skipParameters && j < parameterTypes2.length - skipParameters2; j++) { if (info.parameterTypes[j + skipParameters] != parameterTypes2[j + skipParameters2]) { sameIndexParameters = false; } } if (!sameIndexParameters) { continue; } boolean parameterAsReturn = canBeValueGetter && info.parameterTypes.length > 0 && info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive(); boolean parameterAsReturn2 = canBeValueSetter && parameterTypes2.length > 0 && parameterTypes2[0].isArray() && parameterTypes2[0].getComponentType().isPrimitive(); if (canBeGetter && parameterTypes2.length - (parameterAsReturn ? 0 : 1) == info.parameterTypes.length - skipParameters && (parameterAsReturn ? info.parameterTypes[info.parameterTypes.length - 1] : info.returnType) == parameterTypes2[parameterTypes2.length - 1] && (returnType2 == void.class || returnType2 == info.cls) && (parameterAnnotations2[parameterAnnotations2.length - 1].length == 0 || (Arrays.equals(parameterAnnotations2[parameterAnnotations2.length - 1], info.annotations)))) { pairedMethod = method2; valueGetter = canBeValueGetter; memberGetter = canBeMemberGetter; noReturnGetter = parameterAsReturn; } else if (canBeSetter && info.parameterTypes.length - (parameterAsReturn2 ? 0 : 1) == parameterTypes2.length - skipParameters2 && (parameterAsReturn2 ? parameterTypes2[parameterTypes2.length - 1] : returnType2) == info.parameterTypes[info.parameterTypes.length - 1] && (info.returnType == void.class || info.returnType == info.cls) && (info.parameterAnnotations[info.parameterAnnotations.length - 1].length == 0 || (Arrays.equals(info.parameterAnnotations[info.parameterAnnotations.length - 1], annotations2)))) { pairedMethod = method2; valueSetter = canBeValueSetter; memberSetter = canBeMemberSetter; } } Annotation behavior = behavior(info.annotations); if (canBeGetter && behavior instanceof ValueGetter) { info.valueGetter = true; info.noReturnGetter = noReturnGetter; } else if (canBeSetter && behavior instanceof ValueSetter) { info.valueSetter = true; } else if (canBeGetter && behavior instanceof MemberGetter) { info.memberGetter = true; info.noReturnGetter = noReturnGetter; } else if (canBeSetter && behavior instanceof MemberSetter) { info.memberSetter = true; } else if (canBeAllocator && behavior instanceof Allocator) { info.allocator = true; } else if (canBeArrayAllocator && behavior instanceof ArrayAllocator) { info.allocator = info.arrayAllocator = true; } else if (behavior == null) { // try to guess the behavior of the method if (info.returnType == void.class && "deallocate".equals(info.name) && !Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 2 && info.parameterTypes[0] == long.class && info.parameterTypes[1] == long.class) { info.deallocator = true; } else if (canBeAllocator && "allocate".equals(info.name)) { info.allocator = true; } else if (canBeArrayAllocator && "allocateArray".equals(info.name)) { info.allocator = info.arrayAllocator = true; } else if (info.returnType.isAssignableFrom(ByteBuffer.class) && "asDirectBuffer".equals(info.name) && !Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 0) { info.bufferGetter = true; } else if (valueGetter) { info.valueGetter = true; info.noReturnGetter = noReturnGetter; info.pairedMethod = pairedMethod; } else if (valueSetter) { info.valueSetter = true; info.pairedMethod = pairedMethod; } else if (memberGetter) { info.memberGetter = true; info.noReturnGetter = noReturnGetter; info.pairedMethod = pairedMethod; } else if (memberSetter) { info.memberSetter = true; info.pairedMethod = pairedMethod; } } else if (!(behavior instanceof Function)) { logger.warn("Method \"" + method + "\" cannot behave like a \"" + behavior.annotationType().getSimpleName() + "\". No code will be generated."); return null; } if (name == null && info.pairedMethod != null) { name = info.pairedMethod.getAnnotation(Name.class); if (name != null) { info.memberName = name.value(); } } info.noOffset = info.cls.isAnnotationPresent(NoOffset.class) || method.isAnnotationPresent(NoOffset.class) || method.isAnnotationPresent(Index.class); if (!info.noOffset && info.pairedMethod != null) { info.noOffset = info.pairedMethod.isAnnotationPresent(NoOffset.class) || info.pairedMethod.isAnnotationPresent(Index.class); } if (info.parameterTypes.length == 0 || !info.parameterTypes[0].isArray()) { if (info.valueGetter || info.memberGetter) { info.dim = info.parameterTypes.length; } else if (info.memberSetter || info.valueSetter) { info.dim = info.parameterTypes.length-1; } } info.throwsException = null; if (!noException(info.cls, method)) { if ((by(info.annotations) instanceof ByVal && !noException(info.returnType, method)) || !info.deallocator && !info.valueGetter && !info.valueSetter && !info.memberGetter && !info.memberSetter && !info.bufferGetter) { Class<?>[] exceptions = method.getExceptionTypes(); info.throwsException = exceptions.length > 0 ? exceptions[0] : RuntimeException.class; } } return info; } static boolean noException(Class<?> cls, Method method) { boolean noException = baseClasses.contains(cls) || method.isAnnotationPresent(NoException.class); while (!noException && cls != null) { if (noException = cls.isAnnotationPresent(NoException.class)) { break; } cls = cls.getDeclaringClass(); } return noException; } static class AdapterInformation { String name; int argc; String cast; boolean constant; } AdapterInformation adapterInformation(boolean out, MethodInformation methodInfo, int j) { if (out && (methodInfo.parameterTypes[j] == String.class || methodInfo.valueSetter || methodInfo.memberSetter)) { return null; } String typeName = cast(methodInfo, j); if (typeName != null && typeName.startsWith("(") && typeName.endsWith(")")) { typeName = typeName.substring(1, typeName.length()-1); } if (typeName == null || typeName.length() == 0) { typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j])[0]; } String valueTypeName = valueTypeName(typeName); AdapterInformation adapter = adapterInformation(out, valueTypeName, methodInfo.parameterAnnotations[j]); if (adapter == null && methodInfo.pairedMethod != null && j == methodInfo.parameterTypes.length - 1 && (methodInfo.valueSetter || methodInfo.memberSetter)) { adapter = adapterInformation(out, valueTypeName, methodInfo.pairedMethod.getAnnotations()); } return adapter; } AdapterInformation adapterInformation(boolean out, String valueTypeName, Annotation ... annotations) { AdapterInformation adapterInfo = null; boolean constant = false; String cast = ""; for (Annotation a : annotations) { Adapter adapter = a instanceof Adapter ? (Adapter)a : a.annotationType().getAnnotation(Adapter.class); if (adapter != null) { adapterInfo = new AdapterInformation(); adapterInfo.name = adapter.value(); adapterInfo.argc = adapter.argc(); if (a != adapter) { try { Class cls = a.annotationType(); if (cls.isAnnotationPresent(Const.class)) { constant = true; } try { String value = cls.getDeclaredMethod("value").invoke(a).toString(); if (value != null && value.length() > 0) { valueTypeName = value; } // else use inferred type } catch (NoSuchMethodException e) { // this adapter does not support a template type valueTypeName = null; } Cast c = (Cast)cls.getAnnotation(Cast.class); if (c != null && cast.length() == 0) { cast = c.value()[0]; if (valueTypeName != null) { cast += "< " + valueTypeName + " >"; } if (c.value().length > 1) { cast += c.value()[1]; } } } catch (Exception ex) { logger.warn("Could not invoke the value() method on annotation \"" + a + "\": " + ex); } if (valueTypeName != null && valueTypeName.length() > 0) { adapterInfo.name += "< " + valueTypeName + " >"; } } } else if (a instanceof Const) { constant = true; } else if (a instanceof Cast) { Cast c = ((Cast)a); if (c.value().length > 1) { cast = c.value()[1]; } } } if (adapterInfo != null) { adapterInfo.cast = cast; adapterInfo.constant = constant; } return out && constant ? null : adapterInfo; } String cast(MethodInformation methodInfo, int j) { String cast = cast(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]); if ((cast == null || cast.length() == 0) && j == methodInfo.parameterTypes.length-1 && (methodInfo.valueSetter || methodInfo.memberSetter) && methodInfo.pairedMethod != null) { cast = cast(methodInfo.pairedMethod.getReturnType(), methodInfo.pairedMethod.getAnnotations()); } return cast; } String cast(Class<?> type, Annotation ... annotations) { String[] typeName = null; for (Annotation a : annotations) { if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) { typeName = cppCastTypeName(type, annotations); break; } } return typeName != null && typeName.length > 0 ? "(" + typeName[0] + typeName[1] + ")" : ""; } Annotation by(MethodInformation methodInfo, int j) { Annotation passBy = by(methodInfo.parameterAnnotations[j]); if (passBy == null && methodInfo.pairedMethod != null && (methodInfo.valueSetter || methodInfo.memberSetter)) { passBy = by(methodInfo.pairedMethod.getAnnotations()); } return passBy; } Annotation by(Annotation ... annotations) { Annotation byAnnotation = null; for (Annotation a : annotations) { if (a instanceof ByPtr || a instanceof ByPtrPtr || a instanceof ByPtrRef || a instanceof ByRef || a instanceof ByVal) { if (byAnnotation != null) { logger.warn("\"By\" annotation \"" + byAnnotation + "\" already found. Ignoring superfluous annotation \"" + a + "\"."); } else { byAnnotation = a; } } } return byAnnotation; } Annotation behavior(Annotation ... annotations) { Annotation behaviorAnnotation = null; for (Annotation a : annotations) { if (a instanceof Function || a instanceof Allocator || a instanceof ArrayAllocator || a instanceof ValueSetter || a instanceof ValueGetter || a instanceof MemberGetter || a instanceof MemberSetter) { if (behaviorAnnotation != null) { logger.warn("Behavior annotation \"" + behaviorAnnotation + "\" already found. Ignoring superfluous annotation \"" + a + "\"."); } else { behaviorAnnotation = a; } } } return behaviorAnnotation; } static String constValueTypeName(String ... typeName) { String type = typeName[0]; if (type.endsWith("*") || type.endsWith("&")) { type = type.substring(0, type.length()-1); } return type; } static String valueTypeName(String ... typeName) { String type = typeName[0]; if (type.startsWith("const ")) { type = type.substring(6, type.length()-1); } else if (type.endsWith("*") || type.endsWith("&")) { type = type.substring(0, type.length()-1); } return type; } String[] cppAnnotationTypeName(Class<?> type, Annotation ... annotations) { String[] typeName = cppCastTypeName(type, annotations); String prefix = typeName[0]; String suffix = typeName[1]; boolean casted = false; for (Annotation a : annotations) { if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) { casted = true; break; } } Annotation by = by(annotations); if (by instanceof ByVal) { prefix = constValueTypeName(typeName); } else if (by instanceof ByRef) { prefix = constValueTypeName(typeName) + "&"; } else if (by instanceof ByPtrPtr && !casted) { prefix = prefix + "*"; } else if (by instanceof ByPtrRef) { prefix = prefix + "&"; } // else ByPtr typeName[0] = prefix; typeName[1] = suffix; return typeName; } String[] cppCastTypeName(Class<?> type, Annotation ... annotations) { String[] typeName = null; boolean warning = false, adapter = false; for (Annotation a : annotations) { if (a instanceof Cast) { warning = typeName != null; String prefix = ((Cast)a).value()[0], suffix = ""; int parenthesis = prefix.indexOf(')'); if (parenthesis > 0) { suffix = prefix.substring(parenthesis).trim(); prefix = prefix.substring(0, parenthesis).trim(); } typeName = prefix.length() > 0 ? new String[] { prefix, suffix } : null; } else if (a instanceof Const) { if (warning = typeName != null) { // prioritize @Cast continue; } typeName = cppTypeName(type); boolean[] b = ((Const)a).value(); if (b.length > 1 && b[1]) { typeName[0] = valueTypeName(typeName) + " const *"; } if (b.length > 0 && b[0]) { typeName[0] = "const " + typeName[0]; } Annotation by = by(annotations); if (by instanceof ByPtrPtr) { typeName[0] += "*"; } else if (by instanceof ByPtrRef) { typeName[0] += "&"; } } else if (a instanceof Adapter || a.annotationType().isAnnotationPresent(Adapter.class)) { adapter = true; } } if (warning && !adapter) { logger.warn("Without \"Adapter\", \"Cast\" and \"Const\" annotations are mutually exclusive."); } if (typeName == null) { typeName = cppTypeName(type); } return typeName; } String[] cppTypeName(Class<?> type) { String prefix = "", suffix = ""; if (type == Buffer.class || type == Pointer.class) { prefix = "void*"; } else if (type == byte[].class || type == ByteBuffer.class || type == BytePointer.class) { prefix = "signed char*"; } else if (type == short[].class || type == ShortBuffer.class || type == ShortPointer.class) { prefix = "short*"; } else if (type == int[].class || type == IntBuffer.class || type == IntPointer.class) { prefix = "int*"; } else if (type == long[].class || type == LongBuffer.class || type == LongPointer.class) { prefix = "jlong*"; } else if (type == float[].class || type == FloatBuffer.class || type == FloatPointer.class) { prefix = "float*"; } else if (type == double[].class || type == DoubleBuffer.class || type == DoublePointer.class) { prefix = "double*"; } else if (type == char[].class || type == CharBuffer.class || type == CharPointer.class) { prefix = "unsigned short*"; } else if (type == boolean[].class) { prefix = "unsigned char*"; } else if (type == PointerPointer.class) { prefix = "void**"; } else if (type == String.class) { prefix = "const char*"; } else if (type == byte.class) { prefix = "signed char"; } else if (type == long.class) { prefix = "jlong"; } else if (type == char.class) { prefix = "unsigned short"; } else if (type == boolean.class) { prefix = "unsigned char"; } else if (type.isPrimitive()) { prefix = type.getName(); } else if (FunctionPointer.class.isAssignableFrom(type)) { Method functionMethod = functionMethod(type, null); if (functionMethod != null) { Convention convention = type.getAnnotation(Convention.class); String callingConvention = convention == null ? "" : convention.value() + " "; Namespace namespace = type.getAnnotation(Namespace.class); String spaceName = namespace == null ? "" : namespace.value(); if (spaceName.length() > 0 && !spaceName.endsWith("::")) { spaceName += "::"; } Class returnType = functionMethod.getReturnType(); Class[] parameterTypes = functionMethod.getParameterTypes(); Annotation[] annotations = functionMethod.getAnnotations(); Annotation[][] parameterAnnotations = functionMethod.getParameterAnnotations(); String[] returnTypeName = cppAnnotationTypeName(returnType, annotations); AdapterInformation returnAdapterInfo = adapterInformation(false, valueTypeName(returnTypeName), annotations); if (returnAdapterInfo != null && returnAdapterInfo.cast.length() > 0) { prefix = returnAdapterInfo.cast; } else { prefix = returnTypeName[0] + returnTypeName[1]; } prefix += " (" + callingConvention + spaceName + "*"; suffix = ")("; if (namespace != null && !Pointer.class.isAssignableFrom(parameterTypes[0])) { logger.warn("First parameter of caller method call() or apply() for member function pointer " + type.getCanonicalName() + " is not a Pointer. Compilation will most likely fail."); } for (int j = namespace == null ? 0 : 1; j < parameterTypes.length; j++) { String[] paramTypeName = cppAnnotationTypeName(parameterTypes[j], parameterAnnotations[j]); AdapterInformation paramAdapterInfo = adapterInformation(false, valueTypeName(paramTypeName), parameterAnnotations[j]); if (paramAdapterInfo != null && paramAdapterInfo.cast.length() > 0) { suffix += paramAdapterInfo.cast + " arg" + j; } else { suffix += paramTypeName[0] + " arg" + j + paramTypeName[1]; } if (j < parameterTypes.length - 1) { suffix += ", "; } } suffix += ")"; if (type.isAnnotationPresent(Const.class)) { suffix += " const"; } } } else { String scopedType = cppScopeName(type); if (scopedType.length() > 0) { prefix = scopedType + "*"; } else { logger.warn("The class " + type.getCanonicalName() + " does not map to any C++ type. Compilation will most likely fail."); } } return new String[] { prefix, suffix }; } static String cppScopeName(MethodInformation methodInfo) { String scopeName = cppScopeName(methodInfo.cls); Namespace namespace = methodInfo.method.getAnnotation(Namespace.class); String spaceName = namespace == null ? "" : namespace.value(); if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) { scopeName = ""; // user wants to reset namespace here } if (scopeName.length() > 0 && !scopeName.endsWith("::")) { scopeName += "::"; } scopeName += spaceName; if (spaceName.length() > 0 && !spaceName.endsWith("::")) { scopeName += "::"; } return scopeName + methodInfo.memberName[0]; } static String cppScopeName(Class<?> type) { String scopeName = ""; while (type != null) { Namespace namespace = type.getAnnotation(Namespace.class); String spaceName = namespace == null ? "" : namespace.value(); if (Pointer.class.isAssignableFrom(type) && type != Pointer.class) { Name name = type.getAnnotation(Name.class); String s; if (name == null) { s = type.getName(); int i = s.lastIndexOf("$"); if (i < 0) { i = s.lastIndexOf("."); } s = s.substring(i+1); } else { s = name.value()[0]; } if (spaceName.length() > 0 && !spaceName.endsWith("::")) { spaceName += "::"; } spaceName += s; } if (scopeName.length() > 0 && !spaceName.endsWith("::")) { spaceName += "::"; } scopeName = spaceName + scopeName; if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) { // user wants to reset namespace here break; } type = type.getDeclaringClass(); } return scopeName; } static String jniTypeName(Class type) { if (type == byte.class) { return "jbyte"; } else if (type == short.class) { return "jshort"; } else if (type == int.class) { return "jint"; } else if (type == long.class) { return "jlong"; } else if (type == float.class) { return "jfloat"; } else if (type == double.class) { return "jdouble"; } else if (type == char.class) { return "jchar"; } else if (type == boolean.class) { return "jboolean"; } else if (type == byte[].class) { return "jbyteArray"; } else if (type == short[].class) { return "jshortArray"; } else if (type == int[].class) { return "jintArray"; } else if (type == long[].class) { return "jlongArray"; } else if (type == float[].class) { return "jfloatArray"; } else if (type == double[].class) { return "jdoubleArray"; } else if (type == char[].class) { return "jcharArray"; } else if (type == boolean[].class) { return "jbooleanArray"; } else if (type.isArray()) { return "jobjectArray"; } else if (type == String.class) { return "jstring"; } else if (type == Class.class) { return "jclass"; } else if (type == void.class) { return "void"; } else { return "jobject"; } } static String signature(Class ... types) { StringBuilder signature = new StringBuilder(2*types.length); for (Class type : types) { if (type == byte.class) { signature.append("B"); } else if (type == short.class) { signature.append("S"); } else if (type == int.class) { signature.append("I"); } else if (type == long.class) { signature.append("J"); } else if (type == float.class) { signature.append("F"); } else if (type == double.class) { signature.append("D"); } else if (type == boolean.class) { signature.append("Z"); } else if (type == char.class) { signature.append("C"); } else if (type == void.class) { signature.append("V"); } else if (type.isArray()) { signature.append(type.getName().replace('.', '/')); } else { signature.append("L").append(type.getName().replace('.', '/')).append(";"); } } return signature.toString(); } static String mangle(String name) { StringBuilder mangledName = new StringBuilder(2*name.length()); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { mangledName.append(c); } else if (c == '_') { mangledName.append("_1"); } else if (c == ';') { mangledName.append("_2"); } else if (c == '[') { mangledName.append("_3"); } else if (c == '.' || c == '/') { mangledName.append("_"); } else { String code = Integer.toHexString(c); mangledName.append("_0"); switch (code.length()) { case 1: mangledName.append("0"); case 2: mangledName.append("0"); case 3: mangledName.append("0"); default: mangledName.append(code); } } } return mangledName.toString(); } }
gpl-2.0
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/EncodedGraph.java
2807
/* * Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.nodes; import java.util.List; import org.graalvm.compiler.graph.NodeClass; import jdk.vm.ci.meta.Assumptions; import jdk.vm.ci.meta.ResolvedJavaMethod; /** * A {@link StructuredGraph} encoded in a compact binary representation as a byte[] array. See * {@link GraphEncoder} for a description of the encoding format. Use {@link GraphDecoder} for * decoding. */ public class EncodedGraph { private final byte[] encoding; private final long startOffset; private final Object[] objects; private final NodeClass<?>[] types; private final Assumptions assumptions; private final List<ResolvedJavaMethod> inlinedMethods; /** * The "table of contents" of the encoded graph, i.e., the mapping from orderId numbers to the * offset in the encoded byte[] array. Used as a cache during decoding. */ protected long[] nodeStartOffsets; public EncodedGraph(byte[] encoding, long startOffset, Object[] objects, NodeClass<?>[] types, Assumptions assumptions, List<ResolvedJavaMethod> inlinedMethods) { this.encoding = encoding; this.startOffset = startOffset; this.objects = objects; this.types = types; this.assumptions = assumptions; this.inlinedMethods = inlinedMethods; } public byte[] getEncoding() { return encoding; } public long getStartOffset() { return startOffset; } public Object[] getObjects() { return objects; } public NodeClass<?>[] getNodeClasses() { return types; } public Assumptions getAssumptions() { return assumptions; } public List<ResolvedJavaMethod> getInlinedMethods() { return inlinedMethods; } }
gpl-2.0
DrewG/mzmine2
src/main/java/net/sf/mzmine/modules/peaklistmethods/peakpicking/deconvolution/savitzkygolay/SGDerivative.java
2508
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.savitzkygolay; public final class SGDerivative { /** * This method returns the second smoothed derivative values of an array. * * @param double[] values * @param boolean is first derivative * @param int level of filter (1 - 12) * @return double[] derivative of values */ public static double[] calculateDerivative(double[] values, boolean firstDerivative, int levelOfFilter) { double[] derivative = new double[values.length]; int M = 0; for (int k = 0; k < derivative.length; k++) { // Determine boundaries if (k <= levelOfFilter) M = k; if (k + M > derivative.length - 1) M = derivative.length - (k + 1); // Perform derivative using Savitzky Golay coefficients for (int i = -M; i <= M; i++) { derivative[k] += values[k + i] * getSGCoefficient(M, i, firstDerivative); } // if ((Math.abs(derivative[k])) > maxValueDerivative) // maxValueDerivative = Math.abs(derivative[k]); } return derivative; } /** * This method return the Savitzky-Golay 2nd smoothed derivative coefficient * from an array * * @param M * @param signedC * @return */ private static Double getSGCoefficient(int M, int signedC, boolean firstDerivate) { int C = Math.abs(signedC), sign = 1; if (firstDerivate) { if (signedC < 0) sign = -1; return sign * SGCoefficients.SGCoefficientsFirstDerivativeQuartic[M][C]; } else { return SGCoefficients.SGCoefficientsSecondDerivative[M][C]; } } }
gpl-2.0
xdajog/samsung_sources_i927
libcore/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java
2129
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Yuri A. Kropachev * @version $Revision$ */ package org.apache.harmony.security.provider.crypto; /** * This interface contains : <BR> * - a set of constant values, H0-H4, defined in "SECURE HASH STANDARD", FIPS PUB 180-2 ;<BR> * - implementation constant values to use in classes using SHA-1 algorithm. <BR> */ public interface SHA1_Data { /** * constant defined in "SECURE HASH STANDARD" */ static final int H0 = 0x67452301; /** * constant defined in "SECURE HASH STANDARD" */ static final int H1 = 0xEFCDAB89; /** * constant defined in "SECURE HASH STANDARD" */ static final int H2 = 0x98BADCFE; /** * constant defined in "SECURE HASH STANDARD" */ static final int H3 = 0x10325476; /** * constant defined in "SECURE HASH STANDARD" */ static final int H4 = 0xC3D2E1F0; /** * offset in buffer to store number of bytes in 0-15 word frame */ static final int BYTES_OFFSET = 81; /** * offset in buffer to store current hash value */ static final int HASH_OFFSET = 82; /** * # of bytes in H0-H4 words; <BR> * in this implementation # is set to 20 (in general # varies from 1 to 20) */ static final int DIGEST_LENGTH = 20; }
gpl-2.0