repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
weebl2000/modeshape
modeshape-jdbc/src/main/java/org/modeshape/jdbc/rest/ItemDefinition.java
2396
/* * ModeShape (http://www.modeshape.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.modeshape.jdbc.rest; import javax.jcr.version.OnParentVersionAction; import org.codehaus.jettison.json.JSONObject; import org.modeshape.common.annotation.Immutable; /** * An {@link javax.jcr.nodetype.ItemDefinition} implementation for the ModeShape client. */ @Immutable public abstract class ItemDefinition implements javax.jcr.nodetype.ItemDefinition { private final String declaringNodeTypeName; private final boolean isAutoCreated; private final boolean isMandatory; private final boolean isProtected; private final int onParentVersion; private final NodeTypes nodeTypes; protected ItemDefinition( String declaringNodeTypeName, JSONObject json, NodeTypes nodeTypes ) { this.declaringNodeTypeName = declaringNodeTypeName; this.nodeTypes = nodeTypes; this.isAutoCreated = JSONHelper.valueFrom(json, "jcr:autoCreated", false); this.isMandatory = JSONHelper.valueFrom(json, "jcr:mandatory", false); this.isProtected = JSONHelper.valueFrom(json, "jcr:protected", false); this.onParentVersion = OnParentVersionAction.valueFromName(JSONHelper.valueFrom(json, "jcr:onParentVersion")); } protected NodeTypes nodeTypes() { return nodeTypes; } @Override public NodeType getDeclaringNodeType() { return nodeTypes.getNodeType(declaringNodeTypeName); } @Override public int getOnParentVersion() { return onParentVersion; } @Override public boolean isAutoCreated() { return isAutoCreated; } @Override public boolean isMandatory() { return isMandatory; } @Override public boolean isProtected() { return isProtected; } }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdets-idea/eclipse-src/org.eclipse.php.core/src/org/eclipse/php/core/codeassist/IElementFilter.java
1053
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ package org.eclipse.php.core.codeassist; import org.eclipse.dltk.core.IModelElement; /** * This is a model element filter that filters out model elements from adding * them to code assist list * * @author michael */ public interface IElementFilter { /** * @param element * Model element * @return <code>true</code> if given element must be filtered out from code * assist, otherwise <code>false</code> */ public boolean filter(IModelElement element); }
apache-2.0
gingerwizard/elasticsearch
server/src/test/java/org/elasticsearch/search/suggest/SuggestBuilderTests.java
7298
/* * 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.suggest; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.suggest.completion.CompletionSuggesterBuilderTests; import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilderTests; import org.elasticsearch.search.suggest.term.TermSuggestionBuilderTests; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.EqualsHashCodeTestUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.Map.Entry; import static java.util.Collections.emptyList; public class SuggestBuilderTests extends ESTestCase { private static final int NUMBER_OF_RUNS = 20; private static NamedWriteableRegistry namedWriteableRegistry; private static NamedXContentRegistry xContentRegistry; /** * Setup for the whole base test class. */ @BeforeClass public static void init() { SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList()); namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables()); xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents()); } @AfterClass public static void afterClass() { namedWriteableRegistry = null; xContentRegistry = null; } /** * creates random suggestion builder, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_RUNS; runs++) { SuggestBuilder suggestBuilder = randomSuggestBuilder(); XContentBuilder xContentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { xContentBuilder.prettyPrint(); } suggestBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); try (XContentParser parser = createParser(xContentBuilder)) { SuggestBuilder secondSuggestBuilder = SuggestBuilder.fromXContent(parser); assertNotSame(suggestBuilder, secondSuggestBuilder); assertEquals(suggestBuilder, secondSuggestBuilder); assertEquals(suggestBuilder.hashCode(), secondSuggestBuilder.hashCode()); } } } /** * Test equality and hashCode properties */ public void testEqualsAndHashcode() throws IOException { for (int runs = 0; runs < NUMBER_OF_RUNS; runs++) { // explicit about type parameters, see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=481649 EqualsHashCodeTestUtils.<SuggestBuilder>checkEqualsAndHashCode(randomSuggestBuilder(), original -> { return copyWriteable(original, namedWriteableRegistry, SuggestBuilder::new); }, this::createMutation); } } /** * Test serialization and deserialization */ public void testSerialization() throws IOException { for (int i = 0; i < NUMBER_OF_RUNS; i++) { SuggestBuilder suggestBuilder = randomSuggestBuilder(); SuggestBuilder deserializedModel = copyWriteable(suggestBuilder, namedWriteableRegistry, SuggestBuilder::new); assertEquals(suggestBuilder, deserializedModel); assertEquals(suggestBuilder.hashCode(), deserializedModel.hashCode()); assertNotSame(suggestBuilder, deserializedModel); } } public void testIllegalSuggestionName() { try { new SuggestBuilder().addSuggestion(null, PhraseSuggestionBuilderTests.randomPhraseSuggestionBuilder()); fail("exception expected"); } catch (NullPointerException e) { assertEquals("every suggestion needs a name", e.getMessage()); } try { new SuggestBuilder().addSuggestion("my-suggest", PhraseSuggestionBuilderTests.randomPhraseSuggestionBuilder()) .addSuggestion("my-suggest", PhraseSuggestionBuilderTests.randomPhraseSuggestionBuilder()); fail("exception expected"); } catch (IllegalArgumentException e) { assertEquals("already added another suggestion with name [my-suggest]", e.getMessage()); } } protected SuggestBuilder createMutation(SuggestBuilder original) throws IOException { SuggestBuilder mutation = new SuggestBuilder().setGlobalText(original.getGlobalText()); for (Entry<String, SuggestionBuilder<?>> suggestionBuilder : original.getSuggestions().entrySet()) { mutation.addSuggestion(suggestionBuilder.getKey(), suggestionBuilder.getValue()); } if (randomBoolean()) { mutation.setGlobalText(randomAlphaOfLengthBetween(5, 60)); } else { mutation.addSuggestion(randomAlphaOfLength(10), PhraseSuggestionBuilderTests.randomPhraseSuggestionBuilder()); } return mutation; } public static SuggestBuilder randomSuggestBuilder() { SuggestBuilder builder = new SuggestBuilder(); if (randomBoolean()) { builder.setGlobalText(randomAlphaOfLengthBetween(1, 20)); } final int numSuggestions = randomIntBetween(1, 5); for (int i = 0; i < numSuggestions; i++) { builder.addSuggestion(randomAlphaOfLengthBetween(5, 10), randomSuggestionBuilder()); } return builder; } private static SuggestionBuilder<?> randomSuggestionBuilder() { switch (randomIntBetween(0, 2)) { case 0: return TermSuggestionBuilderTests.randomTermSuggestionBuilder(); case 1: return PhraseSuggestionBuilderTests.randomPhraseSuggestionBuilder(); case 2: return CompletionSuggesterBuilderTests.randomCompletionSuggestionBuilder(); default: return TermSuggestionBuilderTests.randomTermSuggestionBuilder(); } } @Override protected NamedXContentRegistry xContentRegistry() { return xContentRegistry; } }
apache-2.0
jonmcewen/camel
camel-core/src/test/java/org/apache/camel/management/ManagedRouteNoAutoStartupTest.java
3907
/** * 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.management; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.camel.ServiceStatus; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import static org.awaitility.Awaitility.await; /** * Extended test to see if mbeans is removed and stats are correct * * @version */ public class ManagedRouteNoAutoStartupTest extends ManagementTestSupport { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").noAutoStartup() .to("mock:result"); } }; } static ObjectName getRouteObjectName(MBeanServer mbeanServer) throws Exception { Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); assertEquals(1, set.size()); return set.iterator().next(); } public void testRouteNoAutoStartup() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = getRouteObjectName(mbeanServer); // should be stopped String state = (String) mbeanServer.getAttribute(on, "State"); assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); // start mbeanServer.invoke(on, "start", null, null); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // need a bit time to let JMX update await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> { // should have 1 completed exchange Long completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted"); assertEquals(1, completed.longValue()); }); // should be 1 consumer and 1 processor Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=consumers,*"), null); assertEquals("Should be 1 consumer", 1, set.size()); set = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null); assertEquals("Should be 1 processor", 1, set.size()); // stop mbeanServer.invoke(on, "stop", null, null); state = (String) mbeanServer.getAttribute(on, "State"); assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); // should be 0 consumer and 0 processor set = mbeanServer.queryNames(new ObjectName("*:type=consumers,*"), null); assertEquals("Should be 0 consumer", 0, set.size()); set = mbeanServer.queryNames(new ObjectName("*:type=processors,*"), null); assertEquals("Should be 0 processor", 0, set.size()); } }
apache-2.0
dahlstrom-g/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/convertToSingleReturn/beforeNonNulls.java
301
// "Transform body to single exit-point form" "true" class Test { String<caret> process(String s, int x) { if (x > 0) { if (x == 2) { return s.trim(); } System.out.println(s.substring(0)); } return s.substring(1); } }
apache-2.0
mcgilman/nifi
nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/QueryDatabaseTable.java
9016
/* * 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.processors.standard; import org.apache.nifi.annotation.behavior.DynamicProperty; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; import org.apache.nifi.annotation.behavior.PrimaryNodeOnly; import org.apache.nifi.annotation.behavior.Stateful; import org.apache.nifi.annotation.behavior.TriggerSerially; import org.apache.nifi.annotation.behavior.WritesAttribute; import org.apache.nifi.annotation.behavior.WritesAttributes; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.SeeAlso; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.state.Scope; import org.apache.nifi.expression.ExpressionLanguageScope; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processors.standard.sql.DefaultAvroSqlWriter; import org.apache.nifi.processors.standard.sql.SqlWriter; import org.apache.nifi.util.db.JdbcCommon; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.apache.nifi.processors.standard.util.JdbcProperties.DEFAULT_PRECISION; import static org.apache.nifi.processors.standard.util.JdbcProperties.DEFAULT_SCALE; import static org.apache.nifi.processors.standard.util.JdbcProperties.NORMALIZE_NAMES_FOR_AVRO; import static org.apache.nifi.processors.standard.util.JdbcProperties.USE_AVRO_LOGICAL_TYPES; @TriggerSerially @InputRequirement(Requirement.INPUT_FORBIDDEN) @Tags({"sql", "select", "jdbc", "query", "database"}) @SeeAlso({GenerateTableFetch.class, ExecuteSQL.class}) @CapabilityDescription("Generates a SQL select query, or uses a provided statement, and executes it to fetch all rows whose values in the specified " + "Maximum Value column(s) are larger than the " + "previously-seen maxima. Query result will be converted to Avro format. Expression Language is supported for several properties, but no incoming " + "connections are permitted. The Variable Registry may be used to provide values for any property containing Expression Language. If it is desired to " + "leverage flow file attributes to perform these queries, the GenerateTableFetch and/or ExecuteSQL processors can be used for this purpose. " + "Streaming is used so arbitrarily large result sets are supported. This processor can be scheduled to run on " + "a timer or cron expression, using the standard scheduling methods. This processor is intended to be run on the Primary Node only. FlowFile attribute " + "'querydbtable.row.count' indicates how many rows were selected.") @Stateful(scopes = Scope.CLUSTER, description = "After performing a query on the specified table, the maximum values for " + "the specified column(s) will be retained for use in future executions of the query. This allows the Processor " + "to fetch only those records that have max values greater than the retained values. This can be used for " + "incremental fetching, fetching of newly added rows, etc. To clear the maximum values, clear the state of the processor " + "per the State Management documentation") @WritesAttributes({ @WritesAttribute(attribute = "tablename", description="Name of the table being queried"), @WritesAttribute(attribute = "querydbtable.row.count", description="The number of rows selected by the query"), @WritesAttribute(attribute="fragment.identifier", description="If 'Max Rows Per Flow File' is set then all FlowFiles from the same query result set " + "will have the same value for the fragment.identifier attribute. This can then be used to correlate the results."), @WritesAttribute(attribute = "fragment.count", description = "If 'Max Rows Per Flow File' is set then this is the total number of " + "FlowFiles produced by a single ResultSet. This can be used in conjunction with the " + "fragment.identifier attribute in order to know how many FlowFiles belonged to the same incoming ResultSet. If Output Batch Size is set, then this " + "attribute will not be populated."), @WritesAttribute(attribute="fragment.index", description="If 'Max Rows Per Flow File' is set then the position of this FlowFile in the list of " + "outgoing FlowFiles that were all derived from the same result set FlowFile. This can be " + "used in conjunction with the fragment.identifier attribute to know which FlowFiles originated from the same query result set and in what order " + "FlowFiles were produced"), @WritesAttribute(attribute = "maxvalue.*", description = "Each attribute contains the observed maximum value of a specified 'Maximum-value Column'. The " + "suffix of the attribute is the name of the column. If Output Batch Size is set, then this attribute will not be populated.")}) @DynamicProperty(name = "initial.maxvalue.<max_value_column>", value = "Initial maximum value for the specified column", expressionLanguageScope = ExpressionLanguageScope.VARIABLE_REGISTRY, description = "Specifies an initial max value for max value column(s). Properties should " + "be added in the format `initial.maxvalue.<max_value_column>`. This value is only used the first time the table is accessed (when a Maximum Value Column is specified).") @PrimaryNodeOnly public class QueryDatabaseTable extends AbstractQueryDatabaseTable { public QueryDatabaseTable() { final Set<Relationship> r = new HashSet<>(); r.add(REL_SUCCESS); relationships = Collections.unmodifiableSet(r); final List<PropertyDescriptor> pds = new ArrayList<>(); pds.add(DBCP_SERVICE); pds.add(DB_TYPE); pds.add(new PropertyDescriptor.Builder() .fromPropertyDescriptor(TABLE_NAME) .description("The name of the database table to be queried. When a custom query is used, this property is used to alias the query and appears as an attribute on the FlowFile.") .build()); pds.add(COLUMN_NAMES); pds.add(WHERE_CLAUSE); pds.add(SQL_QUERY); pds.add(MAX_VALUE_COLUMN_NAMES); pds.add(QUERY_TIMEOUT); pds.add(FETCH_SIZE); pds.add(MAX_ROWS_PER_FLOW_FILE); pds.add(OUTPUT_BATCH_SIZE); pds.add(MAX_FRAGMENTS); pds.add(NORMALIZE_NAMES_FOR_AVRO); pds.add(TRANS_ISOLATION_LEVEL); pds.add(USE_AVRO_LOGICAL_TYPES); pds.add(DEFAULT_PRECISION); pds.add(DEFAULT_SCALE); propDescriptors = Collections.unmodifiableList(pds); } @Override protected SqlWriter configureSqlWriter(ProcessSession session, ProcessContext context) { final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions().getValue(); final boolean convertNamesForAvro = context.getProperty(NORMALIZE_NAMES_FOR_AVRO).asBoolean(); final Boolean useAvroLogicalTypes = context.getProperty(USE_AVRO_LOGICAL_TYPES).asBoolean(); final Integer maxRowsPerFlowFile = context.getProperty(MAX_ROWS_PER_FLOW_FILE).evaluateAttributeExpressions().asInteger(); final Integer defaultPrecision = context.getProperty(DEFAULT_PRECISION).evaluateAttributeExpressions().asInteger(); final Integer defaultScale = context.getProperty(DEFAULT_SCALE).evaluateAttributeExpressions().asInteger(); final JdbcCommon.AvroConversionOptions options = JdbcCommon.AvroConversionOptions.builder() .recordName(tableName) .convertNames(convertNamesForAvro) .useLogicalTypes(useAvroLogicalTypes) .defaultPrecision(defaultPrecision) .defaultScale(defaultScale) .maxRows(maxRowsPerFlowFile) .build(); return new DefaultAvroSqlWriter(options); } }
apache-2.0
armenrz/adempiere
extend/src/test/functional/TrifonTest.java
1444
package test.functional; import org.compiere.model.MColumn; import org.compiere.model.MInvoice; import org.compiere.model.MProduct; import org.compiere.model.MTable; import org.compiere.model.X_AD_Reference; import org.compiere.util.Env; import test.AdempiereTestCase; public class TrifonTest extends AdempiereTestCase { // Test: Specific variables private MProduct product = null; public void testMProductCreation() { boolean singleCommit = true; MTable mTable = MTable.get(Env.getCtx(), MInvoice.Table_Name ); System.out.println("XML presentation... is: " + mTable.get_xmlDocument(false)); MColumn mcolumn[] = mTable.getColumns(true); for (int i = 0; i < mcolumn.length; i++) { System.out.println("Name............ is: " + mcolumn[i].getName()); System.out.println("ColumnName...... is: " + mcolumn[i].getColumnName()); System.out.println("Desc............ is: " + mcolumn[i].getDescription()); System.out.println("Length.......... is: " + mcolumn[i].getFieldLength()); System.out.println("Reference_ID.... is: " + mcolumn[i].getAD_Reference_ID()); X_AD_Reference reference = new X_AD_Reference(Env.getCtx(), mcolumn[i].getAD_Reference_ID(), getTrxName()); System.out.println("ReferenceName... is: " + reference.getName()); System.out.println(".............................."); } assertTrue(this.getClass().getName(), true); } }
gpl-2.0
jtux270/translate
ovirt/frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/editor/TextBoxChanger.java
474
package org.ovirt.engine.ui.common.widget.editor; import com.google.gwt.user.client.ui.TextBox; /** * A {@link TextBox} that uses a {@link ValueBoxEditorChanger} as the Editor */ public class TextBoxChanger extends TextBox { private ValueBoxEditorChanger<String> editor; @Override public ValueBoxEditorChanger<String> asEditor() { if (editor == null) { editor = ValueBoxEditorChanger.of(this); } return editor; } }
gpl-3.0
andre-nunes/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/candidacyProcess/IndividualCandidacySeriesGradeState.java
1730
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.candidacyProcess; import java.util.Locale; import org.fenixedu.academic.util.Bundle; import org.fenixedu.bennu.core.i18n.BundleUtil; import org.fenixedu.commons.i18n.I18N; public enum IndividualCandidacySeriesGradeState { ACCEPTED, REJECTED, EXCLUDED; public String getName() { return name(); } public String getQualifiedName() { return IndividualCandidacySeriesGradeState.class.getSimpleName() + "." + name(); } public String getFullyQualifiedName() { return IndividualCandidacySeriesGradeState.class.getName() + "." + name(); } protected String localizedName(Locale locale) { return BundleUtil.getString(Bundle.ENUMERATION, locale, getQualifiedName()); } protected String localizedName() { return localizedName(I18N.getLocale()); } public String getLocalizedName() { return localizedName(); } }
lgpl-3.0
xhoong/incubator-calcite
core/src/main/java/org/apache/calcite/sql/SqlInternalOperator.java
3001
/* * 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.calcite.sql; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.sql.type.OperandTypes; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.type.SqlOperandTypeChecker; import org.apache.calcite.sql.type.SqlOperandTypeInference; import org.apache.calcite.sql.type.SqlReturnTypeInference; import org.apache.calcite.sql.validate.SqlValidator; import org.apache.calcite.sql.validate.SqlValidatorScope; /** * Generic operator for nodes with internal syntax. * * <p>If you do not override {@link #getSyntax()} or * {@link #unparse(SqlWriter, SqlCall, int, int)}, they will be unparsed using * function syntax, {@code F(arg1, arg2, ...)}. This may be OK for operators * that never appear in SQL, only as structural elements in an abstract syntax * tree. * * <p>You can use this operator, without creating a sub-class, for * non-expression nodes. Validate will validate the arguments, but will not * attempt to deduce a type. */ public class SqlInternalOperator extends SqlSpecialOperator { //~ Constructors ----------------------------------------------------------- public SqlInternalOperator( String name, SqlKind kind) { this(name, kind, 2); } public SqlInternalOperator( String name, SqlKind kind, int prec) { this(name, kind, prec, true, ReturnTypes.ARG0, null, OperandTypes.VARIADIC); } public SqlInternalOperator( String name, SqlKind kind, int prec, boolean isLeftAssoc, SqlReturnTypeInference returnTypeInference, SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker) { super( name, kind, prec, isLeftAssoc, returnTypeInference, operandTypeInference, operandTypeChecker); } //~ Methods ---------------------------------------------------------------- public SqlSyntax getSyntax() { return SqlSyntax.FUNCTION; } @Override public RelDataType deriveType(SqlValidator validator, SqlValidatorScope scope, SqlCall call) { return validateOperands(validator, scope, call); } } // End SqlInternalOperator.java
apache-2.0
anaerobic/keycloak
forms/login-freemarker/src/main/java/org/keycloak/login/freemarker/model/CodeBean.java
527
package org.keycloak.login.freemarker.model; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class CodeBean { private final String code; private final String error; public CodeBean(String code, String error) { this.code = code; this.error = error; } public boolean isSuccess() { return code != null && error == null; } public String getCode() { return code; } public String getError() { return error; } }
apache-2.0
nomoa/elasticsearch
core/src/test/java/org/elasticsearch/gateway/PriorityComparatorTests.java
8439
/* * 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.gateway; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.test.ESTestCase; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class PriorityComparatorTests extends ESTestCase { public void testPreferNewIndices() { RoutingNodes.UnassignedShards shards = new RoutingNodes.UnassignedShards(null); List<ShardRouting> shardRoutings = Arrays.asList(TestShardRouting.newShardRouting("oldest", 0, null, null, null, randomBoolean(), ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(UnassignedInfo.Reason.values()), "foobar")), TestShardRouting.newShardRouting("newest", 0, null, null, null, randomBoolean(), ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(UnassignedInfo.Reason.values()), "foobar"))); Collections.shuffle(shardRoutings, random()); for (ShardRouting routing : shardRoutings) { shards.add(routing); } shards.sort(new PriorityComparator() { @Override protected Settings getIndexSettings(Index index) { if ("oldest".equals(index.getName())) { return Settings.builder().put(IndexMetaData.SETTING_CREATION_DATE, 10) .put(IndexMetaData.SETTING_PRIORITY, 1).build(); } else if ("newest".equals(index.getName())) { return Settings.builder().put(IndexMetaData.SETTING_CREATION_DATE, 100) .put(IndexMetaData.SETTING_PRIORITY, 1).build(); } return Settings.EMPTY; } }); RoutingNodes.UnassignedShards.UnassignedIterator iterator = shards.iterator(); ShardRouting next = iterator.next(); assertEquals("newest", next.getIndexName()); next = iterator.next(); assertEquals("oldest", next.getIndexName()); assertFalse(iterator.hasNext()); } public void testPreferPriorityIndices() { RoutingNodes.UnassignedShards shards = new RoutingNodes.UnassignedShards((RoutingNodes) null); List<ShardRouting> shardRoutings = Arrays.asList(TestShardRouting.newShardRouting("oldest", 0, null, null, null, randomBoolean(), ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(UnassignedInfo.Reason.values()), "foobar")), TestShardRouting.newShardRouting("newest", 0, null, null, null, randomBoolean(), ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(UnassignedInfo.Reason.values()), "foobar"))); Collections.shuffle(shardRoutings, random()); for (ShardRouting routing : shardRoutings) { shards.add(routing); } shards.sort(new PriorityComparator() { @Override protected Settings getIndexSettings(Index index) { if ("oldest".equals(index.getName())) { return Settings.builder().put(IndexMetaData.SETTING_CREATION_DATE, 10) .put(IndexMetaData.SETTING_PRIORITY, 100).build(); } else if ("newest".equals(index.getName())) { return Settings.builder().put(IndexMetaData.SETTING_CREATION_DATE, 100) .put(IndexMetaData.SETTING_PRIORITY, 1).build(); } return Settings.EMPTY; } }); RoutingNodes.UnassignedShards.UnassignedIterator iterator = shards.iterator(); ShardRouting next = iterator.next(); assertEquals("oldest", next.getIndexName()); next = iterator.next(); assertEquals("newest", next.getIndexName()); assertFalse(iterator.hasNext()); } public void testPriorityComparatorSort() { RoutingNodes.UnassignedShards shards = new RoutingNodes.UnassignedShards((RoutingNodes) null); int numIndices = randomIntBetween(3, 99); IndexMeta[] indices = new IndexMeta[numIndices]; final Map<String, IndexMeta> map = new HashMap<>(); for (int i = 0; i < indices.length; i++) { if (frequently()) { indices[i] = new IndexMeta("idx_2015_04_" + String.format(Locale.ROOT, "%02d", i), randomIntBetween(1, 1000), randomIntBetween(1, 10000)); } else { // sometimes just use defaults indices[i] = new IndexMeta("idx_2015_04_" + String.format(Locale.ROOT, "%02d", i)); } map.put(indices[i].name, indices[i]); } int numShards = randomIntBetween(10, 100); for (int i = 0; i < numShards; i++) { IndexMeta indexMeta = randomFrom(indices); shards.add(TestShardRouting.newShardRouting(indexMeta.name, randomIntBetween(1, 5), null, null, null, randomBoolean(), ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(UnassignedInfo.Reason.values()), "foobar"))); } shards.sort(new PriorityComparator() { @Override protected Settings getIndexSettings(Index index) { IndexMeta indexMeta = map.get(index.getName()); return indexMeta.settings; } }); ShardRouting previous = null; for (ShardRouting routing : shards) { if (previous != null) { IndexMeta prevMeta = map.get(previous.getIndexName()); IndexMeta currentMeta = map.get(routing.getIndexName()); if (prevMeta.priority == currentMeta.priority) { if (prevMeta.creationDate == currentMeta.creationDate) { if (prevMeta.name.equals(currentMeta.name) == false) { assertTrue("indexName mismatch, expected:" + currentMeta.name + " after " + prevMeta.name + " " + prevMeta.name.compareTo(currentMeta.name), prevMeta.name.compareTo(currentMeta.name) > 0); } } else { assertTrue("creationDate mismatch, expected:" + currentMeta.creationDate + " after " + prevMeta.creationDate, prevMeta.creationDate > currentMeta.creationDate); } } else { assertTrue("priority mismatch, expected:" + currentMeta.priority + " after " + prevMeta.priority, prevMeta.priority > currentMeta.priority); } } previous = routing; } } private static class IndexMeta { final String name; final int priority; final long creationDate; final Settings settings; private IndexMeta(String name) { // default this.name = name; this.priority = 1; this.creationDate = -1; this.settings = Settings.EMPTY; } private IndexMeta(String name, int priority, long creationDate) { this.name = name; this.priority = priority; this.creationDate = creationDate; this.settings = Settings.builder().put(IndexMetaData.SETTING_CREATION_DATE, creationDate) .put(IndexMetaData.SETTING_PRIORITY, priority).build(); } } }
apache-2.0
ascherbakoff/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/mvcc/DeadlockDetectionManager.java
13876
/* * 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.ignite.internal.processors.cache.mvcc; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.UUID; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException; import org.apache.ignite.internal.processors.cache.GridCacheSharedManagerAdapter; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocalAdapter; import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxAbstractEnlistFuture; import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal; import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.processors.timeout.GridTimeoutObjectAdapter; import org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException; import static java.util.Collections.singleton; import static org.apache.ignite.internal.GridTopic.TOPIC_DEADLOCK_DETECTION; import static org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL; import static org.apache.ignite.internal.processors.cache.mvcc.MvccUtils.belongToSameTx; /** * Component participating in deadlock detection in a cluster. Detection process is collaborative and it is performed * by relaying special probe messages from waiting transaction to it's blocker. * <p> * Ideas for used detection algorithm are borrowed from Chandy-Misra-Haas deadlock detection algorithm for resource * model. * <p> * Current implementation assumes that transactions obeys 2PL. */ public class DeadlockDetectionManager extends GridCacheSharedManagerAdapter { /** */ private long detectionStartDelay; /** {@inheritDoc} */ @Override protected void start0() throws IgniteCheckedException { detectionStartDelay = cctx.kernalContext().config().getTransactionConfiguration().getDeadlockTimeout(); cctx.gridIO().addMessageListener(TOPIC_DEADLOCK_DETECTION, (nodeId, msg, plc) -> { if (msg instanceof DeadlockProbe) { if (log.isDebugEnabled()) log.debug("Received a probe message [msg=" + msg + ']'); DeadlockProbe msg0 = (DeadlockProbe)msg; handleDeadlockProbe(msg0); } else log.warning("Unexpected message received [node=" + nodeId + ", msg=" + msg + ']'); }); } /** * Starts a dedlock detection after a delay. * * @param waiterVer Version of the waiting transaction. * @param blockerVer Version of the waited for transaction. * @return Cancellable computation. */ public DelayedDeadlockComputation initDelayedComputation(MvccVersion waiterVer, MvccVersion blockerVer) { if (detectionStartDelay <= 0) return null; return new DelayedDeadlockComputation(waiterVer, blockerVer, detectionStartDelay); } /** * Starts a deadlock detection for a given pair of transaction versions (wait-for edge). * * @param waiterVer Version of the waiting transaction. * @param blockerVer Version of the waited for transaction. */ private void startComputation(MvccVersion waiterVer, MvccVersion blockerVer) { if (log.isDebugEnabled()) log.debug("Starting deadlock detection [waiterVer=" + waiterVer + ", blockerVer=" + blockerVer + ']'); Optional<GridDhtTxLocalAdapter> waitingTx = findTx(waiterVer); Optional<GridDhtTxLocalAdapter> blockerTx = findTx(blockerVer); if (waitingTx.isPresent() && blockerTx.isPresent()) { GridDhtTxLocalAdapter wTx = waitingTx.get(); GridDhtTxLocalAdapter bTx = blockerTx.get(); sendProbe( bTx.eventNodeId(), wTx.xidVersion(), // real start time will be filled later when corresponding near node is visited singleton(new ProbedTx(wTx.nodeId(), wTx.xidVersion(), wTx.nearXidVersion(), -1, wTx.lockCounter())), new ProbedTx(bTx.nodeId(), bTx.xidVersion(), bTx.nearXidVersion(), -1, bTx.lockCounter()), true); } } /** */ private Optional<GridDhtTxLocalAdapter> findTx(MvccVersion mvccVer) { return cctx.tm().activeTransactions().stream() .filter(tx -> tx.local() && tx.mvccSnapshot() != null) .filter(tx -> belongToSameTx(mvccVer, tx.mvccSnapshot())) .map(GridDhtTxLocalAdapter.class::cast) .findAny(); } /** * Handles received deadlock probe. Possible outcomes: * <ol> * <li>Deadlock is found.</li> * <li>Probe is relayed to other blocking transactions.</li> * <li>Probe is discarded because receiving transaction is not blocked.</li> * </ol> * * @param probe Received probe message. */ private void handleDeadlockProbe(DeadlockProbe probe) { if (probe.nearCheck()) handleDeadlockProbeForNear(probe); else handleDeadlockProbeForDht(probe); } /** */ private void handleDeadlockProbeForNear(DeadlockProbe probe) { // a probe is simply discarded if next wait-for edge is not found ProbedTx blocker = probe.blocker(); GridNearTxLocal nearTx = cctx.tm().tx(blocker.nearXidVersion()); if (nearTx == null) return; // probe each blocker for (UUID pendingNodeId : getPendingResponseNodes(nearTx)) { sendProbe( pendingNodeId, probe.initiatorVersion(), probe.waitChain(), // real start time is filled here blocker.withStartTime(nearTx.startTime()), false); } } /** */ private void handleDeadlockProbeForDht(DeadlockProbe probe) { // a probe is simply discarded if next wait-for edge is not found cctx.tm().activeTransactions().stream() .filter(IgniteInternalTx::local) .filter(tx -> tx.nearXidVersion().equals(probe.blocker().nearXidVersion())) .findAny() .map(GridDhtTxLocalAdapter.class::cast) .ifPresent(tx -> { // search for locally checked tx (identified as blocker previously) in the wait chain Optional<ProbedTx> repeatedTx = probe.waitChain().stream() .filter(wTx -> wTx.xidVersion().equals(tx.xidVersion())) .findAny(); if (repeatedTx.isPresent()) { // a deadlock found resolveDeadlock(probe, repeatedTx.get(), tx); } else relayProbeIfLocalTxIsWaiting(probe, tx); }); } /** */ private void resolveDeadlock(DeadlockProbe probe, ProbedTx repeatedTx, GridDhtTxLocalAdapter locTx) { if (log.isDebugEnabled()) log.debug("Deadlock detected [probe=" + probe + ']'); ProbedTx victim = chooseVictim( // real start time is filled here for repeated tx repeatedTx.withStartTime(probe.blocker().startTime()), probe.waitChain()); if (victim.xidVersion().equals(locTx.xidVersion())) { if (log.isDebugEnabled()) log.debug("Chosen victim is on local node, tx will be aborted [victim=" + victim + ']'); // if a victim tx has made a progress since it was identified as waiting // it means that detected deadlock was broken by other means (e.g. timeout of another tx) if (victim.lockCounter() == locTx.lockCounter()) abortTx(locTx); } else { if (log.isDebugEnabled()) log.debug("Chosen victim is on remote node, message will be sent [victim=" + victim + ']'); // destination node must determine itself as a victim sendProbe(victim.nodeId(), probe.initiatorVersion(), singleton(victim), victim, false); } } /** */ private void relayProbeIfLocalTxIsWaiting(DeadlockProbe probe, GridDhtTxLocalAdapter locTx) { assert locTx.mvccSnapshot() != null; cctx.coordinators().checkWaiting(locTx.mvccSnapshot()) .flatMap(this::findTx) .ifPresent(nextBlocker -> { ArrayList<ProbedTx> waitChain = new ArrayList<>(probe.waitChain().size() + 1); waitChain.addAll(probe.waitChain()); // real start time is filled here waitChain.add(new ProbedTx(locTx.nodeId(), locTx.xidVersion(), locTx.nearXidVersion(), probe.blocker().startTime(), locTx.lockCounter())); // real start time will be filled later when corresponding near node is visited ProbedTx nextProbedTx = new ProbedTx(nextBlocker.nodeId(), nextBlocker.xidVersion(), nextBlocker.nearXidVersion(), -1, nextBlocker.lockCounter()); sendProbe( nextBlocker.eventNodeId(), probe.initiatorVersion(), waitChain, nextProbedTx, true); }); } /** * Chooses victim basing on tx start time. Algorithm chooses victim in such way that every site detected a deadlock * will choose the same victim. As a result only one tx participating in a deadlock will be aborted. * <p> * Local tx is needed here because start time for it might not be filled yet for corresponding entry in wait chain. * * @param locTx Deadlocked tx on local node. * @param waitChain Wait chain. * @return Tx chosen as a victim. */ @SuppressWarnings("StatementWithEmptyBody") private ProbedTx chooseVictim(ProbedTx locTx, Collection<ProbedTx> waitChain) { Iterator<ProbedTx> it = waitChain.iterator(); // skip until local tx (inclusive), because txs before are not deadlocked while (it.hasNext() && !it.next().xidVersion().equals(locTx.xidVersion())); ProbedTx victim = locTx; long maxStartTime = locTx.startTime(); while (it.hasNext()) { ProbedTx tx = it.next(); // seek for youngest tx in order to guarantee forward progress if (tx.startTime() > maxStartTime) { maxStartTime = tx.startTime(); victim = tx; } // tie-breaking else if (tx.startTime() == maxStartTime && tx.nearXidVersion().compareTo(victim.nearXidVersion()) > 0) victim = tx; } return victim; } /** */ private void abortTx(GridDhtTxLocalAdapter tx) { cctx.coordinators().failWaiter(tx.mvccSnapshot(), new IgniteTxRollbackCheckedException( "Deadlock detected. Transaction will be rolled back [tx=" + tx + ']')); } /** */ private Set<UUID> getPendingResponseNodes(GridNearTxLocal tx) { IgniteInternalFuture lockFut = tx.lockFuture(); if (lockFut instanceof GridNearTxAbstractEnlistFuture) return ((GridNearTxAbstractEnlistFuture<?>)lockFut).pendingResponseNodes(); return Collections.emptySet(); } /** */ private void sendProbe(UUID destNodeId, GridCacheVersion initiatorVer, Collection<ProbedTx> waitChain, ProbedTx blocker, boolean near) { DeadlockProbe probe = new DeadlockProbe(initiatorVer, waitChain, blocker, near); if (log.isDebugEnabled()) log.debug("Sending probe [probe=" + probe + ", destNode=" + destNodeId + ']'); try { cctx.gridIO().sendToGridTopic(destNodeId, TOPIC_DEADLOCK_DETECTION, probe, SYSTEM_POOL); } catch (ClusterTopologyCheckedException ignored) { } catch (IgniteCheckedException e) { log.warning("Failed to send a deadlock probe [nodeId=" + destNodeId + ']', e); } } /** * Delayed deadlock probe computation which can be cancelled. */ public class DelayedDeadlockComputation extends GridTimeoutObjectAdapter { /** */ private final MvccVersion waiterVer; /** */ private final MvccVersion blockerVer; /** {@inheritDoc} */ @Override public void onTimeout() { startComputation(waiterVer, blockerVer); } /** */ private DelayedDeadlockComputation(MvccVersion waiterVer, MvccVersion blockerVer, long timeout) { super(timeout); this.waiterVer = waiterVer; this.blockerVer = blockerVer; cctx.kernalContext().timeout().addTimeoutObject(this); } /** */ public void cancel() { cctx.kernalContext().timeout().removeTimeoutObject(this); } } }
apache-2.0
paplorinc/intellij-community
java/java-tests/testData/inspection/duplicateBranchesInSwitchFix/afterThrow.java
314
// "Merge with 'case 1'" "GENERIC_ERROR_OR_WARNING" class C { String foo(int n) { switch (n) { case 1: case 3: throw new IllegalArgumentException("A"); case 2: throw new IllegalStateException("A"); } return ""; } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/java/awt/EventDispatchThread.java
11656
/* * Copyright (c) 1996, 2010, 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 java.awt; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.lang.reflect.Method; import java.security.AccessController; import sun.security.action.GetPropertyAction; import sun.awt.AWTAutoShutdown; import sun.awt.SunToolkit; import java.util.Vector; import sun.util.logging.PlatformLogger; import sun.awt.dnd.SunDragSourceContextPeer; import sun.awt.EventQueueDelegate; /** * EventDispatchThread is a package-private AWT class which takes * events off the EventQueue and dispatches them to the appropriate * AWT components. * * The Thread starts a "permanent" event pump with a call to * pumpEvents(Conditional) in its run() method. Event handlers can choose to * block this event pump at any time, but should start a new pump (<b>not</b> * a new EventDispatchThread) by again calling pumpEvents(Conditional). This * secondary event pump will exit automatically as soon as the Condtional * evaluate()s to false and an additional Event is pumped and dispatched. * * @author Tom Ball * @author Amy Fowler * @author Fred Ecks * @author David Mendenhall * * @since 1.1 */ class EventDispatchThread extends Thread { private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.EventDispatchThread"); private EventQueue theQueue; private boolean doDispatch = true; private boolean threadDeathCaught = false; private static final int ANY_EVENT = -1; private Vector<EventFilter> eventFilters = new Vector<EventFilter>(); EventDispatchThread(ThreadGroup group, String name, EventQueue queue) { super(group, name); setEventQueue(queue); } /* * Must be called on EDT only, that's why no synchronization */ public void stopDispatching() { doDispatch = false; } public void run() { while (true) { try { pumpEvents(new Conditional() { public boolean evaluate() { return true; } }); } finally { EventQueue eq = getEventQueue(); if (eq.detachDispatchThread(this) || threadDeathCaught) { break; } } } } void pumpEvents(Conditional cond) { pumpEvents(ANY_EVENT, cond); } void pumpEventsForHierarchy(Conditional cond, Component modalComponent) { pumpEventsForHierarchy(ANY_EVENT, cond, modalComponent); } void pumpEvents(int id, Conditional cond) { pumpEventsForHierarchy(id, cond, null); } void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent) { pumpEventsForFilter(id, cond, new HierarchyEventFilter(modalComponent)); } void pumpEventsForFilter(Conditional cond, EventFilter filter) { pumpEventsForFilter(ANY_EVENT, cond, filter); } void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) { addEventFilter(filter); doDispatch = true; while (doDispatch && cond.evaluate()) { if (isInterrupted() || !pumpOneEventForFilters(id)) { doDispatch = false; } } removeEventFilter(filter); } void addEventFilter(EventFilter filter) { eventLog.finest("adding the event filter: " + filter); synchronized (eventFilters) { if (!eventFilters.contains(filter)) { if (filter instanceof ModalEventFilter) { ModalEventFilter newFilter = (ModalEventFilter)filter; int k = 0; for (k = 0; k < eventFilters.size(); k++) { EventFilter f = eventFilters.get(k); if (f instanceof ModalEventFilter) { ModalEventFilter cf = (ModalEventFilter)f; if (cf.compareTo(newFilter) > 0) { break; } } } eventFilters.add(k, filter); } else { eventFilters.add(filter); } } } } void removeEventFilter(EventFilter filter) { eventLog.finest("removing the event filter: " + filter); synchronized (eventFilters) { eventFilters.remove(filter); } } boolean pumpOneEventForFilters(int id) { AWTEvent event = null; boolean eventOK = false; try { EventQueue eq = null; EventQueueDelegate.Delegate delegate = null; do { // EventQueue may change during the dispatching eq = getEventQueue(); delegate = EventQueueDelegate.getDelegate(); if (delegate != null && id == ANY_EVENT) { event = delegate.getNextEvent(eq); } else { event = (id == ANY_EVENT) ? eq.getNextEvent() : eq.getNextEvent(id); } eventOK = true; synchronized (eventFilters) { for (int i = eventFilters.size() - 1; i >= 0; i--) { EventFilter f = eventFilters.get(i); EventFilter.FilterAction accept = f.acceptEvent(event); if (accept == EventFilter.FilterAction.REJECT) { eventOK = false; break; } else if (accept == EventFilter.FilterAction.ACCEPT_IMMEDIATELY) { break; } } } eventOK = eventOK && SunDragSourceContextPeer.checkEvent(event); if (!eventOK) { event.consume(); } } while (eventOK == false); if (eventLog.isLoggable(PlatformLogger.FINEST)) { eventLog.finest("Dispatching: " + event); } Object handle = null; if (delegate != null) { handle = delegate.beforeDispatch(event); } eq.dispatchEvent(event); if (delegate != null) { delegate.afterDispatch(event, handle); } return true; } catch (ThreadDeath death) { threadDeathCaught = true; return false; } catch (InterruptedException interruptedException) { return false; // AppContext.dispose() interrupts all // Threads in the AppContext } catch (Throwable e) { processException(e); } return true; } private void processException(Throwable e) { if (eventLog.isLoggable(PlatformLogger.FINE)) { eventLog.fine("Processing exception: " + e); } getUncaughtExceptionHandler().uncaughtException(this, e); } public synchronized EventQueue getEventQueue() { return theQueue; } public synchronized void setEventQueue(EventQueue eq) { theQueue = eq; } private static class HierarchyEventFilter implements EventFilter { private Component modalComponent; public HierarchyEventFilter(Component modalComponent) { this.modalComponent = modalComponent; } public FilterAction acceptEvent(AWTEvent event) { if (modalComponent != null) { int eventID = event.getID(); boolean mouseEvent = (eventID >= MouseEvent.MOUSE_FIRST) && (eventID <= MouseEvent.MOUSE_LAST); boolean actionEvent = (eventID >= ActionEvent.ACTION_FIRST) && (eventID <= ActionEvent.ACTION_LAST); boolean windowClosingEvent = (eventID == WindowEvent.WINDOW_CLOSING); /* * filter out MouseEvent and ActionEvent that's outside * the modalComponent hierarchy. * KeyEvent is handled by using enqueueKeyEvent * in Dialog.show */ if (Component.isInstanceOf(modalComponent, "javax.swing.JInternalFrame")) { /* * Modal internal frames are handled separately. If event is * for some component from another heavyweight than modalComp, * it is accepted. If heavyweight is the same - we still accept * event and perform further filtering in LightweightDispatcher */ return windowClosingEvent ? FilterAction.REJECT : FilterAction.ACCEPT; } if (mouseEvent || actionEvent || windowClosingEvent) { Object o = event.getSource(); if (o instanceof sun.awt.ModalExclude) { // Exclude this object from modality and // continue to pump it's events. return FilterAction.ACCEPT; } else if (o instanceof Component) { Component c = (Component) o; // 5.0u3 modal exclusion boolean modalExcluded = false; if (modalComponent instanceof Container) { while (c != modalComponent && c != null) { if ((c instanceof Window) && (sun.awt.SunToolkit.isModalExcluded((Window)c))) { // Exclude this window and all its children from // modality and continue to pump it's events. modalExcluded = true; break; } c = c.getParent(); } } if (!modalExcluded && (c != modalComponent)) { return FilterAction.REJECT; } } } } return FilterAction.ACCEPT; } } }
mit
kugelr/inspectIT
CMR/src/info/novatec/inspectit/cmr/spring/aop/MethodLog.java
1291
package info.novatec.inspectit.cmr.spring.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker for methods that will be logged and/or profiled, By placing this annotation on a method * spring will proxy the service and call the interceptor that provides advice to the real method * call. * * @author Patrice Bouillet */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface MethodLog { /** * The log level which can be used. The level from logback cannot be used directly as it is not * allowed as a return type. * * @author Patrice Bouillet * */ public enum Level { OFF, ERROR, WARN, INFO, DEBUG, TRACE, ALL; // NOCHK } /** * The defined level on which the time messages shall be printed to. */ Level timeLogLevel() default Level.DEBUG; /** * The defined level on which the trace messages shall be printed to. */ Level traceLogLevel() default Level.TRACE; /** * Defines a duration limit on this method. If the methods duration exceed the specified one, a * message will be printed into the log. */ long durationLimit() default -1; }
agpl-3.0
sanyaade-g2g-repos/posit-mobile.haiti
src/org/hfoss/posit/android/TrackerSettings.java
3710
/* * File: TrackerSettings.java * * Copyright (C) 2010 The Humanitarian FOSS Project (http://www.hfoss.org) * * This file is part of POSIT, Portable Open Search and Identification Tool. * * POSIT is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published * by the Free Software Foundation; either version 3.0 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 LGPL along with this program; * if not visit http://www.gnu.org/licenses/lgpl.html. * */ package org.hfoss.posit.android; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; /** * Lets the user adjust Tracker parameters. The tracker preferences are * loaded from an XML resource file. Whenever the user changes a preference, * all Listeners that are registered with the PREFERENCES_NAME settings, will * be notified and can take action. TrackerActivity is the only registered * listener. * * @author rmorelli * @see http://code.google.com/p/mytracks/ */ public class TrackerSettings extends PreferenceActivity { public static final String TAG = "PositTracker"; public static final String PREFERENCES_NAME = "TrackerSettings"; // Default settings -- some of these settable in shared preferences public static final int DEFAULT_MIN_RECORDING_DISTANCE = 3; // meters, sp public static final int DEFAULT_MIN_RECORDING_INTERVAL = 2000; public static final int DEFAULT_MIN_REQUIRED_ACCURACY = 200; // Unused public static final int DEFAULT_SWATH_WIDTH = 50; // sp public static final int MIN_LOCAL_EXP_ID = 10000; // lowest random exp id number public static final int LOCAL_EXP_ID_RANGE = 10000; // range of random ids public static final int IDLE = 0; public static final int RUNNING = 1; public static final int PAUSED = 2; // Currently unused public static final int VIEWING_MODE = 3; public static final int SYNCING_POINTS = 4; public static final String TRACKER_STATE_PREFERENCE = "TrackerState"; public static final String POSIT_PROJECT_PREFERENCE = "PROJECT_ID"; public static final String POSIT_SERVER_PREFERENCE = "SERVER_ADDRESS"; public static final String ROW_ID_EXPEDITION_BEING_SYNCED = "RowIdExpeditionBeingSynced"; // These settable Tracker preferences have to be identical to String resources public static final String SWATH_PREFERENCE = "swathWidth"; // @string/swath_width public static final String MINIMUM_DISTANCE_PREFERENCE = "minDistance"; // @string/min_recording_distance /** * Simply tells this Activity what preferences are being updated * and provides the XML for the layout. The PreferenceActivity handles * the rest. Whenever the user changes a preference value, the * preference manager notifies any listeners that have been * registered with it. * * In this case we use DefaultSharedPreferences where all other * Posit preferences are stored. It might make sense to define * a "TrackerSettings" preference?? */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "TrackerSettings, onCreate()"); PreferenceManager.getDefaultSharedPreferences(this); addPreferencesFromResource(R.xml.tracker_preferences); } }
lgpl-2.1
geothomasp/kualico-rice-kc
rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/validation/constraint/provider/AttributeDefinitionConstraintProvider.java
4361
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.datadictionary.validation.constraint.provider; import org.kuali.rice.krad.datadictionary.AttributeDefinition; import org.kuali.rice.krad.datadictionary.validation.ViewAttributeValueReader; import org.kuali.rice.krad.datadictionary.validation.capability.Constrainable; import org.kuali.rice.krad.datadictionary.validation.constraint.CaseConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.DataTypeConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.LengthConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.MustOccurConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.PrerequisiteConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.SimpleConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.ValidCharactersConstraint; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.CaseConstraintResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.ConstraintResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.DefinitionConstraintResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.MustOccurConstraintsResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.PrerequisiteConstraintsResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.SimpleConstraintResolver; import org.kuali.rice.krad.datadictionary.validation.constraint.resolver.ValidCharactersConstraintResolver; import org.kuali.rice.krad.uif.field.InputField; import java.util.HashMap; /** * AttributeDefinitionConstraintProvider looks up constraints for attribute definitions by constraint type * * <p> This can either by instantiated by dependency * injection, in which case a map of class names to constraint resolvers can be injected, or the default map can be * constructed by * calling the init() method immediately after instantiation.</p> * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class AttributeDefinitionConstraintProvider extends BaseConstraintProvider<AttributeDefinition> { @Override public void init() { resolverMap = new HashMap<String, ConstraintResolver<AttributeDefinition>>(); resolverMap.put(SimpleConstraint.class.getName(), new SimpleConstraintResolver<AttributeDefinition>()); resolverMap.put(CaseConstraint.class.getName(), new CaseConstraintResolver<AttributeDefinition>()); resolverMap.put(DataTypeConstraint.class.getName(), new DefinitionConstraintResolver<AttributeDefinition>()); resolverMap.put(LengthConstraint.class.getName(), new DefinitionConstraintResolver<AttributeDefinition>()); resolverMap.put(ValidCharactersConstraint.class.getName(), new ValidCharactersConstraintResolver<AttributeDefinition>()); resolverMap.put(PrerequisiteConstraint.class.getName(), new PrerequisiteConstraintsResolver<AttributeDefinition>()); resolverMap.put(MustOccurConstraint.class.getName(), new MustOccurConstraintsResolver<AttributeDefinition>()); } /** * @see org.kuali.rice.krad.datadictionary.validation.constraint.provider.ConstraintProvider#isSupported(org.kuali.rice.krad.datadictionary.validation.capability.Constrainable) */ @Override public boolean isSupported(Constrainable definition) { if (definition instanceof AttributeDefinition || definition instanceof InputField || definition instanceof ViewAttributeValueReader.InputFieldConstrainableInfo) { return true; } return false; } }
apache-2.0
asedunov/intellij-community
plugins/git4idea/src/git4idea/commands/GitHttpAuthService.java
2465
/* * Copyright 2000-2016 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 git4idea.commands; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.git4idea.http.GitAskPassApp; import org.jetbrains.git4idea.http.GitAskPassXmlRpcHandler; import org.jetbrains.git4idea.ssh.GitXmlRpcHandlerService; import org.jetbrains.git4idea.util.ScriptGenerator; import java.util.Collection; import java.util.UUID; /** * Provides the authentication mechanism for Git HTTP connections. */ public abstract class GitHttpAuthService extends GitXmlRpcHandlerService<GitHttpAuthenticator> { protected GitHttpAuthService() { super("intellij-git-askpass", GitAskPassXmlRpcHandler.HANDLER_NAME, GitAskPassApp.class); } @Override protected void customizeScriptGenerator(@NotNull ScriptGenerator generator) { } @NotNull @Override protected Object createRpcRequestHandlerDelegate() { return new InternalRequestHandlerDelegate(); } /** * Creates new {@link GitHttpAuthenticator} that will be requested to handle username and password requests from Git. */ @NotNull public abstract GitHttpAuthenticator createAuthenticator(@NotNull Project project, @NotNull GitCommand command, @NotNull Collection<String> urls); /** * Internal handler implementation class, it is made public to be accessible via XML RPC. */ public class InternalRequestHandlerDelegate implements GitAskPassXmlRpcHandler { @NotNull @Override public String askUsername(String token, @NotNull String url) { return getHandler(UUID.fromString(token)).askUsername(url); } @NotNull @Override public String askPassword(String token, @NotNull String url) { return getHandler(UUID.fromString(token)).askPassword(url); } } }
apache-2.0
jdahlstrom/vaadin.react
uitest/src/main/java/com/vaadin/tests/application/PreserveWithExpiredHeartbeat.java
1360
/* * Copyright 2000-2014 Vaadin Ltd. * * 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.vaadin.tests.application; import com.vaadin.annotations.PreserveOnRefresh; import com.vaadin.launcher.CustomDeploymentConfiguration; import com.vaadin.launcher.CustomDeploymentConfiguration.Conf; import com.vaadin.server.VaadinRequest; import com.vaadin.tests.components.AbstractTestUI; import com.vaadin.ui.Label; @PreserveOnRefresh @CustomDeploymentConfiguration({ @Conf(name = "heartbeatInterval", value = "5") }) public class PreserveWithExpiredHeartbeat extends AbstractTestUI { @Override protected void setup(VaadinRequest request) { Label label = new Label("UI with id " + getUIId() + " in session " + getSession().getSession().getId()); label.setId("idLabel"); addComponent(label); } }
apache-2.0
WouterBanckenACA/aries
subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/GetDeploymentHeadersAction.java
1399
/* * 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.apache.aries.subsystem.core.internal; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.aries.subsystem.core.archive.Header; public class GetDeploymentHeadersAction implements PrivilegedAction<Map<String, String>> { private final BasicSubsystem subsystem; public GetDeploymentHeadersAction(BasicSubsystem subsystem) { this.subsystem = subsystem; } @Override public Map<String, String> run() { Map<String, Header<?>> headers = subsystem.getDeploymentManifest().getHeaders(); Map<String, String> result = new HashMap<String, String>(headers.size()); for (Entry<String, Header<?>> entry: headers.entrySet()) { Header<?> value = entry.getValue(); result.put(entry.getKey(), value.getValue()); } return result; } }
apache-2.0
roele/sling
bundles/extensions/caconfig/impl/src/test/java/org/apache/sling/caconfig/impl/override/OsgiConfigurationOverrideProviderTest.java
2278
/* * 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.sling.caconfig.impl.override; import static org.junit.Assert.assertTrue; import java.util.Collection; import org.apache.sling.testing.mock.sling.junit.SlingContext; import org.junit.Rule; import org.junit.Test; public class OsgiConfigurationOverrideProviderTest { @Rule public SlingContext context = new SlingContext(); @Test public void testEnabled() { OsgiConfigurationOverrideProvider provider = context.registerInjectActivateService( new OsgiConfigurationOverrideProvider(), "enabled", true, "overrides", new String[] { "test/param1=value1", "[/content]test/param2=value2" }); Collection<String> overrides = provider.getOverrideStrings(); assertTrue(overrides.contains("test/param1=value1")); assertTrue(overrides.contains("[/content]test/param2=value2")); } @Test public void testDisabled() { OsgiConfigurationOverrideProvider provider = context.registerInjectActivateService( new OsgiConfigurationOverrideProvider(), "enabled", false, "overrides", new String[] { "test/param1=value1", "[/content]test/param2=value2" }); Collection<String> overrides = provider.getOverrideStrings(); assertTrue(overrides.isEmpty()); } }
apache-2.0
7ShaYaN7/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/NumberTextView.java
5881
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.ui.Components; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.view.View; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimationCompat.AnimatorListenerAdapterProxy; import org.telegram.messenger.AnimationCompat.ObjectAnimatorProxy; import java.util.ArrayList; import java.util.Locale; public class NumberTextView extends View { private ArrayList<StaticLayout> letters = new ArrayList<>(); private ArrayList<StaticLayout> oldLetters = new ArrayList<>(); private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private ObjectAnimatorProxy animator; private float progress = 0.0f; private int currentNumber = 1; public NumberTextView(Context context) { super(context); } public void setProgress(float value) { if (progress == value) { return; } progress = value; invalidate(); } public float getProgress() { return progress; } public void setNumber(int number, boolean animated) { if (currentNumber == number && animated) { return; } if (animator != null) { animator.cancel(); animator = null; } oldLetters.clear(); oldLetters.addAll(letters); letters.clear(); String oldText = String.format(Locale.US, "%d", currentNumber); String text = String.format(Locale.US, "%d", number); boolean forwardAnimation = number > currentNumber; currentNumber = number; progress = 0; for (int a = 0; a < text.length(); a++) { String ch = text.substring(a, a + 1); String oldCh = !oldLetters.isEmpty() && a < oldText.length() ? oldText.substring(a, a + 1) : null; if (oldCh != null && oldCh.equals(ch)) { letters.add(oldLetters.get(a)); oldLetters.set(a, null); } else { StaticLayout layout = new StaticLayout(ch, textPaint, (int) Math.ceil(textPaint.measureText(ch)), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); letters.add(layout); } } if (animated && !oldLetters.isEmpty()) { animator = ObjectAnimatorProxy.ofFloatProxy(this, "progress", forwardAnimation ? -1 : 1, 0); animator.setDuration(150); animator.addListener(new AnimatorListenerAdapterProxy() { @Override public void onAnimationEnd(Object animation) { animator = null; oldLetters.clear(); } }); animator.start(); } invalidate(); } public void setTextSize(int size) { textPaint.setTextSize(AndroidUtilities.dp(size)); oldLetters.clear(); letters.clear(); setNumber(currentNumber, false); } public void setTextColor(int value) { textPaint.setColor(value); invalidate(); } public void setTypeface(Typeface typeface) { textPaint.setTypeface(typeface); oldLetters.clear(); letters.clear(); setNumber(currentNumber, false); } @Override protected void onDraw(Canvas canvas) { if (letters.isEmpty()) { return; } float height = letters.get(0).getHeight(); canvas.save(); canvas.translate(getPaddingLeft(), (getMeasuredHeight() - height) / 2); int count = Math.max(letters.size(), oldLetters.size()); for (int a = 0; a < count; a++) { canvas.save(); StaticLayout old = a < oldLetters.size() ? oldLetters.get(a) : null; StaticLayout layout = a < letters.size() ? letters.get(a) : null; if (progress > 0) { if (old != null) { textPaint.setAlpha((int) (255 * progress)); canvas.save(); canvas.translate(0, (progress - 1.0f) * height); old.draw(canvas); canvas.restore(); if (layout != null) { textPaint.setAlpha((int) (255 * (1.0f - progress))); canvas.translate(0, progress * height); } } else { textPaint.setAlpha(255); } } else if (progress < 0) { if (old != null) { textPaint.setAlpha((int) (255 * -progress)); canvas.save(); canvas.translate(0, (1.0f + progress) * height); old.draw(canvas); canvas.restore(); } if (layout != null) { if (a == count - 1 || old != null) { textPaint.setAlpha((int) (255 * (1.0f + progress))); canvas.translate(0, progress * height); } else { textPaint.setAlpha(255); } } } else if (layout != null) { textPaint.setAlpha(255); } if (layout != null) { layout.draw(canvas); } canvas.restore(); canvas.translate(layout != null ? layout.getLineWidth(0) : old.getLineWidth(0) + AndroidUtilities.dp(1), 0); } canvas.restore(); } }
gpl-2.0
asheshsaraf/ecommerce-simple
sm-core/src/main/java/com/salesmanager/core/business/catalog/product/dao/availability/ProductAvailabilityDaoImpl.java
479
package com.salesmanager.core.business.catalog.product.dao.availability; import org.springframework.stereotype.Repository; import com.salesmanager.core.business.catalog.product.model.availability.ProductAvailability; import com.salesmanager.core.business.generic.dao.SalesManagerEntityDaoImpl; @Repository("productAvailabilityDao") public class ProductAvailabilityDaoImpl extends SalesManagerEntityDaoImpl<Long, ProductAvailability> implements ProductAvailabilityDao { }
apache-2.0
sdmcraft/sling
tooling/ide/eclipse-m2e-test/src/org/apache/sling/ide/eclipse/m2e/EmbeddedArchetypeInstallerTest.java
3301
/* * 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.sling.ide.eclipse.m2e; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.sling.ide.artifacts.EmbeddedArtifact; import org.eclipse.core.runtime.CoreException; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.embedder.IMaven; import org.junit.After; import org.junit.Before; import org.junit.Test; public class EmbeddedArchetypeInstallerTest { private final String archetypeGroupId = "org.apache.sling"; private final String archetypeArtifactId = "sling-bundle-archetype"; private final String archetypeVersion = "0.1.0-test-only"; @Before @After public void deleteInstalledArtifact() throws CoreException, IOException { File artifactPathLocation = getInstalledArchetypeLocation(); File artifactDirLocation = artifactPathLocation.getParentFile(); FileUtils.deleteDirectory(artifactDirLocation); } @Test public void testInstallArchetype() throws IOException, CoreException { EmbeddedArchetypeInstaller archetypeInstaller = new EmbeddedArchetypeInstaller(archetypeGroupId, archetypeArtifactId, archetypeVersion); EmbeddedArtifact[] archetypeArtifacts = new EmbeddedArtifact[] { new EmbeddedArtifact("jar", archetypeVersion, getClass().getClassLoader().getResource( "META-INF/MANIFEST.MF")), new EmbeddedArtifact("pom", archetypeVersion, getClass().getClassLoader().getResource( "META-INF/MANIFEST.MF")) }; archetypeInstaller.addResource("pom", archetypeArtifacts[0].openInputStream()); archetypeInstaller.addResource("jar", archetypeArtifacts[1].openInputStream()); archetypeInstaller.installArchetype(); File artifactPathLocation = getInstalledArchetypeLocation(); assertTrue("Archetype was not found at " + artifactPathLocation, artifactPathLocation.exists()); } private File getInstalledArchetypeLocation() throws CoreException { IMaven maven = MavenPlugin.getMaven(); String artifactPath = maven.getArtifactPath(maven.getLocalRepository(), archetypeGroupId, archetypeArtifactId, archetypeVersion, "jar", null); String localRepositoryPath = maven.getLocalRepositoryPath(); return new File(localRepositoryPath + File.separatorChar + artifactPath); } }
apache-2.0
raman-bt/autopsy
thirdparty/pasco2/test/isi/pasco2/TestFileTime.java
4159
/* * Copyright 2006 Bradley Schatz. All rights reserved. * * This file is part of pasco2, the next generation Internet Explorer cache * and history record parser. * * pasco2 is free software; you can redistribute it and/or modify * 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. * * pasco2 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 pasco2; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package isi.pasco2; import isi.pasco2.parser.time.FileTime; import isi.pasco2.util.StructConverter; import java.util.Date; import junit.framework.TestCase; import junit.framework.TestSuite; public class TestFileTime extends TestCase { public static TestSuite suite() { return new TestSuite(TestFileTime.class); } public void testFileTime() { long low = -543274336; long high = 29744990; FileTime ft = new FileTime(low, high); long millis = ft.getTimeAsMillis(); //assertEquals(1130902272657L, millis); Date d = ft.asDate(); assertEquals("Wed Nov 02 13:31:12 EST 2005", d.toString()); assertEquals("2005-11-02T03:31:12.657Z", ft.toString()); } public void testBitStuff() { String hex = "40B3B13F"; byte[] bytes = new byte[4]; for (int i=0 ; i < 4 ; i++) { bytes[i] = (byte)Integer.parseInt(hex.substring(i*2, i*2+2), 16); } long res = StructConverter.bytesIntoInt(bytes,0); assertEquals(1068610368,res); long low = Long.parseLong(hex.substring(0,8) , 16); low = ((low & 0xFF) << 24) | ((low & 0x0FF00) << 8) | ((low & 0xFF0000) >> 8) | ((low & 0xFF000000)>> 24); assertEquals(1068610368,low); } public void testHexLittleEndian() { String hex = "40B3B13FED2AC001"; FileTime ft = FileTime.parseLittleEndianHex(hex); //Sat, 30 September 2000 14:46:43 GMT assertEquals("2000-09-30T14:46:43.060Z", ft.toString()); //Wed, 26 April 2000 22:58:55 GMT assertEquals("2000-04-26T22:58:55.899Z", FileTime.parseLittleEndianHex("39B1C8FFD2AFBF01").toString()); //Sat, 30 March 2002 05:15:11 GMT assertEquals("2002-03-30T05:15:11.620Z", FileTime.parseLittleEndianHex("69D8F2DDA9D7C101").toString()); //Mon, 17 October 2005 02:59:22 UTC assertEquals("2005-10-17T02:59:22.147Z", FileTime.parseLittleEndianHex("308F41C6C6D2C501").toString()); } public void testHexBigEndian() { String hex = "01C1D7A9DDF2D869"; FileTime ft = FileTime.parseBigEndianHex(hex); //Sat, 30 March 2002 05:15:11 GMT assertEquals("2002-03-30T05:15:11.620Z", ft.toString()); // Sun, 10 March 2002 06:07:32 GMT assertEquals("2002-03-10T06:07:32.813Z", FileTime.parseBigEndianHex("01C1C7F9DDFBD86F").toString()); // Tue, 20 January 2004 04:58:58 GMT assertEquals("2004-01-20T04:58:58.985Z", FileTime.parseBigEndianHex("01C3DF121D432432").toString()); } public void testPassingInts() { int[] intsLow = { 0x30, 0x8F, 0x41, 0xC6 }; byte[] bytesLow = new byte[4]; for (int i=0 ; i < 4 ; i++) { bytesLow[i] = (byte) (intsLow[i] & 0xFF); } long low = StructConverter.bytesIntoUInt(bytesLow, 0); long lowA = Long.parseLong("308F41C6", 16); lowA = ((lowA & 0xFF) << 24) | ((lowA & 0x0FF00) << 8) | ((lowA & 0xFF0000) >> 8) | ((lowA & 0xFF000000)>> 24); assertEquals(lowA, low); int[] intsHigh = { 0xC6, 0xD2, 0xC5, 0x01 }; byte[] bytesHigh = new byte[4]; for (int i=0 ; i < 4 ; i++) { bytesHigh[i] = (byte) (intsHigh[i] & 0xFF); } long high = StructConverter.bytesIntoUInt(bytesHigh, 0); FileTime ft = new FileTime(low, high); assertEquals("2005-10-17T02:59:22.147Z", ft.toString()); } }
apache-2.0
android-ia/platform_tools_idea
java/idea-ui/src/com/intellij/openapi/project/impl/convertors/Util.java
1166
/* * Copyright 2000-2009 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.openapi.project.impl.convertors; import org.jdom.Element; import java.util.Iterator; class Util { @SuppressWarnings({"HardCodedStringLiteral"}) static Element findComponent(Element root, String className) { for (Iterator iterator = root.getChildren("component").iterator(); iterator.hasNext();) { Element element = (Element)iterator.next(); String className1 = element.getAttributeValue("class"); if (className1 != null && className1.equals(className)) { return element; } } return null; } }
apache-2.0
luoxiaoshenghustedu/actor-platform
actor-apps/core/src/main/java/im/actor/core/entity/compat/content/ObsoleteServiceAdded.java
990
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.entity.compat.content; import java.io.IOException; import im.actor.core.api.ApiMessage; import im.actor.core.api.ApiServiceExUserInvited; import im.actor.core.api.ApiServiceMessage; import im.actor.runtime.bser.BserObject; import im.actor.runtime.bser.BserValues; import im.actor.runtime.bser.BserWriter; public class ObsoleteServiceAdded extends BserObject { private int addedUid; public ObsoleteServiceAdded(BserValues values) throws IOException { parse(values); } public ApiMessage toApiMessage() { return new ApiServiceMessage("Member added", new ApiServiceExUserInvited(addedUid)); } @Override public void parse(BserValues values) throws IOException { addedUid = values.getInt(10); } @Override public void serialize(BserWriter writer) throws IOException { throw new UnsupportedOperationException(); } }
mit
MichaelNedzelsky/intellij-community
platform/lang-impl/src/com/intellij/execution/ExecutionModes.java
3802
/* * 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.execution; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.PairConsumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author Roman.Chernyatchik, oleg */ public class ExecutionModes { private static final Logger LOG = Logger.getInstance(ExecutionMode.class); private static final PairConsumer<ExecutionMode, String> DEFAULT_TIMEOUT_CALLBACK = new PairConsumer<ExecutionMode, String>() { @Override public void consume(ExecutionMode mode, String presentableCmdLine) { final String msg = "Timeout (" + mode.getTimeout() + " sec) on executing: " + presentableCmdLine; LOG.error(msg); } }; /** * Process will be run in back ground mode */ public static class BackGroundMode extends ExecutionMode { public BackGroundMode(final boolean cancelable, @Nullable final String title) { super(cancelable, title, null, true, false, null); } public BackGroundMode(@Nullable final String title) { this(true, title); } } /** * Process will be run in modal dialog */ public static class ModalProgressMode extends ExecutionMode { public ModalProgressMode(final boolean cancelable, @Nullable final String title, JComponent progressParentComponent) { super(cancelable, title, null, false, true, progressParentComponent); } public ModalProgressMode(@Nullable final String title) { this(true, title, null); } public ModalProgressMode(@Nullable final String title, JComponent progressParentComponent) { this(true, title, progressParentComponent); } } /** * Process will be run in the same thread. */ public static class SameThreadMode extends ExecutionMode { private final int myTimeout; @NotNull private final PairConsumer<ExecutionMode, String> myTimeoutCallback; public SameThreadMode(final boolean cancelable, @Nullable final String title2, final int timeout) { this(cancelable, title2, timeout, DEFAULT_TIMEOUT_CALLBACK); } public SameThreadMode(final boolean cancelable, @Nullable final String title2, final int timeout, @NotNull final PairConsumer<ExecutionMode, String> timeoutCallback ) { super(cancelable, null, title2, false, false, null); myTimeout = timeout; myTimeoutCallback = timeoutCallback; } public SameThreadMode(@Nullable final String title2) { this(true, title2, -1); } /** * @param cancelable */ public SameThreadMode(final boolean cancelable) { this(cancelable, null, -1); } /** * @param timeout If less than zero it will be ignored */ public SameThreadMode(final int timeout) { this(false, null, timeout); } public SameThreadMode() { this(true); } @Override public int getTimeout() { return myTimeout; } @NotNull @Override public PairConsumer<ExecutionMode, String> getTimeoutCallback() { return myTimeoutCallback; } } }
apache-2.0
dennishuo/hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/store/records/TestRouterState.java
3118
/** * 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.hdfs.server.federation.store.records; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.hadoop.hdfs.server.federation.router.RouterServiceState; import org.apache.hadoop.hdfs.server.federation.store.driver.StateStoreSerializer; import org.junit.Test; /** * Test the Router State records. */ public class TestRouterState { private static final String ADDRESS = "address"; private static final String VERSION = "version"; private static final String COMPILE_INFO = "compileInfo"; private static final long START_TIME = 100; private static final long DATE_MODIFIED = 200; private static final long DATE_CREATED = 300; private static final long FILE_RESOLVER_VERSION = 500; private static final RouterServiceState STATE = RouterServiceState.RUNNING; private RouterState generateRecord() throws IOException { RouterState record = RouterState.newInstance(ADDRESS, START_TIME, STATE); record.setVersion(VERSION); record.setCompileInfo(COMPILE_INFO); record.setDateCreated(DATE_CREATED); record.setDateModified(DATE_MODIFIED); StateStoreVersion version = StateStoreVersion.newInstance(); version.setMountTableVersion(FILE_RESOLVER_VERSION); record.setStateStoreVersion(version); return record; } private void validateRecord(RouterState record) throws IOException { assertEquals(ADDRESS, record.getAddress()); assertEquals(START_TIME, record.getDateStarted()); assertEquals(STATE, record.getStatus()); assertEquals(COMPILE_INFO, record.getCompileInfo()); assertEquals(VERSION, record.getVersion()); StateStoreVersion version = record.getStateStoreVersion(); assertEquals(FILE_RESOLVER_VERSION, version.getMountTableVersion()); } @Test public void testGetterSetter() throws IOException { RouterState record = generateRecord(); validateRecord(record); } @Test public void testSerialization() throws IOException { RouterState record = generateRecord(); StateStoreSerializer serializer = StateStoreSerializer.getSerializer(); String serializedString = serializer.serializeString(record); RouterState newRecord = serializer.deserialize(serializedString, RouterState.class); validateRecord(newRecord); } }
apache-2.0
Ant-Droid/android_frameworks_base_OLD
tools/layoutlib/create/tests/com/android/tools/layoutlib/create/ClassHasNativeVisitorTest.java
3067
/* * Copyright (C) 2010 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.tools.layoutlib.create; import static org.junit.Assert.*; import org.junit.Test; import org.objectweb.asm.ClassReader; import java.io.IOException; import java.util.ArrayList; /** * Tests {@link ClassHasNativeVisitor}. */ public class ClassHasNativeVisitorTest { @Test public void testHasNative() throws IOException { MockClassHasNativeVisitor cv = new MockClassHasNativeVisitor(); String className = this.getClass().getCanonicalName() + "$" + ClassWithNative.class.getSimpleName(); ClassReader cr = new ClassReader(className); cr.accept(cv, 0 /* flags */); assertArrayEquals(new String[] { "native_method" }, cv.getMethodsFound()); assertTrue(cv.hasNativeMethods()); } @Test public void testHasNoNative() throws IOException { MockClassHasNativeVisitor cv = new MockClassHasNativeVisitor(); String className = this.getClass().getCanonicalName() + "$" + ClassWithoutNative.class.getSimpleName(); ClassReader cr = new ClassReader(className); cr.accept(cv, 0 /* flags */); assertArrayEquals(new String[0], cv.getMethodsFound()); assertFalse(cv.hasNativeMethods()); } //------- /** * Overrides {@link ClassHasNativeVisitor} to collec the name of the native methods found. */ private static class MockClassHasNativeVisitor extends ClassHasNativeVisitor { private ArrayList<String> mMethodsFound = new ArrayList<String>(); public String[] getMethodsFound() { return mMethodsFound.toArray(new String[mMethodsFound.size()]); } @Override protected void setHasNativeMethods(boolean hasNativeMethods, String methodName) { if (hasNativeMethods) { mMethodsFound.add(methodName); } super.setHasNativeMethods(hasNativeMethods, methodName); } } /** * Dummy test class with a native method. */ public static class ClassWithNative { public ClassWithNative() { } public void callTheNativeMethod() { native_method(); } private native void native_method(); } /** * Dummy test class with no native method. */ public static class ClassWithoutNative { public ClassWithoutNative() { } public void someMethod() { } } }
apache-2.0
rokn/Count_Words_2015
testing/spring-boot-master/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/tables/Book.java
3215
/** * This class is generated by jOOQ */ package sample.jooq.domain.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import sample.jooq.domain.Keys; import sample.jooq.domain.Public; import sample.jooq.domain.tables.records.BookRecord; /** * This class is generated by jOOQ. */ @Generated(value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ") @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Book extends TableImpl<BookRecord> { private static final long serialVersionUID = 1858247563; /** * The reference instance of <code>PUBLIC.BOOK</code> */ public static final Book BOOK = new Book(); /** * The class holding records for this type */ @Override public Class<BookRecord> getRecordType() { return BookRecord.class; } /** * The column <code>PUBLIC.BOOK.ID</code>. */ public final TableField<BookRecord, Integer> ID = createField("ID", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>PUBLIC.BOOK.AUTHOR_ID</code>. */ public final TableField<BookRecord, Integer> AUTHOR_ID = createField("AUTHOR_ID", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>PUBLIC.BOOK.TITLE</code>. */ public final TableField<BookRecord, String> TITLE = createField("TITLE", org.jooq.impl.SQLDataType.VARCHAR.length(400).nullable(false), this, ""); /** * The column <code>PUBLIC.BOOK.PUBLISHED_IN</code>. */ public final TableField<BookRecord, Integer> PUBLISHED_IN = createField( "PUBLISHED_IN", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>PUBLIC.BOOK.LANGUAGE_ID</code>. */ public final TableField<BookRecord, Integer> LANGUAGE_ID = createField("LANGUAGE_ID", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * Create a <code>PUBLIC.BOOK</code> table reference */ public Book() { this("BOOK", null); } /** * Create an aliased <code>PUBLIC.BOOK</code> table reference */ public Book(String alias) { this(alias, BOOK); } private Book(String alias, Table<BookRecord> aliased) { this(alias, aliased, null); } private Book(String alias, Table<BookRecord> aliased, Field<?>[] parameters) { super(alias, Public.PUBLIC, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public UniqueKey<BookRecord> getPrimaryKey() { return Keys.CONSTRAINT_1; } /** * {@inheritDoc} */ @Override public List<UniqueKey<BookRecord>> getKeys() { return Arrays.<UniqueKey<BookRecord>>asList(Keys.CONSTRAINT_1); } /** * {@inheritDoc} */ @Override public List<ForeignKey<BookRecord, ?>> getReferences() { return Arrays.<ForeignKey<BookRecord, ?>>asList(Keys.FK_BOOK_AUTHOR, Keys.FK_BOOK_LANGUAGE); } /** * {@inheritDoc} */ @Override public Book as(String alias) { return new Book(alias, this); } /** * Rename this table */ public Book rename(String name) { return new Book(name, null); } }
mit
md-5/jdk10
test/jdk/java/lang/Class/forName/modules/TestMain.java
2413
/* * Copyright (c) 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. */ import java.lang.reflect.Method; public class TestMain { public static void main(String[] args) throws Exception { ModuleLayer boot = ModuleLayer.boot(); Module m1 = boot.findModule("m1").get(); Module m2 = boot.findModule("m2").get(); // find exported and non-exported class from a named module findClass(m1, "p1.A"); findClass(m1, "p1.internal.B"); findClass(m2, "p2.C"); // find class from unnamed module ClassLoader loader = TestMain.class.getClassLoader(); findClass(loader.getUnnamedModule(), "TestDriver"); // check if clinit should not be initialized // compile without module-path; so use reflection Class<?> c = Class.forName(m1, "p1.Initializer"); Method m = c.getMethod("isInited"); Boolean isClinited = (Boolean) m.invoke(null); if (isClinited.booleanValue()) { throw new RuntimeException("clinit should not be invoked"); } } static Class<?> findClass(Module module, String cn) { Class<?> c = Class.forName(module, cn); if (c == null) { throw new RuntimeException(cn + " not found in " + module); } if (c.getModule() != module) { throw new RuntimeException(c.getModule() + " != " + module); } return c; } }
gpl-2.0
jar1karp/rstudio
src/gwt/src/org/rstudio/core/client/layout/BinarySplitLayoutPanel.java
9392
/* * BinarySplitLayoutPanel.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.layout; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.layout.client.Layout; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.*; public class BinarySplitLayoutPanel extends LayoutPanel implements MouseDownHandler, MouseMoveHandler, MouseUpHandler { public BinarySplitLayoutPanel(Widget[] widgets, int splitterHeight) { widgets_ = widgets; splitterHeight_ = splitterHeight; setWidgets(widgets); splitterPos_ = 300; topIsFixed_ = false; splitter_ = new HTML(); splitter_.setStylePrimaryName("gwt-SplitLayoutPanel-VDragger"); splitter_.addMouseDownHandler(this); splitter_.addMouseMoveHandler(this); splitter_.addMouseUpHandler(this); splitter_.getElement().getStyle().setZIndex(200); add(splitter_); setWidgetLeftRight(splitter_, 0, Style.Unit.PX, 0, Style.Unit.PX); setWidgetBottomHeight(splitter_, splitterPos_, Style.Unit.PX, splitterHeight_, Style.Unit.PX); } public void setWidgets(Widget[] widgets) { for (Widget w : widgets_) remove(w); widgets_ = widgets; for (Widget w : widgets) { add(w); setWidgetLeftRight(w, 0, Style.Unit.PX, 0, Style.Unit.PX); setWidgetTopHeight(w, 0, Style.Unit.PX, 100, Style.Unit.PX); w.setVisible(false); AnimationHelper.setParentZindex(w, -10); } if (top_ >= 0) setTopWidget(top_, true); if (bottom_ >= 0) setBottomWidget(bottom_, true); } @Override protected void onAttach() { super.onAttach(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { offsetHeight_ = getOffsetHeight(); } }); } public HandlerRegistration addSplitterBeforeResizeHandler( SplitterBeforeResizeHandler handler) { return addHandler(handler, SplitterBeforeResizeEvent.TYPE); } public HandlerRegistration addSplitterResizedHandler( SplitterResizedHandler handler) { return addHandler(handler, SplitterResizedEvent.TYPE); } public void setTopWidget(Widget widget, boolean manageVisibility) { if (widget == null) { setTopWidget(-1, manageVisibility); return; } for (int i = 0; i < widgets_.length; i++) if (widgets_[i] == widget) { setTopWidget(i, manageVisibility); return; } assert false; } public void setTopWidget(int widgetIndex, boolean manageVisibility) { if (manageVisibility && top_ >= 0) widgets_[top_].setVisible(false); top_ = widgetIndex; if (bottom_ == top_) setBottomWidget(-1, manageVisibility); if (manageVisibility && top_ >= 0) widgets_[top_].setVisible(true); updateLayout(); } public void setBottomWidget(Widget widget, boolean manageVisibility) { if (widget == null) { setBottomWidget(-1, manageVisibility); return; } for (int i = 0; i < widgets_.length; i++) if (widgets_[i] == widget) { setBottomWidget(i, manageVisibility); return; } assert false; } public void setBottomWidget(int widgetIndex, boolean manageVisibility) { if (manageVisibility && bottom_ >= 0) widgets_[bottom_].setVisible(false); bottom_ = widgetIndex; if (top_ == bottom_) setTopWidget(-1, manageVisibility); if (manageVisibility && bottom_ >= 0) widgets_[bottom_].setVisible(true); updateLayout(); } public boolean isSplitterVisible() { return splitter_.isVisible(); } public void setSplitterVisible(boolean visible) { splitter_.setVisible(visible); } public void setSplitterPos(int splitterPos, boolean fromTop) { if (isVisible() && isAttached() && splitter_.isVisible()) { splitterPos = Math.min(getOffsetHeight() - splitterHeight_, splitterPos); } if (splitter_.isVisible()) splitterPos = Math.max(splitterHeight_, splitterPos); if (splitterPos_ == splitterPos && topIsFixed_ == fromTop && offsetHeight_ == getOffsetHeight()) { return; } splitterPos_ = splitterPos; topIsFixed_ = fromTop; offsetHeight_ = getOffsetHeight(); if (topIsFixed_) { setWidgetTopHeight(splitter_, splitterPos_, Style.Unit.PX, splitterHeight_, Style.Unit.PX); } else { setWidgetBottomHeight(splitter_, splitterPos_, Style.Unit.PX, splitterHeight_, Style.Unit.PX); } updateLayout(); } public int getSplitterBottom() { assert !topIsFixed_; return splitterPos_; } private void updateLayout() { if (topIsFixed_) { if (top_ >= 0) setWidgetTopHeight(widgets_[top_], 0, Style.Unit.PX, splitterPos_, Style.Unit.PX); if (bottom_ >= 0) setWidgetTopBottom(widgets_[bottom_], splitterPos_ + splitterHeight_, Style.Unit.PX, 0, Style.Unit.PX); } else { if (top_ >= 0) setWidgetTopBottom(widgets_[top_], 0, Style.Unit.PX, splitterPos_ + splitterHeight_, Style.Unit.PX); if (bottom_ >= 0) setWidgetBottomHeight(widgets_[bottom_], 0, Style.Unit.PX, splitterPos_, Style.Unit.PX); } // Not sure why, but onResize() doesn't seem to get called unless we // do this manually. This matters for ShellPane scroll position updating. animate(0, new Layout.AnimationCallback() { public void onAnimationComplete() { onResize(); } public void onLayout(Layout.Layer layer, double progress) { } }); } @Override public void onResize() { super.onResize(); // getOffsetHeight() > 0 is to deal with Firefox tab tear-off, which // causes us to be resized to 0 (bug 1586) if (offsetHeight_ > 0 && splitter_.isVisible() && getOffsetHeight() > 0) { double pct = ((double)splitterPos_ / offsetHeight_); int newPos = (int) Math.round(getOffsetHeight() * pct); setSplitterPos(newPos, topIsFixed_); } } public void onMouseDown(MouseDownEvent event) { resizing_ = true; Event.setCapture(splitter_.getElement()); event.preventDefault(); event.stopPropagation(); fireEvent(new SplitterBeforeResizeEvent()); } public void onMouseMove(MouseMoveEvent event) { if (event.getNativeButton() == 0) resizing_ = false; if (!resizing_) return; event.preventDefault(); event.stopPropagation(); if (topIsFixed_) setSplitterPos(event.getRelativeY(getElement()), true); else setSplitterPos(getOffsetHeight() - event.getRelativeY(getElement()), false); } public void onMouseUp(MouseUpEvent event) { if (resizing_) { resizing_ = false; Event.releaseCapture(splitter_.getElement()); fireEvent(new SplitterResizedEvent()); } } public int getSplitterHeight() { return splitterHeight_; } private int top_; private int bottom_; private HTML splitter_; private int splitterPos_; private int splitterHeight_; // If true, then bottom widget should scale and top widget should stay // fixed. If false, then vice versa. private boolean topIsFixed_ = true; private Widget[] widgets_; private boolean resizing_; private int offsetHeight_; }
agpl-3.0
SwathiMystery/gora
gora-core/src/main/java/org/apache/gora/avro/query/AvroResult.java
2123
/** * 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.gora.avro.query; import java.io.EOFException; import java.io.IOException; import org.apache.avro.AvroTypeException; import org.apache.avro.io.DatumReader; import org.apache.avro.io.Decoder; import org.apache.gora.avro.store.AvroStore; import org.apache.gora.persistency.impl.PersistentBase; import org.apache.gora.query.impl.ResultBase; /** * Adapter to convert DatumReader to Result. */ public class AvroResult<K, T extends PersistentBase> extends ResultBase<K, T> { private DatumReader<T> reader; private Decoder decoder; public AvroResult(AvroStore<K,T> dataStore, AvroQuery<K,T> query , DatumReader<T> reader, Decoder decoder) { super(dataStore, query); this.reader = reader; this.decoder = decoder; } public void close() throws IOException { } @Override public float getProgress() throws IOException { //TODO: FIXME return 0; } @Override public boolean nextInner() throws IOException { try { persistent = reader.read(persistent, decoder); } catch (AvroTypeException ex) { //TODO: it seems that avro does not respect end-of file and return null //gracefully. Report the issue. return false; } catch (EOFException ex) { return false; } return persistent != null; } }
apache-2.0
zerg000000/mario-ai
src/main/java/ch/idsia/benchmark/mario/environments/MarioEnvironment.java
24496
/* * Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius * 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 Mario AI 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 ch.idsia.benchmark.mario.environments; import ch.idsia.agents.Agent; import ch.idsia.benchmark.mario.engine.*; import ch.idsia.benchmark.mario.engine.level.Level; import ch.idsia.benchmark.mario.engine.sprites.Mario; import ch.idsia.benchmark.mario.engine.sprites.Sprite; import ch.idsia.benchmark.tasks.SystemOfValues; import ch.idsia.tools.EvaluationInfo; import ch.idsia.tools.MarioAIOptions; import ch.idsia.tools.punj.PunctualJudge; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: Sergey Karakovskiy, sergey@idsia.ch * Date: Mar 3, 2010 Time: 10:08:13 PM * Package: ch.idsia.benchmark.mario.environments */ public final class MarioEnvironment implements Environment { private int[] marioEgoPos = new int[2]; private int receptiveFieldHeight = -1; // to be setup via MarioAIOptions private int receptiveFieldWidth = -1; // to be setup via MarioAIOptions private int prevRFH = -1; private int prevRFW = -1; private byte[][] levelSceneZ; // memory is allocated in reset private byte[][] enemiesZ; // memory is allocated in reset private byte[][] mergedZZ; // memory is allocated in reset public List<Sprite> sprites; private int[] serializedLevelScene; // memory is allocated in reset private int[] serializedEnemies; // memory is allocated in reset private int[] serializedMergedObservation; // memory is allocated in reset private final LevelScene levelScene; // private int frame = 0; private MarioVisualComponent marioVisualComponent; private Agent agent; private static final MarioEnvironment ourInstance = new MarioEnvironment(); private static final EvaluationInfo evaluationInfo = new EvaluationInfo(); private static String marioTraceFile; private Recorder recorder; public static SystemOfValues IntermediateRewardsSystemOfValues = new SystemOfValues(); DecimalFormat df = new DecimalFormat("######.#"); public static MarioEnvironment getInstance() { return ourInstance; } private MarioEnvironment() { // System.out.println("System.getProperty(\"java.awt.headless\") = " + System.getProperty("java.awt.headless")); // System.out.println("System.getProperty(\"verbose\") = " + System.getProperty("-verbose")); // System.out.println("Java: JA ZDES'!!"); // System.out.flush(); System.out.println(GlobalOptions.getBenchmarkName()); levelScene = new LevelScene(); } public void resetDefault() { levelScene.resetDefault(); } public void reset(String args) { MarioAIOptions marioAIOptions = MarioAIOptions.getOptionsByString(args); this.reset(marioAIOptions); // MarioAIOptions opts = new MarioAIOptions(setUpOptions); // int[] intOpts = opts.toIntArray(); // this.reset(intOpts); } public void reset(MarioAIOptions setUpOptions) { /*System.out.println("\nsetUpOptions = " + setUpOptions); for (int i = 0; i < setUpOptions.length; ++i) { System.out.print(" op[" + i +"] = " + setUpOptions[i]); } System.out.println(""); System.out.flush();*/ // if (!setUpOptions.getReplayOptions().equals("")) this.setAgent(setUpOptions.getAgent()); receptiveFieldWidth = setUpOptions.getReceptiveFieldWidth(); receptiveFieldHeight = setUpOptions.getReceptiveFieldHeight(); if (receptiveFieldHeight != this.prevRFH || receptiveFieldWidth != this.prevRFW) { serializedLevelScene = new int[receptiveFieldHeight * receptiveFieldWidth]; serializedEnemies = new int[receptiveFieldHeight * receptiveFieldWidth]; serializedMergedObservation = new int[receptiveFieldHeight * receptiveFieldWidth]; levelSceneZ = new byte[receptiveFieldHeight][receptiveFieldWidth]; enemiesZ = new byte[receptiveFieldHeight][receptiveFieldWidth]; mergedZZ = new byte[receptiveFieldHeight][receptiveFieldWidth]; this.prevRFH = this.receptiveFieldHeight; this.prevRFW = this.receptiveFieldWidth; } marioEgoPos[0] = setUpOptions.getMarioEgoPosRow(); marioEgoPos[1] = setUpOptions.getMarioEgoPosCol(); if (marioEgoPos[0] == 9 && getReceptiveFieldWidth() != 19) marioEgoPos[0] = getReceptiveFieldWidth() / 2; if (marioEgoPos[1] == 9 && getReceptiveFieldHeight() != 19) marioEgoPos[1] = getReceptiveFieldHeight() / 2; marioTraceFile = setUpOptions.getTraceFileName(); if (setUpOptions.isVisualization()) { if (marioVisualComponent == null) marioVisualComponent = MarioVisualComponent.getInstance(setUpOptions, this); levelScene.reset(setUpOptions); marioVisualComponent.reset(); marioVisualComponent.postInitGraphicsAndLevel(); marioVisualComponent.setAgent(agent); marioVisualComponent.setLocation(setUpOptions.getViewLocation()); marioVisualComponent.setAlwaysOnTop(setUpOptions.isViewAlwaysOnTop()); if (setUpOptions.isScale2X()) GlobalOptions.changeScale2x(); } else levelScene.reset(setUpOptions); sprites = levelScene.sprites; //create recorder String recordingFileName = setUpOptions.getRecordingFileName(); if (!recordingFileName.equals("off")) { if (recordingFileName.equals("on")) recordingFileName = GlobalOptions.getTimeStamp() + ".zip"; try { if (recordingFileName.equals("lazy")) recorder = new Recorder(); else recorder = new Recorder(recordingFileName); recorder.createFile("level.lvl"); recorder.writeObject(levelScene.level); recorder.closeFile(); recorder.createFile("options"); recorder.writeObject(setUpOptions.asString()); recorder.closeFile(); recorder.createFile("actions.act"); } catch (FileNotFoundException e) { System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed"); } catch (IOException e) { System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed"); e.printStackTrace(); } } evaluationInfo.reset(); PunctualJudge.resetCounter(); } public void tick() { levelScene.tick(); if (GlobalOptions.isVisualization) marioVisualComponent.tick(); } public float[] getMarioFloatPos() { return levelScene.getMarioFloatPos(); } public int getMarioMode() { return levelScene.getMarioMode(); } public byte[][] getLevelSceneObservationZ(int ZLevel) { int mCol = marioEgoPos[1]; int mRow = marioEgoPos[0]; for (int y = levelScene.mario.mapY - mRow, row = 0; y <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1); y++, row++) { for (int x = levelScene.mario.mapX - mCol, col = 0; x <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1); x++, col++) { if (x >= 0 && x < levelScene.level.length && y >= 0 && y < levelScene.level.height) { mergedZZ[row][col] = levelSceneZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevel); } else { mergedZZ[row][col] = levelSceneZ[row][col] = 0; } } } return levelSceneZ; } public byte[][] getEnemiesObservationZ(int ZLevel) { int marioEgoCol = marioEgoPos[1]; int marioEgoRow = marioEgoPos[0]; for (int w = 0; w < enemiesZ.length; w++) for (int h = 0; h < enemiesZ[0].length; h++) enemiesZ[w][h] = 0; for (Sprite sprite : sprites) { if (sprite.isDead() || sprite.kind == levelScene.mario.kind) continue; if (sprite.mapX >= 0 && sprite.mapX >= levelScene.mario.mapX - marioEgoCol && sprite.mapX <= levelScene.mario.mapX + (receptiveFieldWidth - marioEgoCol - 1) && sprite.mapY >= 0 && sprite.mapY >= levelScene.mario.mapY - marioEgoRow && sprite.mapY <= levelScene.mario.mapY + (receptiveFieldHeight - marioEgoRow - 1) && sprite.kind != Sprite.KIND_PRINCESS) { int row = sprite.mapY - levelScene.mario.mapY + marioEgoRow; int col = sprite.mapX - levelScene.mario.mapX + marioEgoCol; // TODO:!H! take care about side effects of line 243 and be sure not to contaminate levelSceneObservation mergedZZ[row][col] = enemiesZ[row][col] = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevel); } } return enemiesZ; } // TODO: !H! substitute the content of getMergedObservationZZ by getLevelSceneObservationZ, // TODO: !H! getEnemiesObservationZ, called one after another! public byte[][] getMergedObservationZZ(int ZLevelScene, int ZLevelEnemies) { // int MarioXInMap = (int) mario.x / cellSize; // int MarioYInMap = (int) mario.y / cellSize; // if (MarioXInMap != (int) mario.x / cellSize ||MarioYInMap != (int) mario.y / cellSize ) // throw new Error("WRONG mario x or y pos"); int mCol = marioEgoPos[1]; int mRow = marioEgoPos[0]; for (int y = levelScene.mario.mapY - mRow/*receptiveFieldHeight / 2*/, row = 0; y <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1)/*receptiveFieldHeight / 2*/; y++, row++) { for (int x = levelScene.mario.mapX - mCol/*receptiveFieldWidth / 2*/, col = 0; x <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1)/*receptiveFieldWidth / 2*/; x++, col++) { if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height) { mergedZZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevelScene); } else mergedZZ[row][col] = 0; // if (x == MarioXInMap && y == MarioYInMap) // mergedZZ[row][col] = mario.kind; } } // for (int w = 0; w < mergedZZ.length; w++) // for (int h = 0; h < mergedZZ[0].length; h++) // mergedZZ[w][h] = -1; for (Sprite sprite : sprites) { if (sprite.isDead() || sprite.kind == levelScene.mario.kind) continue; if (sprite.mapX >= 0 && sprite.mapX >= levelScene.mario.mapX - mCol && sprite.mapX <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1) && sprite.mapY >= 0 && sprite.mapY >= levelScene.mario.mapY - mRow && sprite.mapY <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1) && sprite.kind != Sprite.KIND_PRINCESS) { int row = sprite.mapY - levelScene.mario.mapY + mRow; int col = sprite.mapX - levelScene.mario.mapX + mCol; byte tmp = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevelEnemies); if (tmp != Sprite.KIND_NONE) mergedZZ[row][col] = tmp; } } return mergedZZ; } public List<String> getObservationStrings(boolean Enemies, boolean LevelMap, boolean mergedObservationFlag, int ZLevelScene, int ZLevelEnemies) { List<String> ret = new ArrayList<String>(); if (levelScene.level != null && levelScene.mario != null) { ret.add("Total levelScene length = " + levelScene.level.length); ret.add("Total levelScene height = " + levelScene.level.height); ret.add("Physical Mario Position (x,y): (" + df.format(levelScene.mario.x) + "," + df.format(levelScene.mario.y) + ")"); ret.add("Mario Observation (Receptive Field) Width: " + receptiveFieldWidth + " Height: " + receptiveFieldHeight); ret.add("X Exit Position: " + levelScene.level.xExit); int MarioXInMap = (int) levelScene.mario.x / levelScene.cellSize; //TODO: !!H! doublcheck and replace with levelScene.mario.mapX int MarioYInMap = (int) levelScene.mario.y / levelScene.cellSize; //TODO: !!H! doublcheck and replace with levelScene.mario.mapY ret.add("Calibrated Mario Position (x,y): (" + MarioXInMap + "," + MarioYInMap + ")\n"); byte[][] levelScene = getLevelSceneObservationZ(ZLevelScene); if (LevelMap) { ret.add("~ZLevel: Z" + ZLevelScene + " map:\n"); for (int x = 0; x < levelScene.length; ++x) { String tmpData = ""; for (int y = 0; y < levelScene[0].length; ++y) tmpData += levelSceneCellToString(levelScene[x][y]); ret.add(tmpData); } } byte[][] enemiesObservation = null; if (Enemies || mergedObservationFlag) enemiesObservation = getEnemiesObservationZ(ZLevelEnemies); if (Enemies) { ret.add("~ZLevel: Z" + ZLevelScene + " Enemies Observation:\n"); for (int x = 0; x < enemiesObservation.length; x++) { String tmpData = ""; for (int y = 0; y < enemiesObservation[0].length; y++) { // if (x >=0 && x <= level.xExit) tmpData += enemyToStr(enemiesObservation[x][y]); } ret.add(tmpData); } } if (mergedObservationFlag) { byte[][] mergedObs = getMergedObservationZZ(ZLevelScene, ZLevelEnemies); ret.add("~ZLevelScene: Z" + ZLevelScene + " ZLevelEnemies: Z" + ZLevelEnemies + " ; Merged observation /* Mario ~> #M.# */"); for (int x = 0; x < levelScene.length; ++x) { String tmpData = ""; for (int y = 0; y < levelScene[0].length; ++y) tmpData += levelSceneCellToString(mergedObs[x][y]); ret.add(tmpData); } } } else ret.add("~[MarioAI ERROR] level : " + levelScene.level + " mario : " + levelScene.mario); return ret; } private String levelSceneCellToString(int el) { String s = ""; if (el == 0 || el == 1) s = "##"; s += (el == levelScene.mario.kind) ? "#M.#" : el; while (s.length() < 4) s += "#"; return s + " "; } private String enemyToStr(int el) { String s = ""; if (el == 0) s = ""; s += (el == levelScene.mario.kind) ? "-m" : el; while (s.length() < 2) s += "#"; return s + " "; } public float[] getEnemiesFloatPos() { return levelScene.getEnemiesFloatPos(); } public boolean isMarioOnGround() { return levelScene.isMarioOnGround(); } public boolean isMarioAbleToJump() { return levelScene.isMarioAbleToJump(); } public boolean isMarioCarrying() { return levelScene.isMarioCarrying(); } public boolean isMarioAbleToShoot() { return levelScene.isMarioAbleToShoot(); } public int getReceptiveFieldWidth() { return receptiveFieldWidth; } public int getReceptiveFieldHeight() { return receptiveFieldHeight; } public int getKillsTotal() { return levelScene.getKillsTotal(); } public int getKillsByFire() { return levelScene.getKillsByFire(); } public int getKillsByStomp() { return levelScene.getKillsByStomp(); } public int getKillsByShell() { return levelScene.getKillsByShell(); } public int getMarioStatus() { return levelScene.getMarioStatus(); } public int[] getObservationDetails() { return new int[]{receptiveFieldWidth, receptiveFieldHeight, marioEgoPos[0], marioEgoPos[1]}; } public List<Sprite> getSprites() { return sprites; } public int[] getSerializedFullObservationZZ(int ZLevelScene, int ZLevelEnemies) { int[] obs = new int[receptiveFieldHeight * receptiveFieldWidth * 2 + 11]; // 11 is a size of the MarioState array int receptiveFieldSize = receptiveFieldWidth * receptiveFieldHeight; System.arraycopy(getSerializedLevelSceneObservationZ(ZLevelScene), 0, obs, 0, receptiveFieldSize); System.arraycopy(getSerializedEnemiesObservationZ(ZLevelScene), 0, obs, receptiveFieldSize, receptiveFieldSize); System.arraycopy(getMarioState(), 0, obs, receptiveFieldSize * 2, 11); return obs; } public int[] getSerializedLevelSceneObservationZ(int ZLevelScene) { // serialization into arrays of primitive types to speed up the data transfer. byte[][] levelScene = this.getLevelSceneObservationZ(ZLevelScene); for (int i = 0; i < serializedLevelScene.length; ++i) { final int i1 = i / receptiveFieldWidth; final int i2 = i % receptiveFieldWidth; serializedLevelScene[i] = (int) levelScene[i1][i2]; } return serializedLevelScene; } public int[] getSerializedEnemiesObservationZ(int ZLevelEnemies) { // serialization into arrays of primitive types to speed up the data transfer. byte[][] enemies = this.getEnemiesObservationZ(ZLevelEnemies); for (int i = 0; i < serializedEnemies.length; ++i) serializedEnemies[i] = (int) enemies[i / receptiveFieldWidth][i % receptiveFieldWidth]; return serializedEnemies; } public int[] getSerializedMergedObservationZZ(int ZLevelScene, int ZLevelEnemies) { // serialization into arrays of primitive types to speed up the data transfer. byte[][] merged = this.getMergedObservationZZ(ZLevelScene, ZLevelEnemies); for (int i = 0; i < serializedMergedObservation.length; ++i) serializedMergedObservation[i] = (int) merged[i / receptiveFieldWidth][i % receptiveFieldWidth]; return serializedMergedObservation; } public float[] getCreaturesFloatPos() { return levelScene.getCreaturesFloatPos(); } public int[] getMarioState() { return levelScene.getMarioState(); } public void performAction(boolean[] action) { try { if (recorder != null && recorder.canRecord() && action != null) { recorder.writeAction(action); recorder.changeRecordingState(GlobalOptions.isRecording, getTimeSpent()); } } catch (IOException e) { e.printStackTrace(); } levelScene.performAction(action); } public boolean isLevelFinished() { return levelScene.isLevelFinished(); } public int[] getEvaluationInfoAsInts() { return this.getEvaluationInfo().toIntArray(); } public String getEvaluationInfoAsString() { return this.getEvaluationInfo().toString(); } public EvaluationInfo getEvaluationInfo() { computeEvaluationInfo(); return evaluationInfo; } public Mario getMario() { return levelScene.mario; } public int getTick() { return levelScene.tickCount; } public int getLevelDifficulty() { return levelScene.getLevelDifficulty(); } public long getLevelSeed() { return levelScene.getLevelSeed(); } public int getLevelType() { return levelScene.getLevelType(); } public int getKilledCreaturesTotal() { return levelScene.getKillsTotal(); } public int getLevelLength() { return levelScene.getLevelLength(); } public int getLevelHeight() { return levelScene.getLevelHeight(); } public int getKilledCreaturesByFireBall() { return levelScene.getKillsByFire(); } public int getKilledCreaturesByShell() { return levelScene.getKillsByShell(); } public int getKilledCreaturesByStomp() { return levelScene.getKillsByStomp(); } public int getTimeLeft() { return levelScene.getTimeLeft(); } public Level getLevel() { return levelScene.level; } private void computeEvaluationInfo() { if (recorder != null) closeRecorder(); // evaluationInfo.agentType = agent.getClass().getSimpleName(); // evaluationInfo.agentName = agent.getName(); evaluationInfo.marioStatus = levelScene.getMarioStatus(); evaluationInfo.flowersDevoured = Mario.flowersDevoured; evaluationInfo.distancePassedPhys = (int) levelScene.mario.x; evaluationInfo.distancePassedCells = levelScene.mario.mapX; // evaluationInfo.totalLengthOfLevelCells = levelScene.level.getWidthCells(); // evaluationInfo.totalLengthOfLevelPhys = levelScene.level.getWidthPhys(); evaluationInfo.timeSpent = levelScene.getTimeSpent(); evaluationInfo.timeLeft = levelScene.getTimeLeft(); evaluationInfo.coinsGained = Mario.coins; evaluationInfo.totalNumberOfCoins = levelScene.level.counters.coinsCount; evaluationInfo.totalNumberOfHiddenBlocks = levelScene.level.counters.hiddenBlocksCount; evaluationInfo.totalNumberOfFlowers = levelScene.level.counters.flowers; evaluationInfo.totalNumberOfMushrooms = levelScene.level.counters.mushrooms; evaluationInfo.totalNumberOfCreatures = levelScene.level.counters.creatures; evaluationInfo.marioMode = levelScene.getMarioMode(); evaluationInfo.mushroomsDevoured = Mario.mushroomsDevoured; evaluationInfo.killsTotal = levelScene.getKillsTotal(); evaluationInfo.killsByStomp = levelScene.getKillsByStomp(); evaluationInfo.killsByFire = levelScene.getKillsByFire(); evaluationInfo.killsByShell = levelScene.getKillsByShell(); evaluationInfo.hiddenBlocksFound = Mario.hiddenBlocksFound; evaluationInfo.collisionsWithCreatures = Mario.collisionsWithCreatures; evaluationInfo.Memo = levelScene.memo; evaluationInfo.levelLength = levelScene.level.length; evaluationInfo.marioTraceFileName = marioTraceFile; evaluationInfo.marioTrace = levelScene.level.marioTrace; evaluationInfo.greenMushroomsDevoured = Mario.greenMushroomsDevoured; evaluationInfo.bytecodeInstructions = PunctualJudge.getCounter(); } public void setAgent(Agent agent) { this.agent = agent; } public int getIntermediateReward() { // TODO: reward for coins, killed creatures, cleared dead-ends, bypassed gaps, hidden blocks found return levelScene.getBonusPoints(); } public int[] getMarioEgoPos() { return marioEgoPos; } public void closeRecorder() { if (recorder != null) { try { // recorder.closeFile(); recorder.closeRecorder(getTimeSpent()); //recorder = null; } catch (IOException e) { e.printStackTrace(); } } } public int getTimeSpent() { return levelScene.getTimeSpent(); } public byte[][] getScreenCapture() { return null; } public void setReplayer(Replayer replayer) { levelScene.setReplayer(replayer); } public void saveLastRun(String filename) { if (recorder != null && recorder.canSave()) { try { recorder.saveLastRun(filename); } catch (IOException ex) { System.err.println("[Mario AI EXCEPTION] : Recording could not be saved."); ex.printStackTrace(); } } } //public void setRecording(boolean isRecording) //{ // this.isRecording = isRecording; //} }
bsd-3-clause
paulbatum/azure-mobile-services
sdk/android/test/sdk.testapp/src/main/java/com/microsoft/windowsazure/mobileservices/sdk/testapp/test/LoginTests.java
16473
/* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved Apache 2.0 License 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. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.windowsazure.mobileservices.sdk.testapp.test; import android.test.InstrumentationTestCase; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.microsoft.windowsazure.mobileservices.MobileServiceClient; import com.microsoft.windowsazure.mobileservices.MobileServiceException; import com.microsoft.windowsazure.mobileservices.UserAuthenticationCallback; import com.microsoft.windowsazure.mobileservices.authentication.MobileServiceAuthenticationProvider; import com.microsoft.windowsazure.mobileservices.authentication.MobileServiceUser; import com.microsoft.windowsazure.mobileservices.http.NextServiceFilterCallback; import com.microsoft.windowsazure.mobileservices.http.ServiceFilter; import com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequest; import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse; import com.microsoft.windowsazure.mobileservices.sdk.testapp.framework.filters.ServiceFilterResponseMock; import com.microsoft.windowsazure.mobileservices.sdk.testapp.test.types.ResultsContainer; import junit.framework.Assert; import org.apache.http.Header; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.CountDownLatch; public class LoginTests extends InstrumentationTestCase { String appUrl = ""; String appKey = ""; @Override protected void setUp() throws Exception { appUrl = "http://myapp.com/"; appKey = "qwerty"; super.setUp(); } public void testLoginOperation() throws Throwable { testLoginOperation(MobileServiceAuthenticationProvider.Facebook); testLoginOperation(MobileServiceAuthenticationProvider.Twitter); testLoginOperation(MobileServiceAuthenticationProvider.MicrosoftAccount); testLoginOperation(MobileServiceAuthenticationProvider.Google); testLoginOperation("FaCeBoOk"); testLoginOperation("twitter"); testLoginOperation("MicrosoftAccount"); testLoginOperation("GOOGLE"); } private void testLoginOperation(final Object provider) throws Throwable { final ResultsContainer result = new ResultsContainer(); // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { result.setRequestUrl(request.getUrl()); ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{authenticationToken:'123abc', user:{userId:'123456'}}"); final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); resultFuture.set(response); return resultFuture; } }); try { MobileServiceUser user = null; if (provider.getClass().equals(MobileServiceAuthenticationProvider.class)) { user = client.login((MobileServiceAuthenticationProvider) provider, "{myToken:123}").get(); } else { user = client.login((String) provider, "{myToken:123}").get(); } assertEquals("123456", user.getUserId()); assertEquals("123abc", user.getAuthenticationToken()); } catch (Exception exception) { Assert.fail(); } // Assert String expectedURL = appUrl + "login/" + provider.toString().toLowerCase(Locale.getDefault()); assertEquals(expectedURL, result.getRequestUrl()); } public void testLoginOperationWithParameter() throws Throwable { testLoginOperationWithParameter(MobileServiceAuthenticationProvider.Facebook); testLoginOperationWithParameter(MobileServiceAuthenticationProvider.Twitter); testLoginOperationWithParameter(MobileServiceAuthenticationProvider.MicrosoftAccount); testLoginOperationWithParameter(MobileServiceAuthenticationProvider.Google); testLoginOperationWithParameter("FaCeBoOk"); testLoginOperationWithParameter("twitter"); testLoginOperationWithParameter("MicrosoftAccount"); testLoginOperationWithParameter("GOOGLE"); } private void testLoginOperationWithParameter(final Object provider) throws Throwable { final ResultsContainer result = new ResultsContainer(); // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { result.setRequestUrl(request.getUrl()); ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{authenticationToken:'123abc', user:{userId:'123456'}}"); final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); resultFuture.set(response); return resultFuture; } }); HashMap<String, String> parameters = new HashMap<>(); parameters.put("p1", "p1value"); parameters.put("p2", "p2value"); String parameterQueryString = "?p2=p2value&p1=p1value"; try { MobileServiceUser user; if (provider.getClass().equals(MobileServiceAuthenticationProvider.class)) { client.login((MobileServiceAuthenticationProvider) provider, "{myToken:123}", parameters).get(); } else { client.login((String) provider, "{myToken:123}", parameters).get(); } } catch (Exception exception) { Assert.fail(); } // Assert String expectedURL = appUrl + "login/" + provider.toString().toLowerCase(Locale.getDefault()) + parameterQueryString; assertEquals(expectedURL, result.getRequestUrl()); } public void testLoginCallbackOperation() throws Throwable { testLoginCallbackOperation(MobileServiceAuthenticationProvider.Facebook); testLoginCallbackOperation(MobileServiceAuthenticationProvider.Twitter); testLoginCallbackOperation(MobileServiceAuthenticationProvider.MicrosoftAccount); testLoginCallbackOperation(MobileServiceAuthenticationProvider.Google); testLoginCallbackOperation("FaCeBoOk"); testLoginCallbackOperation("twitter"); testLoginCallbackOperation("MicrosoftAccount"); testLoginCallbackOperation("GOOGLE"); } @SuppressWarnings("deprecation") private void testLoginCallbackOperation(final Object provider) throws Throwable { final CountDownLatch latch = new CountDownLatch(1); final ResultsContainer result = new ResultsContainer(); // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { result.setRequestUrl(request.getUrl()); ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{authenticationToken:'123abc', user:{userId:'123456'}}"); final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); resultFuture.set(response); return resultFuture; } }); UserAuthenticationCallback callback = new UserAuthenticationCallback() { @Override public void onCompleted(MobileServiceUser user, Exception exception, ServiceFilterResponse response) { if (exception == null) { assertEquals("123456", user.getUserId()); assertEquals("123abc", user.getAuthenticationToken()); } else { Assert.fail(); } latch.countDown(); } }; if (provider.getClass().equals(MobileServiceAuthenticationProvider.class)) { client.login((MobileServiceAuthenticationProvider) provider, "{myToken:123}", callback); } else { client.login((String) provider, "{myToken:123}", callback); } latch.await(); // Assert String expectedURL = appUrl + "login/" + provider.toString().toLowerCase(Locale.getDefault()); assertEquals(expectedURL, result.getRequestUrl()); } public void testLoginShouldThrowError() throws Throwable { testLoginShouldThrowError(MobileServiceAuthenticationProvider.Facebook); testLoginShouldThrowError(MobileServiceAuthenticationProvider.MicrosoftAccount); testLoginShouldThrowError(MobileServiceAuthenticationProvider.Twitter); testLoginShouldThrowError(MobileServiceAuthenticationProvider.Google); } private void testLoginShouldThrowError(final MobileServiceAuthenticationProvider provider) throws Throwable { final ResultsContainer result = new ResultsContainer(); final String errorMessage = "fake error"; final String errorJson = "{error:'" + errorMessage + "'}"; // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { result.setRequestUrl(request.getUrl()); ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent(errorJson); response.setStatus(new StatusLine() { @Override public int getStatusCode() { return 400; } @Override public String getReasonPhrase() { return errorMessage; } @Override public ProtocolVersion getProtocolVersion() { return null; } }); final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); resultFuture.set(response); return resultFuture; } }); try { client.login(provider, "{myToken:123}").get(); Assert.fail(); } catch (Exception exception) { assertTrue(exception.getCause() instanceof MobileServiceException); MobileServiceException cause = (MobileServiceException) exception.getCause().getCause(); assertEquals(errorMessage, cause.getMessage()); } } public void testAuthenticatedRequest() throws Throwable { final MobileServiceUser user = new MobileServiceUser("dummyUser"); user.setAuthenticationToken("123abc"); // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); client.setCurrentUser(user); } catch (MalformedURLException e) { } // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { int headerIndex = -1; Header[] headers = request.getHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName() == "X-ZUMO-AUTH") { headerIndex = i; } } if (headerIndex == -1) { Assert.fail(); } assertEquals(user.getAuthenticationToken(), headers[headerIndex].getValue()); ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{}"); final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); resultFuture.set(response); return resultFuture; } }); client.getTable("dummy").execute().get(); } public void testLoginWithEmptyTokenShouldFail() throws Throwable { // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } String token = null; try { client.login(MobileServiceAuthenticationProvider.Facebook, token).get(); Assert.fail(); } catch (IllegalArgumentException e) { // It should throw an exception } try { client.login(MobileServiceAuthenticationProvider.Facebook, "").get(); Assert.fail(); } catch (IllegalArgumentException e) { // It should throw an exception } } public void testLoginWithEmptyProviderShouldFail() throws Throwable { // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } String provider = null; try { client.login(provider, "{myToken:123}").get(); Assert.fail(); } catch (IllegalArgumentException e) { // It should throw an exception } try { client.login("", "{myToken:123}").get(); Assert.fail(); } catch (IllegalArgumentException e) { // It should throw an exception } } public void testLogout() { // Create client MobileServiceClient client = null; try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { } client.setCurrentUser(new MobileServiceUser("abc")); client.logout(); assertNull(client.getCurrentUser()); } }
apache-2.0
nagyistoce/camunda-bpm-platform
engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroupResolver.java
1587
/* 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.camunda.bpm.engine.rest.hal.group; import java.util.ArrayList; import java.util.List; import org.camunda.bpm.engine.IdentityService; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.identity.Group; import org.camunda.bpm.engine.rest.hal.HalResource; import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver; public class HalGroupResolver extends HalIdResourceCacheLinkResolver { protected Class<?> getHalResourceClass() { return HalGroup.class; } protected List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { IdentityService identityService = processEngine.getIdentityService(); List<Group> groups = identityService.createGroupQuery() .groupIdIn(linkedIds) .listPage(0, linkedIds.length); List<HalResource<?>> resolvedGroups = new ArrayList<HalResource<?>>(); for (Group group : groups) { resolvedGroups.add(HalGroup.fromGroup(group)); } return resolvedGroups; } }
apache-2.0
GlenRSmith/elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/fetch/subphase/InnerHitsIT.java
50506
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.fetch.subphase; import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.util.ArrayUtil; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.InnerHitBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.MockScriptEngine; import org.elasticsearch.script.MockScriptPlugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import org.elasticsearch.xcontent.XContentBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHit; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.hasId; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class InnerHitsIT extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(InternalSettingsPlugin.class, CustomScriptPlugin.class); } public static class CustomScriptPlugin extends MockScriptPlugin { @Override protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() { return Collections.singletonMap("5", script -> "5"); } } public void testSimpleNested() throws Exception { assertAcked( prepareCreate("articles").setMapping( jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("comments") .field("type", "nested") .startObject("properties") .startObject("message") .field("type", "text") .field("fielddata", true) .endObject() .endObject() .endObject() .startObject("title") .field("type", "text") .endObject() .endObject() .endObject() .endObject() ) ); List<IndexRequestBuilder> requests = new ArrayList<>(); requests.add( client().prepareIndex("articles") .setId("1") .setSource( jsonBuilder().startObject() .field("title", "quick brown fox") .startArray("comments") .startObject() .field("message", "fox eat quick") .endObject() .startObject() .field("message", "fox ate rabbit x y z") .endObject() .startObject() .field("message", "rabbit got away") .endObject() .endArray() .endObject() ) ); requests.add( client().prepareIndex("articles") .setId("2") .setSource( jsonBuilder().startObject() .field("title", "big gray elephant") .startArray("comments") .startObject() .field("message", "elephant captured") .endObject() .startObject() .field("message", "mice squashed by elephant x") .endObject() .startObject() .field("message", "elephant scared by mice x y") .endObject() .endArray() .endObject() ) ); indexRandom(true, requests); SearchResponse response = client().prepareSearch("articles") .setQuery( nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.Avg).innerHit(new InnerHitBuilder("comment")) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("1")); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("comment"); assertThat(innerHits.getTotalHits().value, equalTo(2L)); assertThat(innerHits.getHits().length, equalTo(2)); assertThat(innerHits.getAt(0).getId(), equalTo("1")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(innerHits.getAt(1).getId(), equalTo("1")); assertThat(innerHits.getAt(1).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(1).getNestedIdentity().getOffset(), equalTo(1)); response = client().prepareSearch("articles") .setQuery( nestedQuery("comments", matchQuery("comments.message", "elephant"), ScoreMode.Avg).innerHit(new InnerHitBuilder("comment")) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("2")); assertThat(response.getHits().getAt(0).getShard(), notNullValue()); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); innerHits = response.getHits().getAt(0).getInnerHits().get("comment"); assertThat(innerHits.getTotalHits().value, equalTo(3L)); assertThat(innerHits.getHits().length, equalTo(3)); assertThat(innerHits.getAt(0).getId(), equalTo("2")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(innerHits.getAt(1).getId(), equalTo("2")); assertThat(innerHits.getAt(1).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(1).getNestedIdentity().getOffset(), equalTo(1)); assertThat(innerHits.getAt(2).getId(), equalTo("2")); assertThat(innerHits.getAt(2).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(2).getNestedIdentity().getOffset(), equalTo(2)); response = client().prepareSearch("articles") .setQuery( nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setHighlightBuilder(new HighlightBuilder().field("comments.message")) .setExplain(true) .addFetchField("comments.mes*") .addScriptField("script", new Script(ScriptType.INLINE, MockScriptEngine.NAME, "5", Collections.emptyMap())) .setSize(1) ) ) .get(); assertNoFailures(response); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); assertThat(innerHits.getTotalHits().value, equalTo(2L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat( innerHits.getAt(0).getHighlightFields().get("comments.message").getFragments()[0].string(), equalTo("<em>fox</em> eat quick") ); assertThat(innerHits.getAt(0).getExplanation().toString(), containsString("weight(comments.message:fox in")); assertThat( innerHits.getAt(0).getFields().get("comments").getValue(), equalTo(Collections.singletonMap("message", Collections.singletonList("fox eat quick"))) ); assertThat(innerHits.getAt(0).getFields().get("script").getValue().toString(), equalTo("5")); response = client().prepareSearch("articles") .setQuery( nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.Avg).innerHit( new InnerHitBuilder().addDocValueField("comments.mes*").setSize(1) ) ) .get(); assertNoFailures(response); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getFields().get("comments.message").getValue().toString(), equalTo("eat")); } public void testRandomNested() throws Exception { assertAcked(prepareCreate("idx").setMapping("field1", "type=nested", "field2", "type=nested")); int numDocs = scaledRandomIntBetween(25, 100); List<IndexRequestBuilder> requestBuilders = new ArrayList<>(); int[] field1InnerObjects = new int[numDocs]; int[] field2InnerObjects = new int[numDocs]; for (int i = 0; i < numDocs; i++) { int numInnerObjects = field1InnerObjects[i] = scaledRandomIntBetween(1, numDocs); XContentBuilder source = jsonBuilder().startObject().field("foo", i).startArray("field1"); for (int j = 0; j < numInnerObjects; j++) { source.startObject().field("x", "y").endObject(); } numInnerObjects = field2InnerObjects[i] = scaledRandomIntBetween(1, numDocs); source.endArray().startArray("field2"); for (int j = 0; j < numInnerObjects; j++) { source.startObject().field("x", "y").endObject(); } source.endArray().endObject(); requestBuilders.add(client().prepareIndex("idx").setId(Integer.toString(i)).setSource(source)); } indexRandom(true, requestBuilders); int size = randomIntBetween(0, numDocs); BoolQueryBuilder boolQuery = new BoolQueryBuilder(); boolQuery.should( nestedQuery("field1", matchAllQuery(), ScoreMode.Avg).innerHit( new InnerHitBuilder("a").setSize(size).addSort(new FieldSortBuilder("_doc").order(SortOrder.ASC)) ) ); boolQuery.should( nestedQuery("field2", matchAllQuery(), ScoreMode.Avg).innerHit( new InnerHitBuilder("b").addSort(new FieldSortBuilder("_doc").order(SortOrder.ASC)).setSize(size) ) ); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(boolQuery) .setSize(numDocs) .addSort("foo", SortOrder.ASC) .get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, numDocs); assertThat(searchResponse.getHits().getHits().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { SearchHit searchHit = searchResponse.getHits().getAt(i); assertThat(searchHit.getShard(), notNullValue()); SearchHits inner = searchHit.getInnerHits().get("a"); assertThat(inner.getTotalHits().value, equalTo((long) field1InnerObjects[i])); for (int j = 0; j < field1InnerObjects[i] && j < size; j++) { SearchHit innerHit = inner.getAt(j); assertThat(innerHit.getNestedIdentity().getField().string(), equalTo("field1")); assertThat(innerHit.getNestedIdentity().getOffset(), equalTo(j)); assertThat(innerHit.getNestedIdentity().getChild(), nullValue()); } inner = searchHit.getInnerHits().get("b"); assertThat(inner.getTotalHits().value, equalTo((long) field2InnerObjects[i])); for (int j = 0; j < field2InnerObjects[i] && j < size; j++) { SearchHit innerHit = inner.getAt(j); assertThat(innerHit.getNestedIdentity().getField().string(), equalTo("field2")); assertThat(innerHit.getNestedIdentity().getOffset(), equalTo(j)); assertThat(innerHit.getNestedIdentity().getChild(), nullValue()); } } } public void testNestedMultipleLayers() throws Exception { assertAcked( prepareCreate("articles").setMapping( jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("comments") .field("type", "nested") .startObject("properties") .startObject("message") .field("type", "text") .endObject() .startObject("remarks") .field("type", "nested") .startObject("properties") .startObject("message") .field("type", "text") .endObject() .endObject() .endObject() .endObject() .endObject() .startObject("title") .field("type", "text") .endObject() .endObject() .endObject() .endObject() ) ); List<IndexRequestBuilder> requests = new ArrayList<>(); requests.add( client().prepareIndex("articles") .setId("1") .setSource( jsonBuilder().startObject() .field("title", "quick brown fox") .startArray("comments") .startObject() .field("message", "fox eat quick") .startArray("remarks") .startObject() .field("message", "good") .endObject() .endArray() .endObject() .startObject() .field("message", "hippo is hungry") .startArray("remarks") .startObject() .field("message", "neutral") .endObject() .endArray() .endObject() .endArray() .endObject() ) ); requests.add( client().prepareIndex("articles") .setId("2") .setSource( jsonBuilder().startObject() .field("title", "big gray elephant") .startArray("comments") .startObject() .field("message", "elephant captured") .startArray("remarks") .startObject() .field("message", "bad") .endObject() .endArray() .endObject() .endArray() .endObject() ) ); indexRandom(true, requests); // Check we can load the first doubly-nested document. SearchResponse response = client().prepareSearch("articles") .setQuery( nestedQuery( "comments", nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "good"), ScoreMode.Avg).innerHit( new InnerHitBuilder("remark") ), ScoreMode.Avg ).innerHit(new InnerHitBuilder()) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("1")); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("1")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); innerHits = innerHits.getAt(0).getInnerHits().get("remark"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("1")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getField().string(), equalTo("remarks")); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getOffset(), equalTo(0)); // Check we can load the second doubly-nested document. response = client().prepareSearch("articles") .setQuery( nestedQuery( "comments", nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "neutral"), ScoreMode.Avg).innerHit( new InnerHitBuilder("remark") ), ScoreMode.Avg ).innerHit(new InnerHitBuilder()) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("1")); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("1")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(1)); innerHits = innerHits.getAt(0).getInnerHits().get("remark"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("1")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(1)); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getField().string(), equalTo("remarks")); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getOffset(), equalTo(0)); // Directly refer to the second level: response = client().prepareSearch("articles") .setQuery( nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "bad"), ScoreMode.Avg).innerHit( new InnerHitBuilder() ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("2")); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); innerHits = response.getHits().getAt(0).getInnerHits().get("comments.remarks"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("2")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getField().string(), equalTo("remarks")); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getOffset(), equalTo(0)); response = client().prepareSearch("articles") .setQuery( nestedQuery( "comments", nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "bad"), ScoreMode.Avg).innerHit( new InnerHitBuilder("remark") ), ScoreMode.Avg ).innerHit(new InnerHitBuilder()) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertSearchHit(response, 1, hasId("2")); assertThat(response.getHits().getAt(0).getInnerHits().size(), equalTo(1)); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("2")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); innerHits = innerHits.getAt(0).getInnerHits().get("remark"); assertThat(innerHits.getTotalHits().value, equalTo(1L)); assertThat(innerHits.getHits().length, equalTo(1)); assertThat(innerHits.getAt(0).getId(), equalTo("2")); assertThat(innerHits.getAt(0).getNestedIdentity().getField().string(), equalTo("comments")); assertThat(innerHits.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getField().string(), equalTo("remarks")); assertThat(innerHits.getAt(0).getNestedIdentity().getChild().getOffset(), equalTo(0)); // Check that inner hits contain _source even when it's disabled on the parent request. response = client().prepareSearch("articles") .setFetchSource(false) .setQuery( nestedQuery( "comments", nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "good"), ScoreMode.Avg).innerHit( new InnerHitBuilder("remark") ), ScoreMode.Avg ).innerHit(new InnerHitBuilder()) ) .get(); assertNoFailures(response); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); innerHits = innerHits.getAt(0).getInnerHits().get("remark"); assertNotNull(innerHits.getAt(0).getSourceAsMap()); assertFalse(innerHits.getAt(0).getSourceAsMap().isEmpty()); response = client().prepareSearch("articles") .setQuery( nestedQuery( "comments", nestedQuery("comments.remarks", matchQuery("comments.remarks.message", "good"), ScoreMode.Avg).innerHit( new InnerHitBuilder("remark") ), ScoreMode.Avg ).innerHit(new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(false))) ) .get(); assertNoFailures(response); innerHits = response.getHits().getAt(0).getInnerHits().get("comments"); innerHits = innerHits.getAt(0).getInnerHits().get("remark"); assertNotNull(innerHits.getAt(0).getSourceAsMap()); assertFalse(innerHits.getAt(0).getSourceAsMap().isEmpty()); } // Issue #9723 public void testNestedDefinedAsObject() throws Exception { assertAcked(prepareCreate("articles").setMapping("comments", "type=nested", "title", "type=text")); List<IndexRequestBuilder> requests = new ArrayList<>(); requests.add( client().prepareIndex("articles") .setId("1") .setSource( jsonBuilder().startObject() .field("title", "quick brown fox") .startObject("comments") .field("message", "fox eat quick") .endObject() .endObject() ) ); indexRandom(true, requests); SearchResponse response = client().prepareSearch("articles") .setQuery(nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.Avg).innerHit(new InnerHitBuilder())) .get(); assertNoFailures(response); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("1")); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getTotalHits().value, equalTo(1L)); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getId(), equalTo("1")); assertThat( response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getNestedIdentity().getField().string(), equalTo("comments") ); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getNestedIdentity().getChild(), nullValue()); } public void testInnerHitsWithObjectFieldThatHasANestedField() throws Exception { assertAcked( prepareCreate("articles") // number_of_shards = 1, because then we catch the expected exception in the same way. // (See expectThrows(...) below) .setSettings(Settings.builder().put("index.number_of_shards", 1)) .setMapping( jsonBuilder().startObject() .startObject("properties") .startObject("comments") .field("type", "object") .startObject("properties") .startObject("messages") .field("type", "nested") .endObject() .endObject() .endObject() .endObject() .endObject() ) ); List<IndexRequestBuilder> requests = new ArrayList<>(); requests.add( client().prepareIndex("articles") .setId("1") .setSource( jsonBuilder().startObject() .field("title", "quick brown fox") .startArray("comments") .startObject() .startArray("messages") .startObject() .field("message", "fox eat quick") .endObject() .startObject() .field("message", "bear eat quick") .endObject() .endArray() .endObject() .startObject() .startArray("messages") .startObject() .field("message", "no fox") .endObject() .endArray() .endObject() .endArray() .endObject() ) ); indexRandom(true, requests); SearchResponse resp1 = client().prepareSearch("articles") .setQuery( nestedQuery("comments.messages", matchQuery("comments.messages.message", "fox"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(true)) ) ) .get(); assertNoFailures(resp1); assertHitCount(resp1, 1); SearchHit parent = resp1.getHits().getAt(0); assertThat(parent.getId(), equalTo("1")); SearchHits inner = parent.getInnerHits().get("comments.messages"); assertThat(inner.getTotalHits().value, equalTo(2L)); assertThat(inner.getAt(0).getSourceAsString(), equalTo("{\"message\":\"no fox\"}")); assertThat(inner.getAt(1).getSourceAsString(), equalTo("{\"message\":\"fox eat quick\"}")); SearchResponse response = client().prepareSearch("articles") .setQuery( nestedQuery("comments.messages", matchQuery("comments.messages.message", "fox"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(false)) ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); SearchHit hit = response.getHits().getAt(0); assertThat(hit.getId(), equalTo("1")); SearchHits messages = hit.getInnerHits().get("comments.messages"); assertThat(messages.getTotalHits().value, equalTo(2L)); assertThat(messages.getAt(0).getId(), equalTo("1")); assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages")); assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(2)); assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue()); assertThat(messages.getAt(1).getId(), equalTo("1")); assertThat(messages.getAt(1).getNestedIdentity().getField().string(), equalTo("comments.messages")); assertThat(messages.getAt(1).getNestedIdentity().getOffset(), equalTo(0)); assertThat(messages.getAt(1).getNestedIdentity().getChild(), nullValue()); response = client().prepareSearch("articles") .setQuery( nestedQuery("comments.messages", matchQuery("comments.messages.message", "bear"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(false)) ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); hit = response.getHits().getAt(0); assertThat(hit.getId(), equalTo("1")); messages = hit.getInnerHits().get("comments.messages"); assertThat(messages.getTotalHits().value, equalTo(1L)); assertThat(messages.getAt(0).getId(), equalTo("1")); assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages")); assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(1)); assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue()); // index the message in an object form instead of an array requests = new ArrayList<>(); requests.add( client().prepareIndex("articles") .setId("1") .setSource( jsonBuilder().startObject() .field("title", "quick brown fox") .startObject("comments") .startObject("messages") .field("message", "fox eat quick") .endObject() .endObject() .endObject() ) ); indexRandom(true, requests); response = client().prepareSearch("articles") .setQuery( nestedQuery("comments.messages", matchQuery("comments.messages.message", "fox"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(false)) ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); hit = response.getHits().getAt(0); assertThat(hit.getId(), equalTo("1")); messages = hit.getInnerHits().get("comments.messages"); assertThat(messages.getTotalHits().value, equalTo(1L)); assertThat(messages.getAt(0).getId(), equalTo("1")); assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages")); assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(0)); assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue()); } public void testMatchesQueriesNestedInnerHits() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("nested1") .field("type", "nested") .startObject("properties") .startObject("n_field1") .field("type", "keyword") .endObject() .endObject() .endObject() .startObject("field1") .field("type", "long") .endObject() .endObject() .endObject() .endObject(); assertAcked(prepareCreate("test").setMapping(builder)); ensureGreen(); List<IndexRequestBuilder> requests = new ArrayList<>(); int numDocs = randomIntBetween(2, 35); requests.add( client().prepareIndex("test") .setId("0") .setSource( jsonBuilder().startObject() .field("field1", 0) .startArray("nested1") .startObject() .field("n_field1", "n_value1_1") .field("n_field2", "n_value2_1") .endObject() .startObject() .field("n_field1", "n_value1_2") .field("n_field2", "n_value2_2") .endObject() .endArray() .endObject() ) ); requests.add( client().prepareIndex("test") .setId("1") .setSource( jsonBuilder().startObject() .field("field1", 1) .startArray("nested1") .startObject() .field("n_field1", "n_value1_8") .field("n_field2", "n_value2_5") .endObject() .startObject() .field("n_field1", "n_value1_3") .field("n_field2", "n_value2_1") .endObject() .endArray() .endObject() ) ); for (int i = 2; i < numDocs; i++) { requests.add( client().prepareIndex("test") .setId(String.valueOf(i)) .setSource( jsonBuilder().startObject() .field("field1", i) .startArray("nested1") .startObject() .field("n_field1", "n_value1_8") .field("n_field2", "n_value2_5") .endObject() .startObject() .field("n_field1", "n_value1_2") .field("n_field2", "n_value2_2") .endObject() .endArray() .endObject() ) ); } indexRandom(true, requests); waitForRelocation(ClusterHealthStatus.GREEN); QueryBuilder query = boolQuery().should(termQuery("nested1.n_field1", "n_value1_1").queryName("test1")) .should(termQuery("nested1.n_field1", "n_value1_3").queryName("test2")) .should(termQuery("nested1.n_field2", "n_value2_2").queryName("test3")); query = nestedQuery("nested1", query, ScoreMode.Avg).innerHit( new InnerHitBuilder().addSort(new FieldSortBuilder("nested1.n_field1").order(SortOrder.ASC)) ); SearchResponse searchResponse = client().prepareSearch("test") .setQuery(query) .setSize(numDocs) .addSort("field1", SortOrder.ASC) .get(); assertNoFailures(searchResponse); assertAllSuccessful(searchResponse); assertThat(searchResponse.getHits().getTotalHits().value, equalTo((long) numDocs)); assertThat(searchResponse.getHits().getAt(0).getId(), equalTo("0")); assertThat(searchResponse.getHits().getAt(0).getInnerHits().get("nested1").getTotalHits().value, equalTo(2L)); assertThat(searchResponse.getHits().getAt(0).getInnerHits().get("nested1").getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getInnerHits().get("nested1").getAt(0).getMatchedQueries()[0], equalTo("test1")); assertThat(searchResponse.getHits().getAt(0).getInnerHits().get("nested1").getAt(1).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).getInnerHits().get("nested1").getAt(1).getMatchedQueries()[0], equalTo("test3")); assertThat(searchResponse.getHits().getAt(1).getId(), equalTo("1")); assertThat(searchResponse.getHits().getAt(1).getInnerHits().get("nested1").getTotalHits().value, equalTo(1L)); assertThat(searchResponse.getHits().getAt(1).getInnerHits().get("nested1").getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(1).getInnerHits().get("nested1").getAt(0).getMatchedQueries()[0], equalTo("test2")); for (int i = 2; i < numDocs; i++) { assertThat(searchResponse.getHits().getAt(i).getId(), equalTo(String.valueOf(i))); assertThat(searchResponse.getHits().getAt(i).getInnerHits().get("nested1").getTotalHits().value, equalTo(1L)); assertThat(searchResponse.getHits().getAt(i).getInnerHits().get("nested1").getAt(0).getMatchedQueries().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(i).getInnerHits().get("nested1").getAt(0).getMatchedQueries()[0], equalTo("test3")); } } public void testNestedSource() throws Exception { assertAcked(prepareCreate("index1").setMapping("comments", "type=nested")); client().prepareIndex("index1") .setId("1") .setSource( jsonBuilder().startObject() .field("message", "quick brown fox") .startArray("comments") .startObject() .field("message", "fox eat quick") .field("x", "y") .endObject() .startObject() .field("message", "fox ate rabbit x y z") .field("x", "y") .endObject() .startObject() .field("message", "rabbit got away") .field("x", "y") .endObject() .endArray() .endObject() ) .get(); refresh(); // the field name (comments.message) used for source filtering should be the same as when using that field for // other features (like in the query dsl or aggs) in order for consistency: SearchResponse response = client().prepareSearch() .setQuery( nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.None).innerHit( new InnerHitBuilder().setFetchSourceContext(new FetchSourceContext(true, new String[] { "comments.message" }, null)) ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getTotalHits().value, equalTo(2L)); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().size(), equalTo(1)); assertThat( response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().get("message"), equalTo("fox eat quick") ); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(1).getSourceAsMap().size(), equalTo(1)); assertThat( response.getHits().getAt(0).getInnerHits().get("comments").getAt(1).getSourceAsMap().get("message"), equalTo("fox ate rabbit x y z") ); response = client().prepareSearch() .setQuery(nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.None).innerHit(new InnerHitBuilder())) .get(); assertNoFailures(response); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getTotalHits().value, equalTo(2L)); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().size(), equalTo(2)); assertThat( response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().get("message"), equalTo("fox eat quick") ); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().size(), equalTo(2)); assertThat( response.getHits().getAt(0).getInnerHits().get("comments").getAt(1).getSourceAsMap().get("message"), equalTo("fox ate rabbit x y z") ); // Source filter on a field that does not exist inside the nested document and just check that we do not fail and // return an empty _source: response = client().prepareSearch() .setQuery( nestedQuery("comments", matchQuery("comments.message", "away"), ScoreMode.None).innerHit( new InnerHitBuilder().setFetchSourceContext( new FetchSourceContext(true, new String[] { "comments.missing_field" }, null) ) ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getTotalHits().value, equalTo(1L)); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().size(), equalTo(0)); // Check that inner hits contain _source even when it's disabled on the root request. response = client().prepareSearch() .setFetchSource(false) .setQuery(nestedQuery("comments", matchQuery("comments.message", "fox"), ScoreMode.None).innerHit(new InnerHitBuilder())) .get(); assertNoFailures(response); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getInnerHits().get("comments").getTotalHits().value, equalTo(2L)); assertFalse(response.getHits().getAt(0).getInnerHits().get("comments").getAt(0).getSourceAsMap().isEmpty()); } public void testInnerHitsWithIgnoreUnmapped() throws Exception { assertAcked(prepareCreate("index1").setMapping("nested_type", "type=nested")); createIndex("index2"); client().prepareIndex("index1").setId("1").setSource("nested_type", Collections.singletonMap("key", "value")).get(); client().prepareIndex("index2").setId("3").setSource("key", "value").get(); refresh(); SearchResponse response = client().prepareSearch("index1", "index2") .setQuery( boolQuery().should( nestedQuery("nested_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true) .innerHit(new InnerHitBuilder().setIgnoreUnmapped(true)) ).should(termQuery("key", "value")) ) .get(); assertNoFailures(response); assertHitCount(response, 2); assertSearchHits(response, "1", "3"); } public void testUseMaxDocInsteadOfSize() throws Exception { assertAcked(prepareCreate("index2").setMapping("nested", "type=nested")); client().admin() .indices() .prepareUpdateSettings("index2") .setSettings(Collections.singletonMap(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), ArrayUtil.MAX_ARRAY_LENGTH)) .get(); client().prepareIndex("index2") .setId("1") .setSource( jsonBuilder().startObject().startArray("nested").startObject().field("field", "value1").endObject().endArray().endObject() ) .setRefreshPolicy(IMMEDIATE) .get(); QueryBuilder query = nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setSize(ArrayUtil.MAX_ARRAY_LENGTH - 1) ); SearchResponse response = client().prepareSearch("index2").setQuery(query).get(); assertNoFailures(response); assertHitCount(response, 1); } public void testTooHighResultWindow() throws Exception { assertAcked(prepareCreate("index2").setMapping("nested", "type=nested")); client().prepareIndex("index2") .setId("1") .setSource( jsonBuilder().startObject().startArray("nested").startObject().field("field", "value1").endObject().endArray().endObject() ) .setRefreshPolicy(IMMEDIATE) .get(); SearchResponse response = client().prepareSearch("index2") .setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(50).setSize(10).setName("_name") ) ) .get(); assertNoFailures(response); assertHitCount(response, 1); Exception e = expectThrows( SearchPhaseExecutionException.class, () -> client().prepareSearch("index2") .setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(100).setSize(10).setName("_name") ) ) .get() ); assertThat( e.getCause().getMessage(), containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]") ); e = expectThrows( SearchPhaseExecutionException.class, () -> client().prepareSearch("index2") .setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(10).setSize(100).setName("_name") ) ) .get() ); assertThat( e.getCause().getMessage(), containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]") ); client().admin() .indices() .prepareUpdateSettings("index2") .setSettings(Collections.singletonMap(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110)) .get(); response = client().prepareSearch("index2") .setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(100).setSize(10).setName("_name") ) ) .get(); assertNoFailures(response); response = client().prepareSearch("index2") .setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(10).setSize(100).setName("_name") ) ) .get(); assertNoFailures(response); } }
apache-2.0
DomenicPuzio/incubator-metron
metron-platform/metron-pcap/src/test/java/org/apache/metron/pcap/filter/PcapFiltersTest.java
1406
/** * 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.metron.pcap.filter; import org.apache.metron.pcap.filter.fixed.FixedPcapFilter; import org.apache.metron.pcap.filter.query.QueryPcapFilter; import org.junit.Assert; import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; public class PcapFiltersTest { @Test public void creates_pcap_filters() throws Exception { Assert.assertThat("filter type should be Fixed", PcapFilters.FIXED.create(), instanceOf(FixedPcapFilter.class)); Assert.assertThat("filter type should be Query", PcapFilters.QUERY.create(), instanceOf(QueryPcapFilter.class)); } }
apache-2.0
md-5/jdk10
src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ElemDesc.java
5664
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * 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.sun.org.apache.xml.internal.serializer; import com.sun.org.apache.xml.internal.serializer.utils.StringToIntTable; /** * This class has a series of flags (bit values) that describe an HTML element * * This class is public because XSLTC uses it, it is not a public API. * * @xsl.usage internal */ public final class ElemDesc { /** Bit flags to tell about this element type. */ private int m_flags; /** * Table of attribute names to integers, which contain bit flags telling about * the attributes. */ private StringToIntTable m_attrs = null; /** Bit position if this element type is empty. */ static final int EMPTY = (1 << 1); /** Bit position if this element type is a flow. */ private static final int FLOW = (1 << 2); /** Bit position if this element type is a block. */ static final int BLOCK = (1 << 3); /** Bit position if this element type is a block form. */ static final int BLOCKFORM = (1 << 4); /** Bit position if this element type is a block form field set. */ static final int BLOCKFORMFIELDSET = (1 << 5); /** Bit position if this element type is CDATA. */ private static final int CDATA = (1 << 6); /** Bit position if this element type is PCDATA. */ private static final int PCDATA = (1 << 7); /** Bit position if this element type is should be raw characters. */ static final int RAW = (1 << 8); /** Bit position if this element type should be inlined. */ private static final int INLINE = (1 << 9); /** Bit position if this element type is INLINEA. */ private static final int INLINEA = (1 << 10); /** Bit position if this element type is an inline label. */ static final int INLINELABEL = (1 << 11); /** Bit position if this element type is a font style. */ static final int FONTSTYLE = (1 << 12); /** Bit position if this element type is a phrase. */ static final int PHRASE = (1 << 13); /** Bit position if this element type is a form control. */ static final int FORMCTRL = (1 << 14); /** Bit position if this element type is ???. */ static final int SPECIAL = (1 << 15); /** Bit position if this element type is ???. */ static final int ASPECIAL = (1 << 16); /** Bit position if this element type is an odd header element. */ static final int HEADMISC = (1 << 17); /** Bit position if this element type is a head element (i.e. H1, H2, etc.) */ static final int HEAD = (1 << 18); /** Bit position if this element type is a list. */ static final int LIST = (1 << 19); /** Bit position if this element type is a preformatted type. */ static final int PREFORMATTED = (1 << 20); /** Bit position if this element type is whitespace sensitive. */ static final int WHITESPACESENSITIVE = (1 << 21); /** Bit position if this element type is a header element (i.e. HEAD). */ static final int HEADELEM = (1 << 22); /** Bit position if this element is the "HTML" element */ private static final int HTMLELEM = (1 << 23); /** Bit position if this attribute type is a URL. */ public static final int ATTRURL = (1 << 1); /** Bit position if this attribute type is an empty type. */ public static final int ATTREMPTY = (1 << 2); /** * Construct an ElemDesc from a set of bit flags. * * * @param flags Bit flags that describe the basic properties of this element type. */ ElemDesc(int flags) { m_flags = flags; } /** * Tell if this element type has the basic bit properties that are passed * as an argument. * * @param flags Bit flags that describe the basic properties of interest. * * @return true if any of the flag bits are true. */ private boolean is(int flags) { // int which = (m_flags & flags); return (m_flags & flags) != 0; } int getFlags() { return m_flags; } /** * Set an attribute name and it's bit properties. * * * @param name non-null name of attribute, in upper case. * @param flags flag bits. */ void setAttr(String name, int flags) { if (null == m_attrs) m_attrs = new StringToIntTable(); m_attrs.put(name, flags); } /** * Tell if any of the bits of interest are set for a named attribute type. * * @param name non-null reference to attribute name, in any case. * @param flags flag mask. * * @return true if any of the flags are set for the named attribute. */ public boolean isAttrFlagSet(String name, int flags) { return (null != m_attrs) ? ((m_attrs.getIgnoreCase(name) & flags) != 0) : false; } }
gpl-2.0
FauxFaux/jdk9-langtools
test/tools/javac/generics/wildcards/AssignmentDifferentTypes.java
2490
/* * Copyright (c) 2003, 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. */ /* * @test * @summary Test subtyping for wildcards with related type bounds. * * @compile/fail/ref=AssignmentDifferentTypes.out -XDrawDiagnostics AssignmentDifferentTypes.java */ public class AssignmentDifferentTypes { public static void main(String[] args) { Ref<Der> derexact = null; Ref<Base> baseexact = null; Ref<? extends Der> derext = null; Ref<? extends Base> baseext = null; Ref<? super Der> dersuper = null; Ref<? super Base> basesuper = null; baseext = derext; // <<pass>> <? extends Base> = <? extends Der> baseext = derexact; // <<pass>> <? extends Base> = <Der> dersuper = basesuper; // <<pass>> <? super Der> = <? super Base> dersuper = baseexact; // <<pass>> <? super Der> = <Base> derexact = baseexact; // <<fail>> <Der> = <Base> baseexact = derexact; // <<fail>> <Base> = <Der> derext = baseext; // <<fail>> <? extends Der> = <? extends Base> derext = baseexact; // <<fail>> <? extends Der> = <Base> derext = basesuper; // <<fail>> <? extends Der> = <? super Base> baseext = dersuper; // <<fail>> <? extends Base> = <? super Der> basesuper = dersuper; // <<fail>> <? super Base> = <? super Der> basesuper = derexact; // <<fail>> <? super Base> = <Der> } } class Ref<T> {} class Base {} class Der extends Base {}
gpl-2.0
coding0011/elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/metrics/InternalGeoCentroidTests.java
5761
/* * 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.metrics; import org.apache.lucene.geo.GeoEncodingUtils; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.search.aggregations.ParsedAggregation; import org.elasticsearch.search.aggregations.metrics.InternalGeoCentroid; import org.elasticsearch.search.aggregations.metrics.ParsedGeoCentroid; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.test.InternalAggregationTestCase; import org.elasticsearch.test.geo.RandomGeoGenerator; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class InternalGeoCentroidTests extends InternalAggregationTestCase<InternalGeoCentroid> { @Override protected InternalGeoCentroid createTestInstance(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) { GeoPoint centroid = RandomGeoGenerator.randomPoint(random()); // Re-encode lat/longs to avoid rounding issue when testing InternalGeoCentroid#hashCode() and // InternalGeoCentroid#equals() int encodedLon = GeoEncodingUtils.encodeLongitude(centroid.lon()); centroid.resetLon(GeoEncodingUtils.decodeLongitude(encodedLon)); int encodedLat = GeoEncodingUtils.encodeLatitude(centroid.lat()); centroid.resetLat(GeoEncodingUtils.decodeLatitude(encodedLat)); long count = randomIntBetween(0, 1000); if (count == 0) { centroid = null; } return new InternalGeoCentroid(name, centroid, count, Collections.emptyList(), Collections.emptyMap()); } @Override protected Writeable.Reader<InternalGeoCentroid> instanceReader() { return InternalGeoCentroid::new; } @Override protected void assertReduced(InternalGeoCentroid reduced, List<InternalGeoCentroid> inputs) { double lonSum = 0; double latSum = 0; int totalCount = 0; for (InternalGeoCentroid input : inputs) { if (input.count() > 0) { lonSum += (input.count() * input.centroid().getLon()); latSum += (input.count() * input.centroid().getLat()); } totalCount += input.count(); } if (totalCount > 0) { assertEquals(latSum/totalCount, reduced.centroid().getLat(), 1E-5D); assertEquals(lonSum/totalCount, reduced.centroid().getLon(), 1E-5D); } assertEquals(totalCount, reduced.count()); } @Override protected void assertFromXContent(InternalGeoCentroid aggregation, ParsedAggregation parsedAggregation) { assertTrue(parsedAggregation instanceof ParsedGeoCentroid); ParsedGeoCentroid parsed = (ParsedGeoCentroid) parsedAggregation; assertEquals(aggregation.centroid(), parsed.centroid()); assertEquals(aggregation.count(), parsed.count()); } @Override protected InternalGeoCentroid mutateInstance(InternalGeoCentroid instance) { String name = instance.getName(); GeoPoint centroid = instance.centroid(); long count = instance.count(); List<PipelineAggregator> pipelineAggregators = instance.pipelineAggregators(); Map<String, Object> metaData = instance.getMetaData(); switch (between(0, 2)) { case 0: name += randomAlphaOfLength(5); break; case 1: count += between(1, 100); if (centroid == null) { // if the new count is > 0 then we need to make sure there is a // centroid or the constructor will throw an exception centroid = new GeoPoint(randomDoubleBetween(-90, 90, false), randomDoubleBetween(-180, 180, false)); } break; case 2: if (centroid == null) { centroid = new GeoPoint(randomDoubleBetween(-90, 90, false), randomDoubleBetween(-180, 180, false)); count = between(1, 100); } else { GeoPoint newCentroid = new GeoPoint(centroid); if (randomBoolean()) { newCentroid.resetLat(centroid.getLat() / 2.0); } else { newCentroid.resetLon(centroid.getLon() / 2.0); } centroid = newCentroid; } break; case 3: if (metaData == null) { metaData = new HashMap<>(1); } else { metaData = new HashMap<>(instance.getMetaData()); } metaData.put(randomAlphaOfLength(15), randomInt()); break; default: throw new AssertionError("Illegal randomisation branch"); } return new InternalGeoCentroid(name, centroid, count, pipelineAggregators, metaData); } }
apache-2.0
alexzaitzev/ignite
modules/ml/src/main/java/org/apache/ignite/ml/preprocessing/imputing/package-info.java
932
/* * 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 description. --> * Contains Imputer preprocessor. */ package org.apache.ignite.ml.preprocessing.imputing;
apache-2.0
GJL/flink
flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobStore.java
2271
/* * 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.flink.runtime.blob; import org.apache.flink.api.common.JobID; import java.io.File; import java.io.IOException; /** * A blob store. */ public interface BlobStore extends BlobView { /** * Copies the local file to the blob store. * * @param localFile The file to copy * @param jobId ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated) * @param blobKey The ID for the file in the blob store * * @return whether the file was copied (<tt>true</tt>) or not (<tt>false</tt>) * @throws IOException If the copy fails */ boolean put(File localFile, JobID jobId, BlobKey blobKey) throws IOException; /** * Tries to delete a blob from storage. * * <p>NOTE: This also tries to delete any created directories if empty.</p> * * @param jobId ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated) * @param blobKey The blob ID * * @return <tt>true</tt> if the given blob is successfully deleted or non-existing; * <tt>false</tt> otherwise */ boolean delete(JobID jobId, BlobKey blobKey); /** * Tries to delete all blobs for the given job from storage. * * <p>NOTE: This also tries to delete any created directories if empty.</p> * * @param jobId The JobID part of all blobs to delete * * @return <tt>true</tt> if the job directory is successfully deleted or non-existing; * <tt>false</tt> otherwise */ boolean deleteAll(JobID jobId); }
apache-2.0
markusweimer/incubator-reef
lang/java/reef-io/src/main/java/org/apache/reef/io/network/impl/NetworkConnectionServiceExceptionHandler.java
1475
/* * 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.reef.io.network.impl; import org.apache.reef.wake.EventHandler; import javax.inject.Inject; import java.util.logging.Level; import java.util.logging.Logger; /** * Default exception handler. */ public final class NetworkConnectionServiceExceptionHandler implements EventHandler<Exception> { private static final Logger LOG = Logger.getLogger(NetworkConnectionServiceExceptionHandler.class.getName()); @Inject public NetworkConnectionServiceExceptionHandler() { } @Override public void onNext(final Exception value) { LOG.log(Level.WARNING, "An exception occurred in transport of NetworkConnectionService: {0}", value); } }
apache-2.0
jwren/intellij-community
java/java-tests/testData/refactoring/introduceParameterObject/typeParameters/after/Param.java
31
public record Param<R>(R r) { }
apache-2.0
Supun94/carbon-device-mgt-plugins
components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.api/src/main/java/org/wso2/carbon/device/mgt/mobile/windows/api/services/authbst/impl/BSTProviderImpl.java
5136
/* * Copyright (c) 2016, 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.device.mgt.mobile.windows.api.services.authbst.impl; import org.apache.commons.codec.binary.Base64; import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.mobile.windows.api.common.beans.Token; import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.AuthenticationException; import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WindowsDeviceEnrolmentException; import org.wso2.carbon.device.mgt.mobile.windows.api.common.util.DeviceUtil; import org.wso2.carbon.device.mgt.mobile.windows.api.services.authbst.BSTProvider; import org.wso2.carbon.device.mgt.mobile.windows.api.services.authbst.beans.Credentials; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.ws.rs.core.Response; /** * Implementation class of BSTProvider interface which authenticates the credentials comes via MDM login page. */ public class BSTProviderImpl implements BSTProvider { /** * This method validates the device user, checking passed credentials and returns the corresponding * binary security token which is used in XCEP and WSTEP stages for authentication. * * @param credentials - Credential object passes from the wab page. * @return - Response with binary security token. */ @Override public Response getBST(Credentials credentials) throws WindowsDeviceEnrolmentException { String domainUser = credentials.getUsername(); String userToken = credentials.getUsertoken(); String encodedToken; try { Token tokenBean = new Token(); tokenBean.setChallengeToken(userToken); Base64 base64 = new Base64(); encodedToken = base64.encodeToString(userToken.getBytes()); DeviceUtil.persistChallengeToken(encodedToken, null, domainUser); JSONObject tokenContent = new JSONObject(); tokenContent.put("UserToken", userToken); return Response.ok().entity(tokenContent.toString()).build(); } catch (JSONException e) { throw new WindowsDeviceEnrolmentException( "Failure occurred in generating Json payload for challenge token.", e); } } /** * This method authenticate the user checking the carbon default user store. * * @param username - Username in username token * @param password - Password in username token * @param tenantDomain - Tenant domain is extracted from the username * @return - Returns boolean representing authentication result * @throws AuthenticationException */ private boolean authenticate(String username, String password, String tenantDomain) throws AuthenticationException { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID); RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); if (realmService == null) { throw new AuthenticationException("RealmService not initialized."); } int tenantId; if (tenantDomain == null || tenantDomain.trim().isEmpty()) { tenantId = MultitenantConstants.SUPER_TENANT_ID; } else { tenantId = realmService.getTenantManager().getTenantId(tenantDomain); } if (tenantId == MultitenantConstants.INVALID_TENANT_ID) { throw new AuthenticationException("Invalid tenant domain " + tenantDomain); } UserRealm userRealm = realmService.getTenantUserRealm(tenantId); return userRealm.getUserStoreManager().authenticate(username, password); } catch (UserStoreException e) { throw new AuthenticationException("User store is not initialized.", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } }
apache-2.0
tracylihui/google-collections
src/com/google/common/collect/AbstractIterator.java
5632
/* * Copyright (C) 2007 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 com.google.common.collect; import com.google.common.annotations.GwtCompatible; import static com.google.common.base.Preconditions.checkState; import java.util.NoSuchElementException; /** * This class provides a skeletal implementation of the {@code Iterator} * interface, to make this interface easier to implement for certain types of * data sources. * * <p>{@code Iterator} requires its implementations to support querying the * end-of-data status without changing the iterator's state, using the {@link * #hasNext} method. But many data sources, such as {@link * java.io.Reader#read()}), do not expose this information; the only way to * discover whether there is any data left is by trying to retrieve it. These * types of data sources are ordinarily difficult to write iterators for. But * using this class, one must implement only the {@link #computeNext} method, * and invoke the {@link #endOfData} method when appropriate. * * <p>Another example is an iterator that skips over null elements in a backing * iterator. This could be implemented as: <pre> {@code * * public static Iterator<String> skipNulls(final Iterator<String> in) { * return new AbstractIterator<String>() { * protected String computeNext() { * while (in.hasNext()) { * String s = in.next(); * if (s != null) { * return s; * } * } * return endOfData(); * } * }; * }}</pre> * * This class supports iterators that include null elements. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> { private State state = State.NOT_READY; private enum State { /** We have computed the next element and haven't returned it yet. */ READY, /** We haven't yet computed or have already returned the element. */ NOT_READY, /** We have reached the end of the data and are finished. */ DONE, /** We've suffered an exception and are kaput. */ FAILED, } private T next; /** * Returns the next element. <b>Note:</b> the implementation must call {@link * #endOfData()} when there are no elements left in the iteration. Failure to * do so could result in an infinite loop. * * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls * this method, as does the first invocation of {@code hasNext} or {@code * next} following each successful call to {@code next}. Once the * implementation either invokes {@code endOfData} or throws an exception, * {@code computeNext} is guaranteed to never be called again. * * <p>If this method throws an exception, it will propagate outward to the * {@code hasNext} or {@code next} invocation that invoked this method. Any * further attempts to use the iterator will result in an {@link * IllegalStateException}. * * <p>The implementation of this method may not invoke the {@code hasNext}, * {@code next}, or {@link #peek()} methods on this instance; if it does, an * {@code IllegalStateException} will result. * * @return the next element if there was one. If {@code endOfData} was called * during execution, the return value will be ignored. * @throws RuntimeException if any unrecoverable error happens. This exception * will propagate outward to the {@code hasNext()}, {@code next()}, or * {@code peek()} invocation that invoked this method. Any further * attempts to use the iterator will result in an * {@link IllegalStateException}. */ protected abstract T computeNext(); /** * Implementations of {@code computeNext} <b>must</b> invoke this method when * there are no elements left in the iteration. * * @return {@code null}; a convenience so your {@link #computeNext} * implementation can use the simple statement {@code return endOfData();} */ protected final T endOfData() { state = State.DONE; return null; } public final boolean hasNext() { checkState(state != State.FAILED); switch (state) { case DONE: return false; case READY: return true; default: } return tryToComputeNext(); } private boolean tryToComputeNext() { state = State.FAILED; // temporary pessimism next = computeNext(); if (state != State.DONE) { state = State.READY; return true; } return false; } public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } state = State.NOT_READY; return next; } /** * Returns the next element in the iteration without advancing the iteration, * according to the contract of {@link PeekingIterator#peek()}. * * <p>Implementations of {@code AbstractIterator} that wish to expose this * functionality should implement {@code PeekingIterator}. */ public final T peek() { if (!hasNext()) { throw new NoSuchElementException(); } return next; } }
apache-2.0
qwerty4030/elasticsearch
server/src/test/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerTests.java
4547
/* * 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.index.analysis; import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.Version; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.indices.analysis.PreBuiltAnalyzers; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import java.io.IOException; import java.util.Collection; import java.util.Locale; import static org.elasticsearch.test.VersionUtils.randomVersion; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; public class PreBuiltAnalyzerTests extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return pluginList(InternalSettingsPlugin.class); } public void testThatDefaultAndStandardAnalyzerAreTheSameInstance() { Analyzer currentStandardAnalyzer = PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.CURRENT); Analyzer currentDefaultAnalyzer = PreBuiltAnalyzers.DEFAULT.getAnalyzer(Version.CURRENT); // special case, these two are the same instance assertThat(currentDefaultAnalyzer, is(currentStandardAnalyzer)); } public void testThatInstancesAreTheSameAlwaysForKeywordAnalyzer() { assertThat(PreBuiltAnalyzers.KEYWORD.getAnalyzer(Version.CURRENT), is(PreBuiltAnalyzers.KEYWORD.getAnalyzer(Version.V_5_0_0))); } public void testThatInstancesAreCachedAndReused() { assertSame(PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.CURRENT), PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.CURRENT)); // same lucene version should be cached assertSame(PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.V_5_2_1), PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.V_5_2_2)); assertNotSame(PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.V_5_0_0), PreBuiltAnalyzers.ARABIC.getAnalyzer(Version.V_5_0_1)); } public void testThatAnalyzersAreUsedInMapping() throws IOException { int randomInt = randomInt(PreBuiltAnalyzers.values().length-1); PreBuiltAnalyzers randomPreBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt]; String analyzerName = randomPreBuiltAnalyzer.name().toLowerCase(Locale.ROOT); Version randomVersion = randomVersion(random()); Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, randomVersion).build(); NamedAnalyzer namedAnalyzer = new PreBuiltAnalyzerProvider(analyzerName, AnalyzerScope.INDEX, randomPreBuiltAnalyzer.getAnalyzer(randomVersion)).get(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field").field("type", "text").field("analyzer", analyzerName).endObject().endObject() .endObject().endObject().string(); DocumentMapper docMapper = createIndex("test", indexSettings).mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping)); FieldMapper fieldMapper = docMapper.mappers().getMapper("field"); assertThat(fieldMapper.fieldType().searchAnalyzer(), instanceOf(NamedAnalyzer.class)); NamedAnalyzer fieldMapperNamedAnalyzer = fieldMapper.fieldType().searchAnalyzer(); assertThat(fieldMapperNamedAnalyzer.analyzer(), is(namedAnalyzer.analyzer())); } }
apache-2.0
franz1981/activemq-artemis
artemis-selector/src/main/java/org/apache/activemq/artemis/selector/filter/XPathExpression.java
2623
/* * 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.activemq.artemis.selector.filter; /** * Used to evaluate an XPath Expression in a JMS selector. */ public final class XPathExpression implements BooleanExpression { public static XPathEvaluatorFactory XPATH_EVALUATOR_FACTORY = null; static { // Install the xalan xpath evaluator if it available. new XalanXPathEvaluator("//root").evaluate("<root></root>"); try { XPATH_EVALUATOR_FACTORY = new XPathExpression.XPathEvaluatorFactory() { @Override public XPathExpression.XPathEvaluator create(String xpath) { return new XalanXPathEvaluator(xpath); } }; } catch (Throwable e) { } } private final String xpath; private final XPathEvaluator evaluator; public interface XPathEvaluatorFactory { XPathEvaluator create(String xpath); } public interface XPathEvaluator { boolean evaluate(Filterable message) throws FilterException; } XPathExpression(String xpath) { if (XPATH_EVALUATOR_FACTORY == null) { throw new IllegalArgumentException("XPATH support not enabled."); } this.xpath = xpath; this.evaluator = XPATH_EVALUATOR_FACTORY.create(xpath); } @Override public Object evaluate(Filterable message) throws FilterException { return evaluator.evaluate(message) ? Boolean.TRUE : Boolean.FALSE; } @Override public String toString() { return "XPATH " + ConstantExpression.encodeString(xpath); } /** * @param message * @return true if the expression evaluates to Boolean.TRUE. * @throws FilterException */ @Override public boolean matches(Filterable message) throws FilterException { Object object = evaluate(message); return object == Boolean.TRUE; } }
apache-2.0
FauxFaux/jdk9-langtools
test/tools/javac/api/T6392782.java
4015
/* * Copyright (c) 2006, 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. */ /* * @test * @bug 6392782 * @summary TreeScanner.visitImport returns null, not result of nested scan * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file */ import java.io.*; import java.util.*; import javax.tools.*; import com.sun.source.tree.*; import com.sun.source.util.*; import com.sun.tools.javac.api.*; public class T6392782 { public static void main(String... args) throws IOException { String testSrc = System.getProperty("test.src", "."); JavacTool tool = JavacTool.create(); try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) { Iterable<? extends JavaFileObject> files = fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6392782.class.getName()+".java"))); JavacTask task = tool.getTask(null, fm, null, null, null, files); Iterable<? extends Tree> trees = task.parse(); TreeScanner<Integer,Void> scanner = new MyScanner(); check(scanner, 6, scanner.scan(trees, null)); CountNodes nodeCounter = new CountNodes(); // 359 nodes with the regular parser; 360 nodes with EndPosParser // We automatically switch to EndPosParser when calling JavacTask.parse() check(nodeCounter, 362, nodeCounter.scan(trees, null)); CountIdentifiers idCounter = new CountIdentifiers(); check(idCounter, 107, idCounter.scan(trees, null)); } } private static void check(TreeScanner<?,?> scanner, int expect, int found) { if (found != expect) throw new AssertionError(scanner.getClass().getName() + ": expected: " + expect + " found: " + found); } static class MyScanner extends TreeScanner<Integer,Void> { @Override public Integer visitImport(ImportTree tree, Void ignore) { //System.err.println(tree); return 1; } @Override public Integer reduce(Integer i1, Integer i2) { return (i1 == null ? 0 : i1) + (i2 == null ? 0 : i2); } } static class CountNodes extends TreeScanner<Integer,Void> { @Override public Integer scan(Tree node, Void p) { if (node == null) return 0; Integer n = super.scan(node, p); return (n == null ? 0 : n) + 1; } @Override public Integer reduce(Integer r1, Integer r2) { return (r1 == null ? 0 : r1) + (r2 == null ? 0 : r2); } } // example from TreeScanner javadoc static class CountIdentifiers extends TreeScanner<Integer,Void> { @Override public Integer visitIdentifier(IdentifierTree node, Void p) { return 1; } @Override public Integer reduce(Integer r1, Integer r2) { return (r1 == null ? 0 : r1) + (r2 == null ? 0 : r2); } } }
gpl-2.0
FauxFaux/jdk9-jdk
src/java.desktop/unix/classes/sun/awt/X11/XEmbeddedFrame.java
4715
/* * Copyright (c) 2002, 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. 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.awt.X11; import java.awt.AWTKeyStroke; import java.awt.Component; import java.awt.Toolkit; import java.awt.peer.ComponentPeer; import sun.awt.AWTAccessor; import sun.awt.EmbeddedFrame; import sun.util.logging.PlatformLogger; @SuppressWarnings("serial") // JDK-implementation class public class XEmbeddedFrame extends EmbeddedFrame { private static final PlatformLogger log = PlatformLogger.getLogger(XEmbeddedFrame.class.getName()); long handle; public XEmbeddedFrame() { } // handle should be a valid X Window. public XEmbeddedFrame(long handle) { this(handle, false); } // Handle is the valid X window public XEmbeddedFrame(long handle, boolean supportsXEmbed, boolean isTrayIconWindow) { super(handle, supportsXEmbed); if (isTrayIconWindow) { XTrayIconPeer.suppressWarningString(this); } this.handle = handle; if (handle != 0) { // Has actual parent addNotify(); if (!isTrayIconWindow) { show(); } } } public void addNotify() { if (!isDisplayable()) { XToolkit toolkit = (XToolkit)Toolkit.getDefaultToolkit(); setPeer(toolkit.createEmbeddedFrame(this)); } super.addNotify(); } public XEmbeddedFrame(long handle, boolean supportsXEmbed) { this(handle, supportsXEmbed, false); } /* * The method shouldn't be called in case of active XEmbed. */ public boolean traverseIn(boolean direction) { XEmbeddedFramePeer peer = AWTAccessor.getComponentAccessor() .getPeer(this); if (peer != null) { if (peer.supportsXEmbed() && peer.isXEmbedActive()) { log.fine("The method shouldn't be called when XEmbed is active!"); } else { return super.traverseIn(direction); } } return false; } protected boolean traverseOut(boolean direction) { XEmbeddedFramePeer xefp = AWTAccessor.getComponentAccessor() .getPeer(this); if (direction == FORWARD) { xefp.traverseOutForward(); } else { xefp.traverseOutBackward(); } return true; } /* * The method shouldn't be called in case of active XEmbed. */ public void synthesizeWindowActivation(boolean doActivate) { XEmbeddedFramePeer peer = AWTAccessor.getComponentAccessor() .getPeer(this); if (peer != null) { if (peer.supportsXEmbed() && peer.isXEmbedActive()) { log.fine("The method shouldn't be called when XEmbed is active!"); } else { peer.synthesizeFocusInOut(doActivate); } } } public void registerAccelerator(AWTKeyStroke stroke) { XEmbeddedFramePeer xefp = AWTAccessor.getComponentAccessor() .getPeer(this); if (xefp != null) { xefp.registerAccelerator(stroke); } } public void unregisterAccelerator(AWTKeyStroke stroke) { XEmbeddedFramePeer xefp = AWTAccessor.getComponentAccessor() .getPeer(this); if (xefp != null) { xefp.unregisterAccelerator(stroke); } } }
gpl-2.0
vadopolski/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetServiceImpl.java
1682
/* * 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.ignite.internal.processors.platform.dotnet; import org.apache.ignite.internal.processors.platform.PlatformContext; import org.apache.ignite.internal.processors.platform.services.PlatformAbstractService; /** * Interop .Net service. */ public class PlatformDotNetServiceImpl extends PlatformAbstractService implements PlatformDotNetService { /** */ private static final long serialVersionUID = 0L; /** * Default constructor for serialization. */ public PlatformDotNetServiceImpl() { // No-op. } /** * Constructor. * * @param svc Service. * @param ctx Context. * @param srvKeepBinary Whether to keep objects binary on server if possible. */ public PlatformDotNetServiceImpl(Object svc, PlatformContext ctx, boolean srvKeepBinary) { super(svc, ctx, srvKeepBinary); } }
apache-2.0
luchuangbin/test1
src/org/jivesoftware/smack/XMPPException.java
6825
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * 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 org.jivesoftware.smack; import org.jivesoftware.smack.packet.StreamError; import org.jivesoftware.smack.packet.XMPPError; import java.io.PrintStream; import java.io.PrintWriter; /** * A generic exception that is thrown when an error occurs performing an * XMPP operation. XMPP servers can respond to error conditions with an error code * and textual description of the problem, which are encapsulated in the XMPPError * class. When appropriate, an XMPPError instance is attached instances of this exception.<p> * * When a stream error occured, the server will send a stream error to the client before * closing the connection. Stream errors are unrecoverable errors. When a stream error * is sent to the client an XMPPException will be thrown containing the StreamError sent * by the server. * * @see XMPPError * @author Matt Tucker */ public class XMPPException extends Exception { private StreamError streamError = null; private XMPPError error = null; private Throwable wrappedThrowable = null; /** * Creates a new XMPPException. */ public XMPPException() { super(); } /** * Creates a new XMPPException with a description of the exception. * * @param message description of the exception. */ public XMPPException(String message) { super(message); } /** * Creates a new XMPPException with the Throwable that was the root cause of the * exception. * * @param wrappedThrowable the root cause of the exception. */ public XMPPException(Throwable wrappedThrowable) { super(); this.wrappedThrowable = wrappedThrowable; } /** * Cretaes a new XMPPException with the stream error that was the root case of the * exception. When a stream error is received from the server then the underlying * TCP connection will be closed by the server. * * @param streamError the root cause of the exception. */ public XMPPException(StreamError streamError) { super(); this.streamError = streamError; } /** * Cretaes a new XMPPException with the XMPPError that was the root case of the * exception. * * @param error the root cause of the exception. */ public XMPPException(XMPPError error) { super(); this.error = error; } /** * Creates a new XMPPException with a description of the exception and the * Throwable that was the root cause of the exception. * * @param message a description of the exception. * @param wrappedThrowable the root cause of the exception. */ public XMPPException(String message, Throwable wrappedThrowable) { super(message); this.wrappedThrowable = wrappedThrowable; } /** * Creates a new XMPPException with a description of the exception, an XMPPError, * and the Throwable that was the root cause of the exception. * * @param message a description of the exception. * @param error the root cause of the exception. * @param wrappedThrowable the root cause of the exception. */ public XMPPException(String message, XMPPError error, Throwable wrappedThrowable) { super(message); this.error = error; this.wrappedThrowable = wrappedThrowable; } /** * Creates a new XMPPException with a description of the exception and the * XMPPException that was the root cause of the exception. * * @param message a description of the exception. * @param error the root cause of the exception. */ public XMPPException(String message, XMPPError error) { super(message); this.error = error; } /** * Returns the XMPPError asscociated with this exception, or <tt>null</tt> if there * isn't one. * * @return the XMPPError asscociated with this exception. */ public XMPPError getXMPPError() { return error; } /** * Returns the StreamError asscociated with this exception, or <tt>null</tt> if there * isn't one. The underlying TCP connection is closed by the server after sending the * stream error to the client. * * @return the StreamError asscociated with this exception. */ public StreamError getStreamError() { return streamError; } /** * Returns the Throwable asscociated with this exception, or <tt>null</tt> if there * isn't one. * * @return the Throwable asscociated with this exception. */ public Throwable getWrappedThrowable() { return wrappedThrowable; } public void printStackTrace() { printStackTrace(System.err); } public void printStackTrace(PrintStream out) { super.printStackTrace(out); if (wrappedThrowable != null) { out.println("Nested Exception: "); wrappedThrowable.printStackTrace(out); } } public void printStackTrace(PrintWriter out) { super.printStackTrace(out); if (wrappedThrowable != null) { out.println("Nested Exception: "); wrappedThrowable.printStackTrace(out); } } public String getMessage() { String msg = super.getMessage(); // If the message was not set, but there is an XMPPError, return the // XMPPError as the message. if (msg == null && error != null) { return error.toString(); } else if (msg == null && streamError != null) { return streamError.toString(); } return msg; } public String toString() { StringBuilder buf = new StringBuilder(); String message = super.getMessage(); if (message != null) { buf.append(message).append(": "); } if (error != null) { buf.append(error); } if (streamError != null) { buf.append(streamError); } if (wrappedThrowable != null) { buf.append("\n -- caused by: ").append(wrappedThrowable); } return buf.toString(); } }
apache-2.0
zhenyuy-fb/presto
presto-tpch/src/main/java/com/facebook/presto/tpch/TpchBucketFunction.java
2142
/* * 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.facebook.presto.tpch; import com.facebook.presto.spi.BucketFunction; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.google.common.primitives.Ints; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.google.common.base.MoreObjects.toStringHelper; public class TpchBucketFunction implements BucketFunction { private final int bucketCount; private final long rowsPerBucket; public TpchBucketFunction(int bucketCount, long rowsPerBucket) { this.bucketCount = bucketCount; this.rowsPerBucket = rowsPerBucket; } @Override public int getBucket(Page page, int position) { Block block = page.getBlock(0); if (block.isNull(position)) { return 0; } long orderKey = BIGINT.getLong(block, position); long rowNumber = rowNumberFromOrderKey(orderKey); int bucket = Ints.checkedCast(rowNumber / rowsPerBucket); // due to rounding, the last bucket has extra rows if (bucket >= bucketCount) { bucket = bucketCount - 1; } return bucket; } @Override public String toString() { return toStringHelper(this) .add("bucketCount", bucketCount) .add("rowsPerBucket", rowsPerBucket) .toString(); } private static long rowNumberFromOrderKey(long orderKey) { // remove bits 3 and 4 return (((orderKey & ~(0b11_111)) >>> 2) | orderKey & 0b111) - 1; } }
apache-2.0
kidaa/incubator-ignite
modules/core/src/main/java/org/apache/ignite/spi/checkpoint/CheckpointListener.java
1135
/* * 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.ignite.spi.checkpoint; /** * Listener for notifications of checkpoints removed by {@link CheckpointSpi}. */ public interface CheckpointListener { /** * Notification for removed checkpoint. * * @param key Key of removed checkpoint. */ public void onCheckpointRemoved(String key); }
apache-2.0
wangcy6/storm_app
frame/java/netty-4.1/codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyProxiedProtocol.java
8198
/* * Copyright 2014 The Netty Project * * The Netty Project 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 io.netty.handler.codec.haproxy; import static io.netty.handler.codec.haproxy.HAProxyConstants.*; /** * A protocol proxied by HAProxy which is represented by its transport protocol and address family. */ public enum HAProxyProxiedProtocol { /** * The UNKNOWN represents a connection which was forwarded for an unknown protocol and an unknown address family. */ UNKNOWN(TPAF_UNKNOWN_BYTE, AddressFamily.AF_UNSPEC, TransportProtocol.UNSPEC), /** * The TCP4 represents a connection which was forwarded for an IPv4 client over TCP. */ TCP4(TPAF_TCP4_BYTE, AddressFamily.AF_IPv4, TransportProtocol.STREAM), /** * The TCP6 represents a connection which was forwarded for an IPv6 client over TCP. */ TCP6(TPAF_TCP6_BYTE, AddressFamily.AF_IPv6, TransportProtocol.STREAM), /** * The UDP4 represents a connection which was forwarded for an IPv4 client over UDP. */ UDP4(TPAF_UDP4_BYTE, AddressFamily.AF_IPv4, TransportProtocol.DGRAM), /** * The UDP6 represents a connection which was forwarded for an IPv6 client over UDP. */ UDP6(TPAF_UDP6_BYTE, AddressFamily.AF_IPv6, TransportProtocol.DGRAM), /** * The UNIX_STREAM represents a connection which was forwarded for a UNIX stream socket. */ UNIX_STREAM(TPAF_UNIX_STREAM_BYTE, AddressFamily.AF_UNIX, TransportProtocol.STREAM), /** * The UNIX_DGRAM represents a connection which was forwarded for a UNIX datagram socket. */ UNIX_DGRAM(TPAF_UNIX_DGRAM_BYTE, AddressFamily.AF_UNIX, TransportProtocol.DGRAM); private final byte byteValue; private final AddressFamily addressFamily; private final TransportProtocol transportProtocol; /** * Creates a new instance. */ HAProxyProxiedProtocol( byte byteValue, AddressFamily addressFamily, TransportProtocol transportProtocol) { this.byteValue = byteValue; this.addressFamily = addressFamily; this.transportProtocol = transportProtocol; } /** * Returns the {@link HAProxyProxiedProtocol} represented by the specified byte. * * @param tpafByte transport protocol and address family byte */ public static HAProxyProxiedProtocol valueOf(byte tpafByte) { switch (tpafByte) { case TPAF_TCP4_BYTE: return TCP4; case TPAF_TCP6_BYTE: return TCP6; case TPAF_UNKNOWN_BYTE: return UNKNOWN; case TPAF_UDP4_BYTE: return UDP4; case TPAF_UDP6_BYTE: return UDP6; case TPAF_UNIX_STREAM_BYTE: return UNIX_STREAM; case TPAF_UNIX_DGRAM_BYTE: return UNIX_DGRAM; default: throw new IllegalArgumentException( "unknown transport protocol + address family: " + (tpafByte & 0xFF)); } } /** * Returns the byte value of this protocol and address family. */ public byte byteValue() { return byteValue; } /** * Returns the {@link AddressFamily} of this protocol and address family. */ public AddressFamily addressFamily() { return addressFamily; } /** * Returns the {@link TransportProtocol} of this protocol and address family. */ public TransportProtocol transportProtocol() { return transportProtocol; } /** * The address family of an HAProxy proxy protocol header. */ public enum AddressFamily { /** * The UNSPECIFIED address family represents a connection which was forwarded for an unknown protocol. */ AF_UNSPEC(AF_UNSPEC_BYTE), /** * The IPV4 address family represents a connection which was forwarded for an IPV4 client. */ AF_IPv4(AF_IPV4_BYTE), /** * The IPV6 address family represents a connection which was forwarded for an IPV6 client. */ AF_IPv6(AF_IPV6_BYTE), /** * The UNIX address family represents a connection which was forwarded for a unix socket. */ AF_UNIX(AF_UNIX_BYTE); /** * The highest 4 bits of the transport protocol and address family byte contain the address family */ private static final byte FAMILY_MASK = (byte) 0xf0; private final byte byteValue; /** * Creates a new instance */ AddressFamily(byte byteValue) { this.byteValue = byteValue; } /** * Returns the {@link AddressFamily} represented by the highest 4 bits of the specified byte. * * @param tpafByte transport protocol and address family byte */ public static AddressFamily valueOf(byte tpafByte) { int addressFamily = tpafByte & FAMILY_MASK; switch((byte) addressFamily) { case AF_IPV4_BYTE: return AF_IPv4; case AF_IPV6_BYTE: return AF_IPv6; case AF_UNSPEC_BYTE: return AF_UNSPEC; case AF_UNIX_BYTE: return AF_UNIX; default: throw new IllegalArgumentException("unknown address family: " + addressFamily); } } /** * Returns the byte value of this address family. */ public byte byteValue() { return byteValue; } } /** * The transport protocol of an HAProxy proxy protocol header */ public enum TransportProtocol { /** * The UNSPEC transport protocol represents a connection which was forwarded for an unknown protocol. */ UNSPEC(TRANSPORT_UNSPEC_BYTE), /** * The STREAM transport protocol represents a connection which was forwarded for a TCP connection. */ STREAM(TRANSPORT_STREAM_BYTE), /** * The DGRAM transport protocol represents a connection which was forwarded for a UDP connection. */ DGRAM(TRANSPORT_DGRAM_BYTE); /** * The transport protocol is specified in the lowest 4 bits of the transport protocol and address family byte */ private static final byte TRANSPORT_MASK = 0x0f; private final byte transportByte; /** * Creates a new instance. */ TransportProtocol(byte transportByte) { this.transportByte = transportByte; } /** * Returns the {@link TransportProtocol} represented by the lowest 4 bits of the specified byte. * * @param tpafByte transport protocol and address family byte */ public static TransportProtocol valueOf(byte tpafByte) { int transportProtocol = tpafByte & TRANSPORT_MASK; switch ((byte) transportProtocol) { case TRANSPORT_STREAM_BYTE: return STREAM; case TRANSPORT_UNSPEC_BYTE: return UNSPEC; case TRANSPORT_DGRAM_BYTE: return DGRAM; default: throw new IllegalArgumentException("unknown transport protocol: " + transportProtocol); } } /** * Returns the byte value of this transport protocol. */ public byte byteValue() { return transportByte; } } }
apache-2.0
paplorinc/intellij-community
jps/jps-builders/testData/referencesIndex/castData/Foo.java
72
class Foo { void m(CharSequence c) { ((String)c).getBytes(); } }
apache-2.0
gspandy/pinpoint
thrift/src/main/java/com/navercorp/pinpoint/thrift/dto/command/TThreadDumpType.java
936
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package com.navercorp.pinpoint.thrift.dto.command; import java.util.Map; import java.util.HashMap; import org.apache.thrift.TEnum; public enum TThreadDumpType implements org.apache.thrift.TEnum { TARGET(0), PENDING(1); private final int value; private TThreadDumpType(int value) { this.value = value; } /** * Get the integer value of this enum value, as defined in the Thrift IDL. */ public int getValue() { return value; } /** * Find a the enum type by its integer value, as defined in the Thrift IDL. * @return null if the value is not found. */ public static TThreadDumpType findByValue(int value) { switch (value) { case 0: return TARGET; case 1: return PENDING; default: return null; } } }
apache-2.0
firateren52/gitblit
src/main/java/com/gitblit/wicket/panels/FilterableProjectList.java
4350
/* * Copyright 2013 gitblit.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.gitblit.wicket.panels; import java.io.Serializable; import java.text.DateFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.wicket.behavior.HeaderContributor; import org.apache.wicket.markup.html.basic.Label; import com.gitblit.Keys; import com.gitblit.models.ProjectModel; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.freemarker.FreemarkerPanel; import com.gitblit.wicket.ng.NgController; /** * A client-side filterable rich project list which uses Freemarker, Wicket, * and AngularJS. * * @author James Moger * */ public class FilterableProjectList extends BasePanel { private static final long serialVersionUID = 1L; private final List<ProjectModel> projects; private String title; private String iconClass; public FilterableProjectList(String id, List<ProjectModel> projects) { super(id); this.projects = projects; } public void setTitle(String title, String iconClass) { this.title = title; this.iconClass = iconClass; } @Override protected void onInitialize() { super.onInitialize(); String id = getId(); String ngCtrl = id + "Ctrl"; String ngList = id + "List"; Map<String, Object> values = new HashMap<String, Object>(); values.put("ngCtrl", ngCtrl); values.put("ngList", ngList); // use Freemarker to setup an AngularJS/Wicket html snippet FreemarkerPanel panel = new FreemarkerPanel("listComponent", "FilterableProjectList.fm", values); panel.setParseGeneratedMarkup(true); panel.setRenderBodyOnly(true); add(panel); // add the Wicket controls that are referenced in the snippet String listTitle = StringUtils.isEmpty(title) ? getString("gb.projects") : title; panel.add(new Label(ngList + "Title", MessageFormat.format("{0} ({1})", listTitle, projects.size()))); if (StringUtils.isEmpty(iconClass)) { panel.add(new Label(ngList + "Icon").setVisible(false)); } else { Label icon = new Label(ngList + "Icon"); WicketUtils.setCssClass(icon, iconClass); panel.add(icon); } String format = app().settings().getString(Keys.web.datestampShortFormat, "MM/dd/yy"); final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(getTimeZone()); Collections.sort(projects, new Comparator<ProjectModel>() { @Override public int compare(ProjectModel o1, ProjectModel o2) { return o2.lastChange.compareTo(o1.lastChange); } }); List<ProjectListItem> list = new ArrayList<ProjectListItem>(); for (ProjectModel proj : projects) { if (proj.isUserProject() || proj.repositories.isEmpty()) { // exclude user projects from list continue; } ProjectListItem item = new ProjectListItem(); item.p = proj.name; item.n = StringUtils.isEmpty(proj.title) ? proj.name : proj.title; item.i = proj.description; item.t = getTimeUtils().timeAgo(proj.lastChange); item.d = df.format(proj.lastChange); item.c = proj.repositories.size(); list.add(item); } // inject an AngularJS controller with static data NgController ctrl = new NgController(ngCtrl); ctrl.addVariable(ngList, list); add(new HeaderContributor(ctrl)); } protected class ProjectListItem implements Serializable { private static final long serialVersionUID = 1L; String p; // path String n; // name String t; // time ago String d; // last updated String i; // information/description long c; // repository count } }
apache-2.0
md-5/jdk10
src/java.xml/share/classes/org/w3c/dom/events/DocumentEvent.java
4312
/* * 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 and, per its terms, should not be removed: * * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; import org.w3c.dom.DOMException; /** * The <code>DocumentEvent</code> interface provides a mechanism by which the * user can create an Event of a type supported by the implementation. It is * expected that the <code>DocumentEvent</code> interface will be * implemented on the same object which implements the <code>Document</code> * interface in an implementation which supports the Event model. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since 1.5, DOM Level 2 */ public interface DocumentEvent { /** * * @param eventType The <code>eventType</code> parameter specifies the * type of <code>Event</code> interface to be created. If the * <code>Event</code> interface specified is supported by the * implementation this method will return a new <code>Event</code> of * the interface type requested. If the <code>Event</code> is to be * dispatched via the <code>dispatchEvent</code> method the * appropriate event init method must be called after creation in * order to initialize the <code>Event</code>'s values. As an example, * a user wishing to synthesize some kind of <code>UIEvent</code> * would call <code>createEvent</code> with the parameter "UIEvents". * The <code>initUIEvent</code> method could then be called on the * newly created <code>UIEvent</code> to set the specific type of * UIEvent to be dispatched and set its context information.The * <code>createEvent</code> method is used in creating * <code>Event</code>s when it is either inconvenient or unnecessary * for the user to create an <code>Event</code> themselves. In cases * where the implementation provided <code>Event</code> is * insufficient, users may supply their own <code>Event</code> * implementations for use with the <code>dispatchEvent</code> method. * @return The newly created <code>Event</code> * @exception DOMException * NOT_SUPPORTED_ERR: Raised if the implementation does not support the * type of <code>Event</code> interface requested */ public Event createEvent(String eventType) throws DOMException; }
gpl-2.0
marktriggs/nyu-sakai-10.4
samigo/samigo-hibernate/src/java/org/sakaiproject/tool/assessment/data/dao/assessment/AssessmentAccessControl.java
12150
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.assessment.data.dao.assessment; import org.sakaiproject.tool.assessment.data.dao.authz.AuthorizationData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentBaseIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentTemplateIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc; //import org.sakaiproject.tool.assessment.facade.AuthzQueriesFacadeAPI; //import org.sakaiproject.tool.assessment.services.PersistenceService; import java.util.Date; import java.util.Iterator; import java.util.List; /** * This keeps track of the submission scheme, and the number allowed. * * @author Rachel Gollub */ public class AssessmentAccessControl implements java.io.Serializable, AssessmentAccessControlIfc { // keep in mind that this id can be an assesmentId or assessmentTemplateId. // This depends on the AssessmentBase object (superclass of AssessmentData and // AssessmentTemplateData) that is associated with it. /** * */ private static final long serialVersionUID = 8330416434678491916L; // flag it when no editing on the property is desire public static final Integer NO_EDIT = Integer.valueOf(-1); // timedAssessment public static final Integer TIMED_ASSESSMENT = Integer.valueOf(1); public static final Integer DO_NOT_TIMED_ASSESSMENT = Integer.valueOf(0); // autoSubmit public static final Integer AUTO_SUBMIT = Integer.valueOf(1); public static final Integer DO_NOT_AUTO_SUBMIT = Integer.valueOf(0); // autoSave public static final Integer SAVE_ON_CLICK = Integer.valueOf(1); public static final Integer AUTO_SAVE = Integer.valueOf(2); // itemNavigation public static final Integer LINEAR_ACCESS = Integer.valueOf(1); public static final Integer RANDOM_ACCESS = Integer.valueOf(2); // assessmentFormat public static final Integer BY_QUESTION = Integer.valueOf(1); public static final Integer BY_PART = Integer.valueOf(2); public static final Integer BY_ASSESSMENT = Integer.valueOf(3); // itemNumbering public static final Integer CONTINUOUS_NUMBERING = Integer.valueOf(1); public static final Integer RESTART_NUMBERING_BY_PART = Integer.valueOf(2); // markForReview public static final Integer MARK_FOR_REVIEW = Integer.valueOf(1); public static final Integer NOT_MARK_FOR_REVIEW = Integer.valueOf(0); // submissionsAllowed public static final Integer UNLIMITED_SUBMISSIONS_ALLOWED = Integer.valueOf(9999); // lateHandling public static final Integer ACCEPT_LATE_SUBMISSION = Integer.valueOf(1); public static final Integer NOT_ACCEPT_LATE_SUBMISSION = Integer.valueOf(2); private Long id; private AssessmentBaseIfc assessmentBase; private Integer submissionsAllowed; private Boolean unlimitedSubmissions; private Integer submissionsSaved; private Integer assessmentFormat; private Integer bookMarkingItem; private Integer timeLimit; private Integer timedAssessment; private Integer retryAllowed; private Integer lateHandling; private Date startDate; private Date dueDate; private Date scoreDate; private Date feedbackDate; private Date retractDate; private Integer autoSubmit; // auto submit when time expires private Integer itemNavigation; // linear (1)or random (0) private Integer itemNumbering; // continuous between parts(1), restart between parts(0) private String submissionMessage; private String finalPageUrl; private String releaseTo; private String username; private String password; private Integer markForReview; /** * Creates a new SubmissionModel object. */ public AssessmentAccessControl() { this.submissionsAllowed = Integer.valueOf(9999); // = no limit this.submissionsSaved = Integer.valueOf(1); // no. of copy } public AssessmentAccessControl(Integer submissionsAllowed, Integer submissionsSaved, Integer assessmentFormat, Integer bookMarkingItem, Integer timeLimit, Integer timedAssessment, Integer retryAllowed, Integer lateHandling, Date startDate, Date dueDate, Date scoreDate, Date feedbackDate, Date retractDate, Integer autoSubmit, Integer itemNavigation, Integer itemNumbering, String submissionMessage, String releaseTo) { this.submissionsAllowed = submissionsAllowed; // = no limit this.submissionsSaved = submissionsSaved; // no. of copy this.assessmentFormat = assessmentFormat; this.bookMarkingItem = bookMarkingItem; this.timeLimit = timeLimit; this.timedAssessment = timedAssessment; this.retryAllowed = retryAllowed; // cannot edit(0) this.lateHandling = lateHandling; // cannot edit(0) this.startDate = startDate; this.dueDate = dueDate; this.scoreDate = scoreDate; this.feedbackDate = feedbackDate; this.retractDate = retractDate; this.autoSubmit = autoSubmit; // cannot edit (0) auto submit(1) when time expires (2) this.itemNavigation = itemNavigation; // cannot edit (0) linear(1) or random (2) this.itemNumbering = itemNumbering; // cannot edit(0) continuous between parts (1), restart between parts (2) this.submissionMessage = submissionMessage; this.releaseTo = releaseTo; } public Object clone() throws CloneNotSupportedException{ Object cloned = new AssessmentAccessControl( this.getSubmissionsAllowed(), this.getSubmissionsSaved(), this.getAssessmentFormat(), this.getBookMarkingItem(), this.getTimeLimit(), this.getTimedAssessment(), this.getRetryAllowed(), this.getLateHandling(), this.getStartDate(), this.getDueDate(), this.getScoreDate(), this.getFeedbackDate(), this.getRetractDate(), this.getAutoSubmit(), this.getItemNavigation(), this.getItemNumbering(), this.getSubmissionMessage(), this.getReleaseTo()); ((AssessmentAccessControl)cloned).setRetractDate(this.retractDate); ((AssessmentAccessControl)cloned).setAutoSubmit(this.autoSubmit); ((AssessmentAccessControl)cloned).setItemNavigation(this.itemNavigation); ((AssessmentAccessControl)cloned).setItemNumbering(this.itemNumbering); ((AssessmentAccessControl)cloned).setSubmissionMessage(this.submissionMessage); ((AssessmentAccessControl)cloned).setUsername(this.username); ((AssessmentAccessControl)cloned).setPassword(this.password); ((AssessmentAccessControl)cloned).setFinalPageUrl(this.finalPageUrl); ((AssessmentAccessControl)cloned).setUnlimitedSubmissions(this.unlimitedSubmissions); ((AssessmentAccessControl)cloned).setMarkForReview(this.markForReview); return cloned; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setAssessmentBase(AssessmentBaseIfc assessmentBase) { this.assessmentBase = assessmentBase; } public AssessmentBaseIfc getAssessmentBase() { if (assessmentBase.getIsTemplate().equals(Boolean.TRUE)) return (AssessmentTemplateIfc)assessmentBase; else return (AssessmentIfc)assessmentBase; } public Integer getSubmissionsAllowed() { return submissionsAllowed; } public void setSubmissionsAllowed(Integer psubmissionsAllowed) { submissionsAllowed = psubmissionsAllowed; } public Integer getSubmissionsSaved() { return submissionsSaved; } public void setSubmissionsSaved(Integer psubmissionsSaved) { submissionsSaved = psubmissionsSaved; } public Integer getAssessmentFormat() { return assessmentFormat; } public void setAssessmentFormat(Integer assessmentFormat) { this.assessmentFormat = assessmentFormat; } public Integer getBookMarkingItem() { return bookMarkingItem; } public void setBookMarkingItem(Integer bookMarkingItem) { this.bookMarkingItem = bookMarkingItem; } public Integer getTimeLimit() { return timeLimit; } public void setTimeLimit(Integer timeLimit) { this.timeLimit = timeLimit; } public Integer getTimedAssessment() { return timedAssessment; } public void setTimedAssessment(Integer timedAssessment) { this.timedAssessment = timedAssessment; } public void setRetryAllowed(Integer retryAllowed) { this.retryAllowed = retryAllowed; } public Integer getRetryAllowed() { return retryAllowed; } public void setLateHandling(Integer lateHandling) { this.lateHandling = lateHandling; } public Integer getLateHandling() { return lateHandling; } public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getDueDate() { return this.dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public Date getScoreDate() { return this.scoreDate; } public void setScoreDate(Date scoreDate) { this.scoreDate = scoreDate; } public Date getFeedbackDate() { return this.feedbackDate; } public void setFeedbackDate(Date feedbackDate) { this.feedbackDate = feedbackDate; } public Date getRetractDate() { return this.retractDate; } public void setRetractDate(Date retractDate) { this.retractDate = retractDate; } public void setAutoSubmit(Integer autoSubmit) { this.autoSubmit = autoSubmit; } public Integer getAutoSubmit() { return autoSubmit; } public void setItemNavigation(Integer itemNavigation) { this.itemNavigation = itemNavigation; } public Integer getItemNavigation() { return itemNavigation; } public void setItemNumbering(Integer itemNumbering) { this.itemNumbering = itemNumbering; } public Integer getItemNumbering() { return itemNumbering; } public void setSubmissionMessage(String submissionMessage) { this.submissionMessage = submissionMessage; } public String getSubmissionMessage() { return submissionMessage; } public void setFinalPageUrl(String finalPageUrl) { this.finalPageUrl = finalPageUrl; } public String getFinalPageUrl() { return finalPageUrl; } public String getReleaseTo() { return this.releaseTo; } public void setReleaseTo(String releaseTo) { this.releaseTo = releaseTo; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Boolean getUnlimitedSubmissions() { return this.unlimitedSubmissions; } public void setUnlimitedSubmissions(Boolean unlimitedSubmissions) { this.unlimitedSubmissions = unlimitedSubmissions; } public Integer getMarkForReview() { return this.markForReview; } public void setMarkForReview(Integer markForReview) { this.markForReview = markForReview; } }
apache-2.0
cloudbearings/BroadleafCommerce
common/src/main/java/org/broadleafcommerce/common/vendor/service/monitor/ServiceMonitor.java
3467
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.common.vendor.service.monitor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.broadleafcommerce.common.vendor.service.monitor.handler.LogStatusHandler; import org.broadleafcommerce.common.vendor.service.type.ServiceStatusType; import java.util.HashMap; import java.util.Map; public class ServiceMonitor { private static final Log LOG = LogFactory.getLog(ServiceMonitor.class); protected Map<ServiceStatusDetectable, StatusHandler> serviceHandlers = new HashMap<ServiceStatusDetectable, StatusHandler>(); protected StatusHandler defaultHandler = new LogStatusHandler(); protected Map<ServiceStatusDetectable, ServiceStatusType> statusMap = new HashMap<ServiceStatusDetectable, ServiceStatusType>(); public synchronized void init() { for (ServiceStatusDetectable statusDetectable : serviceHandlers.keySet()) { checkService(statusDetectable); } } public Object checkServiceAOP(ProceedingJoinPoint call) throws Throwable { try { checkService((ServiceStatusDetectable) call.getThis()); } catch (Throwable e) { LOG.error("Could not check service status", e); } return call.proceed(); } public void checkService(ServiceStatusDetectable statusDetectable) { ServiceStatusType type = statusDetectable.getServiceStatus(); if (!statusMap.containsKey(statusDetectable)) { statusMap.put(statusDetectable, type); if (type.equals(ServiceStatusType.DOWN)) { handleStatusChange(statusDetectable, type); } } if (!statusMap.get(statusDetectable).equals(type)) { handleStatusChange(statusDetectable, type); statusMap.put(statusDetectable, type); } } protected void handleStatusChange(ServiceStatusDetectable serviceStatus, ServiceStatusType serviceStatusType) { if (serviceHandlers.containsKey(serviceStatus)) { serviceHandlers.get(serviceStatus).handleStatus(serviceStatus.getServiceName(), serviceStatusType); } else { defaultHandler.handleStatus(serviceStatus.getServiceName(), serviceStatusType); } } public Map<ServiceStatusDetectable, StatusHandler> getServiceHandlers() { return serviceHandlers; } public void setServiceHandlers(Map<ServiceStatusDetectable, StatusHandler> serviceHandlers) { this.serviceHandlers = serviceHandlers; } public StatusHandler getDefaultHandler() { return defaultHandler; } public void setDefaultHandler(StatusHandler defaultHandler) { this.defaultHandler = defaultHandler; } }
apache-2.0
sheofir/aws-sdk-java
aws-java-sdk-sts/src/main/java/com/amazonaws/services/securitytoken/model/transform/GetSessionTokenRequestMarshaller.java
2315
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.securitytoken.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.internal.ListWithAutoConstructFlag; import com.amazonaws.services.securitytoken.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Get Session Token Request Marshaller */ public class GetSessionTokenRequestMarshaller implements Marshaller<Request<GetSessionTokenRequest>, GetSessionTokenRequest> { public Request<GetSessionTokenRequest> marshall(GetSessionTokenRequest getSessionTokenRequest) { if (getSessionTokenRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<GetSessionTokenRequest> request = new DefaultRequest<GetSessionTokenRequest>(getSessionTokenRequest, "AWSSecurityTokenService"); request.addParameter("Action", "GetSessionToken"); request.addParameter("Version", "2011-06-15"); if (getSessionTokenRequest.getDurationSeconds() != null) { request.addParameter("DurationSeconds", StringUtils.fromInteger(getSessionTokenRequest.getDurationSeconds())); } if (getSessionTokenRequest.getSerialNumber() != null) { request.addParameter("SerialNumber", StringUtils.fromString(getSessionTokenRequest.getSerialNumber())); } if (getSessionTokenRequest.getTokenCode() != null) { request.addParameter("TokenCode", StringUtils.fromString(getSessionTokenRequest.getTokenCode())); } return request; } }
apache-2.0
haikuowuya/android_system_code
src/android/widget/ExpandableListAdapter.java
8297
/* * Copyright (C) 2007 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 android.widget; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; /** * An adapter that links a {@link ExpandableListView} with the underlying * data. The implementation of this interface will provide access * to the data of the children (categorized by groups), and also instantiate * {@link View}s for children and groups. */ public interface ExpandableListAdapter { /** * @see Adapter#registerDataSetObserver(DataSetObserver) */ void registerDataSetObserver(DataSetObserver observer); /** * @see Adapter#unregisterDataSetObserver(DataSetObserver) */ void unregisterDataSetObserver(DataSetObserver observer); /** * Gets the number of groups. * * @return the number of groups */ int getGroupCount(); /** * Gets the number of children in a specified group. * * @param groupPosition the position of the group for which the children * count should be returned * @return the children count in the specified group */ int getChildrenCount(int groupPosition); /** * Gets the data associated with the given group. * * @param groupPosition the position of the group * @return the data child for the specified group */ Object getGroup(int groupPosition); /** * Gets the data associated with the given child within the given group. * * @param groupPosition the position of the group that the child resides in * @param childPosition the position of the child with respect to other * children in the group * @return the data of the child */ Object getChild(int groupPosition, int childPosition); /** * Gets the ID for the group at the given position. This group ID must be * unique across groups. The combined ID (see * {@link #getCombinedGroupId(long)}) must be unique across ALL items * (groups and all children). * * @param groupPosition the position of the group for which the ID is wanted * @return the ID associated with the group */ long getGroupId(int groupPosition); /** * Gets the ID for the given child within the given group. This ID must be * unique across all children within the group. The combined ID (see * {@link #getCombinedChildId(long, long)}) must be unique across ALL items * (groups and all children). * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child within the group for which * the ID is wanted * @return the ID associated with the child */ long getChildId(int groupPosition, int childPosition); /** * Indicates whether the child and group IDs are stable across changes to the * underlying data. * * @return whether or not the same ID always refers to the same object * @see Adapter#hasStableIds() */ boolean hasStableIds(); /** * Gets a View that displays the given group. This View is only for the * group--the Views for the group's children will be fetched using * {@link #getChildView(int, int, boolean, View, ViewGroup)}. * * @param groupPosition the position of the group for which the View is * returned * @param isExpanded whether the group is expanded or collapsed * @param convertView the old view to reuse, if possible. You should check * that this view is non-null and of an appropriate type before * using. If it is not possible to convert this view to display * the correct data, this method can create a new view. It is not * guaranteed that the convertView will have been previously * created by * {@link #getGroupView(int, boolean, View, ViewGroup)}. * @param parent the parent that this view will eventually be attached to * @return the View corresponding to the group at the specified position */ View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent); /** * Gets a View that displays the data for the given child within the given * group. * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child (for which the View is * returned) within the group * @param isLastChild Whether the child is the last child within the group * @param convertView the old view to reuse, if possible. You should check * that this view is non-null and of an appropriate type before * using. If it is not possible to convert this view to display * the correct data, this method can create a new view. It is not * guaranteed that the convertView will have been previously * created by * {@link #getChildView(int, int, boolean, View, ViewGroup)}. * @param parent the parent that this view will eventually be attached to * @return the View corresponding to the child at the specified position */ View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent); /** * Whether the child at the specified position is selectable. * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child within the group * @return whether the child is selectable. */ boolean isChildSelectable(int groupPosition, int childPosition); /** * @see ListAdapter#areAllItemsEnabled() */ boolean areAllItemsEnabled(); /** * @see ListAdapter#isEmpty() */ boolean isEmpty(); /** * Called when a group is expanded. * * @param groupPosition The group being expanded. */ void onGroupExpanded(int groupPosition); /** * Called when a group is collapsed. * * @param groupPosition The group being collapsed. */ void onGroupCollapsed(int groupPosition); /** * Gets an ID for a child that is unique across any item (either group or * child) that is in this list. Expandable lists require each item (group or * child) to have a unique ID among all children and groups in the list. * This method is responsible for returning that unique ID given a child's * ID and its group's ID. Furthermore, if {@link #hasStableIds()} is true, the * returned ID must be stable as well. * * @param groupId The ID of the group that contains this child. * @param childId The ID of the child. * @return The unique (and possibly stable) ID of the child across all * groups and children in this list. */ long getCombinedChildId(long groupId, long childId); /** * Gets an ID for a group that is unique across any item (either group or * child) that is in this list. Expandable lists require each item (group or * child) to have a unique ID among all children and groups in the list. * This method is responsible for returning that unique ID given a group's * ID. Furthermore, if {@link #hasStableIds()} is true, the returned ID must be * stable as well. * * @param groupId The ID of the group * @return The unique (and possibly stable) ID of the group across all * groups and children in this list. */ long getCombinedGroupId(long groupId); }
apache-2.0
guodroid/okwallet
wallet/src/org/bitcoinj/wallet/listeners/KeyChainEventListener.java
1093
/* * Copyright 2013 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.bitcoinj.wallet.listeners; import org.bitcoinj.core.ECKey; import org.bitcoinj.wallet.KeyChain; import java.util.List; public interface KeyChainEventListener { /** * Called whenever a new key is added to the key chain, whether that be via an explicit addition or due to some * other automatic derivation. See the documentation for your {@link KeyChain} implementation for details on what * can trigger this event. */ void onKeysAdded(List<ECKey> keys); }
apache-2.0
panchenko/spring-security
acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java
4994
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.security.acls.domain; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; import java.io.Serializable; /** * An immutable default implementation of <code>AccessControlEntry</code>. * * @author Ben Alex */ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAccessControlEntry { // ~ Instance fields // ================================================================================================ private final Acl acl; private Permission permission; private final Serializable id; private final Sid sid; private boolean auditFailure = false; private boolean auditSuccess = false; private final boolean granting; // ~ Constructors // =================================================================================================== public AccessControlEntryImpl(Serializable id, Acl acl, Sid sid, Permission permission, boolean granting, boolean auditSuccess, boolean auditFailure) { Assert.notNull(acl, "Acl required"); Assert.notNull(sid, "Sid required"); Assert.notNull(permission, "Permission required"); this.id = id; this.acl = acl; // can be null this.sid = sid; this.permission = permission; this.granting = granting; this.auditSuccess = auditSuccess; this.auditFailure = auditFailure; } // ~ Methods // ======================================================================================================== public boolean equals(Object arg0) { if (!(arg0 instanceof AccessControlEntryImpl)) { return false; } AccessControlEntryImpl rhs = (AccessControlEntryImpl) arg0; if (this.acl == null) { if (rhs.getAcl() != null) { return false; } // Both this.acl and rhs.acl are null and thus equal } else { // this.acl is non-null if (rhs.getAcl() == null) { return false; } // Both this.acl and rhs.acl are non-null, so do a comparison if (this.acl.getObjectIdentity() == null) { if (rhs.acl.getObjectIdentity() != null) { return false; } // Both this.acl and rhs.acl are null and thus equal } else { // Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null if (!this.acl.getObjectIdentity() .equals(rhs.getAcl().getObjectIdentity())) { return false; } } } if (this.id == null) { if (rhs.id != null) { return false; } // Both this.id and rhs.id are null and thus equal } else { // this.id is non-null if (rhs.id == null) { return false; } // Both this.id and rhs.id are non-null if (!this.id.equals(rhs.id)) { return false; } } if ((this.auditFailure != rhs.isAuditFailure()) || (this.auditSuccess != rhs.isAuditSuccess()) || (this.granting != rhs.isGranting()) || !this.permission.equals(rhs.getPermission()) || !this.sid.equals(rhs.getSid())) { return false; } return true; } public Acl getAcl() { return acl; } public Serializable getId() { return id; } public Permission getPermission() { return permission; } public Sid getSid() { return sid; } public boolean isAuditFailure() { return auditFailure; } public boolean isAuditSuccess() { return auditSuccess; } public boolean isGranting() { return granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
apache-2.0
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/gnu/java/nio/charset/iconv/IconvCharset.java
2634
/* IconvCharset.java -- Wrapper for iconv charsets. Copyright (C) 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.nio.charset.iconv; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; public final class IconvCharset extends Charset { private IconvMetaData info; public IconvCharset(IconvMetaData info) { super(info.nioCanonical(), info.aliases()); this.info = info; if (newEncoder() == null || newDecoder() == null) throw new IllegalArgumentException(); } public boolean contains(Charset cs) { return false; } public CharsetDecoder newDecoder() { try { return new IconvDecoder(this, info); } catch (IllegalArgumentException e) { return null; } } public CharsetEncoder newEncoder() { try { return new IconvEncoder(this, info); } catch (IllegalArgumentException e) { return null; } } }
bsd-3-clause
anoordover/camel
components/camel-azure/src/main/java/org/apache/camel/component/azure/queue/QueueServiceEndpoint.java
2923
/** * 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.azure.queue; import org.apache.camel.Component; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The azure-queue component is used for storing and retrieving messages from Azure Storage Queue Service. */ @UriEndpoint(firstVersion = "2.19.0", scheme = "azure-queue", title = "Azure Storage Queue Service", syntax = "azure-blob:containerAndQueueUri", consumerClass = QueueServiceConsumer.class, label = "cloud,queue,azure") public class QueueServiceEndpoint extends DefaultEndpoint { private static final Logger LOG = LoggerFactory.getLogger(QueueServiceEndpoint.class); @UriPath(description = "Container Queue compact Uri") @Metadata(required = "true") private String containerAndQueueUri; // to support component docs @UriParam private QueueServiceConfiguration configuration; public QueueServiceEndpoint(String uri, Component comp, QueueServiceConfiguration configuration) { super(uri, comp); this.configuration = configuration; } public Consumer createConsumer(Processor processor) throws Exception { LOG.trace("Creating a consumer"); QueueServiceConsumer consumer = new QueueServiceConsumer(this, processor); configureConsumer(consumer); return consumer; } public Producer createProducer() throws Exception { LOG.trace("Creating a producer"); return new QueueServiceProducer(this); } public boolean isSingleton() { return true; } public QueueServiceConfiguration getConfiguration() { return configuration; } public void setConfiguration(QueueServiceConfiguration configuration) { this.configuration = configuration; } }
apache-2.0
apratkin/pentaho-kettle
core/src/org/pentaho/di/core/database/KingbaseESDatabaseMeta.java
18815
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.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 org.pentaho.di.core.database; import org.pentaho.di.core.Const; import org.pentaho.di.core.row.ValueMetaInterface; /** * Contains Firebird specific information through static final members * * @author jjchu * @since 21-03-2008 */ public class KingbaseESDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface { /** * @return The extra option separator in database URL for this platform */ @Override public String getExtraOptionSeparator() { return "&"; } /** * @return This indicator separates the normal URL from the options */ @Override public String getExtraOptionIndicator() { return "?"; } @Override public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC }; } @Override public int getDefaultDatabasePort() { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) { return 54321; } return -1; } @Override public String getDriverClass() { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) { return "sun.jdbc.odbc.JdbcOdbcDriver"; } else { return "com.kingbase.Driver"; } } @Override public String getURL( String hostname, String port, String databaseName ) { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) { return "jdbc:odbc:" + getDatabaseName(); } else { return "jdbc:kingbase://" + hostname + ":" + port + "/" + databaseName; } } /** * Checks whether or not the command setFetchSize() is supported by the JDBC driver... * * @return true is setFetchSize() is supported! */ @Override public boolean isFetchSizeSupported() { return true; } /** * @return true if the database supports bitmap indexes */ @Override public boolean supportsBitmapIndex() { return false; } /** * @return true if the database supports synonyms */ @Override public boolean supportsSynonyms() { return false; } @Override public boolean supportsSequences() { return true; } /** * Kingbase only support the data type: serial, it is not a real autoInc */ @Override public boolean supportsAutoInc() { return false; } @Override public String getLimitClause( int nrRows ) { return " limit " + nrRows; } /** * Get the SQL to get the next value of a sequence. * * @param sequenceName * The sequence name * @return the SQL to get the next value of a sequence. */ @Override public String getSQLNextSequenceValue( String sequenceName ) { return "SELECT nextval('" + sequenceName + "')"; } /** * Get the SQL to get the next value of a sequence. * * @param sequenceName * The sequence name * @return the SQL to get the next value of a sequence. */ @Override public String getSQLCurrentSequenceValue( String sequenceName ) { return "SELECT currval('" + sequenceName + "')"; } /** * Check if a sequence exists. * * @param sequenceName * The sequence to check * @return The SQL to get the name of the sequence back from the databases data dictionary */ @Override public String getSQLSequenceExists( String sequenceName ) { return "SELECT relname AS sequence_name FROM sys_class WHERE relname = '" + sequenceName.toLowerCase() + "'"; } /** * Generates the SQL statement to add a column to the specified table * * @param tablename * The table to add * @param v * The column defined as a value * @param tk * the name of the technical key field * @param use_autoinc * whether or not this field uses auto increment * @param pk * the name of the primary key field * @param semicolon * whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ @Override public String getAddColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " ADD COLUMN " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); } /** * Generates the SQL statement to drop a column from the specified table * * @param tablename * The table to add * @param v * The column defined as a value * @param tk * the name of the technical key field * @param use_autoinc * whether or not this field uses auto increment * @param pk * the name of the primary key field * @param semicolon * whether or not to add a semi-colon behind the statement. * @return the SQL statement to drop a column from the specified table */ @Override public String getDropColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " DROP COLUMN " + v.getName() + Const.CR; } /** * Generates the SQL statement to modify a column in the specified table * * @param tablename * The table to add * @param v * The column defined as a value * @param tk * the name of the technical key field * @param use_autoinc * whether or not this field uses auto increment * @param pk * the name of the primary key field * @param semicolon * whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ @Override public String getModifyColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { String retval = ""; retval += "ALTER TABLE " + tablename + " DROP COLUMN " + v.getName() + Const.CR + ";" + Const.CR; retval += "ALTER TABLE " + tablename + " ADD COLUMN " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); return retval; } @Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if ( add_fieldname ) { retval += fieldname + " "; } int type = v.getType(); switch ( type ) { case ValueMetaInterface.TYPE_DATE: retval += "TIMESTAMP"; break; case ValueMetaInterface.TYPE_BOOLEAN: if ( supportsBooleanDataType() ) { retval += "BOOLEAN"; } else { retval += "CHAR(1)"; } break; case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_BIGNUMBER: if ( fieldname.equalsIgnoreCase( tk ) || // Technical key fieldname.equalsIgnoreCase( pk ) // Primary key ) { retval += "BIGSERIAL"; } else { if ( length > 0 ) { if ( precision > 0 || length > 18 ) { retval += "NUMERIC(" + length + ", " + precision + ")"; } else { if ( length > 9 ) { retval += "BIGINT"; } else { if ( length < 5 ) { retval += "SMALLINT"; } else { retval += "INTEGER"; } } } } else { retval += "DOUBLE PRECISION"; } } break; case ValueMetaInterface.TYPE_STRING: if ( length < 1 || length >= DatabaseMeta.CLOB_LENGTH ) { retval += "TEXT"; } else { retval += "VARCHAR(" + length + ")"; } break; default: retval += " UNKNOWN"; break; } if ( add_cr ) { retval += Const.CR; } return retval; } /** * @param the * schema name to search in or null if you want to search the whole DB * @return The SQL on this database to get a list of stored procedures. */ public String getSQLListOfProcedures( String schemaName ) { return "select proname " + "from sys_proc, sys_user " + "where sys_user.usesysid = sys_proc.proowner " + "and upper(sys_user.usename) = '" + getUsername().toUpperCase() + "'"; } /* * (non-Javadoc) * * @see com.kingbase.ketl.core.database.DatabaseInterface#getReservedWords() */ @Override public String[] getReservedWords() { return new String[] { // http://www.postgresql.org/docs/8.1/static/sql-keywords-appendix.html // added also non-reserved key words because there is progress from the Postgre developers to add them "A", "ABORT", "ABS", "ABSOLUTE", "ACCESS", "ACTION", "ADA", "ADD", "ADMIN", "AFTER", "AGGREGATE", "ALIAS", "ALL", "ALLOCATE", "ALSO", "ALTER", "ALWAYS", "ANALYSE", "ANALYZE", "AND", "ANY", "ARE", "ARRAY", "AS", "ASC", "ASENSITIVE", "ASSERTION", "ASSIGNMENT", "ASYMMETRIC", "AT", "ATOMIC", "ATTRIBUTE", "ATTRIBUTES", "AUTHORIZATION", "AVG", "BACKWARD", "BEFORE", "BEGIN", "BERNOULLI", "BETWEEN", "BIGINT", "BINARY", "BIT", "BITVAR", "BIT_LENGTH", "BLOB", "BOOLEAN", "BOTH", "BREADTH", "BY", "C", "CACHE", "CALL", "CALLED", "CARDINALITY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CATALOG_NAME", "CEIL", "CEILING", "CHAIN", "CHAR", "CHARACTER", "CHARACTERISTICS", "CHARACTERS", "CHARACTER_LENGTH", "CHARACTER_SET_CATALOG", "CHARACTER_SET_NAME", "CHARACTER_SET_SCHEMA", "CHAR_LENGTH", "CHECK", "CHECKED", "CHECKPOINT", "CLASS", "CLASS_ORIGIN", "CLOB", "CLOSE", "CLUSTER", "COALESCE", "COBOL", "COLLATE", "COLLATION", "COLLATION_CATALOG", "COLLATION_NAME", "COLLATION_SCHEMA", "COLLECT", "COLUMN", "COLUMN_NAME", "COMMAND_FUNCTION", "COMMAND_FUNCTION_CODE", "COMMENT", "COMMIT", "COMMITTED", "COMPLETION", "CONDITION", "CONDITION_NUMBER", "CONNECT", "CONNECTION", "CONNECTION_NAME", "CONSTRAINT", "CONSTRAINTS", "CONSTRAINT_CATALOG", "CONSTRAINT_NAME", "CONSTRAINT_SCHEMA", "CONSTRUCTOR", "CONTAINS", "CONTINUE", "CONVERSION", "CONVERT", "COPY", "CORR", "CORRESPONDING", "COUNT", "COVAR_POP", "COVAR_SAMP", "CREATE", "CREATEDB", "CREATEROLE", "CREATEUSER", "CROSS", "CSV", "CUBE", "CUME_DIST", "CURRENT", "CURRENT_DATE", "CURRENT_DEFAULT_TRANSFORM_GROUP", "CURRENT_PATH", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_TRANSFORM_GROUP_FOR_TYPE", "CURRENT_USER", "CURSOR", "CURSOR_NAME", "CYCLE", "DATA", "DATABASE", "DATE", "DATETIME_INTERVAL_CODE", "DATETIME_INTERVAL_PRECISION", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFAULTS", "DEFERRABLE", "DEFERRED", "DEFINED", "DEFINER", "DEGREE", "DELETE", "DELIMITER", "DELIMITERS", "DENSE_RANK", "DEPTH", "DEREF", "DERIVED", "DESC", "DESCRIBE", "DESCRIPTOR", "DESTROY", "DESTRUCTOR", "DETERMINISTIC", "DIAGNOSTICS", "DICTIONARY", "DISABLE", "DISCONNECT", "DISPATCH", "DISTINCT", "DO", "DOMAIN", "DOUBLE", "DROP", "DYNAMIC", "DYNAMIC_FUNCTION", "DYNAMIC_FUNCTION_CODE", "EACH", "ELEMENT", "ELSE", "ENABLE", "ENCODING", "ENCRYPTED", "END", "END-EXEC", "EQUALS", "ESCAPE", "EVERY", "EXCEPT", "EXCEPTION", "EXCLUDE", "EXCLUDING", "EXCLUSIVE", "EXEC", "EXECUTE", "EXISTING", "EXISTS", "EXP", "EXPLAIN", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FILTER", "FINAL", "FIRST", "FLOAT", "FLOOR", "FOLLOWING", "FOR", "FORCE", "FOREIGN", "FORTRAN", "FORWARD", "FOUND", "FREE", "FREEZE", "FROM", "FULL", "FUNCTION", "FUSION", "G", "GENERAL", "GENERATED", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GRANTED", "GREATEST", "GROUP", "GROUPING", "HANDLER", "HAVING", "HEADER", "HIERARCHY", "HOLD", "HOST", "HOUR", "IDENTITY", "IGNORE", "ILIKE", "IMMEDIATE", "IMMUTABLE", "IMPLEMENTATION", "IMPLICIT", "IN", "INCLUDING", "INCREMENT", "INDEX", "INDICATOR", "INFIX", "INHERIT", "INHERITS", "INITIALIZE", "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE", "INSERT", "INSTANCE", "INSTANTIABLE", "INSTEAD", "INT", "INTEGER", "INTERSECT", "INTERSECTION", "INTERVAL", "INTO", "INVOKER", "IS", "ISNULL", "ISOLATION", "ITERATE", "JOIN", "K", "KEY", "KEY_MEMBER", "KEY_TYPE", "LANCOMPILER", "LANGUAGE", "LARGE", "LAST", "LATERAL", "LEADING", "LEAST", "LEFT", "LENGTH", "LESS", "LEVEL", "LIKE", "LIMIT", "LISTEN", "LN", "LOAD", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATION", "LOCATOR", "LOCK", "LOGIN", "LOWER", "M", "MAP", "MATCH", "MATCHED", "MAX", "MAXVALUE", "MEMBER", "MERGE", "MESSAGE_LENGTH", "MESSAGE_OCTET_LENGTH", "MESSAGE_TEXT", "METHOD", "MIN", "MINUTE", "MINVALUE", "MOD", "MODE", "MODIFIES", "MODIFY", "MODULE", "MONTH", "MORE", "MOVE", "MULTISET", "MUMPS", "NAME", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NESTING", "NEW", "NEXT", "NO", "NOCREATEDB", "NOCREATEROLE", "NOCREATEUSER", "NOINHERIT", "NOLOGIN", "NONE", "NORMALIZE", "NORMALIZED", "NOSUPERUSER", "NOT", "NOTHING", "NOTIFY", "NOTNULL", "NOWAIT", "NULL", "NULLABLE", "NULLIF", "NULLS", "NUMBER", "NUMERIC", "OBJECT", "OCTETS", "OCTET_LENGTH", "OF", "OFF", "OFFSET", "OIDS", "OLD", "ON", "ONLY", "OPEN", "OPERATION", "OPERATOR", "OPTION", "OPTIONS", "OR", "ORDER", "ORDERING", "ORDINALITY", "OTHERS", "OUT", "OUTER", "OUTPUT", "OVER", "OVERLAPS", "OVERLAY", "OVERRIDING", "OWNER", "PAD", "PARAMETER", "PARAMETERS", "PARAMETER_MODE", "PARAMETER_NAME", "PARAMETER_ORDINAL_POSITION", "PARAMETER_SPECIFIC_CATALOG", "PARAMETER_SPECIFIC_NAME", "PARAMETER_SPECIFIC_SCHEMA", "PARTIAL", "PARTITION", "PASCAL", "PASSWORD", "PATH", "PERCENTILE_CONT", "PERCENTILE_DISC", "PERCENT_RANK", "PLACING", "PLI", "POSITION", "POSTFIX", "POWER", "PRECEDING", "PRECISION", "PREFIX", "PREORDER", "PREPARE", "PREPARED", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURAL", "PROCEDURE", "PUBLIC", "QUOTE", "RANGE", "RANK", "READ", "READS", "REAL", "RECHECK", "RECURSIVE", "REF", "REFERENCES", "REFERENCING", "REGR_AVGX", "REGR_AVGY", "REGR_COUNT", "REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX", "REGR_SXY", "REGR_SYY", "REINDEX", "RELATIVE", "RELEASE", "RENAME", "REPEATABLE", "REPLACE", "RESET", "RESTART", "RESTRICT", "RESULT", "RETURN", "RETURNED_CARDINALITY", "RETURNED_LENGTH", "RETURNED_OCTET_LENGTH", "RETURNED_SQLSTATE", "RETURNS", "REVOKE", "RIGHT", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE", "ROUTINE_CATALOG", "ROUTINE_NAME", "ROUTINE_SCHEMA", "ROW", "ROWS", "ROW_COUNT", "ROW_NUMBER", "RULE", "SAVEPOINT", "SCALE", "SCHEMA", "SCHEMA_NAME", "SCOPE", "SCOPE_CATALOG", "SCOPE_NAME", "SCOPE_SCHEMA", "SCROLL", "SEARCH", "SECOND", "SECTION", "SECURITY", "SELECT", "SELF", "SENSITIVE", "SEQUENCE", "SERIALIZABLE", "SERVER_NAME", "SESSION", "SESSION_USER", "SET", "SETOF", "SETS", "SHARE", "SHOW", "SIMILAR", "SIMPLE", "SIZE", "SMALLINT", "SOME", "SOURCE", "SPACE", "SPECIFIC", "SPECIFICTYPE", "SPECIFIC_NAME", "SQL", "SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQRT", "STABLE", "START", "STATE", "STATEMENT", "STATIC", "STATISTICS", "STDDEV_POP", "STDDEV_SAMP", "STDIN", "STDOUT", "STORAGE", "STRICT", "STRUCTURE", "STYLE", "SUBCLASS_ORIGIN", "SUBLIST", "SUBMULTISET", "SUBSTRING", "SUM", "SUPERUSER", "SYMMETRIC", "SYSID", "SYSTEM", "SYSTEM_USER", "TABLE", "TABLESAMPLE", "TABLESPACE", "TABLE_NAME", "TEMP", "TEMPLATE", "TEMPORARY", "TERMINATE", "THAN", "THEN", "TIES", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TOAST", "TOP_LEVEL_COUNT", "TRAILING", "TRANSACTION", "TRANSACTIONS_COMMITTED", "TRANSACTIONS_ROLLED_BACK", "TRANSACTION_ACTIVE", "TRANSFORM", "TRANSFORMS", "TRANSLATE", "TRANSLATION", "TREAT", "TRIGGER", "TRIGGER_CATALOG", "TRIGGER_NAME", "TRIGGER_SCHEMA", "TRIM", "TRUE", "TRUNCATE", "TRUSTED", "TYPE", "UESCAPE", "UNBOUNDED", "UNCOMMITTED", "UNDER", "UNENCRYPTED", "UNION", "UNIQUE", "UNKNOWN", "UNLISTEN", "UNNAMED", "UNNEST", "UNTIL", "UPDATE", "UPPER", "USAGE", "USER", "USER_DEFINED_TYPE_CATALOG", "USER_DEFINED_TYPE_CODE", "USER_DEFINED_TYPE_NAME", "USER_DEFINED_TYPE_SCHEMA", "USING", "VACUUM", "VALID", "VALIDATOR", "VALUE", "VALUES", "VARCHAR", "VARIABLE", "VARYING", "VAR_POP", "VAR_SAMP", "VERBOSE", "VIEW", "VOLATILE", "WHEN", "WHENEVER", "WHERE", "WIDTH_BUCKET", "WINDOW", "WITH", "WITHIN", "WITHOUT", "WORK", "WRITE", "YEAR", "ZONE" }; } /** * @param tableNames * The names of the tables to lock * @return The SQL commands to lock database tables for write purposes. */ @Override public String getSQLLockTables( String[] tableNames ) { String sql = "LOCK TABLE "; for ( int i = 0; i < tableNames.length; i++ ) { if ( i > 0 ) { sql += ", "; } sql += tableNames[i] + " "; } sql += "IN ACCESS EXCLUSIVE MODE;" + Const.CR; return sql; } /** * @param tableName * The name of the table to unlock * @return The SQL command to unlock a database table. */ @Override public String getSQLUnlockTables( String[] tableName ) { return null; // commit unlocks everything! } /** * @return true if the database defaults to naming tables and fields in uppercase. True for most databases except for * stuborn stuff like Postgres ;-) */ @Override public boolean isDefaultingToUppercase() { return false; } @Override public String[] getUsedLibraries() { return new String[] { "kingbasejdbc4.jar" }; } /** * @return true if the database supports timestamp to date conversion. Kingbase doesn't support this! */ @Override public boolean supportsTimeStampToDateConversion() { return false; } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftSynthesizer/UnloadAllInstruments.java
2546
/* * Copyright (c) 2007, 2010, 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. */ /* @test @summary Test SoftSynthesizer unloadAllInstruments method */ import javax.sound.midi.MidiDevice; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Patch; import javax.sound.midi.Soundbank; import javax.sound.sampled.*; import javax.sound.midi.MidiDevice.Info; import com.sun.media.sound.*; public class UnloadAllInstruments { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { AudioSynthesizer synth = new SoftSynthesizer(); synth.openStream(null, null); Soundbank defsbk = synth.getDefaultSoundbank(); if(defsbk != null) { synth.unloadAllInstruments(defsbk); assertTrue(synth.getLoadedInstruments().length == 0); synth.loadAllInstruments(defsbk); assertTrue(synth.getLoadedInstruments().length != 0); synth.unloadAllInstruments(defsbk); assertTrue(synth.getLoadedInstruments().length == 0); } synth.close(); } }
mit
hatiboy/AppIntro
example/src/main/java/com/github/paolorotolo/appintroexample/indicators/ProgressIndicator.java
1260
package com.github.paolorotolo.appintroexample.indicators; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.github.paolorotolo.appintro.AppIntro; import com.github.paolorotolo.appintroexample.MainActivity; import com.github.paolorotolo.appintroexample.R; import com.github.paolorotolo.appintroexample.SampleSlide; public class ProgressIndicator extends AppIntro { @Override public void init(Bundle savedInstanceState) { addSlide(SampleSlide.newInstance(R.layout.intro)); addSlide(SampleSlide.newInstance(R.layout.intro2)); addSlide(SampleSlide.newInstance(R.layout.intro3)); addSlide(SampleSlide.newInstance(R.layout.intro4)); setProgressIndicator(); } private void loadMainActivity(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } @Override public void onSkipPressed() { loadMainActivity(); Toast.makeText(getApplicationContext(), getString(R.string.skip), Toast.LENGTH_SHORT).show(); } @Override public void onDonePressed() { loadMainActivity(); } public void getStarted(View v){ loadMainActivity(); } }
apache-2.0
dkm2110/Microsoft-cisl
lang/java/reef-common/src/main/java/org/apache/reef/driver/parameters/ServiceEvaluatorFailedHandlers.java
1380
/* * 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.reef.driver.parameters; import org.apache.reef.driver.evaluator.FailedEvaluator; import org.apache.reef.tang.annotations.Name; import org.apache.reef.tang.annotations.NamedParameter; import org.apache.reef.wake.EventHandler; import java.util.Set; /** * Called when an exception occurs on a running evaluator. */ @NamedParameter(doc = "Called when an exception occurs on a running evaluator.") public final class ServiceEvaluatorFailedHandlers implements Name<Set<EventHandler<FailedEvaluator>>> { private ServiceEvaluatorFailedHandlers() { } }
apache-2.0
madhawa-gunasekara/carbon-commons
components/ws-discovery-core/org.wso2.carbon.discovery.core/src/main/java/org/wso2/carbon/discovery/TargetServiceObserver.java
5386
/* * Copyright 2004,2005 The Apache Software 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.wso2.carbon.discovery; import org.apache.axis2.description.*; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.AxisEvent; import org.apache.axis2.engine.AxisObserver; import org.apache.axis2.AxisFault; import org.apache.axiom.om.OMElement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.discovery.util.DiscoveryMgtUtils; import org.wso2.carbon.discovery.workers.MessageSender; import org.wso2.carbon.CarbonConstants; import java.util.ArrayList; import java.util.Map; /** * This AxisObserver implementation monitors the AxisConfiguration for service * life cycle events such as service start, stop, transport binding updates and * sends WS-D notifications as necessary. */ public class TargetServiceObserver implements AxisObserver { ParameterInclude parameterInclude = null; AxisConfiguration axisConfiguration = null; private Log log = LogFactory.getLog(TargetServiceObserver.class); public TargetServiceObserver() { if (log.isDebugEnabled()) { log.debug("Initializing the TargetServiceObserver for WS-Discovery notifications"); } this.parameterInclude = new ParameterIncludeImpl(); } public void init(AxisConfiguration axisConfig) { this.axisConfiguration = axisConfig; // There may be services deployed already // We need to send Hello messages for such services // Services deployed later will be picked up by the serviceUpdate event Map<String, AxisService> services = axisConfig.getServices(); for (AxisService service : services.values()) { sendHello(service); } } private void sendHello(AxisService service) { // send the hello message MessageSender messageSender = new MessageSender(); Parameter discoveryProxyParam = DiscoveryMgtUtils.getDiscoveryParam(this.axisConfiguration); if (discoveryProxyParam != null) { if (log.isDebugEnabled()) { log.debug("Sending WS-Discovery Hello message for the " + "service " + service.getName()); } try { messageSender.sendHello(service, (String) discoveryProxyParam.getValue()); } catch (DiscoveryException e) { log.error("Cannot send the hello message ", e); } } } public void serviceUpdate(AxisEvent event, AxisService service) { int eventType = event.getEventType(); if (eventType == AxisEvent.SERVICE_START || eventType == AxisEvent.SERVICE_DEPLOY || eventType == CarbonConstants.AxisEvent.TRANSPORT_BINDING_ADDED || eventType == CarbonConstants.AxisEvent.TRANSPORT_BINDING_REMOVED) { // send the hello message sendHello(service); } else if ((event.getEventType() == AxisEvent.SERVICE_STOP) || (event.getEventType() == AxisEvent.SERVICE_REMOVE)){ // send the bye message MessageSender messageSender = new MessageSender(); Parameter discoveryProxyParam = this.axisConfiguration.getParameter(DiscoveryConstants.DISCOVERY_PROXY); if (discoveryProxyParam != null) { if (log.isDebugEnabled()) { log.debug("Sending WS-Discovery Bye message for the " + "service " + service.getName()); } try { messageSender.sendBye(service, (String) discoveryProxyParam.getValue()); } catch (DiscoveryException e) { log.error("Cannot send the bye message ", e); } } } } public void serviceGroupUpdate(AxisEvent event, AxisServiceGroup serviceGroup) { } public void moduleUpdate(AxisEvent event, AxisModule module) { } public void addParameter(Parameter param) throws AxisFault { this.parameterInclude.addParameter(param); } public void removeParameter(Parameter param) throws AxisFault { this.parameterInclude.removeParameter(param); } public void deserializeParameters(OMElement parameterElement) throws AxisFault { this.parameterInclude.deserializeParameters(parameterElement); } public Parameter getParameter(String name) { return this.parameterInclude.getParameter(name); } public ArrayList<Parameter> getParameters() { return this.parameterInclude.getParameters(); } public boolean isParameterLocked(String parameterName) { return this.parameterInclude.isParameterLocked(parameterName); } }
apache-2.0
curso007/camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpChangedRootDirReadLockFastExistCheckTest.java
1157
/** * 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.file.remote; /** * */ public class FtpChangedRootDirReadLockFastExistCheckTest extends FtpChangedRootDirReadLockTest { protected String getFtpUrl() { return "ftp://admin@localhost:" + getPort() + "/?password=admin&readLock=changed&readLockCheckInterval=1000&delete=true&fastExistsCheck=true"; } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jaxp/src/com/sun/org/apache/xerces/internal/impl/dv/ValidatedInfo.java
2890
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 2001, 2002,2004 The Apache Software 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 com.sun.org.apache.xerces.internal.impl.dv; import com.sun.org.apache.xerces.internal.xs.ShortList; /** * Class to get the information back after content is validated. This info * would be filled by validate(). * * @xerces.internal * * @author Neeraj Bajaj, Sun Microsystems, inc. * */ public class ValidatedInfo { /** * The normalized value of a string value */ public String normalizedValue; /** * The actual value from a string value (QName, Boolean, etc.) * An array of Objects if the type is a list. */ public Object actualValue; /** * The type of the actual value. It's one of the _DT constants * defined in XSConstants.java. The value is used to indicate * the most specific built-in type. * (i.e. short instead of decimal or integer). */ public short actualValueType; /** * If the type is a union type, then the member type which * actually validated the string value. */ public XSSimpleType memberType; /** * If * 1. the type is a union type where one of the member types is a list, or * if the type is a list; and * 2. the item type of the list is a union type * then an array of member types used to validate the values. */ public XSSimpleType[] memberTypes; /** * In the case the value is a list or a list of unions, this value * indicates the type(s) of the items in the list. * For a normal list, the length of the array is 1; for list of unions, * the length of the array is the same as the length of the list. */ public ShortList itemValueTypes; /** * reset the state of this object */ public void reset() { this.normalizedValue = null; this.actualValue = null; this.memberType = null; this.memberTypes = null; } /** * Return a string representation of the value. If there is an actual * value, use toString; otherwise, use the normalized value. */ public String stringValue() { if (actualValue == null) return normalizedValue; else return actualValue.toString(); } }
mit
abstractj/keycloak
testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/GreenMailRule.java
4380
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.util; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetup; import org.junit.rules.ExternalResource; import org.keycloak.models.RealmModel; import javax.mail.internet.MimeMessage; import java.lang.Thread.UncaughtExceptionHandler; import java.net.SocketException; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class GreenMailRule extends ExternalResource { private GreenMail greenMail; private int port = 3025; private String host = "localhost"; public GreenMailRule() { } public GreenMailRule(int port, String host) { this.port = port; this.host = host; } @Override protected void before() throws Throwable { ServerSetup setup = new ServerSetup(port, host, "smtp"); greenMail = new GreenMail(setup); greenMail.start(); } public void credentials(String username, String password) { greenMail.setUser(username, password); } @Override protected void after() { if (greenMail != null) { // Suppress error from GreenMail on shutdown Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (!(e.getCause() instanceof SocketException && t.getClass().getName() .equals("com.icegreen.greenmail.smtp.SmtpHandler"))) { System.err.print("Exception in thread \"" + t.getName() + "\" "); e.printStackTrace(System.err); } } }); greenMail.stop(); } } public void configureRealm(RealmModel realm) { Map<String, String> config = new HashMap<>(); config.put("from", "auto@keycloak.org"); config.put("host", "localhost"); config.put("port", "3025"); realm.setSmtpConfig(config); } public MimeMessage[] getReceivedMessages() { return greenMail.getReceivedMessages(); } /** * Returns the very last received message. When no message is available, returns {@code null}. * @return see description */ public MimeMessage getLastReceivedMessage() { MimeMessage[] receivedMessages = greenMail.getReceivedMessages(); return (receivedMessages == null || receivedMessages.length == 0) ? null : receivedMessages[receivedMessages.length - 1]; } /** * Use this method if you are sending email in a different thread from the one you're testing from. * Block waits for an email to arrive in any mailbox for any user. * Implementation Detail: No polling wait implementation * * @param timeout maximum time in ms to wait for emailCount of messages to arrive before giving up and returning false * @param emailCount waits for these many emails to arrive before returning * @return * @throws InterruptedException */ public boolean waitForIncomingEmail(long timeout, int emailCount) throws InterruptedException { return greenMail.waitForIncomingEmail(timeout, emailCount); } /** * Does the same thing as Object.wait(long, int) but with a timeout of 5000ms. * @param emailCount waits for these many emails to arrive before returning * @return * @throws InterruptedException */ public boolean waitForIncomingEmail(int emailCount) throws InterruptedException { return greenMail.waitForIncomingEmail(emailCount); } }
apache-2.0
mag/robolectric
robolectric/src/test/java/org/robolectric/internal/bytecode/ShadowWranglerUnitTest.java
2357
package org.robolectric.internal.bytecode; import org.junit.Before; import org.junit.Test; import org.robolectric.internal.SdkConfig; import org.robolectric.util.Function; import java.util.LinkedHashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("unchecked") public class ShadowWranglerUnitTest { private ShadowWrangler shadowWrangler; @Before public void setup() throws Exception { shadowWrangler = new ShadowWrangler(ShadowMap.EMPTY); } @Test public void getInterceptionHandler_whenCallIsNotRecognized_shouldReturnDoNothingHandler() throws Exception { MethodSignature methodSignature = MethodSignature.parse("java/lang/Object/unknownMethod()V"); Function<Object,Object> handler = shadowWrangler.getInterceptionHandler(methodSignature); assertThat(handler.call(null, null, new Object[0])).isNull(); } @Test public void getInterceptionHandler_whenInterceptingElderOnLinkedHashMap_shouldReturnNonDoNothingHandler() throws Exception { MethodSignature methodSignature = MethodSignature.parse("java/util/LinkedHashMap/eldest()Ljava/lang/Object;"); Function<Object,Object> handler = shadowWrangler.getInterceptionHandler(methodSignature); assertThat(handler).isNotSameAs(ShadowWrangler.DO_NOTHING_HANDLER); } @Test public void intercept_elderOnLinkedHashMapHandler_shouldReturnEldestMemberOfLinkedHashMap() throws Throwable { LinkedHashMap<Integer, String> map = new LinkedHashMap<>(2); map.put(1, "one"); map.put(2, "two"); Map.Entry<Integer, String> result = (Map.Entry<Integer, String>) shadowWrangler.intercept("java/util/LinkedHashMap/eldest()Ljava/lang/Object;", map, null, getClass()); Map.Entry<Integer, String> eldestMember = map.entrySet().iterator().next(); assertThat(result).isEqualTo(eldestMember); assertThat(result.getKey()).isEqualTo(1); assertThat(result.getValue()).isEqualTo("one"); } @Test public void intercept_elderOnLinkedHashMapHandler_shouldReturnNullForEmptyMap() throws Throwable { LinkedHashMap<Integer, String> map = new LinkedHashMap<>(); Map.Entry<Integer, String> result = (Map.Entry<Integer, String>) shadowWrangler.intercept("java/util/LinkedHashMap/eldest()Ljava/lang/Object;", map, null, getClass()); assertThat(result).isNull(); } }
mit
jorgereina1986/cw-omnibus
EmPubLite-AndroidStudio/T13-Prefs/EmPubLite/app/src/main/java/com/commonsware/empublite/EmPubLiteActivity.java
3774
package com.commonsware.empublite; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import de.greenrobot.event.EventBus; public class EmPubLiteActivity extends Activity { private static final String MODEL="model"; private static final String PREF_LAST_POSITION="lastPosition"; private static final String PREF_SAVE_LAST_POSITION="saveLastPosition"; private static final String PREF_KEEP_SCREEN_ON="keepScreenOn"; private ViewPager pager=null; private ContentsAdapter adapter=null; private ModelFragment mfrag=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupStrictMode(); setContentView(R.layout.main); pager=(ViewPager)findViewById(R.id.pager); } @Override public void onResume() { super.onResume(); EventBus.getDefault().register(this); if (adapter==null) { mfrag=(ModelFragment)getFragmentManager().findFragmentByTag(MODEL); if (mfrag==null) { mfrag=new ModelFragment(); getFragmentManager() .beginTransaction() .add(mfrag, MODEL) .commit(); } else if (mfrag.getBook()!=null) { setupPager(mfrag.getBook()); } } if (mfrag.getPrefs()!=null) { pager.setKeepScreenOn(mfrag.getPrefs() .getBoolean(PREF_KEEP_SCREEN_ON, false)); } } @Override public void onPause() { EventBus.getDefault().unregister(this); if (mfrag.getPrefs()!=null) { int position=pager.getCurrentItem(); mfrag.getPrefs().edit().putInt(PREF_LAST_POSITION, position) .apply(); } super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options, menu); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: Intent i = new Intent(this, SimpleContentActivity.class) .putExtra(SimpleContentActivity.EXTRA_FILE, "file:///android_asset/misc/about.html"); startActivity(i); return(true); case R.id.help: i = new Intent(this, SimpleContentActivity.class) .putExtra(SimpleContentActivity.EXTRA_FILE, "file:///android_asset/misc/help.html"); startActivity(i); return(true); case R.id.settings: startActivity(new Intent(this, Preferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } @SuppressWarnings("unused") public void onEventMainThread(BookLoadedEvent event) { setupPager(event.getBook()); } private void setupPager(BookContents contents) { adapter=new ContentsAdapter(this, contents); pager.setAdapter(adapter); findViewById(R.id.progressBar1).setVisibility(View.GONE); pager.setVisibility(View.VISIBLE); SharedPreferences prefs=mfrag.getPrefs(); if (prefs!=null) { if (prefs.getBoolean(PREF_SAVE_LAST_POSITION, false)) { pager.setCurrentItem(prefs.getInt(PREF_LAST_POSITION, 0)); } pager.setKeepScreenOn(prefs.getBoolean(PREF_KEEP_SCREEN_ON, false)); } } private void setupStrictMode() { StrictMode.ThreadPolicy.Builder builder= new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog(); if (BuildConfig.DEBUG) { builder.penaltyFlashScreen(); } StrictMode.setThreadPolicy(builder.build()); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMXSImplementationSourceImpl.java
3821
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 2001, 2002,2004 The Apache Software 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 com.sun.org.apache.xerces.internal.dom; import com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl; import org.w3c.dom.DOMImplementationList; import org.w3c.dom.DOMImplementation; import java.util.Vector; /** * Allows to retrieve <code>XSImplementation</code>, DOM Level 3 Core and LS implementations * and PSVI implementation. * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#DOMImplementationSource'>Document Object Model (DOM) Level 3 Core Specification</a>. * * @xerces.internal * * @author Elena Litani, IBM */ public class DOMXSImplementationSourceImpl extends DOMImplementationSourceImpl { /** * A method to request a DOM implementation. * @param features A string that specifies which features are required. * This is a space separated list in which each feature is specified * by its name optionally followed by a space and a version number. * This is something like: "XML 1.0 Traversal Events 2.0" * @return An implementation that has the desired features, or * <code>null</code> if this source has none. */ public DOMImplementation getDOMImplementation(String features) { DOMImplementation impl = super.getDOMImplementation(features); if (impl != null){ return impl; } // if not try the PSVIDOMImplementation impl = PSVIDOMImplementationImpl.getDOMImplementation(); if (testImpl(impl, features)) { return impl; } // if not try the XSImplementation impl = XSImplementationImpl.getDOMImplementation(); if (testImpl(impl, features)) { return impl; } return null; } /** * A method to request a list of DOM implementations that support the * specified features and versions, as specified in . * @param features A string that specifies which features and versions * are required. This is a space separated list in which each feature * is specified by its name optionally followed by a space and a * version number. This is something like: "XML 3.0 Traversal +Events * 2.0" * @return A list of DOM implementations that support the desired * features. */ public DOMImplementationList getDOMImplementationList(String features) { final Vector implementations = new Vector(); // first check whether the CoreDOMImplementation would do DOMImplementationList list = super.getDOMImplementationList(features); //Add core DOMImplementations for (int i=0; i < list.getLength(); i++ ) { implementations.addElement(list.item(i)); } DOMImplementation impl = PSVIDOMImplementationImpl.getDOMImplementation(); if (testImpl(impl, features)) { implementations.addElement(impl); } impl = XSImplementationImpl.getDOMImplementation(); if (testImpl(impl, features)) { implementations.addElement(impl); } return new DOMImplementationListImpl(implementations); } }
mit
curso007/camel
components/camel-netty4/src/test/java/org/apache/camel/component/netty4/LogCaptureTest.java
1349
/** * 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.netty4; import io.netty.util.ResourceLeakDetector; import io.netty.util.internal.logging.InternalLoggerFactory; import org.junit.Assert; import org.junit.Test; /** * This test ensures LogCaptureAppender is configured properly */ public class LogCaptureTest { @Test public void testCapture() { InternalLoggerFactory.getInstance(ResourceLeakDetector.class).error("testError"); Assert.assertFalse(LogCaptureAppender.getEvents().isEmpty()); LogCaptureAppender.reset(); } }
apache-2.0
curso007/camel
camel-core/src/main/java/org/apache/camel/util/component/AbstractApiProducer.java
7762
/** * 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.util.component; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.RuntimeCamelException; import org.apache.camel.impl.DefaultAsyncProducer; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for API based Producers */ public abstract class AbstractApiProducer<E extends Enum<E> & ApiName, T> extends DefaultAsyncProducer implements PropertiesInterceptor, ResultInterceptor { // API Endpoint protected final AbstractApiEndpoint<E, T> endpoint; // properties helper protected final ApiMethodPropertiesHelper<T> propertiesHelper; // method helper protected final ApiMethodHelper<?> methodHelper; // logger private final transient Logger log = LoggerFactory.getLogger(getClass()); public AbstractApiProducer(AbstractApiEndpoint<E, T> endpoint, ApiMethodPropertiesHelper<T> propertiesHelper) { super(endpoint); this.propertiesHelper = propertiesHelper; this.endpoint = endpoint; this.methodHelper = endpoint.getMethodHelper(); } @Override public boolean process(final Exchange exchange, final AsyncCallback callback) { // properties for method arguments final Map<String, Object> properties = new HashMap<String, Object>(); properties.putAll(endpoint.getEndpointProperties()); propertiesHelper.getExchangeProperties(exchange, properties); // let the endpoint and the Producer intercept properties endpoint.interceptProperties(properties); interceptProperties(properties); // decide which method to invoke final ApiMethod method = findMethod(exchange, properties); if (method == null) { // synchronous failure callback.done(true); return true; } // create a runnable invocation task to be submitted on a background thread pool // this way we avoid blocking the current thread for long running methods Runnable invocation = new Runnable() { @Override public void run() { try { if (log.isDebugEnabled()) { log.debug("Invoking operation {} with {}", method.getName(), properties.keySet()); } Object result = doInvokeMethod(method, properties); // producer returns a single response, even for methods with List return types exchange.getOut().setBody(result); // copy headers exchange.getOut().setHeaders(exchange.getIn().getHeaders()); interceptResult(result, exchange); } catch (Throwable t) { exchange.setException(ObjectHelper.wrapRuntimeCamelException(t)); } finally { callback.done(false); } } }; endpoint.getExecutorService().submit(invocation); return false; } @Override public void interceptProperties(Map<String, Object> properties) { // do nothing by default } /** * Invoke the API method. Derived classes can override, but MUST call super.doInvokeMethod(). * @param method API method to invoke. * @param properties method arguments from endpoint properties and exchange In headers. * @return API method invocation result. * @throws RuntimeCamelException on error. Exceptions thrown by API method are wrapped. */ protected Object doInvokeMethod(ApiMethod method, Map<String, Object> properties) throws RuntimeCamelException { return ApiMethodHelper.invokeMethod(endpoint.getApiProxy(method, properties), method, properties); } @Override public final Object splitResult(Object result) { // producer never splits results return result; } @Override public void interceptResult(Object methodResult, Exchange resultExchange) { // do nothing by default } protected ApiMethod findMethod(Exchange exchange, Map<String, Object> properties) { ApiMethod method = null; final List<ApiMethod> candidates = endpoint.getCandidates(); if (processInBody(exchange, properties)) { // filter candidates based on endpoint and exchange properties final Set<String> argNames = properties.keySet(); final List<ApiMethod> filteredMethods = methodHelper.filterMethods( candidates, ApiMethodHelper.MatchType.SUPER_SET, argNames); // get the method to call if (filteredMethods.isEmpty()) { throw new RuntimeCamelException(String.format("Missing properties for %s, need one or more from %s", endpoint.getMethodName(), methodHelper.getMissingProperties(endpoint.getMethodName(), argNames)) ); } else if (filteredMethods.size() == 1) { // found an exact match method = filteredMethods.get(0); } else { method = ApiMethodHelper.getHighestPriorityMethod(filteredMethods); log.warn("Calling highest priority operation {} from operations {}", method, filteredMethods); } } return method; } // returns false on exception, which is set in exchange private boolean processInBody(Exchange exchange, Map<String, Object> properties) { final String inBodyProperty = endpoint.getInBody(); if (inBodyProperty != null) { Object value = exchange.getIn().getBody(); if (value != null) { try { value = endpoint.getCamelContext().getTypeConverter().mandatoryConvertTo( endpoint.getConfiguration().getClass().getDeclaredField(inBodyProperty).getType(), exchange, value); } catch (Exception e) { exchange.setException(new RuntimeCamelException(String.format( "Error converting value %s to property %s: %s", value, inBodyProperty, e.getMessage()), e)); return false; } } else { // allow null values for inBody only if its a nullable option if (!methodHelper.getNullableArguments().contains(inBodyProperty)) { exchange.setException(new NullPointerException(inBodyProperty)); return false; } } log.debug("Property [{}] has message body value {}", inBodyProperty, value); properties.put(inBodyProperty, value); } return true; } }
apache-2.0
HKMOpen/SmartTabLayout
utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/FragmentStatePagerItemAdapter.java
2445
/** * Copyright (C) 2015 ogaclejapan * * 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.ogaclejapan.smarttablayout.utils.v4; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.util.SparseArrayCompat; import android.view.ViewGroup; import java.lang.ref.WeakReference; public class FragmentStatePagerItemAdapter extends FragmentStatePagerAdapter { private final FragmentPagerItems pages; private final SparseArrayCompat<WeakReference<Fragment>> holder; public FragmentStatePagerItemAdapter(FragmentManager fm, FragmentPagerItems pages) { super(fm); this.pages = pages; this.holder = new SparseArrayCompat<>(pages.size()); } @Override public int getCount() { return pages.size(); } @Override public Fragment getItem(int position) { return getPagerItem(position).instantiate(pages.getContext(), position); } @Override public Object instantiateItem(ViewGroup container, int position) { Object item = super.instantiateItem(container, position); if (item instanceof Fragment) { holder.put(position, new WeakReference<Fragment>((Fragment) item)); } return item; } @Override public void destroyItem(ViewGroup container, int position, Object object) { holder.remove(position); super.destroyItem(container, position, object); } @Override public CharSequence getPageTitle(int position) { return getPagerItem(position).getTitle(); } @Override public float getPageWidth(int position) { return getPagerItem(position).getWidth(); } public Fragment getPage(int position) { final WeakReference<Fragment> weakRefItem = holder.get(position); return (weakRefItem != null) ? weakRefItem.get() : null; } protected FragmentPagerItem getPagerItem(int position) { return pages.get(position); } }
apache-2.0
wuranbo/elasticsearch
core/src/main/java/org/elasticsearch/index/analysis/PersianNormalizationFilterFactory.java
1615
/* * 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.index.analysis; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.fa.PersianNormalizationFilter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexSettings; public class PersianNormalizationFilterFactory extends AbstractTokenFilterFactory implements MultiTermAwareComponent { public PersianNormalizationFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) { super(indexSettings, name, settings); } @Override public TokenStream create(TokenStream tokenStream) { return new PersianNormalizationFilter(tokenStream); } @Override public Object getMultiTermComponent() { return this; } }
apache-2.0
kuzemchik/presto
presto-main/src/test/java/com/facebook/presto/execution/TestSimpleMarker.java
1679
/* * 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.facebook.presto.execution; import com.facebook.presto.spi.SerializableNativeValue; import io.airlift.json.JsonCodec; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestSimpleMarker { private static final JsonCodec<SimpleMarker> codec = JsonCodec.jsonCodec(SimpleMarker.class); @Test public void testRoundTrip() { SimpleMarker expected = new SimpleMarker(true, new SerializableNativeValue(Long.class, new Long(10))); assertEquals(codec.fromJson(codec.toJson(expected)), expected); expected = new SimpleMarker(false, new SerializableNativeValue(Double.class, new Double(10))); assertEquals(codec.fromJson(codec.toJson(expected)), expected); expected = new SimpleMarker(true, new SerializableNativeValue(Boolean.class, new Boolean(true))); assertEquals(codec.fromJson(codec.toJson(expected)), expected); expected = new SimpleMarker(true, new SerializableNativeValue(String.class, new String("123"))); assertEquals(codec.fromJson(codec.toJson(expected)), expected); } }
apache-2.0
jamesfeshner/openmrs-module
web/src/main/java/org/openmrs/web/OpenmrsBindingInitializer.java
6788
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.web; import java.text.NumberFormat; import java.util.Date; import org.openmrs.Cohort; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptClass; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptMapType; import org.openmrs.ConceptName; import org.openmrs.ConceptNumeric; import org.openmrs.ConceptReferenceTerm; import org.openmrs.ConceptSource; import org.openmrs.Drug; import org.openmrs.Encounter; import org.openmrs.Form; import org.openmrs.Location; import org.openmrs.LocationAttributeType; import org.openmrs.LocationTag; import org.openmrs.Order; import org.openmrs.Patient; import org.openmrs.PatientIdentifierType; import org.openmrs.Person; import org.openmrs.PersonAttribute; import org.openmrs.PersonAttributeType; import org.openmrs.Privilege; import org.openmrs.Program; import org.openmrs.ProgramWorkflow; import org.openmrs.ProgramWorkflowState; import org.openmrs.Provider; import org.openmrs.Role; import org.openmrs.User; import org.openmrs.Visit; import org.openmrs.VisitType; import org.openmrs.api.context.Context; import org.openmrs.propertyeditor.CohortEditor; import org.openmrs.propertyeditor.ConceptAnswerEditor; import org.openmrs.propertyeditor.ConceptClassEditor; import org.openmrs.propertyeditor.ConceptDatatypeEditor; import org.openmrs.propertyeditor.ConceptEditor; import org.openmrs.propertyeditor.ConceptMapTypeEditor; import org.openmrs.propertyeditor.ConceptNameEditor; import org.openmrs.propertyeditor.ConceptNumericEditor; import org.openmrs.propertyeditor.ConceptReferenceTermEditor; import org.openmrs.propertyeditor.ConceptSourceEditor; import org.openmrs.propertyeditor.DateOrDatetimeEditor; import org.openmrs.propertyeditor.DrugEditor; import org.openmrs.propertyeditor.EncounterEditor; import org.openmrs.propertyeditor.FormEditor; import org.openmrs.propertyeditor.LocationAttributeTypeEditor; import org.openmrs.propertyeditor.LocationEditor; import org.openmrs.propertyeditor.LocationTagEditor; import org.openmrs.propertyeditor.OrderEditor; import org.openmrs.propertyeditor.PatientEditor; import org.openmrs.propertyeditor.PatientIdentifierTypeEditor; import org.openmrs.propertyeditor.PersonAttributeEditor; import org.openmrs.propertyeditor.PersonAttributeTypeEditor; import org.openmrs.propertyeditor.PersonEditor; import org.openmrs.propertyeditor.PrivilegeEditor; import org.openmrs.propertyeditor.ProgramEditor; import org.openmrs.propertyeditor.ProgramWorkflowEditor; import org.openmrs.propertyeditor.ProgramWorkflowStateEditor; import org.openmrs.propertyeditor.ProviderEditor; import org.openmrs.propertyeditor.RoleEditor; import org.openmrs.propertyeditor.UserEditor; import org.openmrs.propertyeditor.VisitEditor; import org.openmrs.propertyeditor.VisitTypeEditor; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; /** * Shared WebBindingInitializer that allows all OpenMRS annotated controllers to use our custom * editors. */ public class OpenmrsBindingInitializer implements WebBindingInitializer { /** * @see org.springframework.web.bind.support.WebBindingInitializer#initBinder(org.springframework.web.bind.WebDataBinder, * org.springframework.web.context.request.WebRequest) */ @Override public void initBinder(WebDataBinder wdb, WebRequest request) { wdb.registerCustomEditor(Cohort.class, new CohortEditor()); wdb.registerCustomEditor(Concept.class, new ConceptEditor()); wdb.registerCustomEditor(ConceptAnswer.class, new ConceptAnswerEditor()); wdb.registerCustomEditor(ConceptClass.class, new ConceptClassEditor()); wdb.registerCustomEditor(ConceptDatatype.class, new ConceptDatatypeEditor()); wdb.registerCustomEditor(ConceptName.class, new ConceptNameEditor()); wdb.registerCustomEditor(ConceptNumeric.class, new ConceptNumericEditor()); wdb.registerCustomEditor(ConceptSource.class, new ConceptSourceEditor()); wdb.registerCustomEditor(Drug.class, new DrugEditor()); wdb.registerCustomEditor(Encounter.class, new EncounterEditor()); wdb.registerCustomEditor(Form.class, new FormEditor()); wdb.registerCustomEditor(Location.class, new LocationEditor()); wdb.registerCustomEditor(LocationTag.class, new LocationTagEditor()); wdb.registerCustomEditor(LocationAttributeType.class, new LocationAttributeTypeEditor()); wdb.registerCustomEditor(Order.class, new OrderEditor()); wdb.registerCustomEditor(Patient.class, new PatientEditor()); wdb.registerCustomEditor(PatientIdentifierType.class, new PatientIdentifierTypeEditor()); wdb.registerCustomEditor(PersonAttribute.class, new PersonAttributeEditor()); wdb.registerCustomEditor(PersonAttributeType.class, new PersonAttributeTypeEditor()); wdb.registerCustomEditor(Person.class, new PersonEditor()); wdb.registerCustomEditor(Privilege.class, new PrivilegeEditor()); wdb.registerCustomEditor(Program.class, new ProgramEditor()); wdb.registerCustomEditor(ProgramWorkflow.class, new ProgramWorkflowEditor()); wdb.registerCustomEditor(ProgramWorkflowState.class, new ProgramWorkflowStateEditor()); wdb.registerCustomEditor(Provider.class, new ProviderEditor()); wdb.registerCustomEditor(Role.class, new RoleEditor()); wdb.registerCustomEditor(User.class, new UserEditor()); wdb.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, NumberFormat .getInstance(Context.getLocale()), true)); wdb.registerCustomEditor(Date.class, new DateOrDatetimeEditor()); wdb.registerCustomEditor(PatientIdentifierType.class, new PatientIdentifierTypeEditor()); wdb.registerCustomEditor(ConceptMapType.class, new ConceptMapTypeEditor()); wdb.registerCustomEditor(ConceptSource.class, new ConceptSourceEditor()); wdb.registerCustomEditor(ConceptReferenceTerm.class, new ConceptReferenceTermEditor()); wdb.registerCustomEditor(VisitType.class, new VisitTypeEditor()); wdb.registerCustomEditor(Visit.class, new VisitEditor()); // can't really do this because PropertyEditors are not told what type of class they are changing :-( //wdb.registerCustomEditor(OpenmrsObject.class, new OpenmrsObjectByUuidEditor()); } }
mpl-2.0
ervinyang/tutorial_zookeeper
zookeeper-trunk/src/contrib/rest/src/test/org/apache/zookeeper/server/jersey/ExistsTest.java
2613
/** * 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.zookeeper.server.jersey; import java.util.Arrays; import java.util.Collection; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.sun.jersey.api.client.ClientResponse; /** * Test stand-alone server. * */ @RunWith(Parameterized.class) public class ExistsTest extends Base { protected static final Logger LOG = LoggerFactory.getLogger(ExistsTest.class); private String path; private ClientResponse.Status expectedStatus; @Parameters public static Collection<Object[]> data() throws Exception { String baseZnode = Base.createBaseZNode(); return Arrays.asList(new Object[][] { {baseZnode, ClientResponse.Status.OK }, {baseZnode + "dkdk38383", ClientResponse.Status.NOT_FOUND } }); } public ExistsTest(String path, ClientResponse.Status status) { this.path = path; this.expectedStatus = status; } private void verify(String type) { ClientResponse cr = znodesr.path(path).accept(type).type(type).head(); if (type.equals(MediaType.APPLICATION_OCTET_STREAM) && expectedStatus == ClientResponse.Status.OK) { Assert.assertEquals(ClientResponse.Status.NO_CONTENT, cr.getClientResponseStatus()); } else { Assert.assertEquals(expectedStatus, cr.getClientResponseStatus()); } } @Test public void testExists() throws Exception { verify(MediaType.APPLICATION_OCTET_STREAM); verify(MediaType.APPLICATION_JSON); verify(MediaType.APPLICATION_XML); } }
mit
joakibj/camel
components/camel-apns/src/main/java/org/apache/camel/component/apns/ApnsComponent.java
1812
/** * 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.apns; import java.util.Map; import com.notnoop.apns.ApnsService; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; public class ApnsComponent extends UriEndpointComponent { private ApnsService apnsService; public ApnsComponent() { super(ApnsEndpoint.class); } public ApnsComponent(ApnsService apnsService) { this(); this.apnsService = apnsService; } protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { ApnsEndpoint endpoint = new ApnsEndpoint(uri, this); endpoint.setName(remaining); setProperties(endpoint, parameters); return endpoint; } public ApnsService getApnsService() { return apnsService; } /** * To use a custom @{link ApnsService} */ public void setApnsService(ApnsService apnsService) { this.apnsService = apnsService; } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jdk/test/java/util/concurrent/FutureTask/Customized.java
7692
/* * Copyright (c) 2007, 2010, 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. */ /* * @test * @bug 6464365 * @summary Test state transitions; check protected methods are called * @author Martin Buchholz */ import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class Customized { static final AtomicLong doneCount = new AtomicLong(0); static final AtomicLong setCount = new AtomicLong(0); static final AtomicLong setExceptionCount = new AtomicLong(0); static void equal(long expected, AtomicLong actual) { equal(expected, actual.get()); } static void equalCounts(long x, long y, long z) { equal(x, doneCount); equal(y, setCount); equal(z, setExceptionCount); } static class MyFutureTask<V> extends FutureTask<V> { MyFutureTask(Runnable r, V result) { super(r, result); } protected void done() { doneCount.getAndIncrement(); super.done(); } protected void set(V v) { setCount.getAndIncrement(); super.set(v); } protected void setException(Throwable t) { setExceptionCount.getAndIncrement(); super.setException(t); } public boolean runAndReset() { return super.runAndReset(); } } static <V> void checkReady(final FutureTask<V> task) { check(! task.isDone()); check(! task.isCancelled()); THROWS(TimeoutException.class, new Fun(){void f() throws Throwable { task.get(0L, TimeUnit.SECONDS); }}); } static <V> void checkDone(final FutureTask<V> task) { try { check(task.isDone()); check(! task.isCancelled()); check(task.get() != null); } catch (Throwable t) { unexpected(t); } } static <V> void checkCancelled(final FutureTask<V> task) { check(task.isDone()); check(task.isCancelled()); THROWS(CancellationException.class, new Fun(){void f() throws Throwable { task.get(0L, TimeUnit.SECONDS); }}, new Fun(){void f() throws Throwable { task.get(); }}); } static <V> void checkThrew(final FutureTask<V> task) { check(task.isDone()); check(! task.isCancelled()); THROWS(ExecutionException.class, new Fun(){void f() throws Throwable { task.get(0L, TimeUnit.SECONDS); }}, new Fun(){void f() throws Throwable { task.get(); }}); } static <V> void cancel(FutureTask<V> task, boolean mayInterruptIfRunning) { task.cancel(mayInterruptIfRunning); checkCancelled(task); } static <V> void run(FutureTask<V> task) { boolean isCancelled = task.isCancelled(); task.run(); check(task.isDone()); equal(isCancelled, task.isCancelled()); } static void realMain(String[] args) throws Throwable { final Runnable nop = new Runnable() { public void run() {}}; final Runnable bad = new Runnable() { public void run() { throw new Error(); }}; try { final MyFutureTask<Long> task = new MyFutureTask<Long>(nop, 42L); checkReady(task); equalCounts(0,0,0); check(task.runAndReset()); checkReady(task); equalCounts(0,0,0); run(task); checkDone(task); equalCounts(1,1,0); equal(42L, task.get()); run(task); checkDone(task); equalCounts(1,1,0); equal(42L, task.get()); } catch (Throwable t) { unexpected(t); } try { final MyFutureTask<Long> task = new MyFutureTask<Long>(nop, 42L); cancel(task, false); equalCounts(2,1,0); cancel(task, false); equalCounts(2,1,0); run(task); equalCounts(2,1,0); check(! task.runAndReset()); } catch (Throwable t) { unexpected(t); } try { final MyFutureTask<Long> task = new MyFutureTask<Long>(bad, 42L); checkReady(task); run(task); checkThrew(task); equalCounts(3,1,1); run(task); equalCounts(3,1,1); } catch (Throwable t) { unexpected(t); } try { final MyFutureTask<Long> task = new MyFutureTask<Long>(nop, 42L); checkReady(task); task.set(99L); checkDone(task); equalCounts(4,2,1); run(task); equalCounts(4,2,1); task.setException(new Throwable()); checkDone(task); equalCounts(4,2,2); } catch (Throwable t) { unexpected(t); } try { final MyFutureTask<Long> task = new MyFutureTask<Long>(nop, 42L); checkReady(task); task.setException(new Throwable()); checkThrew(task); equalCounts(5,2,3); run(task); equalCounts(5,2,3); task.set(99L); checkThrew(task); equalCounts(5,3,3); } catch (Throwable t) { unexpected(t); } System.out.printf("doneCount=%d%n", doneCount.get()); System.out.printf("setCount=%d%n", setCount.get()); System.out.printf("setExceptionCount=%d%n", setExceptionCount.get()); } //--------------------- Infrastructure --------------------------- static volatile int passed = 0, failed = 0; static void pass() {passed++;} static void fail() {failed++; Thread.dumpStack();} static void fail(String msg) {System.out.println(msg); fail();} static void unexpected(Throwable t) {failed++; t.printStackTrace();} static void check(boolean cond) {if (cond) pass(); else fail();} static void equal(Object x, Object y) { if (x == null ? y == null : x.equals(y)) pass(); else fail(x + " not equal to " + y);} public static void main(String[] args) throws Throwable { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} private abstract static class Fun {abstract void f() throws Throwable;} static void THROWS(Class<? extends Throwable> k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } catch (Throwable t) { if (k.isAssignableFrom(t.getClass())) pass(); else unexpected(t);}} }
mit
leftbrainstrain/Arduino-ESP8266
arduino-core/src/cc/arduino/filters/FileExecutablePredicate.java
1666
/* * This file is part of Arduino. * * Copyright 2015 Arduino LLC (http://www.arduino.cc/) * * Arduino 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. */ package cc.arduino.filters; import com.google.common.base.Predicate; import java.io.File; public class FileExecutablePredicate implements Predicate<File> { @Override public boolean apply(File file) { return file.isFile() && file.exists() && file.canRead() && file.canExecute(); } }
lgpl-2.1
udayakiran/udayakiran.github.io
vendor/gems/ruby/2.7.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser/vendor/http-parser-java/src/impl/http_parser/lolevel/HTTPParser.java
66091
package http_parser.lolevel; import java.nio.ByteBuffer; import http_parser.HTTPException; import http_parser.HTTPMethod; import http_parser.HTTPParserUrl; import http_parser.ParserType; import static http_parser.lolevel.HTTPParser.C.*; import static http_parser.lolevel.HTTPParser.State.*; public class HTTPParser { /* lots of unsigned chars here, not sure what to about them, `bytes` in java suck... */ ParserType type; State state; HState header_state; boolean strict; int index; int flags; // TODO int nread; long content_length; int p_start; // updated each call to execute to indicate where the buffer was before we began calling it. /** READ-ONLY **/ public int http_major; public int http_minor; public int status_code; /* responses only */ public HTTPMethod method; /* requests only */ /* true = Upgrade header was present and the parser has exited because of that. * false = No upgrade header present. * Should be checked when http_parser_execute() returns in addition to * error checking. */ public boolean upgrade; /** PUBLIC **/ // TODO : this is used in c to maintain application state. // is this even necessary? we have state in java ? // consider // Object data; /* A pointer to get hook to the "connection" or "socket" object */ /* * technically we could combine all of these (except for url_mark) into one * variable, saving stack space, but it seems more clear to have them * separated. */ int header_field_mark = -1; int header_value_mark = -1; int url_mark = -1; int body_mark = -1; /** * Construct a Parser for ParserType.HTTP_BOTH, meaning it * determines whether it's parsing a request or a response. */ public HTTPParser() { this(ParserType.HTTP_BOTH); } /** * Construct a Parser and initialise it to parse either * requests or responses. */ public HTTPParser(ParserType type) { this.type = type; switch(type) { case HTTP_REQUEST: this.state = State.start_req; break; case HTTP_RESPONSE: this.state = State.start_res; break; case HTTP_BOTH: this.state = State.start_req_or_res; break; default: throw new HTTPException("can't happen, invalid ParserType enum"); } } /* * Utility to facilitate System.out.println style debugging (the way god intended) */ static void p(Object o) {System.out.println(o);} /** Comment from C version follows * * Our URL parser. * * This is designed to be shared by http_parser_execute() for URL validation, * hence it has a state transition + byte-for-byte interface. In addition, it * is meant to be embedded in http_parser_parse_url(), which does the dirty * work of turning state transitions URL components for its API. * * This function should only be invoked with non-space characters. It is * assumed that the caller cares about (and can detect) the transition between * URL and non-URL states by looking for these. */ public State parse_url_char(byte ch) { int chi = ch & 0xff; // utility, ch without signedness for table lookups. if(SPACE == ch){ throw new HTTPException("space as url char"); } switch(state) { case req_spaces_before_url: /* Proxied requests are followed by scheme of an absolute URI (alpha). * All methods except CONNECT are followed by '/' or '*'. */ if(SLASH == ch || STAR == ch){ return req_path; } if(isAtoZ(ch)){ return req_schema; } break; case req_schema: if(isAtoZ(ch)){ return req_schema; } if(COLON == ch){ return req_schema_slash; } break; case req_schema_slash: if(SLASH == ch){ return req_schema_slash_slash; } break; case req_schema_slash_slash: if(SLASH == ch){ return req_host_start; } break; case req_host_start: if (ch == (byte)'[') { return req_host_v6_start; } if (isHostChar(ch)) { return req_host; } break; case req_host: if (isHostChar(ch)) { return req_host; } /* FALLTHROUGH */ case req_host_v6_end: switch (ch) { case ':': return req_port_start; case '/': return req_path; case '?': return req_query_string_start; } break; case req_host_v6: if (ch == ']') { return req_host_v6_end; } /* FALLTHROUGH */ case req_host_v6_start: if (isHex(ch) || ch == ':') { return req_host_v6; } break; case req_port: switch (ch) { case '/': return req_path; case '?': return req_query_string_start; } /* FALLTHROUGH */ case req_port_start: if (isDigit(ch)) { return req_port; } break; case req_path: if (isNormalUrlChar(chi)) { return req_path; } switch (ch) { case '?': return req_query_string_start; case '#': return req_fragment_start; } break; case req_query_string_start: case req_query_string: if (isNormalUrlChar(chi)) { return req_query_string; } switch (ch) { case '?': /* allow extra '?' in query string */ return req_query_string; case '#': return req_fragment_start; } break; case req_fragment_start: if (isNormalUrlChar(chi)) { return req_fragment; } switch (ch) { case '?': return req_fragment; case '#': return req_fragment_start; } break; case req_fragment: if (isNormalUrlChar(ch)) { return req_fragment; } switch (ch) { case '?': case '#': return req_fragment; } break; default: break; } /* We should never fall out of the switch above unless there's an error */ return dead; } /** Execute the parser with the currently available data contained in * the buffer. The buffers position() and limit() need to be set * correctly (obviously) and a will be updated approriately when the * method returns to reflect the consumed data. */ public int execute(ParserSettings settings, ByteBuffer data) { int p = data.position(); this.p_start = p; // this is used for pretty printing errors. // and returning the amount of processed bytes. // In case the headers don't provide information about the content // length, `execute` needs to be called with an empty buffer to // indicate that all the data has been send be the client/server, // else there is no way of knowing the message is complete. int len = (data.limit() - data.position()); if (0 == len) { // if (State.body_identity_eof == state) { // settings.call_on_message_complete(this); // } switch (state) { case body_identity_eof: settings.call_on_message_complete(this); return data.position() - this.p_start; case dead: case start_req_or_res: case start_res: case start_req: return data.position() - this.p_start; default: // should we really consider this an error!? throw new HTTPException("empty bytes! "+state); // error } } // in case the _previous_ call to the parser only has data to get to // the middle of certain fields, we need to update marks to point at // the beginning of the current buffer. switch (state) { case header_field: header_field_mark = p; break; case header_value: header_value_mark = p; break; case req_path: case req_schema: case req_schema_slash: case req_schema_slash_slash: case req_host_start: case req_host_v6_start: case req_host_v6: case req_host_v6_end: case req_host: case req_port_start: case req_port: case req_query_string_start: case req_query_string: case req_fragment_start: case req_fragment: url_mark = p; break; } boolean reexecute = false; int pe = 0; byte ch = 0; int chi = 0; byte c = -1; int to_read = 0; // this is where the work gets done, traverse the available data... while (data.position() != data.limit() || reexecute) { // p(state + ": r: " + reexecute + " :: " +p ); if(!reexecute){ p = data.position(); pe = data.limit(); ch = data.get(); // the current character to process. chi = ch & 0xff; // utility, ch without signedness for table lookups. c = -1; // utility variably used for up- and downcasing etc. to_read = 0; // used to keep track of how much of body, etc. is left to read if (parsing_header(state)) { ++nread; if (nread > HTTP_MAX_HEADER_SIZE) { return error(settings, "possible buffer overflow", data); } } } reexecute = false; // p(state + " ::: " + ch + " : " + (((CR == ch) || (LF == ch)) ? ch : ("'" + (char)ch + "'")) +": "+p ); switch (state) { /* * this state is used after a 'Connection: close' message * the parser will error out if it reads another message */ case dead: if (CR == ch || LF == ch){ break; } return error(settings, "Connection already closed", data); case start_req_or_res: if (CR == ch || LF == ch){ break; } flags = 0; content_length = -1; if (H == ch) { state = State.res_or_resp_H; } else { type = ParserType.HTTP_REQUEST; method = start_req_method_assign(ch); if (null == method) { return error(settings, "invalid method", data); } index = 1; state = State.req_method; } settings.call_on_message_begin(this); break; case res_or_resp_H: if (T == ch) { type = ParserType.HTTP_RESPONSE; state = State.res_HT; } else { if (E != ch) { return error(settings, "not E", data); } type = ParserType.HTTP_REQUEST; method = HTTPMethod.HTTP_HEAD; index = 2; state = State.req_method; } break; case start_res: flags = 0; content_length = -1; switch(ch) { case H: state = State.res_H; break; case CR: case LF: break; default: return error(settings, "Not H or CR/LF", data); } settings.call_on_message_begin(this); break; case res_H: if (strict && T != ch) { return error(settings, "Not T", data); } state = State.res_HT; break; case res_HT: if (strict && T != ch) { return error(settings, "Not T2", data); } state = State.res_HTT; break; case res_HTT: if (strict && P != ch) { return error(settings, "Not P", data); } state = State.res_HTTP; break; case res_HTTP: if (strict && SLASH != ch) { return error(settings, "Not '/'", data); } state = State.res_first_http_major; break; case res_first_http_major: if (!isDigit(ch)) { return error(settings, "Not a digit", data); } http_major = (int) ch - 0x30; state = State.res_http_major; break; /* major HTTP version or dot */ case res_http_major: if (DOT == ch) { state = State.res_first_http_minor; break; } if (!isDigit(ch)) { return error(settings, "Not a digit", data); } http_major *= 10; http_major += (ch - 0x30); if (http_major > 999) { return error(settings, "invalid http major version: ", data); } break; /* first digit of minor HTTP version */ case res_first_http_minor: if (!isDigit(ch)) { return error(settings, "Not a digit", data); } http_minor = (int)ch - 0x30; state = State.res_http_minor; break; /* minor HTTP version or end of request line */ case res_http_minor: if (SPACE == ch) { state = State.res_first_status_code; break; } if (!isDigit(ch)) { return error(settings, "Not a digit", data); } http_minor *= 10; http_minor += (ch - 0x30); if (http_minor > 999) { return error(settings, "invalid http minor version: ", data); } break; case res_first_status_code: if (!isDigit(ch)) { if (SPACE == ch) { break; } return error(settings, "Not a digit (status code)", data); } status_code = (int)ch - 0x30; state = State.res_status_code; break; case res_status_code: if (!isDigit(ch)) { switch(ch) { case SPACE: state = State.res_status; break; case CR: state = State.res_line_almost_done; break; case LF: state = State.header_field_start; break; default: return error(settings, "not a valid status code", data); } break; } status_code *= 10; status_code += (int)ch - 0x30; if (status_code > 999) { return error(settings, "ridiculous status code:", data); } if (status_code > 99) { settings.call_on_status_complete(this); } break; case res_status: /* the human readable status. e.g. "NOT FOUND" * we are not humans so just ignore this * we are not men, we are devo. */ if (CR == ch) { state = State.res_line_almost_done; break; } if (LF == ch) { state = State.header_field_start; break; } break; case res_line_almost_done: if (strict && LF != ch) { return error(settings, "not LF", data); } state = State.header_field_start; break; case start_req: if (CR==ch || LF == ch) { break; } flags = 0; content_length = -1; if(!isAtoZ(ch)){ return error(settings, "invalid method", data); } method = start_req_method_assign(ch); if (null == method) { return error(settings, "invalid method", data); } index = 1; state = State.req_method; settings.call_on_message_begin(this); break; case req_method: if (0 == ch) { return error(settings, "NULL in method", data); } byte [] arr = method.bytes; if (SPACE == ch && index == arr.length) { state = State.req_spaces_before_url; } else if (arr[index] == ch) { // wuhu! } else if (HTTPMethod.HTTP_CONNECT == method) { if (1 == index && H == ch) { method = HTTPMethod.HTTP_CHECKOUT; } else if (2 == index && P == ch) { method = HTTPMethod.HTTP_COPY; } } else if (HTTPMethod.HTTP_MKCOL == method) { if (1 == index && O == ch) { method = HTTPMethod.HTTP_MOVE; } else if (1 == index && E == ch) { method = HTTPMethod.HTTP_MERGE; } else if (1 == index && DASH == ch) { /* M-SEARCH */ method = HTTPMethod.HTTP_MSEARCH; } else if (2 == index && A == ch) { method = HTTPMethod.HTTP_MKACTIVITY; } } else if (1 == index && HTTPMethod.HTTP_POST == method) { if(R == ch) { method = HTTPMethod.HTTP_PROPFIND; /* or HTTP_PROPPATCH */ }else if(U == ch){ method = HTTPMethod.HTTP_PUT; /* or HTTP_PURGE */ }else if(A == ch){ method = HTTPMethod.HTTP_PATCH; } } else if (2 == index) { if(HTTPMethod.HTTP_PUT == method) { if(R == ch){ method = HTTPMethod.HTTP_PURGE; } }else if(HTTPMethod.HTTP_UNLOCK == method){ if(S == ch){ method = HTTPMethod.HTTP_UNSUBSCRIBE; } } }else if(4 == index && HTTPMethod.HTTP_PROPFIND == method && P == ch){ method = HTTPMethod.HTTP_PROPPATCH; } else { return error(settings, "Invalid HTTP method", data); } ++index; break; /******************* URL *******************/ case req_spaces_before_url: if (SPACE == ch) { break; } url_mark = p; if(HTTPMethod.HTTP_CONNECT == method){ state = req_host_start; } state = parse_url_char(ch); if(state == dead){ return error(settings, "Invalid something", data); } break; case req_schema: case req_schema_slash: case req_schema_slash_slash: case req_host_start: case req_host_v6_start: case req_host_v6: case req_port_start: switch (ch) { /* No whitespace allowed here */ case SPACE: case CR: case LF: return error(settings, "unexpected char in path", data); default: state = parse_url_char(ch); if(dead == state){ return error(settings, "unexpected char in path", data); } } break; case req_host: case req_host_v6_end: case req_port: case req_path: case req_query_string_start: case req_query_string: case req_fragment_start: case req_fragment: switch (ch) { case SPACE: settings.call_on_url(this, data, url_mark, p-url_mark); settings.call_on_path(this, data, url_mark, p - url_mark); url_mark = -1; state = State.req_http_start; break; case CR: case LF: http_major = 0; http_minor = 9; state = (CR == ch) ? req_line_almost_done : header_field_start; settings.call_on_url(this, data, url_mark, p-url_mark); //TODO check params!!! settings.call_on_path(this, data, url_mark, p-url_mark); url_mark = -1; break; default: state = parse_url_char(ch); if(dead == state){ return error(settings, "unexpected char in path", data); } } break; /******************* URL *******************/ /******************* HTTP 1.1 *******************/ case req_http_start: switch (ch) { case H: state = State.req_http_H; break; case SPACE: break; default: return error(settings, "error in req_http_H", data); } break; case req_http_H: if (strict && T != ch) { return error(settings, "unexpected char", data); } state = State.req_http_HT; break; case req_http_HT: if (strict && T != ch) { return error(settings, "unexpected char", data); } state = State.req_http_HTT; break; case req_http_HTT: if (strict && P != ch) { return error(settings, "unexpected char", data); } state = State.req_http_HTTP; break; case req_http_HTTP: if (strict && SLASH != ch) { return error(settings, "unexpected char", data); } state = req_first_http_major; break; /* first digit of major HTTP version */ case req_first_http_major: if (!isDigit(ch)) { return error(settings, "non digit in http major", data); } http_major = (int)ch - 0x30; state = State.req_http_major; break; /* major HTTP version or dot */ case req_http_major: if (DOT == ch) { state = State.req_first_http_minor; break; } if (!isDigit(ch)) { return error(settings, "non digit in http major", data); } http_major *= 10; http_major += (int)ch - 0x30; if (http_major > 999) { return error(settings, "ridiculous http major", data); }; break; /* first digit of minor HTTP version */ case req_first_http_minor: if (!isDigit(ch)) { return error(settings, "non digit in http minor", data); } http_minor = (int)ch - 0x30; state = State.req_http_minor; break; case req_http_minor: if (ch == CR) { state = State.req_line_almost_done; break; } if (ch == LF) { state = State.header_field_start; break; } /* XXX allow spaces after digit? */ if (!isDigit(ch)) { return error(settings, "non digit in http minor", data); } http_minor *= 10; http_minor += (int)ch - 0x30; if (http_minor > 999) { return error(settings, "ridiculous http minor", data); }; break; /* end of request line */ case req_line_almost_done: { if (ch != LF) { return error(settings, "missing LF after request line", data); } state = header_field_start; break; } /******************* HTTP 1.1 *******************/ /******************* Header *******************/ case header_field_start: { if (ch == CR) { state = headers_almost_done; break; } if (ch == LF) { /* they might be just sending \n instead of \r\n so this would be * the second \n to denote the end of headers*/ state = State.headers_almost_done; reexecute = true; break; } c = token(ch); if (0 == c) { return error(settings, "invalid char in header:", data); } header_field_mark = p; index = 0; state = State.header_field; switch (c) { case C: header_state = HState.C; break; case P: header_state = HState.matching_proxy_connection; break; case T: header_state = HState.matching_transfer_encoding; break; case U: header_state = HState.matching_upgrade; break; default: header_state = HState.general; break; } break; } case header_field: { c = token(ch); if (0 != c) { switch (header_state) { case general: break; case C: index++; header_state = (O == c ? HState.CO : HState.general); break; case CO: index++; header_state = (N == c ? HState.CON : HState.general); break; case CON: index++; switch (c) { case N: header_state = HState.matching_connection; break; case T: header_state = HState.matching_content_length; break; default: header_state = HState.general; break; } break; /* connection */ case matching_connection: index++; if (index > CONNECTION.length || c != CONNECTION[index]) { header_state = HState.general; } else if (index == CONNECTION.length-1) { header_state = HState.connection; } break; /* proxy-connection */ case matching_proxy_connection: index++; if (index > PROXY_CONNECTION.length || c != PROXY_CONNECTION[index]) { header_state = HState.general; } else if (index == PROXY_CONNECTION.length-1) { header_state = HState.connection; } break; /* content-length */ case matching_content_length: index++; if (index > CONTENT_LENGTH.length || c != CONTENT_LENGTH[index]) { header_state = HState.general; } else if (index == CONTENT_LENGTH.length-1) { header_state = HState.content_length; } break; /* transfer-encoding */ case matching_transfer_encoding: index++; if (index > TRANSFER_ENCODING.length || c != TRANSFER_ENCODING[index]) { header_state = HState.general; } else if (index == TRANSFER_ENCODING.length-1) { header_state = HState.transfer_encoding; } break; /* upgrade */ case matching_upgrade: index++; if (index > UPGRADE.length || c != UPGRADE[index]) { header_state = HState.general; } else if (index == UPGRADE.length-1) { header_state = HState.upgrade; } break; case connection: case content_length: case transfer_encoding: case upgrade: if (SPACE != ch) header_state = HState.general; break; default: return error(settings, "Unknown Header State", data); } // switch: header_state break; } // 0 != c if (COLON == ch) { settings.call_on_header_field(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; state = State.header_value_start; break; } if (CR == ch) { state = State.header_almost_done; settings.call_on_header_field(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; break; } if (ch == LF) { settings.call_on_header_field(this, data, header_field_mark, p-header_field_mark); header_field_mark = -1; state = State.header_field_start; break; } return error(settings, "invalid header field", data); } case header_value_start: { if ((SPACE == ch) || (TAB == ch)) break; header_value_mark = p; state = State.header_value; index = 0; if (CR == ch) { settings.call_on_header_value(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; header_state = HState.general; state = State.header_almost_done; break; } if (LF == ch) { settings.call_on_header_value(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; state = State.header_field_start; break; } c = upper(ch); switch (header_state) { case upgrade: flags |= F_UPGRADE; header_state = HState.general; break; case transfer_encoding: /* looking for 'Transfer-Encoding: chunked' */ if (C == c) { header_state = HState.matching_transfer_encoding_chunked; } else { header_state = HState.general; } break; case content_length: if (!isDigit(ch)) { return error(settings, "Content-Length not numeric", data); } content_length = (int)ch - 0x30; break; case connection: /* looking for 'Connection: keep-alive' */ if (K == c) { header_state = HState.matching_connection_keep_alive; /* looking for 'Connection: close' */ } else if (C == c) { header_state = HState.matching_connection_close; } else { header_state = HState.general; } break; default: header_state = HState.general; break; } break; } // header value start case header_value: { if (CR == ch) { settings.call_on_header_value(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; state = State.header_almost_done; break; } if (LF == ch) { settings.call_on_header_value(this, data, header_value_mark, p-header_value_mark); header_value_mark = -1; state = header_almost_done; reexecute = true; break; } c = upper(ch); switch (header_state) { case general: break; case connection: case transfer_encoding: return error(settings, "Shouldn't be here", data); case content_length: if (SPACE == ch) { break; } if (!isDigit(ch)) { return error(settings, "Content-Length not numeric", data); } long t = content_length; t *= 10; t += (long)ch - 0x30; /* Overflow? */ // t will wrap and become negative ... if (t < content_length) { return error(settings, "Invalid content length", data); } content_length = t; break; /* Transfer-Encoding: chunked */ case matching_transfer_encoding_chunked: index++; if (index > CHUNKED.length || c != CHUNKED[index]) { header_state = HState.general; } else if (index == CHUNKED.length-1) { header_state = HState.transfer_encoding_chunked; } break; /* looking for 'Connection: keep-alive' */ case matching_connection_keep_alive: index++; if (index > KEEP_ALIVE.length || c != KEEP_ALIVE[index]) { header_state = HState.general; } else if (index == KEEP_ALIVE.length-1) { header_state = HState.connection_keep_alive; } break; /* looking for 'Connection: close' */ case matching_connection_close: index++; if (index > CLOSE.length || c != CLOSE[index]) { header_state = HState.general; } else if (index == CLOSE.length-1) { header_state = HState.connection_close; } break; case transfer_encoding_chunked: case connection_keep_alive: case connection_close: if (SPACE != ch) header_state = HState.general; break; default: state = State.header_value; header_state = HState.general; break; } break; } // header_value case header_almost_done: if (!header_almost_done(ch)) { return error(settings, "incorrect header ending, expecting LF", data); } break; case header_value_lws: if (SPACE == ch || TAB == ch ){ state = header_value_start; } else { state = header_field_start; reexecute = true; } break; case headers_almost_done: if (LF != ch) { return error(settings, "header not properly completed", data); } if (0 != (flags & F_TRAILING)) { /* End of a chunked request */ state = new_message(); settings.call_on_headers_complete(this); settings.call_on_message_complete(this); break; } state = headers_done; if (0 != (flags & F_UPGRADE) || HTTPMethod.HTTP_CONNECT == method) { upgrade = true; } /* Here we call the headers_complete callback. This is somewhat * different than other callbacks because if the user returns 1, we * will interpret that as saying that this message has no body. This * is needed for the annoying case of recieving a response to a HEAD * request. */ /* (responses to HEAD request contain a CONTENT-LENGTH header * but no content) * * Consider what to do here: I don't like the idea of the callback * interface having a different contract in the case of HEAD * responses. The alternatives would be either to: * * a.) require the header_complete callback to implement a different * interface or * * b.) provide an overridden execute(bla, bla, boolean * parsingHeader) implementation ... */ /*TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO */ if (null != settings.on_headers_complete) { settings.call_on_headers_complete(this); //return; } // if (null != settings.on_headers_complete) { // switch (settings.on_headers_complete.cb(parser)) { // case 0: // break; // // case 1: // flags |= F_SKIPBODY; // break; // // default: // return p - data; /* Error */ // TODO // RuntimeException ? // } // } reexecute = true; break; case headers_done: if (strict && (LF != ch)) { return error(settings, "STRICT CHECK", data); //TODO correct error msg } nread = 0; // Exit, the rest of the connect is in a different protocol. if (upgrade) { state = new_message(); settings.call_on_message_complete(this); return data.position()-this.p_start; } if (0 != (flags & F_SKIPBODY)) { state = new_message(); settings.call_on_message_complete(this); } else if (0 != (flags & F_CHUNKED)) { /* chunked encoding - ignore Content-Length header */ state = State.chunk_size_start; } else { if (content_length == 0) { /* Content-Length header given but zero: Content-Length: 0\r\n */ state = new_message(); settings.call_on_message_complete(this); } else if (content_length != -1) { /* Content-Length header given and non-zero */ state = State.body_identity; } else { if (type == ParserType.HTTP_REQUEST || !http_message_needs_eof()) { /* Assume content-length 0 - read the next */ state = new_message(); settings.call_on_message_complete(this); } else { /* Read body until EOF */ state = State.body_identity_eof; } } } break; /******************* Header *******************/ /******************* Body *******************/ case body_identity: to_read = min(pe - p, content_length); //TODO change to use buffer? body_mark = p; if (to_read > 0) { settings.call_on_body(this, data, p, to_read); data.position(p+to_read); content_length -= to_read; if (content_length == 0) { state = message_done; reexecute = true; } } break; case body_identity_eof: to_read = pe - p; // TODO change to use buffer ? if (to_read > 0) { settings.call_on_body(this, data, p, to_read); data.position(p+to_read); } break; case message_done: state = new_message(); settings.call_on_message_complete(this); break; /******************* Body *******************/ /******************* Chunk *******************/ case chunk_size_start: if (1 != this.nread) { return error(settings, "nread != 1 (chunking)", data); } if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } c = UNHEX[chi]; if (c == -1) { return error(settings, "invalid hex char in chunk content length", data); } content_length = c; state = State.chunk_size; break; case chunk_size: if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } if (CR == ch) { state = State.chunk_size_almost_done; break; } c = UNHEX[chi]; if (c == -1) { if (SEMI == ch || SPACE == ch) { state = State.chunk_parameters; break; } return error(settings, "invalid hex char in chunk content length", data); } long t = content_length; t *= 16; t += c; if(t < content_length){ return error(settings, "invalid content length", data); } content_length = t; break; case chunk_parameters: if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } /* just ignore this shit. TODO check for overflow */ if (CR == ch) { state = State.chunk_size_almost_done; break; } break; case chunk_size_almost_done: if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } if (strict && LF != ch) { return error(settings, "expected LF at end of chunk size", data); } this.nread = 0; if (0 == content_length) { flags |= F_TRAILING; state = State.header_field_start; } else { state = State.chunk_data; } break; case chunk_data: //TODO Apply changes from C version for s_chunk_data if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } to_read = min(pe-p, content_length); if (to_read > 0) { settings.call_on_body(this, data, p, to_read); data.position(p+to_read); } if (to_read == content_length) { state = State.chunk_data_almost_done; } content_length -= to_read; break; case chunk_data_almost_done: if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } if (strict && CR != ch) { return error(settings, "chunk data terminated incorrectly, expected CR", data); } state = State.chunk_data_done; //TODO CALLBACK_DATA(body) // settings.call_on_body(this, data,p,?); break; case chunk_data_done: if (0 == (flags & F_CHUNKED)) { return error(settings, "not chunked", data); } if (strict && LF != ch) { return error(settings, "chunk data terminated incorrectly, expected LF", data); } state = State.chunk_size_start; break; /******************* Chunk *******************/ default: return error(settings, "unhandled state", data); } // switch } // while p = data.position(); /* Reaching this point assumes that we only received part of a * message, inform the callbacks about the progress made so far*/ settings.call_on_header_field(this, data, header_field_mark, p-header_field_mark); settings.call_on_header_value(this, data, header_value_mark, p-header_value_mark); settings.call_on_url (this, data, url_mark, p-url_mark); settings.call_on_path (this, data, url_mark, p-url_mark); return data.position()-this.p_start; } // execute int error (ParserSettings settings, String mes, ByteBuffer data) { settings.call_on_error(this, mes, data, this.p_start); this.state = State.dead; return data.position()-this.p_start; } public boolean http_message_needs_eof() { if(type == ParserType.HTTP_REQUEST){ return false; } /* See RFC 2616 section 4.4 */ if ((status_code / 100 == 1) || /* 1xx e.g. Continue */ (status_code == 204) || /* No Content */ (status_code == 304) || /* Not Modified */ (flags & F_SKIPBODY) != 0) { /* response to a HEAD request */ return false; } if ((flags & F_CHUNKED) != 0 || content_length != -1) { return false; } return true; } /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns true, then this will be should be * the last message on the connection. * If you are the server, respond with the "Connection: close" header. * If you are the client, close the connection. */ public boolean http_should_keep_alive() { if (http_major > 0 && http_minor > 0) { /* HTTP/1.1 */ if ( 0 != (flags & F_CONNECTION_CLOSE) ) { return false; } } else { /* HTTP/1.0 or earlier */ if ( 0 == (flags & F_CONNECTION_KEEP_ALIVE) ) { return false; } } return !http_message_needs_eof(); } public int parse_url(ByteBuffer data, boolean is_connect, HTTPParserUrl u) { UrlFields uf = UrlFields.UF_MAX; UrlFields old_uf = UrlFields.UF_MAX; u.port = 0; u.field_set = 0; state = (is_connect ? State.req_host_start : State.req_spaces_before_url); int p_init = data.position(); int p = 0; byte ch = 0; while (data.position() != data.limit()) { p = data.position(); ch = data.get(); state = parse_url_char(ch); switch(state) { case dead: return 1; /* Skip delimeters */ case req_schema_slash: case req_schema_slash_slash: case req_host_start: case req_host_v6_start: case req_host_v6_end: case req_port_start: case req_query_string_start: case req_fragment_start: continue; case req_schema: uf = UrlFields.UF_SCHEMA; break; case req_host: case req_host_v6: uf = UrlFields.UF_HOST; break; case req_port: uf = UrlFields.UF_PORT; break; case req_path: uf = UrlFields.UF_PATH; break; case req_query_string: uf = UrlFields.UF_QUERY; break; case req_fragment: uf = UrlFields.UF_FRAGMENT; break; default: return 1; } /* Nothing's changed; soldier on */ if (uf == old_uf) { u.field_data[uf.getIndex()].len++; continue; } u.field_data[uf.getIndex()].off = p - p_init; u.field_data[uf.getIndex()].len = 1; u.field_set |= (1 << uf.getIndex()); old_uf = uf; } /* CONNECT requests can only contain "hostname:port" */ if (is_connect && u.field_set != ((1 << UrlFields.UF_HOST.getIndex())|(1 << UrlFields.UF_PORT.getIndex()))) { return 1; } /* Make sure we don't end somewhere unexpected */ switch (state) { case req_host_v6_start: case req_host_v6: case req_host_v6_end: case req_host: case req_port_start: return 1; default: break; } if (0 != (u.field_set & (1 << UrlFields.UF_PORT.getIndex()))) { /* Don't bother with endp; we've already validated the string */ int v = strtoi(data, p_init + u.field_data[UrlFields.UF_PORT.getIndex()].off); /* Ports have a max value of 2^16 */ if (v > 0xffff) { return 1; } u.port = v; } return 0; } //hacky reimplementation of srttoul, tailored for our simple needs //we only need to parse port val, so no negative values etc int strtoi(ByteBuffer data, int start_pos) { data.position(start_pos); byte ch; String str = ""; while(data.position() < data.limit()) { ch = data.get(); if(Character.isWhitespace((char)ch)){ continue; } if(isDigit(ch)){ str = str + (char)ch; //TODO replace with something less hacky }else{ break; } } return Integer.parseInt(str); } boolean isDigit(byte b) { if (b >= 0x30 && b <=0x39) { return true; } return false; } boolean isHex(byte b) { return isDigit(b) || (lower(b) >= 0x61 /*a*/ && lower(b) <= 0x66 /*f*/); } boolean isAtoZ(byte b) { byte c = lower(b); return (c>= 0x61 /*a*/ && c <= 0x7a /*z*/); } byte lower (byte b) { return (byte)(b|0x20); } byte upper(byte b) { char c = (char)(b); return (byte)Character.toUpperCase(c); } byte token(byte b) { if(!strict){ return (b == (byte)' ') ? (byte)' ' : (byte)tokens[b] ; }else{ return (byte)tokens[b]; } } boolean isHostChar(byte ch){ if(!strict){ return (isAtoZ(ch)) || isDigit(ch) || DOT == ch || DASH == ch || UNDER == ch ; }else{ return (isAtoZ(ch)) || isDigit(ch) || DOT == ch || DASH == ch; } } boolean isNormalUrlChar(int chi) { if(!strict){ return (chi > 0x80) || normal_url_char[chi]; }else{ return normal_url_char[chi]; } } HTTPMethod start_req_method_assign(byte c){ switch (c) { case C: return HTTPMethod.HTTP_CONNECT; /* or COPY, CHECKOUT */ case D: return HTTPMethod.HTTP_DELETE; case G: return HTTPMethod.HTTP_GET; case H: return HTTPMethod.HTTP_HEAD; case L: return HTTPMethod.HTTP_LOCK; case M: return HTTPMethod.HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH */ case N: return HTTPMethod.HTTP_NOTIFY; case O: return HTTPMethod.HTTP_OPTIONS; case P: return HTTPMethod.HTTP_POST; /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ case R: return HTTPMethod.HTTP_REPORT; case S: return HTTPMethod.HTTP_SUBSCRIBE; case T: return HTTPMethod.HTTP_TRACE; case U: return HTTPMethod.HTTP_UNLOCK; /* or UNSUBSCRIBE */ } return null; // ugh. } boolean header_almost_done(byte ch) { if (strict && LF != ch) { return false; } state = State.header_value_lws; // TODO java enums support some sort of bitflag mechanism !? switch (header_state) { case connection_keep_alive: flags |= F_CONNECTION_KEEP_ALIVE; break; case connection_close: flags |= F_CONNECTION_CLOSE; break; case transfer_encoding_chunked: flags |= F_CHUNKED; break; default: break; } return true; } // boolean headers_almost_done (byte ch, ParserSettings settings) { // } // headers_almost_done final int min (int a, int b) { return a < b ? a : b; } final int min (int a, long b) { return a < b ? a : (int)b; } /* probably not the best place to hide this ... */ public boolean HTTP_PARSER_STRICT; State new_message() { if (HTTP_PARSER_STRICT){ return http_should_keep_alive() ? start_state() : State.dead; } else { return start_state(); } } State start_state() { return type == ParserType.HTTP_REQUEST ? State.start_req : State.start_res; } boolean parsing_header(State state) { switch (state) { case chunk_data : case chunk_data_almost_done : case chunk_data_done : case body_identity : case body_identity_eof : case message_done : return false; } return true; } /* "Dial C for Constants" */ static class C { static final int HTTP_MAX_HEADER_SIZE = 80 * 1024; static final int F_CHUNKED = 1 << 0; static final int F_CONNECTION_KEEP_ALIVE = 1 << 1; static final int F_CONNECTION_CLOSE = 1 << 2; static final int F_TRAILING = 1 << 3; static final int F_UPGRADE = 1 << 4; static final int F_SKIPBODY = 1 << 5; static final byte [] UPCASE = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x2d,0x00,0x2f, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, 0x38,0x39,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x00,0x00,0x00,0x00,0x5f, 0x00,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, }; static final byte [] CONNECTION = { 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x49, 0x4f, 0x4e, }; static final byte [] PROXY_CONNECTION = { 0x50, 0x52, 0x4f, 0x58, 0x59, 0x2d, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x49, 0x4f, 0x4e, }; static final byte [] CONTENT_LENGTH = { 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x4e, 0x54, 0x2d, 0x4c, 0x45, 0x4e, 0x47, 0x54, 0x48, }; static final byte [] TRANSFER_ENCODING = { 0x54, 0x52, 0x41, 0x4e, 0x53, 0x46, 0x45, 0x52, 0x2d, 0x45, 0x4e, 0x43, 0x4f, 0x44, 0x49, 0x4e, 0x47, }; static final byte [] UPGRADE = { 0x55, 0x50, 0x47, 0x52, 0x41, 0x44, 0x45, }; static final byte [] CHUNKED = { 0x43, 0x48, 0x55, 0x4e, 0x4b, 0x45, 0x44, }; static final byte [] KEEP_ALIVE = { 0x4b, 0x45, 0x45, 0x50, 0x2d, 0x41, 0x4c, 0x49, 0x56, 0x45, }; static final byte [] CLOSE = { 0x43, 0x4c, 0x4f, 0x53, 0x45, }; /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1*<any CHAR except CTLs or separators> * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ static final char [] tokens = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ 0, 0, 0, 0, 0, 0, 0, 0, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ 0, 0, 0, 0, 0, 0, 0, 0, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ 0, 0, 0, 0, 0, 0, 0, 0, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0, 0, 0, 0, 0, 0, 0, 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ 0, '!', 0, '#', '$', '%', '&', '\'', /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 0, 0, '*', '+', 0, '-', '.', 0 , /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ '0', '1', '2', '3', '4', '5', '6', '7', /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ '8', '9', 0, 0, 0, 0, 0, 0, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ 'X', 'Y', 'Z', 0, 0, 0, 0, '_', /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ 'X', 'Y', 'Z', 0, '|', 0, '~', 0, /* hi bit set, not ascii */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static final byte [] UNHEX = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; static final boolean [] normal_url_char = { /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ false, false, false, false, false, false, false, false, /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ false, false, false, false, false, false, false, false, /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ false, false, false, false, false, false, false, false, /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ false, false, false, false, false, false, false, false, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ false, true, true, false, true, true, true, true, /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ true, true, true, true, true, true, true, true, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ true, true, true, true, true, true, true, true, /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ true, true, true, true, true, true, true, false, /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ true, true, true, true, true, true, true, true, /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ true, true, true, true, true, true, true, true, /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ true, true, true, true, true, true, true, true, /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ true, true, true, true, true, true, true, true, /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ true, true, true, true, true, true, true, true, /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ true, true, true, true, true, true, true, true, /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ true, true, true, true, true, true, true, true, /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ true, true, true, true, true, true, true, false, /* hi bit set, not ascii */ /* Remainder of non-ASCII range are accepted as-is to support implicitly UTF-8 * encoded paths. This is out of spec, but clients generate this and most other * HTTP servers support it. We should, too. */ true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, }; public static final byte A = 0x41; public static final byte B = 0x42; public static final byte C = 0x43; public static final byte D = 0x44; public static final byte E = 0x45; public static final byte F = 0x46; public static final byte G = 0x47; public static final byte H = 0x48; public static final byte I = 0x49; public static final byte J = 0x4a; public static final byte K = 0x4b; public static final byte L = 0x4c; public static final byte M = 0x4d; public static final byte N = 0x4e; public static final byte O = 0x4f; public static final byte P = 0x50; public static final byte Q = 0x51; public static final byte R = 0x52; public static final byte S = 0x53; public static final byte T = 0x54; public static final byte U = 0x55; public static final byte V = 0x56; public static final byte W = 0x57; public static final byte X = 0x58; public static final byte Y = 0x59; public static final byte Z = 0x5a; public static final byte UNDER = 0x5f; public static final byte CR = 0x0d; public static final byte LF = 0x0a; public static final byte DOT = 0x2e; public static final byte SPACE = 0x20; public static final byte TAB = 0x09; public static final byte SEMI = 0x3b; public static final byte COLON = 0x3a; public static final byte HASH = 0x23; public static final byte QMARK = 0x3f; public static final byte SLASH = 0x2f; public static final byte DASH = 0x2d; public static final byte STAR = 0x2a; public static final byte NULL = 0x00; } enum State { dead , start_req_or_res , res_or_resp_H , start_res , res_H , res_HT , res_HTT , res_HTTP , res_first_http_major , res_http_major , res_first_http_minor , res_http_minor , res_first_status_code , res_status_code , res_status , res_line_almost_done , start_req , req_method , req_spaces_before_url , req_schema , req_schema_slash , req_schema_slash_slash , req_host_start , req_host_v6_start , req_host_v6 , req_host_v6_end , req_host , req_port_start , req_port , req_path , req_query_string_start , req_query_string , req_fragment_start , req_fragment , req_http_start , req_http_H , req_http_HT , req_http_HTT , req_http_HTTP , req_first_http_major , req_http_major , req_first_http_minor , req_http_minor , req_line_almost_done , header_field_start , header_field , header_value_start , header_value , header_value_lws , header_almost_done , chunk_size_start , chunk_size , chunk_parameters , chunk_size_almost_done , headers_almost_done , headers_done // This space intentionally not left blank, comment from c, for orientation... // the c version uses <= s_header_almost_done in java, we list the states explicitly // in `parsing_header()` /* Important: 's_headers_done' must be the last 'header' state. All * states beyond this must be 'body' states. It is used for overflow * checking. See the PARSING_HEADER() macro. */ , chunk_data , chunk_data_almost_done , chunk_data_done , body_identity , body_identity_eof , message_done } enum HState { general , C , CO , CON , matching_connection , matching_proxy_connection , matching_content_length , matching_transfer_encoding , matching_upgrade , connection , content_length , transfer_encoding , upgrade , matching_transfer_encoding_chunked , matching_connection_keep_alive , matching_connection_close , transfer_encoding_chunked , connection_keep_alive , connection_close } public enum UrlFields { UF_SCHEMA(0) , UF_HOST(1) , UF_PORT(2) , UF_PATH(3) , UF_QUERY(4) , UF_FRAGMENT(5) , UF_MAX(6); private final int index; private UrlFields(int index) { this.index = index; } public int getIndex() { return index; } } }
mit
RohanHart/camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/listener/MapEntryListener.java
1482
/** * 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.hazelcast.listener; import com.hazelcast.map.listener.EntryAddedListener; import com.hazelcast.map.listener.EntryEvictedListener; import com.hazelcast.map.listener.EntryMergedListener; import com.hazelcast.map.listener.EntryRemovedListener; import com.hazelcast.map.listener.EntryUpdatedListener; import com.hazelcast.map.listener.MapClearedListener; import com.hazelcast.map.listener.MapEvictedListener; public interface MapEntryListener<K, V> extends MapClearedListener, MapEvictedListener, EntryAddedListener<K, V>, EntryEvictedListener<K, V>, EntryRemovedListener<K, V>, EntryMergedListener<K, V>, EntryUpdatedListener<K, V> { }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/jdk/test/javax/management/openmbean/IsValueTest.java
5585
/* * Copyright (c) 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. * * 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. */ /* * @test * @bug 5072004 * @summary Test new rules for isValue * @author Eamonn McManus */ import javax.management.openmbean.*; public class IsValueTest { private static String failed; public static void main(String[] args) throws Exception { CompositeType ctOld = new CompositeType("same.type.name", "old", new String[] {"int", "string"}, new String[] {"an int", "a string"}, new OpenType[] {SimpleType.INTEGER, SimpleType.STRING}); CompositeType ctNew = new CompositeType("same.type.name", "new", new String[] {"int", "int2", "string"}, new String[] {"an int", "another int", "a string"}, new OpenType[] {SimpleType.INTEGER, SimpleType.INTEGER, SimpleType.STRING}); CompositeData cdOld = new CompositeDataSupport(ctOld, new String[] {"string", "int"}, new Object[] {"bar", 17}); CompositeData cdNew = new CompositeDataSupport(ctNew, new String[] {"int2", "int", "string"}, new Object[] {4, 3, "foo"}); // Check that adding fields doesn't make isValue return false check(ctOld.isValue(cdNew), "isValue: " + ctOld + "[" + cdNew + "]"); // Check that removing fields does make isValue return false check(!ctNew.isValue(cdOld), "isValue: " + ctNew + "[" + cdOld + "]"); // Check that we can add a contained CompositeData with extra fields // inside another CompositeData CompositeType ctWrapOld = new CompositeType("wrapper", "wrapper", new String[] {"wrapped"}, new String[] {"wrapped"}, new OpenType[] {ctOld}); try { new CompositeDataSupport(ctWrapOld, new String[] {"wrapped"}, new Object[] {cdNew}); check(true, "CompositeDataSupport containing CompositeDataSupport"); } catch (Exception e) { e.printStackTrace(System.out); check(false, "CompositeDataSupport containing CompositeDataSupport: " + e); } // ...but not the contrary CompositeType ctWrapNew = new CompositeType("wrapper", "wrapper", new String[] {"wrapped"}, new String[] {"wrapped"}, new OpenType[] {ctNew}); try { new CompositeDataSupport(ctWrapNew, new String[] {"wrapped"}, new Object[] {cdOld}); check(false, "CompositeDataSupport containing old did not get exception"); } catch (OpenDataException e) { check(true, "CompositeDataSupport containing old got expected exception: " + e); } // Check that a TabularData can get an extended CompositeData row TabularType ttOld = new TabularType("tabular", "tabular", ctOld, new String[] {"int"}); TabularData tdOld = new TabularDataSupport(ttOld); try { tdOld.put(cdNew); check(true, "TabularDataSupport adding extended CompositeData"); } catch (Exception e) { e.printStackTrace(System.out); check(false, "TabularDataSupport adding extended CompositeData: " + e); } // Check that an extended TabularData can be put into a CompositeData TabularType ttNew = new TabularType("tabular", "tabular", ctNew, new String[] {"int"}); TabularData tdNew = new TabularDataSupport(ttNew); CompositeType cttWrap = new CompositeType("wrapTT", "wrapTT", new String[] {"wrapped"}, new String[] {"wrapped"}, new OpenType[] {ttOld}); try { new CompositeDataSupport(cttWrap, new String[] {"wrapped"}, new Object[] {tdNew}); check(true, "CompositeDataSupport adding extended TabularData"); } catch (Exception e) { e.printStackTrace(System.out); check(false, "CompositeDataSupport adding extended TabularData: " + e); } if (failed != null) throw new Exception("TEST FAILED: " + failed); } private static void check(boolean value, String what) { if (value) System.out.println("OK: " + what); else { failed = what; System.out.println("FAILED: " + what); } } }
mit
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javac/tree/TreePosRoundsTest.java
7450
/* * Copyright (c) 2010, 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. */ /* * @test * @bug 6985205 6986246 * @summary access to tree positions and doc comments may be lost across annotation processing rounds * @build TreePosRoundsTest * @compile -proc:only -processor TreePosRoundsTest TreePosRoundsTest.java * @run main TreePosRoundsTest */ import java.io.*; import java.util.*; import javax.annotation.processing.*; import javax.lang.model.*; import javax.lang.model.element.*; import javax.tools.*; import com.sun.source.tree.*; import com.sun.source.util.*; import javax.tools.JavaCompiler.CompilationTask; // This test is an annotation processor that performs multiple rounds of // processing, and on each round, it checks that source positions are // available and correct. // // The test can be run directly as a processor from the javac command line // or via JSR 199 by invoking the main program. @SupportedAnnotationTypes("*") public class TreePosRoundsTest extends AbstractProcessor { public static void main(String... args) throws Exception { String testSrc = System.getProperty("test.src"); String testClasses = System.getProperty("test.classes"); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = c.getStandardFileManager(null, null, null); String thisName = TreePosRoundsTest.class.getName(); File thisFile = new File(testSrc, thisName + ".java"); Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(thisFile); List<String> options = Arrays.asList( "-proc:only", "-processor", thisName, "-processorpath", testClasses); CompilationTask t = c.getTask(null, fm, null, options, null, files); boolean ok = t.call(); if (!ok) throw new Exception("processing failed"); } Filer filer; Messager messager; Trees trees; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } @Override public void init(ProcessingEnvironment pEnv) { super.init(pEnv); filer = pEnv.getFiler(); messager = pEnv.getMessager(); trees = Trees.instance(pEnv); } int round = 0; @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { round++; // Scan trees for elements, verifying source tree positions for (Element e: roundEnv.getRootElements()) { try { TreePath p = trees.getPath(e); new TestTreeScanner(p.getCompilationUnit(), trees).scan(trees.getPath(e), null); } catch (IOException ex) { messager.printMessage(Diagnostic.Kind.ERROR, "Cannot get source: " + ex, e); } } final int MAXROUNDS = 3; if (round < MAXROUNDS) generateSource("Gen" + round); return true; } void generateSource(String name) { StringBuilder text = new StringBuilder(); text.append("class ").append(name).append("{\n"); text.append(" int one = 1;\n"); text.append(" int two = 2;\n"); text.append(" int three = one + two;\n"); text.append("}\n"); try { JavaFileObject fo = filer.createSourceFile(name); Writer out = fo.openWriter(); try { out.write(text.toString()); } finally { out.close(); } } catch (IOException e) { throw new Error(e); } } class TestTreeScanner extends TreePathScanner<Void,Void> { TestTreeScanner(CompilationUnitTree unit, Trees trees) throws IOException { this.unit = unit; JavaFileObject sf = unit.getSourceFile(); source = sf.getCharContent(true).toString(); sourcePositions = trees.getSourcePositions(); } @Override public Void visitVariable(VariableTree tree, Void _) { check(getCurrentPath()); return super.visitVariable(tree, _); } void check(TreePath tp) { Tree tree = tp.getLeaf(); String expect = tree.toString(); if (tree.getKind() == Tree.Kind.VARIABLE) { // tree.toString() does not know enough context to add ";", // so deal with that manually... Tree.Kind enclKind = tp.getParentPath().getLeaf().getKind(); //System.err.println(" encl: " +enclKind); if (enclKind == Tree.Kind.CLASS || enclKind == Tree.Kind.BLOCK) expect += ";"; } //System.err.println("expect: " + expect); int start = (int)sourcePositions.getStartPosition(unit, tree); if (start == Diagnostic.NOPOS) { messager.printMessage(Diagnostic.Kind.ERROR, "start pos not set for " + trim(tree)); return; } int end = (int)sourcePositions.getEndPosition(unit, tree); if (end == Diagnostic.NOPOS) { messager.printMessage(Diagnostic.Kind.ERROR, "end pos not set for " + trim(tree)); return; } String found = source.substring(start, end); //System.err.println(" found: " + found); // allow for long lines, in which case just compare beginning and // end of the strings boolean equal; if (found.contains("\n")) { String head = found.substring(0, found.indexOf("\n")); String tail = found.substring(found.lastIndexOf("\n")).trim(); equal = expect.startsWith(head) && expect.endsWith(tail); } else { equal = expect.equals(found); } if (!equal) { messager.printMessage(Diagnostic.Kind.ERROR, "unexpected value found: '" + found + "'; expected: '" + expect + "'"); } } String trim(Tree tree) { final int MAXLEN = 32; String s = tree.toString().replaceAll("\\s+", " ").trim(); return (s.length() < MAXLEN) ? s : s.substring(0, MAXLEN); } CompilationUnitTree unit; SourcePositions sourcePositions; String source; } }
mit
dgrif/binnavi
src/main/java/com/google/security/zynamics/reil/translators/ppc/LhzuxTranslator.java
1532
/* Copyright 2015 Google Inc. 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.security.zynamics.reil.translators.ppc; import com.google.security.zynamics.reil.OperandSize; import com.google.security.zynamics.reil.ReilInstruction; import com.google.security.zynamics.reil.translators.IInstructionTranslator; import com.google.security.zynamics.reil.translators.ITranslationEnvironment; import com.google.security.zynamics.reil.translators.InternalTranslationException; import com.google.security.zynamics.zylib.disassembly.IInstruction; import java.util.List; public class LhzuxTranslator implements IInstructionTranslator { @Override public void translate(final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { LoadGenerator.generate(instruction.getAddress().toLong() * 0x100, environment, instruction, instructions, "lhzux", OperandSize.WORD, true, true, false, false, false); } }
apache-2.0
asedunov/intellij-community
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayoutUiFactoryImpl.java
1468
/* * Copyright 2000-2009 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.execution.ui.layout.impl; import com.intellij.execution.ExecutionManager; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class RunnerLayoutUiFactoryImpl extends RunnerLayoutUi.Factory { private final Project myProject; public RunnerLayoutUiFactoryImpl(Project project, ExecutionManager executionManager) { myProject = project; executionManager.getContentManager(); // ensure dockFactory is registered } @NotNull @Override public RunnerLayoutUi create(@NotNull final String runnerId, @NotNull final String runnerTitle, @NotNull final String sessionName, @NotNull final Disposable parent) { return new RunnerLayoutUiImpl(myProject, parent, runnerId, runnerTitle, sessionName); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/langtools/test/tools/javap/4111861/A.java
521
class A { public static final int i = 42; public static final boolean b = true; public static final float f = 1.0f; public static final double d = 1.0d; public static final short s = 1; public static final long l = 1l; public static final char cA = 'A'; public static final char c0 = '\u0000'; public static final char cn = '\n'; public static final char cq1 = '\''; public static final char cq2 = '"'; public static final java.lang.String t1 = "abc \u0000 \f\n\r\t'\""; }
mit
davidwilliams1978/camel
components/camel-gae/src/test/java/org/apache/camel/component/gae/http/GHttpOutboundRouteBuilderTest.java
3798
/** * 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.gae.http; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.appengine.tools.development.testing.LocalURLFetchServiceTestConfig; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.ProducerTemplate; import org.eclipse.jetty.server.Server; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/org/apache/camel/component/gae/http/context-outbound.xml"}) public class GHttpOutboundRouteBuilderTest { private static Server testServer = GHttpTestUtils.createTestServer(); private final LocalURLFetchServiceTestConfig config = new LocalURLFetchServiceTestConfig(); private final LocalServiceTestHelper helper = new LocalServiceTestHelper(config); @Autowired private ProducerTemplate producerTemplate; @BeforeClass public static void setUpBeforeClass() throws Exception { testServer.start(); } @AfterClass public static void tearDownAfterClass() throws Exception { testServer.stop(); } @Before public void setUp() throws Exception { helper.setUp(); } @After public void tearDown() throws Exception { helper.tearDown(); } @Test public void testPost() { Exchange result = producerTemplate.request("direct:input1", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("testBody1"); exchange.getIn().setHeader("test", "testHeader1"); } }); assertEquals("testBody1", result.getOut().getBody(String.class)); assertEquals("testHeader1", result.getOut().getHeader("test")); assertEquals("a=b", result.getOut().getHeader("testQuery")); assertEquals("POST", result.getOut().getHeader("testMethod")); assertEquals(200, result.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE)); } @Test public void testGet() { Exchange result = producerTemplate.request("direct:input1", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("test", "testHeader1"); } }); assertEquals("testHeader1", result.getOut().getHeader("test")); assertEquals("a=b", result.getOut().getHeader("testQuery")); assertEquals("GET", result.getOut().getHeader("testMethod")); assertEquals(200, result.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE)); } }
apache-2.0
kdwink/intellij-community
java/compiler/forms-compiler/src/com/intellij/uiDesigner/lw/LwIntroIconProperty.java
1093
/* * Copyright 2000-2009 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.uiDesigner.lw; import com.intellij.uiDesigner.UIFormXmlConstants; import org.jdom.Element; /** * @author yole */ public class LwIntroIconProperty extends LwIntrospectedProperty { public LwIntroIconProperty(final String name) { super(name, "javax.swing.Icon"); } public Object read(Element element) throws Exception { String value = LwXmlReader.getRequiredString(element, UIFormXmlConstants.ATTRIBUTE_VALUE); return new IconDescriptor(value); } }
apache-2.0