repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
pleacu/jbpm
jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/query/mapper/TaskSummaryQueryMapper.java
4178
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.kie.services.impl.query.mapper; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.dashbuilder.dataset.DataSet; import org.jbpm.services.api.query.QueryResultMapper; import org.jbpm.services.task.query.TaskSummaryImpl; import org.kie.api.task.model.Status; import org.kie.api.task.model.TaskSummary; /** * Dedicated mapper that transform data set into List of TaskSummary * */ public class TaskSummaryQueryMapper extends AbstractQueryMapper<TaskSummary> implements QueryResultMapper<List<TaskSummary>> { private static final long serialVersionUID = 5935133069234696712L; /** * Dedicated for ServiceLoader to create instance, use <code>get()</code> method instead */ public TaskSummaryQueryMapper() { super(); } public static TaskSummaryQueryMapper get() { return new TaskSummaryQueryMapper(); } @Override public List<TaskSummary> map(Object result) { if (result instanceof DataSet) { DataSet dataSetResult = (DataSet) result; List<TaskSummary> mappedResult = new ArrayList<TaskSummary>(); if (dataSetResult != null) { for (int i = 0; i < dataSetResult.getRowCount(); i++) { TaskSummary ut = buildInstance(dataSetResult, i); mappedResult.add(ut); } } return mappedResult; } throw new IllegalArgumentException("Unsupported result for mapping " + result); } @Override protected TaskSummary buildInstance(DataSet dataSetResult, int index) { TaskSummary userTask = new TaskSummaryImpl( getColumnLongValue(dataSetResult, COLUMN_TASKID, index),//taskId, getColumnStringValue(dataSetResult, COLUMN_NAME, index),//name, getColumnStringValue(dataSetResult, COLUMN_SUBJECT, index),//subject, getColumnStringValue(dataSetResult, COLUMN_DESCRIPTION, index),//description, Status.valueOf(getColumnStringValue(dataSetResult, COLUMN_TASK_STATUS, index)),//status, getColumnIntValue(dataSetResult, COLUMN_PRIORITY, index),//priority, getColumnStringValue(dataSetResult, COLUMN_ACTUALOWNER, index),//actualOwner, getColumnStringValue(dataSetResult, COLUMN_CREATEDBY, index),//createdBy, getColumnDateValue(dataSetResult, COLUMN_CREATEDON, index),//createdOn, getColumnDateValue(dataSetResult, COLUMN_ACTIVATIONTIME, index),//activationTime, getColumnDateValue(dataSetResult, COLUMN_DUEDATE, index),//dueDate getColumnStringValue(dataSetResult, COLUMN_TASK_PROCESSID, index),//processId, getColumnLongValue(dataSetResult, COLUMN_TASK_PROCESSINSTANCEID, index),//processInstanceId, -1l, getColumnStringValue(dataSetResult, COLUMN_DEPLOYMENTID, index),//deploymentId, false ); return userTask; } @Override public String getName() { return "TaskSummaries"; } @Override public Class<?> getType() { return TaskSummary.class; } @Override public QueryResultMapper<List<TaskSummary>> forColumnMapping(Map<String, String> columnMapping) { return new TaskSummaryQueryMapper(); } }
apache-2.0
SaiNadh001/aws-sdk-for-java
src/main/java/com/amazonaws/services/sqs/model/ChangeMessageVisibilityBatchRequest.java
8150
/* * Copyright 2010-2012 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.sqs.model; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.sqs.AmazonSQS#changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest) ChangeMessageVisibilityBatch operation}. * <p> * This is a batch version of ChangeMessageVisibility. It takes multiple receipt handles and performs the operation on each of the them. The result of * the operation on each message is reported individually in the response. * </p> * * @see com.amazonaws.services.sqs.AmazonSQS#changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest) */ public class ChangeMessageVisibilityBatchRequest extends AmazonWebServiceRequest { /** * The URL of the SQS queue to take action on. */ private String queueUrl; /** * A list of receipt handles of the messages for which the visibility * timeout must be changed. */ private java.util.List<ChangeMessageVisibilityBatchRequestEntry> entries; /** * Default constructor for a new ChangeMessageVisibilityBatchRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public ChangeMessageVisibilityBatchRequest() {} /** * Constructs a new ChangeMessageVisibilityBatchRequest object. * Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param queueUrl The URL of the SQS queue to take action on. * @param entries A list of receipt handles of the messages for which the * visibility timeout must be changed. */ public ChangeMessageVisibilityBatchRequest(String queueUrl, java.util.List<ChangeMessageVisibilityBatchRequestEntry> entries) { this.queueUrl = queueUrl; this.entries = entries; } /** * The URL of the SQS queue to take action on. * * @return The URL of the SQS queue to take action on. */ public String getQueueUrl() { return queueUrl; } /** * The URL of the SQS queue to take action on. * * @param queueUrl The URL of the SQS queue to take action on. */ public void setQueueUrl(String queueUrl) { this.queueUrl = queueUrl; } /** * The URL of the SQS queue to take action on. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param queueUrl The URL of the SQS queue to take action on. * * @return A reference to this updated object so that method calls can be chained * together. */ public ChangeMessageVisibilityBatchRequest withQueueUrl(String queueUrl) { this.queueUrl = queueUrl; return this; } /** * A list of receipt handles of the messages for which the visibility * timeout must be changed. * * @return A list of receipt handles of the messages for which the visibility * timeout must be changed. */ public java.util.List<ChangeMessageVisibilityBatchRequestEntry> getEntries() { if (entries == null) { entries = new java.util.ArrayList<ChangeMessageVisibilityBatchRequestEntry>(); } return entries; } /** * A list of receipt handles of the messages for which the visibility * timeout must be changed. * * @param entries A list of receipt handles of the messages for which the visibility * timeout must be changed. */ public void setEntries(java.util.Collection<ChangeMessageVisibilityBatchRequestEntry> entries) { if (entries == null) { this.entries = null; return; } java.util.List<ChangeMessageVisibilityBatchRequestEntry> entriesCopy = new java.util.ArrayList<ChangeMessageVisibilityBatchRequestEntry>(entries.size()); entriesCopy.addAll(entries); this.entries = entriesCopy; } /** * A list of receipt handles of the messages for which the visibility * timeout must be changed. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param entries A list of receipt handles of the messages for which the visibility * timeout must be changed. * * @return A reference to this updated object so that method calls can be chained * together. */ public ChangeMessageVisibilityBatchRequest withEntries(ChangeMessageVisibilityBatchRequestEntry... entries) { if (getEntries() == null) setEntries(new java.util.ArrayList<ChangeMessageVisibilityBatchRequestEntry>(entries.length)); for (ChangeMessageVisibilityBatchRequestEntry value : entries) { getEntries().add(value); } return this; } /** * A list of receipt handles of the messages for which the visibility * timeout must be changed. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param entries A list of receipt handles of the messages for which the visibility * timeout must be changed. * * @return A reference to this updated object so that method calls can be chained * together. */ public ChangeMessageVisibilityBatchRequest withEntries(java.util.Collection<ChangeMessageVisibilityBatchRequestEntry> entries) { if (entries == null) { this.entries = null; } else { java.util.List<ChangeMessageVisibilityBatchRequestEntry> entriesCopy = new java.util.ArrayList<ChangeMessageVisibilityBatchRequestEntry>(entries.size()); entriesCopy.addAll(entries); this.entries = entriesCopy; } return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (queueUrl != null) sb.append("QueueUrl: " + queueUrl + ", "); if (entries != null) sb.append("Entries: " + entries + ", "); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getQueueUrl() == null) ? 0 : getQueueUrl().hashCode()); hashCode = prime * hashCode + ((getEntries() == null) ? 0 : getEntries().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ChangeMessageVisibilityBatchRequest == false) return false; ChangeMessageVisibilityBatchRequest other = (ChangeMessageVisibilityBatchRequest)obj; if (other.getQueueUrl() == null ^ this.getQueueUrl() == null) return false; if (other.getQueueUrl() != null && other.getQueueUrl().equals(this.getQueueUrl()) == false) return false; if (other.getEntries() == null ^ this.getEntries() == null) return false; if (other.getEntries() != null && other.getEntries().equals(this.getEntries()) == false) return false; return true; } }
apache-2.0
gmrodrigues/crate
sql/src/main/java/io/crate/metadata/sys/SysSchemaInfo.java
3186
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.metadata.sys; import com.google.common.collect.ImmutableMap; import io.crate.metadata.table.SchemaInfo; import io.crate.metadata.table.TableInfo; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Singleton; import javax.annotation.Nonnull; import java.util.Iterator; @Singleton public class SysSchemaInfo implements SchemaInfo { public static final String NAME = "sys"; private final ImmutableMap<String, TableInfo> tableInfos; @Inject public SysSchemaInfo(ClusterService clusterService) { SysNodesTableInfo sysNodesTableInfo = new SysNodesTableInfo(clusterService, this); tableInfos = ImmutableMap.<String, TableInfo>builder() .put(SysClusterTableInfo.IDENT.name(), new SysClusterTableInfo(clusterService, this)) .put(SysNodesTableInfo.IDENT.name(), sysNodesTableInfo) .put(SysShardsTableInfo.IDENT.name(), new SysShardsTableInfo(clusterService, this, sysNodesTableInfo)) .put(SysJobsTableInfo.IDENT.name(), new SysJobsTableInfo(clusterService, this)) .put(SysJobsLogTableInfo.IDENT.name(), new SysJobsLogTableInfo(clusterService, this)) .put(SysOperationsTableInfo.IDENT.name(), new SysOperationsTableInfo(clusterService, this, sysNodesTableInfo)) .put(SysOperationsLogTableInfo.IDENT.name(), new SysOperationsLogTableInfo(clusterService, this)) .put(SysChecksTableInfo.IDENT.name(), new SysChecksTableInfo(clusterService, this)) .build(); } @Override public TableInfo getTableInfo(String name) { return tableInfos.get(name); } @Override public String name() { return NAME; } @Override public boolean systemSchema() { return true; } @Override public void invalidateTableCache(String tableName) { } @Override @Nonnull public Iterator<TableInfo> iterator() { return tableInfos.values().iterator(); } @Override public void close() throws Exception { } }
apache-2.0
hgschmie/presto
presto-spi/src/main/java/io/prestosql/spi/predicate/Domain.java
9508
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.spi.predicate; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.prestosql.spi.connector.ConnectorSession; import io.prestosql.spi.type.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Defines the possible values of a single variable in terms of its valid scalar values and nullability. * <p> * For example: * <p> * <ul> * <li>Domain.none() => no scalar values allowed, NULL not allowed * <li>Domain.all() => all scalar values allowed, NULL allowed * <li>Domain.onlyNull() => no scalar values allowed, NULL allowed * <li>Domain.notNull() => all scalar values allowed, NULL not allowed * </ul> * <p> */ public final class Domain { private final ValueSet values; private final boolean nullAllowed; private Domain(ValueSet values, boolean nullAllowed) { this.values = requireNonNull(values, "values is null"); this.nullAllowed = nullAllowed; } @JsonCreator public static Domain create( @JsonProperty("values") ValueSet values, @JsonProperty("nullAllowed") boolean nullAllowed) { return new Domain(values, nullAllowed); } public static Domain none(Type type) { return new Domain(ValueSet.none(type), false); } public static Domain all(Type type) { return new Domain(ValueSet.all(type), true); } public static Domain onlyNull(Type type) { return new Domain(ValueSet.none(type), true); } public static Domain notNull(Type type) { return new Domain(ValueSet.all(type), false); } public static Domain singleValue(Type type, Object value) { return new Domain(ValueSet.of(type, value), false); } public static Domain multipleValues(Type type, List<?> values) { if (values.isEmpty()) { throw new IllegalArgumentException("values cannot be empty"); } if (values.size() == 1) { return singleValue(type, values.get(0)); } return new Domain(ValueSet.of(type, values.get(0), values.subList(1, values.size()).toArray()), false); } public Type getType() { return values.getType(); } @JsonProperty public ValueSet getValues() { return values; } @JsonProperty public boolean isNullAllowed() { return nullAllowed; } public boolean isNone() { return values.isNone() && !nullAllowed; } public boolean isAll() { return values.isAll() && nullAllowed; } public boolean isSingleValue() { return !nullAllowed && values.isSingleValue(); } public boolean isNullableSingleValue() { if (nullAllowed) { return values.isNone(); } else { return values.isSingleValue(); } } public boolean isOnlyNull() { return values.isNone() && nullAllowed; } public Object getSingleValue() { if (!isSingleValue()) { throw new IllegalStateException("Domain is not a single value"); } return values.getSingleValue(); } public Object getNullableSingleValue() { if (!isNullableSingleValue()) { throw new IllegalStateException("Domain is not a nullable single value"); } if (nullAllowed) { return null; } else { return values.getSingleValue(); } } public boolean includesNullableValue(Object value) { return value == null ? nullAllowed : values.containsValue(value); } boolean isNullableDiscreteSet() { return values.isNone() ? nullAllowed : values.isDiscreteSet(); } DiscreteSet getNullableDiscreteSet() { if (!isNullableDiscreteSet()) { throw new IllegalStateException("Domain is not a nullable discrete set"); } return new DiscreteSet( values.isNone() ? List.of() : values.getDiscreteSet(), nullAllowed); } public boolean overlaps(Domain other) { checkCompatibility(other); if (this.isNullAllowed() && other.isNullAllowed()) { return true; } return values.overlaps(other.getValues()); } public boolean contains(Domain other) { checkCompatibility(other); return this.union(other).equals(this); } public Domain intersect(Domain other) { checkCompatibility(other); return new Domain(values.intersect(other.getValues()), this.isNullAllowed() && other.isNullAllowed()); } public Domain union(Domain other) { checkCompatibility(other); return new Domain(values.union(other.getValues()), this.isNullAllowed() || other.isNullAllowed()); } public static Domain union(List<Domain> domains) { if (domains.isEmpty()) { throw new IllegalArgumentException("domains cannot be empty for union"); } if (domains.size() == 1) { return domains.get(0); } boolean nullAllowed = false; List<ValueSet> valueSets = new ArrayList<>(domains.size()); for (Domain domain : domains) { valueSets.add(domain.getValues()); nullAllowed = nullAllowed || domain.nullAllowed; } ValueSet unionedValues = valueSets.get(0).union(valueSets.subList(1, valueSets.size())); return new Domain(unionedValues, nullAllowed); } public Domain complement() { return new Domain(values.complement(), !nullAllowed); } public Domain subtract(Domain other) { checkCompatibility(other); return new Domain(values.subtract(other.getValues()), this.isNullAllowed() && !other.isNullAllowed()); } private void checkCompatibility(Domain domain) { if (!getType().equals(domain.getType())) { throw new IllegalArgumentException(format("Mismatched Domain types: %s vs %s", getType(), domain.getType())); } if (values.getClass() != domain.values.getClass()) { throw new IllegalArgumentException(format("Mismatched Domain value set classes: %s vs %s", values.getClass(), domain.values.getClass())); } } @Override public int hashCode() { return Objects.hash(values, nullAllowed); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Domain other = (Domain) obj; return Objects.equals(this.values, other.values) && this.nullAllowed == other.nullAllowed; } /** * Reduces the number of discrete components in the Domain if there are too many. */ public Domain simplify() { return simplify(32); } public Domain simplify(int threshold) { ValueSet simplifiedValueSet = values.getValuesProcessor().<Optional<ValueSet>>transform( ranges -> { if (ranges.getRangeCount() <= threshold) { return Optional.empty(); } return Optional.of(ValueSet.ofRanges(ranges.getSpan())); }, discreteValues -> { if (discreteValues.getValuesCount() <= threshold) { return Optional.empty(); } return Optional.of(ValueSet.all(values.getType())); }, allOrNone -> Optional.empty()) .orElse(values); return Domain.create(simplifiedValueSet, nullAllowed); } @Override public String toString() { return "[ " + (nullAllowed ? "NULL, " : "") + values.toString() + " ]"; } public String toString(ConnectorSession session) { return "[ " + (nullAllowed ? "NULL, " : "") + values.toString(session) + " ]"; } static class DiscreteSet { private final List<Object> nonNullValues; private final boolean containsNull; DiscreteSet(List<Object> values, boolean containsNull) { this.nonNullValues = requireNonNull(values, "values is null"); this.containsNull = containsNull; if (!containsNull && values.isEmpty()) { throw new IllegalArgumentException("Discrete set cannot be empty"); } } List<Object> getNonNullValues() { return nonNullValues; } boolean containsNull() { return containsNull; } } }
apache-2.0
vschs007/buck
src/com/facebook/buck/rules/BuildOutputInitializer.java
2286
/* * Copyright 2014-present Facebook, 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.facebook.buck.rules; import com.facebook.buck.model.BuildTarget; import java.io.IOException; import javax.annotation.Nullable; /** * Delegates the actual reading of disk-cached data to the {@link InitializableFromDisk} and is * responsible for safely storing and retrieving the in-memory data structures. */ public class BuildOutputInitializer<T> { private final BuildTarget buildTarget; private final InitializableFromDisk<T> initializableFromDisk; @Nullable private T buildOutput; public BuildOutputInitializer( BuildTarget buildTarget, InitializableFromDisk<T> initializableFromDisk) { this.buildTarget = buildTarget; this.initializableFromDisk = initializableFromDisk; } public T initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) throws IOException { return initializableFromDisk.initializeFromDisk(onDiskBuildInfo); } /** * This should be invoked only by the build engine (currently, {@link CachingBuildEngine}) * that invoked {@link #initializeFromDisk(OnDiskBuildInfo)}. * <p> * @throws IllegalStateException if this method has already been invoked. */ public void setBuildOutput(T buildOutput) throws IllegalStateException { this.buildOutput = buildOutput; } /** * @return the value passed to {@link #setBuildOutput(Object)}. * @throws IllegalStateException if {@link #setBuildOutput(Object)} has not been invoked yet. */ public T getBuildOutput() throws IllegalStateException { if (buildOutput == null) { throw new IllegalStateException( String.format("buildOutput must already be set for %s", buildTarget)); } return buildOutput; } }
apache-2.0
mmacfadden/orientdb
core/src/test/java/com/orientechnologies/orient/core/index/sbtree/local/SBTreeWAL.java
15266
package com.orientechnologies.orient.core.index.sbtree.local; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory; import com.orientechnologies.orient.core.storage.cache.local.OWOWCache; import com.orientechnologies.orient.core.storage.cache.OWriteCache; import com.orientechnologies.orient.core.storage.fs.OFileClassic; import com.orientechnologies.orient.core.storage.impl.local.OStorageVariableParser; import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperationsManager; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.*; import com.orientechnologies.common.serialization.types.OIntegerSerializer; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.config.OStorageClusterConfiguration; import com.orientechnologies.orient.core.config.OStorageConfiguration; import com.orientechnologies.orient.core.config.OStorageSegmentConfiguration; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.storage.cache.OCacheEntry; import com.orientechnologies.orient.core.storage.cache.OReadCache; import com.orientechnologies.orient.core.storage.cache.local.O2QCache; import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer; import com.orientechnologies.orient.core.storage.impl.local.paginated.OClusterPage; import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage; import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.*; /** * @author Andrey Lomakin * @since 8/27/13 */ @Test public class SBTreeWAL extends SBTreeTest { static { OGlobalConfiguration.INDEX_TX_MODE.setValue("FULL"); OGlobalConfiguration.FILE_LOCK.setValue(false); } private String buildDirectory; private String actualStorageDir; private String expectedStorageDir; private ODiskWriteAheadLog writeAheadLog; private OReadCache actualReadCache; private OWriteCache actualWriteCache; private OReadCache expectedReadCache; private OWriteCache expectedWriteCache; private OLocalPaginatedStorage actualStorage; private OSBTree<Integer, OIdentifiable> expectedSBTree; private OLocalPaginatedStorage expectedStorage; private OStorageConfiguration expectedStorageConfiguration; private OStorageConfiguration actualStorageConfiguration; private OAtomicOperationsManager actualAtomicOperationsManager; @BeforeClass @Override public void beforeClass() { actualStorage = mock(OLocalPaginatedStorage.class); actualStorageConfiguration = mock(OStorageConfiguration.class); expectedStorage = mock(OLocalPaginatedStorage.class); expectedStorageConfiguration = mock(OStorageConfiguration.class); } @AfterClass @Override public void afterClass() { } @BeforeMethod public void beforeMethod() throws IOException { Mockito.reset(actualStorage, expectedStorage, expectedStorageConfiguration, actualStorageConfiguration); buildDirectory = System.getProperty("buildDirectory", "."); buildDirectory += "/sbtreeWithWALTest"; createExpectedSBTree(); createActualSBTree(); } @AfterMethod @Override public void afterMethod() throws Exception { Assert.assertNull(actualAtomicOperationsManager.getCurrentOperation()); sbTree.delete(); expectedSBTree.delete(); actualReadCache.deleteStorage(actualWriteCache); actualReadCache.clear(); expectedReadCache.deleteStorage(expectedWriteCache); expectedReadCache.clear(); writeAheadLog.delete(); Assert.assertTrue(new File(actualStorageDir).delete()); Assert.assertTrue(new File(expectedStorageDir).delete()); Assert.assertTrue(new File(buildDirectory).delete()); } private void createActualSBTree() throws IOException { actualStorageConfiguration.clusters = new ArrayList<OStorageClusterConfiguration>(); actualStorageConfiguration.fileTemplate = new OStorageSegmentConfiguration(); actualStorageConfiguration.binaryFormatVersion = Integer.MAX_VALUE; actualStorageDir = buildDirectory + "/sbtreeWithWALTestActual"; when(actualStorage.getStoragePath()).thenReturn(actualStorageDir); when(actualStorage.getName()).thenReturn("sbtreeWithWALTesActual"); File buildDir = new File(buildDirectory); if (!buildDir.exists()) buildDir.mkdirs(); File actualStorageDirFile = new File(actualStorageDir); if (!actualStorageDirFile.exists()) actualStorageDirFile.mkdirs(); writeAheadLog = new ODiskWriteAheadLog(6000, -1, 10 * 1024L * OWALPage.PAGE_SIZE, actualStorage); OStorageVariableParser variableParser = new OStorageVariableParser(actualStorageDir); when(actualStorage.getVariableParser()).thenReturn(variableParser); when(actualStorage.getComponentsFactory()).thenReturn(new OCurrentStorageComponentsFactory(actualStorageConfiguration)); when(actualStorage.getWALInstance()).thenReturn(writeAheadLog); actualAtomicOperationsManager = new OAtomicOperationsManager(actualStorage); actualWriteCache = new OWOWCache(false, OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, 1000000, writeAheadLog, 100, 1648L * 1024 * 1024, 2 * 1648L * 1024 * 1024, actualStorage, true, 10); actualReadCache = new O2QCache(1648L * 1024 * 1024, OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, true, 20); when(actualStorage.getStorageTransaction()).thenReturn(null); when(actualStorage.getReadCache()).thenReturn(actualReadCache); when(actualStorage.getAtomicOperationsManager()).thenReturn(actualAtomicOperationsManager); when(actualStorage.getConfiguration()).thenReturn(actualStorageConfiguration); when(actualStorage.getMode()).thenReturn("rw"); when(actualStorageConfiguration.getDirectory()).thenReturn(actualStorageDir); sbTree = new OSBTree<Integer, OIdentifiable>("actualSBTree", ".sbt", true, ".nbt", actualStorage); sbTree.create(OIntegerSerializer.INSTANCE, OLinkSerializer.INSTANCE, null, 1, false); } private void createExpectedSBTree() { expectedStorageConfiguration.clusters = new ArrayList<OStorageClusterConfiguration>(); expectedStorageConfiguration.fileTemplate = new OStorageSegmentConfiguration(); expectedStorageConfiguration.binaryFormatVersion = Integer.MAX_VALUE; expectedStorageDir = buildDirectory + "/sbtreeWithWALTestExpected"; when(expectedStorage.getStoragePath()).thenReturn(expectedStorageDir); when(expectedStorage.getName()).thenReturn("sbtreeWithWALTesExpected"); File buildDir = new File(buildDirectory); if (!buildDir.exists()) buildDir.mkdirs(); File expectedStorageDirFile = new File(expectedStorageDir); if (!expectedStorageDirFile.exists()) expectedStorageDirFile.mkdirs(); OStorageVariableParser variableParser = new OStorageVariableParser(expectedStorageDir); when(expectedStorage.getVariableParser()).thenReturn(variableParser); when(expectedStorage.getComponentsFactory()).thenReturn(new OCurrentStorageComponentsFactory(expectedStorageConfiguration)); expectedWriteCache = new OWOWCache(false, OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, 1000000, writeAheadLog, 100, 1648L * 1024 * 1024, 400L * 1024 * 1024 * 1024 + 1648L * 1024 * 1024, expectedStorage, true, 20); expectedReadCache = new O2QCache(400L * 1024 * 1024 * 1024, OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, false, 20); OAtomicOperationsManager atomicOperationsManager = new OAtomicOperationsManager(expectedStorage); when(expectedStorage.getStorageTransaction()).thenReturn(null); when(expectedStorage.getReadCache()).thenReturn(expectedReadCache); when(expectedStorage.getWALInstance()).thenReturn(null); when(expectedStorage.getAtomicOperationsManager()).thenReturn(atomicOperationsManager); when(expectedStorage.getConfiguration()).thenReturn(expectedStorageConfiguration); when(expectedStorage.getMode()).thenReturn("rw"); when(expectedStorageConfiguration.getDirectory()).thenReturn(expectedStorageDir); expectedSBTree = new OSBTree<Integer, OIdentifiable>("expectedSBTree", ".sbt", true, ".nbt", expectedStorage); expectedSBTree.create(OIntegerSerializer.INSTANCE, OLinkSerializer.INSTANCE, null, 1, false); } @Override @Test(enabled = false) protected void doReset() { Mockito.reset(actualStorage, actualStorageConfiguration); when(actualStorage.getStorageTransaction()).thenReturn(null); when(actualStorage.getReadCache()).thenReturn(actualReadCache); when(actualStorage.getAtomicOperationsManager()).thenReturn(actualAtomicOperationsManager); when(actualStorage.getConfiguration()).thenReturn(actualStorageConfiguration); when(actualStorage.getMode()).thenReturn("rw"); when(actualStorage.getStoragePath()).thenReturn(actualStorageDir); when(actualStorage.getName()).thenReturn("sbtreeWithWALTesActual"); } @Override public void testKeyPut() throws Exception { super.testKeyPut(); assertFileRestoreFromWAL(); } @Override public void testKeyPutRandomUniform() throws Exception { super.testKeyPutRandomUniform(); assertFileRestoreFromWAL(); } @Override public void testKeyPutRandomGaussian() throws Exception { super.testKeyPutRandomGaussian(); assertFileRestoreFromWAL(); } @Override public void testKeyDeleteRandomUniform() throws Exception { super.testKeyDeleteRandomUniform(); assertFileRestoreFromWAL(); } @Override public void testKeyDeleteRandomGaussian() throws Exception { super.testKeyDeleteRandomGaussian(); assertFileRestoreFromWAL(); } @Override public void testKeyDelete() throws Exception { super.testKeyDelete(); assertFileRestoreFromWAL(); } @Override public void testKeyAddDelete() throws Exception { super.testKeyAddDelete(); assertFileRestoreFromWAL(); } @Override public void testAddKeyValuesInTwoBucketsAndMakeFirstEmpty() throws Exception { super.testAddKeyValuesInTwoBucketsAndMakeFirstEmpty(); assertFileRestoreFromWAL(); } @Override public void testAddKeyValuesInTwoBucketsAndMakeLastEmpty() throws Exception { super.testAddKeyValuesInTwoBucketsAndMakeLastEmpty(); assertFileRestoreFromWAL(); } @Override public void testAddKeyValuesAndRemoveFirstMiddleAndLastPages() throws Exception { super.testAddKeyValuesAndRemoveFirstMiddleAndLastPages(); assertFileRestoreFromWAL(); } @Test(enabled = false) @Override public void testNullKeysInSBTree() { super.testNullKeysInSBTree(); } @Test(enabled = false) @Override public void testIterateEntriesMajor() { super.testIterateEntriesMajor(); } @Test(enabled = false) @Override public void testIterateEntriesMinor() { super.testIterateEntriesMinor(); } @Test(enabled = false) @Override public void testIterateEntriesBetween() { super.testIterateEntriesBetween(); } private void assertFileRestoreFromWAL() throws IOException { sbTree.close(); writeAheadLog.close(); expectedSBTree.close(); ((O2QCache) actualReadCache).clear(); restoreDataFromWAL(); ((O2QCache) expectedReadCache).clear(); assertFileContentIsTheSame(expectedSBTree.getName(), sbTree.getName()); } private void restoreDataFromWAL() throws IOException { ODiskWriteAheadLog log = new ODiskWriteAheadLog(4, -1, 10 * 1024L * OWALPage.PAGE_SIZE, actualStorage); OLogSequenceNumber lsn = log.begin(); List<OWALRecord> atomicUnit = new ArrayList<OWALRecord>(); boolean atomicChangeIsProcessed = false; while (lsn != null) { OWALRecord walRecord = log.read(lsn); atomicUnit.add(walRecord); if (!atomicChangeIsProcessed) { Assert.assertTrue(walRecord instanceof OAtomicUnitStartRecord); atomicChangeIsProcessed = true; } else if (walRecord instanceof OAtomicUnitEndRecord) { atomicChangeIsProcessed = false; for (OWALRecord restoreRecord : atomicUnit) { if (restoreRecord instanceof OAtomicUnitStartRecord || restoreRecord instanceof OAtomicUnitEndRecord || restoreRecord instanceof ONonTxOperationPerformedWALRecord || restoreRecord instanceof OFileCreatedWALRecord) continue; final OUpdatePageRecord updatePageRecord = (OUpdatePageRecord) restoreRecord; final long fileId = updatePageRecord.getFileId(); final long pageIndex = updatePageRecord.getPageIndex(); if (!expectedWriteCache.isOpen(fileId)) expectedReadCache.openFile(fileId, expectedWriteCache); OCacheEntry cacheEntry = expectedReadCache.load(fileId, pageIndex, true, expectedWriteCache); if (cacheEntry == null) { do { cacheEntry = expectedReadCache.allocateNewPage(fileId, expectedWriteCache); } while (cacheEntry.getPageIndex() != pageIndex); } cacheEntry.acquireExclusiveLock(); try { ODurablePage durablePage = new ODurablePage(cacheEntry, null); durablePage.restoreChanges(updatePageRecord.getChanges()); durablePage.setLsn(updatePageRecord.getLsn()); cacheEntry.markDirty(); } finally { cacheEntry.releaseExclusiveLock(); expectedReadCache.release(cacheEntry, expectedWriteCache); } } atomicUnit.clear(); } else { Assert.assertTrue(walRecord instanceof OUpdatePageRecord || walRecord instanceof ONonTxOperationPerformedWALRecord || walRecord instanceof OFileCreatedWALRecord); } lsn = log.next(lsn); } Assert.assertTrue(atomicUnit.isEmpty()); log.close(); } private void assertFileContentIsTheSame(String expectedBTree, String actualBTree) throws IOException { File expectedFile = new File(expectedStorageDir, expectedBTree + ".sbt"); RandomAccessFile fileOne = new RandomAccessFile(expectedFile, "r"); RandomAccessFile fileTwo = new RandomAccessFile(new File(actualStorageDir, actualBTree + ".sbt"), "r"); Assert.assertEquals(fileOne.length(), fileTwo.length()); byte[] expectedContent = new byte[OClusterPage.PAGE_SIZE]; byte[] actualContent = new byte[OClusterPage.PAGE_SIZE]; fileOne.seek(OFileClassic.HEADER_SIZE); fileTwo.seek(OFileClassic.HEADER_SIZE); int bytesRead = fileOne.read(expectedContent); while (bytesRead >= 0) { fileTwo.readFully(actualContent, 0, bytesRead); Assert.assertEquals(expectedContent, actualContent); expectedContent = new byte[OClusterPage.PAGE_SIZE]; actualContent = new byte[OClusterPage.PAGE_SIZE]; bytesRead = fileOne.read(expectedContent); } fileOne.close(); fileTwo.close(); } }
apache-2.0
shun634501730/java_source_cn
src_en/com/sun/org/apache/xerces/internal/impl/xs/XSImplementationImpl.java
4390
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2003,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.xs; import com.sun.org.apache.xerces.internal.dom.CoreDOMImplementationImpl; import com.sun.org.apache.xerces.internal.dom.DOMMessageFormatter; import com.sun.org.apache.xerces.internal.impl.xs.util.StringListImpl; import com.sun.org.apache.xerces.internal.xs.StringList; import com.sun.org.apache.xerces.internal.xs.XSException; import com.sun.org.apache.xerces.internal.xs.XSImplementation; import com.sun.org.apache.xerces.internal.xs.XSLoader; import org.w3c.dom.DOMImplementation; /** * Implements XSImplementation interface that allows one to retrieve an instance of <code>XSLoader</code>. * This interface should be implemented on the same object that implements * DOMImplementation. * * @xerces.internal * * @author Elena Litani, IBM */ public class XSImplementationImpl extends CoreDOMImplementationImpl implements XSImplementation { // // Data // // static /** Dom implementation singleton. */ static XSImplementationImpl singleton = new XSImplementationImpl(); // // Public methods // /** NON-DOM: Obtain and return the single shared object */ public static DOMImplementation getDOMImplementation() { return singleton; } // // DOMImplementation methods // /** * Test if the DOM implementation supports a specific "feature" -- * currently meaning language and level thereof. * * @param feature The package name of the feature to test. * In Level 1, supported values are "HTML" and "XML" (case-insensitive). * At this writing, com.sun.org.apache.xerces.internal.dom supports only XML. * * @param version The version number of the feature being tested. * This is interpreted as "Version of the DOM API supported for the * specified Feature", and in Level 1 should be "1.0" * * @return true iff this implementation is compatable with the specified * feature and version. */ public boolean hasFeature(String feature, String version) { return (feature.equalsIgnoreCase("XS-Loader") && (version == null || version.equals("1.0")) || super.hasFeature(feature, version)); } // hasFeature(String,String):boolean /* (non-Javadoc) * @see com.sun.org.apache.xerces.internal.xs.XSImplementation#createXSLoader(com.sun.org.apache.xerces.internal.xs.StringList) */ public XSLoader createXSLoader(StringList versions) throws XSException { XSLoader loader = new XSLoaderImpl(); if (versions == null){ return loader; } for (int i=0; i<versions.getLength();i++){ if (!versions.item(i).equals("1.0")){ String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { versions.item(i) }); throw new XSException(XSException.NOT_SUPPORTED_ERR, msg); } } return loader; } /* (non-Javadoc) * @see com.sun.org.apache.xerces.internal.xs.XSImplementation#getRecognizedVersions() */ public StringList getRecognizedVersions() { StringListImpl list = new StringListImpl(new String[]{"1.0"}, 1); return list; } } // class XSImplementationImpl
apache-2.0
hugoYe/Roid-Library
src/com/rincliu/library/activity/RLFragmentActivity.java
5962
/** * Copyright (c) 2013-2014, Rinc Liu (http://rincliu.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.rincliu.library.activity; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.rincliu.library.BuildConfig; import com.rincliu.library.R; import com.rincliu.library.app.RLApplication; import com.rincliu.library.app.RLCrashHandler; import com.rincliu.library.common.reference.analytics.RLAnalyticsHelper; import com.rincliu.library.common.reference.feedback.RLFeedbackHelper; import com.rincliu.library.util.RLSysUtil; public class RLFragmentActivity extends FragmentActivity { private boolean isEnableCrashHandler = true; private boolean isEnableAnalytics = false; private boolean isEnableFeedback = false; private int displayRotation = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); displayRotation = getWindowManager().getDefaultDisplay().getRotation(); String enableCrashHandler = RLSysUtil.getApplicationMetaData(this, "ENABLE_CRASH_HANDLER"); if (enableCrashHandler != null && enableCrashHandler.equals("false")) { isEnableCrashHandler = false; } String enableAnalytics = RLSysUtil.getApplicationMetaData(this, "ENABLE_ANALYTICS"); if (enableAnalytics != null && enableAnalytics.equals("true")) { isEnableAnalytics = true; } String enableFeedback = RLSysUtil.getApplicationMetaData(this, "ENABLE_FEEDBACK"); if (enableFeedback != null && enableFeedback.equals("true")) { isEnableFeedback = true; } if (isEnableCrashHandler) { RLCrashHandler.getInstance().init(this); } if (isEnableAnalytics) { RLAnalyticsHelper.init(this, BuildConfig.DEBUG); } if (isEnableFeedback) { RLFeedbackHelper.init(this, BuildConfig.DEBUG); } if (getApplication() instanceof RLApplication) { ((RLApplication) getApplication()).setDisplayInfo(RLSysUtil.getDisplayInfo(this)); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); displayRotation = getWindowManager().getDefaultDisplay().getRotation(); } @Override protected void onStart() { super.onStart(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onResume() { super.onResume(); if (isEnableAnalytics) { RLAnalyticsHelper.onResume(this); } } @Override protected void onPause() { super.onPause(); if (isEnableAnalytics) { RLAnalyticsHelper.onPause(this); } } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void startActivity(Intent intent) { super.startActivity(intent); overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left); } @Override public void startActivityForResult(Intent intent, int requestCode) { super.startActivityForResult(intent, requestCode); overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left); } @Override public void startActivityFromChild(Activity child, Intent intent, int requestCode) { super.startActivityFromChild(child, intent, requestCode); overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override public void finishActivity(int requestCode) { super.finishActivity(requestCode); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override public void finishFromChild(Activity child) { super.finishFromChild(child); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override public void finishActivityFromChild(Activity child, int requestCode) { super.finishActivityFromChild(child, requestCode); overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (getApplication() instanceof RLApplication) { ((RLApplication) getApplication()).setDisplayInfo(RLSysUtil.getDisplayInfo(this)); } displayRotation = getWindowManager().getDefaultDisplay().getRotation(); } @Override public void onLowMemory() { super.onLowMemory(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } /** * @return */ public int getDisplayRotation() { return displayRotation; } }
apache-2.0
liveqmock/platform-tools-idea
platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaSpinnerUI.java
6199
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.ui.laf.darcula.ui; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.UIUtil; import org.intellij.lang.annotations.MagicConstant; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicSpinnerUI; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; /** * @author Konstantin Bulenkov */ public class DarculaSpinnerUI extends BasicSpinnerUI { private FocusAdapter myFocusListener = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { spinner.repaint(); } @Override public void focusLost(FocusEvent e) { spinner.repaint(); } }; @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new DarculaSpinnerUI(); } @Override protected void replaceEditor(JComponent oldEditor, JComponent newEditor) { super.replaceEditor(oldEditor, newEditor); if (oldEditor != null) { oldEditor.getComponents()[0].removeFocusListener(myFocusListener); } if (newEditor != null) { newEditor.getComponents()[0].addFocusListener(myFocusListener); } } @Override protected JComponent createEditor() { final JComponent editor = super.createEditor(); editor.getComponents()[0].addFocusListener(myFocusListener); return editor; } @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); final Border border = spinner.getBorder(); if (border != null) { border.paintBorder(c, g, 0, 0, spinner.getWidth(), spinner.getHeight()); } } @Override protected Component createPreviousButton() { JButton button = createArrow(SwingConstants.SOUTH); button.setName("Spinner.previousButton"); button.setBorder(new EmptyBorder(1, 1, 1, 1)); installPreviousButtonListeners(button); return button; } @Override protected Component createNextButton() { JButton button = createArrow(SwingConstants.NORTH); button.setName("Spinner.nextButton"); button.setBorder(new EmptyBorder(1, 1, 1, 1)); installNextButtonListeners(button); return button; } @Override protected LayoutManager createLayout() { return new LayoutManagerDelegate(super.createLayout()) { @Override public void layoutContainer(Container parent) { super.layoutContainer(parent); final JComponent editor = spinner.getEditor(); if (editor != null) { final Rectangle bounds = editor.getBounds(); editor.setBounds(bounds.x, bounds.y, bounds.width - 6, bounds.height); } } }; } private JButton createArrow(@MagicConstant(intValues = {SwingConstants.NORTH, SwingConstants.SOUTH}) int direction) { final Color shadow = UIUtil.getPanelBackground(); final Color darkShadow = UIUtil.getLabelForeground(); JButton b = new BasicArrowButton(direction, shadow, shadow, darkShadow, shadow) { @Override public void paint(Graphics g) { int y = direction == NORTH ? getHeight() - 6 : 2; paintTriangle(g, 0, y, 0, direction, DarculaSpinnerUI.this.spinner.isEnabled()); } @Override public boolean isOpaque() { return false; } @Override public void paintTriangle(Graphics g, int x, int y, int size, int direction, boolean isEnabled) { final GraphicsConfig config = GraphicsUtil.setupAAPainting(g); int mid; final int w = 8; final int h = 6; mid = w / 2; g.setColor(isEnabled ? darkShadow : darkShadow.darker()); g.translate(x, y); switch (direction) { case SOUTH: g.fillPolygon(new int[]{0, w, mid}, new int[]{1, 1, h}, 3); break; case NORTH: g.fillPolygon(new int[]{0, w, mid}, new int[]{h - 1, h - 1, 0}, 3); break; case WEST: case EAST: } g.translate(-x, -y); config.restore(); } }; Border buttonBorder = UIManager.getBorder("Spinner.arrowButtonBorder"); if (buttonBorder instanceof UIResource) { // Wrap the border to avoid having the UIResource be replaced by // the ButtonUI. This is the opposite of using BorderUIResource. b.setBorder(new CompoundBorder(buttonBorder, null)); } else { b.setBorder(buttonBorder); } b.setInheritsPopupMenu(true); return b; } static class LayoutManagerDelegate implements LayoutManager { protected final LayoutManager myDelegate; LayoutManagerDelegate(LayoutManager delegate) { myDelegate = delegate; } @Override public void addLayoutComponent(String name, Component comp) { myDelegate.addLayoutComponent(name, comp); } @Override public void removeLayoutComponent(Component comp) { myDelegate.removeLayoutComponent(comp); } @Override public Dimension preferredLayoutSize(Container parent) { return myDelegate.preferredLayoutSize(parent); } @Override public Dimension minimumLayoutSize(Container parent) { return myDelegate.minimumLayoutSize(parent); } @Override public void layoutContainer(Container parent) { myDelegate.layoutContainer(parent); } } }
apache-2.0
onders86/camel
camel-core/src/test/java/org/apache/camel/component/bean/ClassComponentWithPropertiesLookupSetFromEndpointTest.java
1951
/** * 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.bean; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry; import org.junit.Test; /** * @version */ public class ClassComponentWithPropertiesLookupSetFromEndpointTest extends ContextTestSupport { @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("foo", "Hi"); return jndi; } @Test public void testClassComponent() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hi World"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .to("class:org.apache.camel.component.bean.MyPrefixBean?bean.prefix=#foo") .to("mock:result"); } }; } }
apache-2.0
ngocnguyen/crigtt
crigtt-web/src/main/java/gov/hhs/onc/crigtt/web/validate/ValidatorParameters.java
471
package gov.hhs.onc.crigtt.web.validate; import gov.hhs.onc.crigtt.json.JsonConstant; public final class ValidatorParameters { @JsonConstant public final static String FILE_NAME = "file"; @JsonConstant public final static String FORMAT_NAME = "format"; @JsonConstant public final static String TESTCASE_NAME = "testcase"; @JsonConstant public final static String TIME_ZONE_NAME = "timeZone"; private ValidatorParameters() { } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-run/v1alpha1/1.29.2/com/google/api/services/run/v1alpha1/model/ConfigurationCondition.java
6084
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.run.v1alpha1.model; /** * ConfigurationCondition defines a readiness condition for a Configuration. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Run API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class ConfigurationCondition extends com.google.api.client.json.GenericJson { /** * Last time the condition transitioned from one status to another. +optional * The value may be {@code null}. */ @com.google.api.client.util.Key private String lastTransitionTime; /** * Human-readable message indicating details about last transition. +optional * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * One-word CamelCase reason for the condition's last transition. +optional * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String reason; /** * How to interpret failures of this condition, one of Error, Warning, Info +optional * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String severity; /** * Status of the condition, one of True, False, Unknown. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String status; /** * ConfigurationConditionType is used to communicate the status of the reconciliation process. See * also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and- * reporting Types include:"Ready" * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Last time the condition transitioned from one status to another. +optional * @return value or {@code null} for none */ public String getLastTransitionTime() { return lastTransitionTime; } /** * Last time the condition transitioned from one status to another. +optional * @param lastTransitionTime lastTransitionTime or {@code null} for none */ public ConfigurationCondition setLastTransitionTime(String lastTransitionTime) { this.lastTransitionTime = lastTransitionTime; return this; } /** * Human-readable message indicating details about last transition. +optional * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * Human-readable message indicating details about last transition. +optional * @param message message or {@code null} for none */ public ConfigurationCondition setMessage(java.lang.String message) { this.message = message; return this; } /** * One-word CamelCase reason for the condition's last transition. +optional * @return value or {@code null} for none */ public java.lang.String getReason() { return reason; } /** * One-word CamelCase reason for the condition's last transition. +optional * @param reason reason or {@code null} for none */ public ConfigurationCondition setReason(java.lang.String reason) { this.reason = reason; return this; } /** * How to interpret failures of this condition, one of Error, Warning, Info +optional * @return value or {@code null} for none */ public java.lang.String getSeverity() { return severity; } /** * How to interpret failures of this condition, one of Error, Warning, Info +optional * @param severity severity or {@code null} for none */ public ConfigurationCondition setSeverity(java.lang.String severity) { this.severity = severity; return this; } /** * Status of the condition, one of True, False, Unknown. * @return value or {@code null} for none */ public java.lang.String getStatus() { return status; } /** * Status of the condition, one of True, False, Unknown. * @param status status or {@code null} for none */ public ConfigurationCondition setStatus(java.lang.String status) { this.status = status; return this; } /** * ConfigurationConditionType is used to communicate the status of the reconciliation process. See * also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and- * reporting Types include:"Ready" * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * ConfigurationConditionType is used to communicate the status of the reconciliation process. See * also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and- * reporting Types include:"Ready" * @param type type or {@code null} for none */ public ConfigurationCondition setType(java.lang.String type) { this.type = type; return this; } @Override public ConfigurationCondition set(String fieldName, Object value) { return (ConfigurationCondition) super.set(fieldName, value); } @Override public ConfigurationCondition clone() { return (ConfigurationCondition) super.clone(); } }
apache-2.0
khmarbaise/sapm-test
src/main/java/com/soebes/subversion/sapm/Path.java
1962
/** * The Subversion Authentication Parse Module (SAPM for short). * * Copyright (c) 2010, 2011 by SoftwareEntwicklung Beratung Schulung (SoEBeS) * Copyright (c) 2010, 2011 by Karl Heinz Marbaise * * 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.soebes.subversion.sapm; /** * This class represents a path in the meaning * of a folder. * * @author Karl Heinz Marbaise * */ public class Path { private String path; public Path(String path) { super(); setPath(path); } public Path() { setPath(null); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } /** * This will check if the given path * is part of the path which is represented by * this instance. * @see {@link PathTest} * @param path The path to check for. * @return true if the given path is contained in false otherwise. */ public boolean contains(String path) { boolean result = false; FileName fn = new FileName(path); if (fn.getPath().startsWith(getPath())) { result = true; } return result; } }
apache-2.0
zwets/flowable-engine
modules/flowable-spring/src/test/java/org/flowable/spring/test/fieldinjection/SingletonDelegateExpressionBean.java
2128
/* 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.flowable.spring.test.fieldinjection; import java.util.concurrent.atomic.AtomicInteger; import org.flowable.engine.common.api.delegate.Expression; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.DelegateHelper; import org.flowable.engine.delegate.JavaDelegate; /** * @author Joram Barrez */ public class SingletonDelegateExpressionBean implements JavaDelegate { public static AtomicInteger INSTANCE_COUNT = new AtomicInteger(0); public SingletonDelegateExpressionBean() { INSTANCE_COUNT.incrementAndGet(); } @Override public void execute(DelegateExecution execution) { // just a quick check to avoid creating a specific test for it int nrOfFieldExtensions = DelegateHelper.getFields(execution).size(); if (nrOfFieldExtensions != 3) { throw new RuntimeException("Error: 3 field extensions expected, but was " + nrOfFieldExtensions); } Expression fieldAExpression = DelegateHelper.getFieldExpression(execution, "fieldA"); Number fieldA = (Number) fieldAExpression.getValue(execution); Expression fieldBExpression = DelegateHelper.getFieldExpression(execution, "fieldB"); Number fieldB = (Number) fieldBExpression.getValue(execution); int result = fieldA.intValue() + fieldB.intValue(); String resultVariableName = DelegateHelper.getFieldExpression(execution, "resultVariableName").getValue(execution).toString(); execution.setVariable(resultVariableName, result); } }
apache-2.0
michaelgallacher/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootProblemNotifier.java
10785
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.roots; import com.intellij.idea.ActionsBundle; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.util.Collection; import java.util.List; import java.util.Set; import static com.intellij.openapi.util.text.StringUtil.pluralize; /** * Searches for Vcs roots problems via {@link VcsRootErrorsFinder} and notifies about them. */ public class VcsRootProblemNotifier { public static final Function<VcsRootError, String> PATH_FROM_ROOT_ERROR = VcsRootError::getMapping; @NotNull private final Project myProject; @NotNull private final VcsConfiguration mySettings; @NotNull private final ProjectLevelVcsManager myVcsManager; @NotNull private final ChangeListManager myChangeListManager; @NotNull private final ProjectFileIndex myProjectFileIndex; @NotNull private final Set<String> myReportedUnregisteredRoots; @Nullable private Notification myNotification; @NotNull private final Object NOTIFICATION_LOCK = new Object(); public static VcsRootProblemNotifier getInstance(@NotNull Project project) { return new VcsRootProblemNotifier(project); } private VcsRootProblemNotifier(@NotNull Project project) { myProject = project; mySettings = VcsConfiguration.getInstance(myProject); myChangeListManager = ChangeListManager.getInstance(project); myProjectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject); myVcsManager = ProjectLevelVcsManager.getInstance(project); myReportedUnregisteredRoots = new HashSet<>(mySettings.IGNORED_UNREGISTERED_ROOTS); } public void rescanAndNotifyIfNeeded() { Collection<VcsRootError> errors = scan(); if (errors.isEmpty()) { synchronized (NOTIFICATION_LOCK) { expireNotification(); } return; } Collection<VcsRootError> importantUnregisteredRoots = getImportantUnregisteredMappings(errors); Collection<VcsRootError> invalidRoots = getInvalidRoots(errors); List<String> unregRootPaths = ContainerUtil.map(importantUnregisteredRoots, PATH_FROM_ROOT_ERROR); if (invalidRoots.isEmpty() && (importantUnregisteredRoots.isEmpty() || myReportedUnregisteredRoots.containsAll(unregRootPaths))) { return; } myReportedUnregisteredRoots.addAll(unregRootPaths); String title = makeTitle(importantUnregisteredRoots, invalidRoots); String description = makeDescription(importantUnregisteredRoots, invalidRoots); synchronized (NOTIFICATION_LOCK) { expireNotification(); NotificationListener listener = new MyNotificationListener(myProject, mySettings, myVcsManager, importantUnregisteredRoots); VcsNotifier notifier = VcsNotifier.getInstance(myProject); myNotification = invalidRoots.isEmpty() ? notifier.notifyMinorInfo(title, description, listener) : notifier.notifyError(title, description, listener); } } private boolean isUnderOrAboveProjectDir(@NotNull String mapping) { String projectDir = ObjectUtils.assertNotNull(myProject.getBasePath()); return mapping.equals(VcsDirectoryMapping.PROJECT_CONSTANT) || FileUtil.isAncestor(projectDir, mapping, false) || FileUtil.isAncestor(mapping, projectDir, false); } private boolean isIgnoredOrExcluded(@NotNull String mapping) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(mapping); return file != null && (myChangeListManager.isIgnoredFile(file) || myProjectFileIndex.isExcluded(file)); } private void expireNotification() { if (myNotification != null) { final Notification notification = myNotification; ApplicationManager.getApplication().invokeLater(notification::expire); myNotification = null; } } @NotNull private Collection<VcsRootError> scan() { return new VcsRootErrorsFinder(myProject).find(); } @SuppressWarnings("StringConcatenationInsideStringBufferAppend") @NotNull private static String makeDescription(@NotNull Collection<VcsRootError> unregisteredRoots, @NotNull Collection<VcsRootError> invalidRoots) { Function<VcsRootError, String> rootToDisplayableString = rootError -> { if (rootError.getMapping().equals(VcsDirectoryMapping.PROJECT_CONSTANT)) { return StringUtil.escapeXml(rootError.getMapping()); } return FileUtil.toSystemDependentName(rootError.getMapping()); }; StringBuilder description = new StringBuilder(); if (!invalidRoots.isEmpty()) { if (invalidRoots.size() == 1) { VcsRootError rootError = invalidRoots.iterator().next(); String vcsName = rootError.getVcsKey().getName(); description.append(String.format("The directory %s is registered as a %s root, but no %s repositories were found there.", rootToDisplayableString.fun(rootError), vcsName, vcsName)); } else { description.append("The following directories are registered as VCS roots, but they are not: <br/>" + StringUtil.join(invalidRoots, rootToDisplayableString, "<br/>")); } description.append("<br/>"); } if (!unregisteredRoots.isEmpty()) { if (unregisteredRoots.size() == 1) { VcsRootError unregisteredRoot = unregisteredRoots.iterator().next(); description.append(String.format("The directory %s is under %s, but is not registered in the Settings.", rootToDisplayableString.fun(unregisteredRoot), unregisteredRoot.getVcsKey().getName())); } else { description.append("The following directories are roots of VCS repositories, but they are not registered in the Settings: <br/>" + StringUtil.join(unregisteredRoots, rootToDisplayableString, "<br/>")); } description.append("<br/>"); } String add = invalidRoots.isEmpty() ? "<a href='add'>Add " + pluralize("root", unregisteredRoots.size()) + "</a>&nbsp;&nbsp;" : ""; String configure = "<a href='configure'>Configure</a>"; String ignore = invalidRoots.isEmpty() ? "&nbsp;&nbsp;<a href='ignore'>Ignore</a>" : ""; description.append(add + configure + ignore); return description.toString(); } @NotNull private static String makeTitle(@NotNull Collection<VcsRootError> unregisteredRoots, @NotNull Collection<VcsRootError> invalidRoots) { String title; if (unregisteredRoots.isEmpty()) { title = "Invalid VCS root " + pluralize("mapping", invalidRoots.size()); } else if (invalidRoots.isEmpty()) { title = "Unregistered VCS " + pluralize("root", unregisteredRoots.size()) + " detected"; } else { title = "VCS root configuration problems"; } return title; } @NotNull private List<VcsRootError> getImportantUnregisteredMappings(@NotNull Collection<VcsRootError> errors) { return ContainerUtil.filter(errors, error -> { String mapping = error.getMapping(); return error.getType() == VcsRootError.Type.UNREGISTERED_ROOT && isUnderOrAboveProjectDir(mapping) && !isIgnoredOrExcluded(mapping); }); } @NotNull private static Collection<VcsRootError> getInvalidRoots(@NotNull Collection<VcsRootError> errors) { return ContainerUtil.filter(errors, error -> error.getType() == VcsRootError.Type.EXTRA_MAPPING); } private static class MyNotificationListener extends NotificationListener.Adapter { @NotNull private final Project myProject; @NotNull private final VcsConfiguration mySettings; @NotNull private final ProjectLevelVcsManager myVcsManager; @NotNull private final Collection<VcsRootError> myImportantUnregisteredRoots; private MyNotificationListener(@NotNull Project project, @NotNull VcsConfiguration settings, @NotNull ProjectLevelVcsManager vcsManager, @NotNull Collection<VcsRootError> importantUnregisteredRoots) { myProject = project; mySettings = settings; myVcsManager = vcsManager; myImportantUnregisteredRoots = importantUnregisteredRoots; } @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getDescription().equals("configure") && !myProject.isDisposed()) { ShowSettingsUtil.getInstance().showSettingsDialog(myProject, ActionsBundle.message("group.VcsGroup.text")); Collection<VcsRootError> errorsAfterPossibleFix = getInstance(myProject).scan(); if (errorsAfterPossibleFix.isEmpty() && !notification.isExpired()) { notification.expire(); } } else if (event.getDescription().equals("ignore")) { mySettings.addIgnoredUnregisteredRoots(ContainerUtil.map(myImportantUnregisteredRoots, PATH_FROM_ROOT_ERROR)); notification.expire(); } else if (event.getDescription().equals("add")) { List<VcsDirectoryMapping> mappings = myVcsManager.getDirectoryMappings(); for (VcsRootError root : myImportantUnregisteredRoots) { mappings = VcsUtil.addMapping(mappings, root.getMapping(), root.getVcsKey().getName()); } myVcsManager.setDirectoryMappings(mappings); } } } }
apache-2.0
tdiesler/camel
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AmqpComponentBuilderFactory.java
97779
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.amqp.AMQPComponent; /** * Messaging with AMQP protocol using Apache QPid Client. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface AmqpComponentBuilderFactory { /** * AMQP (camel-amqp) * Messaging with AMQP protocol using Apache QPid Client. * * Category: messaging * Since: 1.2 * Maven coordinates: org.apache.camel:camel-amqp * * @return the dsl builder */ static AmqpComponentBuilder amqp() { return new AmqpComponentBuilderImpl(); } /** * Builder for the AMQP component. */ interface AmqpComponentBuilder extends ComponentBuilder<AMQPComponent> { /** * Sets the JMS client ID to use. Note that this value, if specified, * must be unique and can only be used by a single JMS connection * instance. It is typically only required for durable topic * subscriptions. If using Apache ActiveMQ you may prefer to use Virtual * Topics instead. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param clientId the value to set * @return the dsl builder */ default AmqpComponentBuilder clientId(java.lang.String clientId) { doSetProperty("clientId", clientId); return this; } /** * The connection factory to be use. A connection factory must be * configured either on the component or endpoint. * * The option is a: &lt;code&gt;javax.jms.ConnectionFactory&lt;/code&gt; * type. * * Group: common * * @param connectionFactory the value to set * @return the dsl builder */ default AmqpComponentBuilder connectionFactory( javax.jms.ConnectionFactory connectionFactory) { doSetProperty("connectionFactory", connectionFactory); return this; } /** * Specifies whether Camel ignores the JMSReplyTo header in messages. If * true, Camel does not send a reply back to the destination specified * in the JMSReplyTo header. You can use this option if you want Camel * to consume from a route and you do not want Camel to automatically * send back a reply message because another component in your code * handles the reply message. You can also use this option if you want * to use Camel as a proxy between different message brokers and you * want to route message from one system to another. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: common * * @param disableReplyTo the value to set * @return the dsl builder */ default AmqpComponentBuilder disableReplyTo(boolean disableReplyTo) { doSetProperty("disableReplyTo", disableReplyTo); return this; } /** * The durable subscriber name for specifying durable topic * subscriptions. The clientId option must be configured as well. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param durableSubscriptionName the value to set * @return the dsl builder */ default AmqpComponentBuilder durableSubscriptionName( java.lang.String durableSubscriptionName) { doSetProperty("durableSubscriptionName", durableSubscriptionName); return this; } /** * Whether to include AMQP annotations when mapping from AMQP to Camel * Message. Setting this to true maps AMQP message annotations that * contain a JMS_AMQP_MA_ prefix to message headers. Due to limitations * in Apache Qpid JMS API, currently delivery annotations are ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: common * * @param includeAmqpAnnotations the value to set * @return the dsl builder */ default AmqpComponentBuilder includeAmqpAnnotations( boolean includeAmqpAnnotations) { doSetProperty("includeAmqpAnnotations", includeAmqpAnnotations); return this; } /** * Allows you to force the use of a specific javax.jms.Message * implementation for sending JMS messages. Possible values are: Bytes, * Map, Object, Stream, Text. By default, Camel would determine which * JMS message type to use from the In body type. This option allows you * to specify it. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.JmsMessageType&lt;/code&gt; type. * * Group: common * * @param jmsMessageType the value to set * @return the dsl builder */ default AmqpComponentBuilder jmsMessageType( org.apache.camel.component.jms.JmsMessageType jmsMessageType) { doSetProperty("jmsMessageType", jmsMessageType); return this; } /** * Provides an explicit ReplyTo destination (overrides any incoming * value of Message.getJMSReplyTo() in consumer). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param replyTo the value to set * @return the dsl builder */ default AmqpComponentBuilder replyTo(java.lang.String replyTo) { doSetProperty("replyTo", replyTo); return this; } /** * Specifies whether to test the connection on startup. This ensures * that when Camel starts that all the JMS consumers have a valid * connection to the JMS broker. If a connection cannot be granted then * Camel throws an exception on startup. This ensures that Camel is not * started with failed connections. The JMS producers is tested as well. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: common * * @param testConnectionOnStartup the value to set * @return the dsl builder */ default AmqpComponentBuilder testConnectionOnStartup( boolean testConnectionOnStartup) { doSetProperty("testConnectionOnStartup", testConnectionOnStartup); return this; } /** * The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, * CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: AUTO_ACKNOWLEDGE * Group: consumer * * @param acknowledgementModeName the value to set * @return the dsl builder */ default AmqpComponentBuilder acknowledgementModeName( java.lang.String acknowledgementModeName) { doSetProperty("acknowledgementModeName", acknowledgementModeName); return this; } /** * Consumer priorities allow you to ensure that high priority consumers * receive messages while they are active. Normally, active consumers * connected to a queue receive messages from it in a round-robin * fashion. When consumer priorities are in use, messages are delivered * round-robin if multiple active consumers exist with the same high * priority. Messages will only going to lower priority consumers when * the high priority consumers do not have credit available to consume * the message, or those high priority consumers have declined to accept * the message (for instance because it does not meet the criteria of * any selectors associated with the consumer). * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: consumer * * @param artemisConsumerPriority the value to set * @return the dsl builder */ default AmqpComponentBuilder artemisConsumerPriority( int artemisConsumerPriority) { doSetProperty("artemisConsumerPriority", artemisConsumerPriority); return this; } /** * Whether the JmsConsumer processes the Exchange asynchronously. If * enabled then the JmsConsumer may pickup the next message from the JMS * queue, while the previous message is being processed asynchronously * (by the Asynchronous Routing Engine). This means that messages may be * processed not 100% strictly in order. If disabled (as default) then * the Exchange is fully processed before the JmsConsumer will pickup * the next message from the JMS queue. Note if transacted has been * enabled, then asyncConsumer=true does not run asynchronously, as * transaction must be executed synchronously (Camel 3.0 may support * async transactions). * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param asyncConsumer the value to set * @return the dsl builder */ default AmqpComponentBuilder asyncConsumer(boolean asyncConsumer) { doSetProperty("asyncConsumer", asyncConsumer); return this; } /** * Specifies whether the consumer container should auto-startup. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param autoStartup the value to set * @return the dsl builder */ default AmqpComponentBuilder autoStartup(boolean autoStartup) { doSetProperty("autoStartup", autoStartup); return this; } /** * Sets the cache level by ID for the underlying JMS resources. See * cacheLevelName option for more details. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: consumer * * @param cacheLevel the value to set * @return the dsl builder */ default AmqpComponentBuilder cacheLevel(int cacheLevel) { doSetProperty("cacheLevel", cacheLevel); return this; } /** * Sets the cache level by name for the underlying JMS resources. * Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, * CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See * the Spring documentation and Transactions Cache Levels for more * information. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: CACHE_AUTO * Group: consumer * * @param cacheLevelName the value to set * @return the dsl builder */ default AmqpComponentBuilder cacheLevelName( java.lang.String cacheLevelName) { doSetProperty("cacheLevelName", cacheLevelName); return this; } /** * Specifies the default number of concurrent consumers when consuming * from JMS (not for request/reply over JMS). See also the * maxMessagesPerTask option to control dynamic scaling up/down of * threads. When doing request/reply over JMS then the option * replyToConcurrentConsumers is used to control number of concurrent * consumers on the reply message listener. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: consumer * * @param concurrentConsumers the value to set * @return the dsl builder */ default AmqpComponentBuilder concurrentConsumers(int concurrentConsumers) { doSetProperty("concurrentConsumers", concurrentConsumers); return this; } /** * Specifies the maximum number of concurrent consumers when consuming * from JMS (not for request/reply over JMS). See also the * maxMessagesPerTask option to control dynamic scaling up/down of * threads. When doing request/reply over JMS then the option * replyToMaxConcurrentConsumers is used to control number of concurrent * consumers on the reply message listener. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: consumer * * @param maxConcurrentConsumers the value to set * @return the dsl builder */ default AmqpComponentBuilder maxConcurrentConsumers( int maxConcurrentConsumers) { doSetProperty("maxConcurrentConsumers", maxConcurrentConsumers); return this; } /** * Specifies whether to use persistent delivery by default for replies. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param replyToDeliveryPersistent the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToDeliveryPersistent( boolean replyToDeliveryPersistent) { doSetProperty("replyToDeliveryPersistent", replyToDeliveryPersistent); return this; } /** * Sets the JMS selector to use. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param selector the value to set * @return the dsl builder */ default AmqpComponentBuilder selector(java.lang.String selector) { doSetProperty("selector", selector); return this; } /** * Set whether to make the subscription durable. The durable * subscription name to be used can be specified through the * subscriptionName property. Default is false. Set this to true to * register a durable subscription, typically in combination with a * subscriptionName value (unless your message listener class name is * good enough as subscription name). Only makes sense when listening to * a topic (pub-sub domain), therefore this method switches the * pubSubDomain flag as well. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param subscriptionDurable the value to set * @return the dsl builder */ default AmqpComponentBuilder subscriptionDurable( boolean subscriptionDurable) { doSetProperty("subscriptionDurable", subscriptionDurable); return this; } /** * Set the name of a subscription to create. To be applied in case of a * topic (pub-sub domain) with a shared or durable subscription. The * subscription name needs to be unique within this client's JMS client * id. Default is the class name of the specified message listener. * Note: Only 1 concurrent consumer (which is the default of this * message listener container) is allowed for each subscription, except * for a shared subscription (which requires JMS 2.0). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param subscriptionName the value to set * @return the dsl builder */ default AmqpComponentBuilder subscriptionName( java.lang.String subscriptionName) { doSetProperty("subscriptionName", subscriptionName); return this; } /** * Set whether to make the subscription shared. The shared subscription * name to be used can be specified through the subscriptionName * property. Default is false. Set this to true to register a shared * subscription, typically in combination with a subscriptionName value * (unless your message listener class name is good enough as * subscription name). Note that shared subscriptions may also be * durable, so this flag can (and often will) be combined with * subscriptionDurable as well. Only makes sense when listening to a * topic (pub-sub domain), therefore this method switches the * pubSubDomain flag as well. Requires a JMS 2.0 compatible message * broker. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param subscriptionShared the value to set * @return the dsl builder */ default AmqpComponentBuilder subscriptionShared( boolean subscriptionShared) { doSetProperty("subscriptionShared", subscriptionShared); return this; } /** * Specifies whether the consumer accept messages while it is stopping. * You may consider enabling this option, if you start and stop JMS * routes at runtime, while there are still messages enqueued on the * queue. If this option is false, and you stop the JMS route, then * messages may be rejected, and the JMS broker would have to attempt * redeliveries, which yet again may be rejected, and eventually the * message may be moved at a dead letter queue on the JMS broker. To * avoid this its recommended to enable this option. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param acceptMessagesWhileStopping the value to set * @return the dsl builder */ default AmqpComponentBuilder acceptMessagesWhileStopping( boolean acceptMessagesWhileStopping) { doSetProperty("acceptMessagesWhileStopping", acceptMessagesWhileStopping); return this; } /** * Whether the DefaultMessageListenerContainer used in the reply * managers for request-reply messaging allow the * DefaultMessageListenerContainer.runningAllowed flag to quick stop in * case JmsConfiguration#isAcceptMessagesWhileStopping is enabled, and * org.apache.camel.CamelContext is currently being stopped. This quick * stop ability is enabled by default in the regular JMS consumers but * to enable for reply managers you must enable this flag. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param allowReplyManagerQuickStop the value to set * @return the dsl builder */ default AmqpComponentBuilder allowReplyManagerQuickStop( boolean allowReplyManagerQuickStop) { doSetProperty("allowReplyManagerQuickStop", allowReplyManagerQuickStop); return this; } /** * The consumer type to use, which can be one of: Simple, Default, or * Custom. The consumer type determines which Spring JMS listener to * use. Default will use * org.springframework.jms.listener.DefaultMessageListenerContainer, * Simple will use * org.springframework.jms.listener.SimpleMessageListenerContainer. When * Custom is specified, the MessageListenerContainerFactory defined by * the messageListenerContainerFactory option will determine what * org.springframework.jms.listener.AbstractMessageListenerContainer to * use. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.ConsumerType&lt;/code&gt; * type. * * Default: Default * Group: consumer (advanced) * * @param consumerType the value to set * @return the dsl builder */ default AmqpComponentBuilder consumerType( org.apache.camel.component.jms.ConsumerType consumerType) { doSetProperty("consumerType", consumerType); return this; } /** * Specifies what default TaskExecutor type to use in the * DefaultMessageListenerContainer, for both consumer endpoints and the * ReplyTo consumer of producer endpoints. Possible values: SimpleAsync * (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool (uses Spring's * ThreadPoolTaskExecutor with optimal values - cached threadpool-like). * If not set, it defaults to the previous behaviour, which uses a * cached thread pool for consumer endpoints and SimpleAsync for reply * consumers. The use of ThreadPool is recommended to reduce thread * trash in elastic configurations with dynamically increasing and * decreasing concurrent consumers. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.DefaultTaskExecutorType&lt;/code&gt; type. * * Group: consumer (advanced) * * @param defaultTaskExecutorType the value to set * @return the dsl builder */ default AmqpComponentBuilder defaultTaskExecutorType( org.apache.camel.component.jms.DefaultTaskExecutorType defaultTaskExecutorType) { doSetProperty("defaultTaskExecutorType", defaultTaskExecutorType); return this; } /** * Enables eager loading of JMS properties and payload as soon as a * message is loaded which generally is inefficient as the JMS * properties may not be required but sometimes can catch early any * issues with the underlying JMS provider and the use of JMS * properties. See also the option eagerPoisonBody. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param eagerLoadingOfProperties the value to set * @return the dsl builder */ default AmqpComponentBuilder eagerLoadingOfProperties( boolean eagerLoadingOfProperties) { doSetProperty("eagerLoadingOfProperties", eagerLoadingOfProperties); return this; } /** * If eagerLoadingOfProperties is enabled and the JMS message payload * (JMS body or JMS properties) is poison (cannot be read/mapped), then * set this text as the message body instead so the message can be * processed (the cause of the poison are already stored as exception on * the Exchange). This can be turned off by setting * eagerPoisonBody=false. See also the option eagerLoadingOfProperties. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: Poison JMS message due to ${exception.message} * Group: consumer (advanced) * * @param eagerPoisonBody the value to set * @return the dsl builder */ default AmqpComponentBuilder eagerPoisonBody( java.lang.String eagerPoisonBody) { doSetProperty("eagerPoisonBody", eagerPoisonBody); return this; } /** * Specifies whether the listener session should be exposed when * consuming messages. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param exposeListenerSession the value to set * @return the dsl builder */ default AmqpComponentBuilder exposeListenerSession( boolean exposeListenerSession) { doSetProperty("exposeListenerSession", exposeListenerSession); return this; } /** * Whether a JMS consumer is allowed to send a reply message to the same * destination that the consumer is using to consume from. This prevents * an endless loop by consuming and sending back the same message to * itself. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param replyToSameDestinationAllowed the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToSameDestinationAllowed( boolean replyToSameDestinationAllowed) { doSetProperty("replyToSameDestinationAllowed", replyToSameDestinationAllowed); return this; } /** * Allows you to specify a custom task executor for consuming messages. * * The option is a: * &lt;code&gt;org.springframework.core.task.TaskExecutor&lt;/code&gt; * type. * * Group: consumer (advanced) * * @param taskExecutor the value to set * @return the dsl builder */ default AmqpComponentBuilder taskExecutor( org.springframework.core.task.TaskExecutor taskExecutor) { doSetProperty("taskExecutor", taskExecutor); return this; } /** * Sets delivery delay to use for send calls for JMS. This option * requires JMS 2.0 compliant broker. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: -1 * Group: producer * * @param deliveryDelay the value to set * @return the dsl builder */ default AmqpComponentBuilder deliveryDelay(long deliveryDelay) { doSetProperty("deliveryDelay", deliveryDelay); return this; } /** * Specifies the delivery mode to be used. Possible values are those * defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT * = 2. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: producer * * @param deliveryMode the value to set * @return the dsl builder */ default AmqpComponentBuilder deliveryMode(java.lang.Integer deliveryMode) { doSetProperty("deliveryMode", deliveryMode); return this; } /** * Specifies whether persistent delivery is used by default. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer * * @param deliveryPersistent the value to set * @return the dsl builder */ default AmqpComponentBuilder deliveryPersistent( boolean deliveryPersistent) { doSetProperty("deliveryPersistent", deliveryPersistent); return this; } /** * Set if the deliveryMode, priority or timeToLive qualities of service * should be used when sending messages. This option is based on * Spring's JmsTemplate. The deliveryMode, priority and timeToLive * options are applied to the current endpoint. This contrasts with the * preserveMessageQos option, which operates at message granularity, * reading QoS properties exclusively from the Camel In message headers. * * The option is a: &lt;code&gt;java.lang.Boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param explicitQosEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder explicitQosEnabled( java.lang.Boolean explicitQosEnabled) { doSetProperty("explicitQosEnabled", explicitQosEnabled); return this; } /** * Sets whether JMS date properties should be formatted according to the * ISO 8601 standard. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param formatDateHeadersToIso8601 the value to set * @return the dsl builder */ default AmqpComponentBuilder formatDateHeadersToIso8601( boolean formatDateHeadersToIso8601) { doSetProperty("formatDateHeadersToIso8601", formatDateHeadersToIso8601); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default AmqpComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Set to true, if you want to send message using the QoS settings * specified on the message, instead of the QoS settings on the JMS * endpoint. The following three headers are considered JMSPriority, * JMSDeliveryMode, and JMSExpiration. You can provide all or only some * of them. If not provided, Camel will fall back to use the values from * the endpoint instead. So, when using this option, the headers * override the values from the endpoint. The explicitQosEnabled option, * by contrast, will only use options set on the endpoint, and not * values from the message header. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param preserveMessageQos the value to set * @return the dsl builder */ default AmqpComponentBuilder preserveMessageQos( boolean preserveMessageQos) { doSetProperty("preserveMessageQos", preserveMessageQos); return this; } /** * Values greater than 1 specify the message priority when sending * (where 1 is the lowest priority and 9 is the highest). The * explicitQosEnabled option must also be enabled in order for this * option to have any effect. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 4 * Group: producer * * @param priority the value to set * @return the dsl builder */ default AmqpComponentBuilder priority(int priority) { doSetProperty("priority", priority); return this; } /** * Specifies the default number of concurrent consumers when doing * request/reply over JMS. See also the maxMessagesPerTask option to * control dynamic scaling up/down of threads. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: producer * * @param replyToConcurrentConsumers the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToConcurrentConsumers( int replyToConcurrentConsumers) { doSetProperty("replyToConcurrentConsumers", replyToConcurrentConsumers); return this; } /** * Specifies the maximum number of concurrent consumers when using * request/reply over JMS. See also the maxMessagesPerTask option to * control dynamic scaling up/down of threads. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: producer * * @param replyToMaxConcurrentConsumers the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToMaxConcurrentConsumers( int replyToMaxConcurrentConsumers) { doSetProperty("replyToMaxConcurrentConsumers", replyToMaxConcurrentConsumers); return this; } /** * Specifies the maximum number of concurrent consumers for continue * routing when timeout occurred when using request/reply over JMS. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: producer * * @param replyToOnTimeoutMaxConcurrentConsumers the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToOnTimeoutMaxConcurrentConsumers( int replyToOnTimeoutMaxConcurrentConsumers) { doSetProperty("replyToOnTimeoutMaxConcurrentConsumers", replyToOnTimeoutMaxConcurrentConsumers); return this; } /** * Provides an explicit ReplyTo destination in the JMS message, which * overrides the setting of replyTo. It is useful if you want to forward * the message to a remote Queue and receive the reply message from the * ReplyTo destination. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param replyToOverride the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToOverride( java.lang.String replyToOverride) { doSetProperty("replyToOverride", replyToOverride); return this; } /** * Allows for explicitly specifying which kind of strategy to use for * replyTo queues when doing request/reply over JMS. Possible values * are: Temporary, Shared, or Exclusive. By default Camel will use * temporary queues. However if replyTo has been configured, then Shared * is used by default. This option allows you to use exclusive queues * instead of shared ones. See Camel JMS documentation for more details, * and especially the notes about the implications if running in a * clustered environment, and the fact that Shared reply queues has * lower performance than its alternatives Temporary and Exclusive. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.ReplyToType&lt;/code&gt; * type. * * Group: producer * * @param replyToType the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToType( org.apache.camel.component.jms.ReplyToType replyToType) { doSetProperty("replyToType", replyToType); return this; } /** * The timeout for waiting for a reply when using the InOut Exchange * Pattern (in milliseconds). The default is 20 seconds. You can include * the header CamelJmsRequestTimeout to override this endpoint * configured timeout value, and thus have per message individual * timeout values. See also the requestTimeoutCheckerInterval option. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 20000 * Group: producer * * @param requestTimeout the value to set * @return the dsl builder */ default AmqpComponentBuilder requestTimeout(long requestTimeout) { doSetProperty("requestTimeout", requestTimeout); return this; } /** * When sending messages, specifies the time-to-live of the message (in * milliseconds). * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: -1 * Group: producer * * @param timeToLive the value to set * @return the dsl builder */ default AmqpComponentBuilder timeToLive(long timeToLive) { doSetProperty("timeToLive", timeToLive); return this; } /** * This option is used to allow additional headers which may have values * that are invalid according to JMS specification. For example some * message systems such as WMQ do this with header names using prefix * JMS_IBM_MQMD_ containing values with byte array or other invalid * types. You can specify multiple header names separated by comma, and * use as suffix for wildcard matching. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer (advanced) * * @param allowAdditionalHeaders the value to set * @return the dsl builder */ default AmqpComponentBuilder allowAdditionalHeaders( java.lang.String allowAdditionalHeaders) { doSetProperty("allowAdditionalHeaders", allowAdditionalHeaders); return this; } /** * Whether to allow sending messages with no body. If this option is * false and the message body is null, then an JMSException is thrown. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param allowNullBody the value to set * @return the dsl builder */ default AmqpComponentBuilder allowNullBody(boolean allowNullBody) { doSetProperty("allowNullBody", allowNullBody); return this; } /** * If true, Camel will always make a JMS message copy of the message * when it is passed to the producer for sending. Copying the message is * needed in some situations, such as when a * replyToDestinationSelectorName is set (incidentally, Camel will set * the alwaysCopyMessage option to true, if a * replyToDestinationSelectorName is set). * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param alwaysCopyMessage the value to set * @return the dsl builder */ default AmqpComponentBuilder alwaysCopyMessage(boolean alwaysCopyMessage) { doSetProperty("alwaysCopyMessage", alwaysCopyMessage); return this; } /** * When using InOut exchange pattern use this JMS property instead of * JMSCorrelationID JMS property to correlate messages. If set messages * will be correlated solely on the value of this property * JMSCorrelationID property will be ignored and not set by Camel. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer (advanced) * * @param correlationProperty the value to set * @return the dsl builder */ default AmqpComponentBuilder correlationProperty( java.lang.String correlationProperty) { doSetProperty("correlationProperty", correlationProperty); return this; } /** * Use this option to force disabling time to live. For example when you * do request/reply over JMS, then Camel will by default use the * requestTimeout value as time to live on the message being sent. The * problem is that the sender and receiver systems have to have their * clocks synchronized, so they are in sync. This is not always so easy * to archive. So you can use disableTimeToLive=true to not set a time * to live value on the sent message. Then the message will not expire * on the receiver system. See below in section About time to live for * more details. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param disableTimeToLive the value to set * @return the dsl builder */ default AmqpComponentBuilder disableTimeToLive(boolean disableTimeToLive) { doSetProperty("disableTimeToLive", disableTimeToLive); return this; } /** * When using mapJmsMessage=false Camel will create a new JMS message to * send to a new JMS destination if you touch the headers (get or set) * during the route. Set this option to true to force Camel to send the * original JMS message that was received. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param forceSendOriginalMessage the value to set * @return the dsl builder */ default AmqpComponentBuilder forceSendOriginalMessage( boolean forceSendOriginalMessage) { doSetProperty("forceSendOriginalMessage", forceSendOriginalMessage); return this; } /** * Only applicable when sending to JMS destination using InOnly (eg fire * and forget). Enabling this option will enrich the Camel Exchange with * the actual JMSMessageID that was used by the JMS client when the * message was sent to the JMS destination. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param includeSentJMSMessageID the value to set * @return the dsl builder */ default AmqpComponentBuilder includeSentJMSMessageID( boolean includeSentJMSMessageID) { doSetProperty("includeSentJMSMessageID", includeSentJMSMessageID); return this; } /** * Sets the cache level by name for the reply consumer when doing * request/reply over JMS. This option only applies when using fixed * reply queues (not temporary). Camel will by default use: * CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And * CACHE_SESSION for shared without replyToSelectorName. Some JMS * brokers such as IBM WebSphere may require to set the * replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary * queues then CACHE_NONE is not allowed, and you must use a higher * value such as CACHE_CONSUMER or CACHE_SESSION. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer (advanced) * * @param replyToCacheLevelName the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToCacheLevelName( java.lang.String replyToCacheLevelName) { doSetProperty("replyToCacheLevelName", replyToCacheLevelName); return this; } /** * Sets the JMS Selector using the fixed name to be used so you can * filter out your own replies from the others when using a shared queue * (that is, if you are not using a temporary reply queue). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer (advanced) * * @param replyToDestinationSelectorName the value to set * @return the dsl builder */ default AmqpComponentBuilder replyToDestinationSelectorName( java.lang.String replyToDestinationSelectorName) { doSetProperty("replyToDestinationSelectorName", replyToDestinationSelectorName); return this; } /** * Sets whether StreamMessage type is enabled or not. Message payloads * of streaming kind such as files, InputStream, etc will either by sent * as BytesMessage or StreamMessage. This option controls which kind * will be used. By default BytesMessage is used which enforces the * entire message payload to be read into memory. By enabling this * option the message payload is read into memory in chunks and each * chunk is then written to the StreamMessage until no more data. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param streamMessageTypeEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder streamMessageTypeEnabled( boolean streamMessageTypeEnabled) { doSetProperty("streamMessageTypeEnabled", streamMessageTypeEnabled); return this; } /** * Whether to auto-discover ConnectionFactory from the registry, if no * connection factory has been configured. If only one instance of * ConnectionFactory is found then it will be used. This is enabled by * default. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param allowAutoWiredConnectionFactory the value to set * @return the dsl builder */ default AmqpComponentBuilder allowAutoWiredConnectionFactory( boolean allowAutoWiredConnectionFactory) { doSetProperty("allowAutoWiredConnectionFactory", allowAutoWiredConnectionFactory); return this; } /** * Whether to auto-discover DestinationResolver from the registry, if no * destination resolver has been configured. If only one instance of * DestinationResolver is found then it will be used. This is enabled by * default. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param allowAutoWiredDestinationResolver the value to set * @return the dsl builder */ default AmqpComponentBuilder allowAutoWiredDestinationResolver( boolean allowAutoWiredDestinationResolver) { doSetProperty("allowAutoWiredDestinationResolver", allowAutoWiredDestinationResolver); return this; } /** * Controls whether or not to include serialized headers. Applies only * when transferExchange is true. This requires that the objects are * serializable. Camel will exclude any non-serializable objects and log * it at WARN level. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param allowSerializedHeaders the value to set * @return the dsl builder */ default AmqpComponentBuilder allowSerializedHeaders( boolean allowSerializedHeaders) { doSetProperty("allowSerializedHeaders", allowSerializedHeaders); return this; } /** * Whether optimizing for Apache Artemis streaming mode. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param artemisStreamingEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder artemisStreamingEnabled( boolean artemisStreamingEnabled) { doSetProperty("artemisStreamingEnabled", artemisStreamingEnabled); return this; } /** * Whether to startup the JmsConsumer message listener asynchronously, * when starting a route. For example if a JmsConsumer cannot get a * connection to a remote JMS broker, then it may block while retrying * and/or failover. This will cause Camel to block while starting * routes. By setting this option to true, you will let routes startup, * while the JmsConsumer connects to the JMS broker using a dedicated * thread in asynchronous mode. If this option is used, then beware that * if the connection could not be established, then an exception is * logged at WARN level, and the consumer will not be able to receive * messages; You can then restart the route to retry. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param asyncStartListener the value to set * @return the dsl builder */ default AmqpComponentBuilder asyncStartListener( boolean asyncStartListener) { doSetProperty("asyncStartListener", asyncStartListener); return this; } /** * Whether to stop the JmsConsumer message listener asynchronously, when * stopping a route. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param asyncStopListener the value to set * @return the dsl builder */ default AmqpComponentBuilder asyncStopListener(boolean asyncStopListener) { doSetProperty("asyncStopListener", asyncStopListener); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use a shared JMS configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.JmsConfiguration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default AmqpComponentBuilder configuration( org.apache.camel.component.jms.JmsConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * A pluggable * org.springframework.jms.support.destination.DestinationResolver that * allows you to use your own resolver (for example, to lookup the real * destination in a JNDI registry). * * The option is a: * &lt;code&gt;org.springframework.jms.support.destination.DestinationResolver&lt;/code&gt; type. * * Group: advanced * * @param destinationResolver the value to set * @return the dsl builder */ default AmqpComponentBuilder destinationResolver( org.springframework.jms.support.destination.DestinationResolver destinationResolver) { doSetProperty("destinationResolver", destinationResolver); return this; } /** * Specifies a org.springframework.util.ErrorHandler to be invoked in * case of any uncaught exceptions thrown while processing a Message. By * default these exceptions will be logged at the WARN level, if no * errorHandler has been configured. You can configure logging level and * whether stack traces should be logged using errorHandlerLoggingLevel * and errorHandlerLogStackTrace options. This makes it much easier to * configure, than having to code a custom errorHandler. * * The option is a: * &lt;code&gt;org.springframework.util.ErrorHandler&lt;/code&gt; type. * * Group: advanced * * @param errorHandler the value to set * @return the dsl builder */ default AmqpComponentBuilder errorHandler( org.springframework.util.ErrorHandler errorHandler) { doSetProperty("errorHandler", errorHandler); return this; } /** * Specifies the JMS Exception Listener that is to be notified of any * underlying JMS exceptions. * * The option is a: &lt;code&gt;javax.jms.ExceptionListener&lt;/code&gt; * type. * * Group: advanced * * @param exceptionListener the value to set * @return the dsl builder */ default AmqpComponentBuilder exceptionListener( javax.jms.ExceptionListener exceptionListener) { doSetProperty("exceptionListener", exceptionListener); return this; } /** * Specify the limit for the number of consumers that are allowed to be * idle at any given time. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: advanced * * @param idleConsumerLimit the value to set * @return the dsl builder */ default AmqpComponentBuilder idleConsumerLimit(int idleConsumerLimit) { doSetProperty("idleConsumerLimit", idleConsumerLimit); return this; } /** * Specifies the limit for idle executions of a receive task, not having * received any message within its execution. If this limit is reached, * the task will shut down and leave receiving to other executing tasks * (in the case of dynamic scheduling; see the maxConcurrentConsumers * setting). There is additional doc available from Spring. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: advanced * * @param idleTaskExecutionLimit the value to set * @return the dsl builder */ default AmqpComponentBuilder idleTaskExecutionLimit( int idleTaskExecutionLimit) { doSetProperty("idleTaskExecutionLimit", idleTaskExecutionLimit); return this; } /** * Whether to include all JMSXxxx properties when mapping from JMS to * Camel Message. Setting this to true will include properties such as * JMSXAppID, and JMSXUserID etc. Note: If you are using a custom * headerFilterStrategy then this option does not apply. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param includeAllJMSXProperties the value to set * @return the dsl builder */ default AmqpComponentBuilder includeAllJMSXProperties( boolean includeAllJMSXProperties) { doSetProperty("includeAllJMSXProperties", includeAllJMSXProperties); return this; } /** * Pluggable strategy for encoding and decoding JMS keys so they can be * compliant with the JMS specification. Camel provides two * implementations out of the box: default and passthrough. The default * strategy will safely marshal dots and hyphens (. and -). The * passthrough strategy leaves the key as is. Can be used for JMS * brokers which do not care whether JMS header keys contain illegal * characters. You can provide your own implementation of the * org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it * using the # notation. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.JmsKeyFormatStrategy&lt;/code&gt; type. * * Group: advanced * * @param jmsKeyFormatStrategy the value to set * @return the dsl builder */ default AmqpComponentBuilder jmsKeyFormatStrategy( org.apache.camel.component.jms.JmsKeyFormatStrategy jmsKeyFormatStrategy) { doSetProperty("jmsKeyFormatStrategy", jmsKeyFormatStrategy); return this; } /** * Specifies whether Camel should auto map the received JMS message to a * suited payload type, such as javax.jms.TextMessage to a String etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param mapJmsMessage the value to set * @return the dsl builder */ default AmqpComponentBuilder mapJmsMessage(boolean mapJmsMessage) { doSetProperty("mapJmsMessage", mapJmsMessage); return this; } /** * The number of messages per task. -1 is unlimited. If you use a range * for concurrent consumers (eg min max), then this option can be used * to set a value to eg 100 to control how fast the consumers will * shrink when less work is required. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: -1 * Group: advanced * * @param maxMessagesPerTask the value to set * @return the dsl builder */ default AmqpComponentBuilder maxMessagesPerTask(int maxMessagesPerTask) { doSetProperty("maxMessagesPerTask", maxMessagesPerTask); return this; } /** * To use a custom Spring * org.springframework.jms.support.converter.MessageConverter so you can * be in control how to map to/from a javax.jms.Message. * * The option is a: * &lt;code&gt;org.springframework.jms.support.converter.MessageConverter&lt;/code&gt; type. * * Group: advanced * * @param messageConverter the value to set * @return the dsl builder */ default AmqpComponentBuilder messageConverter( org.springframework.jms.support.converter.MessageConverter messageConverter) { doSetProperty("messageConverter", messageConverter); return this; } /** * To use the given MessageCreatedStrategy which are invoked when Camel * creates new instances of javax.jms.Message objects when Camel is * sending a JMS message. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.MessageCreatedStrategy&lt;/code&gt; type. * * Group: advanced * * @param messageCreatedStrategy the value to set * @return the dsl builder */ default AmqpComponentBuilder messageCreatedStrategy( org.apache.camel.component.jms.MessageCreatedStrategy messageCreatedStrategy) { doSetProperty("messageCreatedStrategy", messageCreatedStrategy); return this; } /** * When sending, specifies whether message IDs should be added. This is * just an hint to the JMS broker. If the JMS provider accepts this * hint, these messages must have the message ID set to null; if the * provider ignores the hint, the message ID must be set to its normal * unique value. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param messageIdEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder messageIdEnabled(boolean messageIdEnabled) { doSetProperty("messageIdEnabled", messageIdEnabled); return this; } /** * Registry ID of the MessageListenerContainerFactory used to determine * what * org.springframework.jms.listener.AbstractMessageListenerContainer to * use to consume messages. Setting this will automatically set * consumerType to Custom. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.MessageListenerContainerFactory&lt;/code&gt; type. * * Group: advanced * * @param messageListenerContainerFactory the value to set * @return the dsl builder */ default AmqpComponentBuilder messageListenerContainerFactory( org.apache.camel.component.jms.MessageListenerContainerFactory messageListenerContainerFactory) { doSetProperty("messageListenerContainerFactory", messageListenerContainerFactory); return this; } /** * Specifies whether timestamps should be enabled by default on sending * messages. This is just an hint to the JMS broker. If the JMS provider * accepts this hint, these messages must have the timestamp set to * zero; if the provider ignores the hint the timestamp must be set to * its normal value. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param messageTimestampEnabled the value to set * @return the dsl builder */ default AmqpComponentBuilder messageTimestampEnabled( boolean messageTimestampEnabled) { doSetProperty("messageTimestampEnabled", messageTimestampEnabled); return this; } /** * Specifies whether to inhibit the delivery of messages published by * its own connection. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param pubSubNoLocal the value to set * @return the dsl builder */ default AmqpComponentBuilder pubSubNoLocal(boolean pubSubNoLocal) { doSetProperty("pubSubNoLocal", pubSubNoLocal); return this; } /** * To use a custom QueueBrowseStrategy when browsing queues. * * The option is a: * &lt;code&gt;org.apache.camel.component.jms.QueueBrowseStrategy&lt;/code&gt; type. * * Group: advanced * * @param queueBrowseStrategy the value to set * @return the dsl builder */ default AmqpComponentBuilder queueBrowseStrategy( org.apache.camel.component.jms.QueueBrowseStrategy queueBrowseStrategy) { doSetProperty("queueBrowseStrategy", queueBrowseStrategy); return this; } /** * The timeout for receiving messages (in milliseconds). * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 1000 * Group: advanced * * @param receiveTimeout the value to set * @return the dsl builder */ default AmqpComponentBuilder receiveTimeout(long receiveTimeout) { doSetProperty("receiveTimeout", receiveTimeout); return this; } /** * Specifies the interval between recovery attempts, i.e. when a * connection is being refreshed, in milliseconds. The default is 5000 * ms, that is, 5 seconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 5000 * Group: advanced * * @param recoveryInterval the value to set * @return the dsl builder */ default AmqpComponentBuilder recoveryInterval(long recoveryInterval) { doSetProperty("recoveryInterval", recoveryInterval); return this; } /** * Configures how often Camel should check for timed out Exchanges when * doing request/reply over JMS. By default Camel checks once per * second. But if you must react faster when a timeout occurs, then you * can lower this interval, to check more frequently. The timeout is * determined by the option requestTimeout. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 1000 * Group: advanced * * @param requestTimeoutCheckerInterval the value to set * @return the dsl builder */ default AmqpComponentBuilder requestTimeoutCheckerInterval( long requestTimeoutCheckerInterval) { doSetProperty("requestTimeoutCheckerInterval", requestTimeoutCheckerInterval); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param synchronous the value to set * @return the dsl builder */ default AmqpComponentBuilder synchronous(boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * If enabled and you are using Request Reply messaging (InOut) and an * Exchange failed on the consumer side, then the caused Exception will * be send back in response as a javax.jms.ObjectMessage. If the client * is Camel, the returned Exception is rethrown. This allows you to use * Camel JMS as a bridge in your routing - for example, using persistent * queues to enable robust routing. Notice that if you also have * transferExchange enabled, this option takes precedence. The caught * exception is required to be serializable. The original Exception on * the consumer side can be wrapped in an outer exception such as * org.apache.camel.RuntimeCamelException when returned to the producer. * Use this with caution as the data is using Java Object serialization * and requires the received to be able to deserialize the data at Class * level, which forces a strong coupling between the producers and * consumer!. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param transferException the value to set * @return the dsl builder */ default AmqpComponentBuilder transferException(boolean transferException) { doSetProperty("transferException", transferException); return this; } /** * You can transfer the exchange over the wire instead of just the body * and headers. The following fields are transferred: In body, Out body, * Fault body, In headers, Out headers, Fault headers, exchange * properties, exchange exception. This requires that the objects are * serializable. Camel will exclude any non-serializable objects and log * it at WARN level. You must enable this option on both the producer * and consumer side, so Camel knows the payloads is an Exchange and not * a regular payload. Use this with caution as the data is using Java * Object serialization and requires the received to be able to * deserialize the data at Class level, which forces a strong coupling * between the producers and consumer having to use compatible Camel * versions!. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param transferExchange the value to set * @return the dsl builder */ default AmqpComponentBuilder transferExchange(boolean transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } /** * Specifies whether JMSMessageID should always be used as * JMSCorrelationID for InOut messages. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param useMessageIDAsCorrelationID the value to set * @return the dsl builder */ default AmqpComponentBuilder useMessageIDAsCorrelationID( boolean useMessageIDAsCorrelationID) { doSetProperty("useMessageIDAsCorrelationID", useMessageIDAsCorrelationID); return this; } /** * Number of times to wait for provisional correlation id to be updated * to the actual correlation id when doing request/reply over JMS and * when the option useMessageIDAsCorrelationID is enabled. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 50 * Group: advanced * * @param waitForProvisionCorrelationToBeUpdatedCounter the value to set * @return the dsl builder */ default AmqpComponentBuilder waitForProvisionCorrelationToBeUpdatedCounter( int waitForProvisionCorrelationToBeUpdatedCounter) { doSetProperty("waitForProvisionCorrelationToBeUpdatedCounter", waitForProvisionCorrelationToBeUpdatedCounter); return this; } /** * Interval in millis to sleep each time while waiting for provisional * correlation id to be updated. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 100 * Group: advanced * * @param waitForProvisionCorrelationToBeUpdatedThreadSleepingTime the * value to set * @return the dsl builder */ default AmqpComponentBuilder waitForProvisionCorrelationToBeUpdatedThreadSleepingTime( long waitForProvisionCorrelationToBeUpdatedThreadSleepingTime) { doSetProperty("waitForProvisionCorrelationToBeUpdatedThreadSleepingTime", waitForProvisionCorrelationToBeUpdatedThreadSleepingTime); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * header to and from Camel message. * * The option is a: * &lt;code&gt;org.apache.camel.spi.HeaderFilterStrategy&lt;/code&gt; * type. * * Group: filter * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AmqpComponentBuilder headerFilterStrategy( org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Allows to configure the default errorHandler logging level for * logging uncaught exceptions. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: WARN * Group: logging * * @param errorHandlerLoggingLevel the value to set * @return the dsl builder */ default AmqpComponentBuilder errorHandlerLoggingLevel( org.apache.camel.LoggingLevel errorHandlerLoggingLevel) { doSetProperty("errorHandlerLoggingLevel", errorHandlerLoggingLevel); return this; } /** * Allows to control whether stacktraces should be logged or not, by the * default errorHandler. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: logging * * @param errorHandlerLogStackTrace the value to set * @return the dsl builder */ default AmqpComponentBuilder errorHandlerLogStackTrace( boolean errorHandlerLogStackTrace) { doSetProperty("errorHandlerLogStackTrace", errorHandlerLogStackTrace); return this; } /** * Password to use with the ConnectionFactory. You can also configure * username/password directly on the ConnectionFactory. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param password the value to set * @return the dsl builder */ default AmqpComponentBuilder password(java.lang.String password) { doSetProperty("password", password); return this; } /** * Username to use with the ConnectionFactory. You can also configure * username/password directly on the ConnectionFactory. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param username the value to set * @return the dsl builder */ default AmqpComponentBuilder username(java.lang.String username) { doSetProperty("username", username); return this; } /** * Specifies whether to use transacted mode. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: transaction * * @param transacted the value to set * @return the dsl builder */ default AmqpComponentBuilder transacted(boolean transacted) { doSetProperty("transacted", transacted); return this; } /** * Specifies whether InOut operations (request reply) default to using * transacted mode If this flag is set to true, then Spring JmsTemplate * will have sessionTransacted set to true, and the acknowledgeMode as * transacted on the JmsTemplate used for InOut operations. Note from * Spring JMS: that within a JTA transaction, the parameters passed to * createQueue, createTopic methods are not taken into account. * Depending on the Java EE transaction context, the container makes its * own decisions on these values. Analogously, these parameters are not * taken into account within a locally managed transaction either, since * Spring JMS operates on an existing JMS Session in this case. Setting * this flag to true will use a short local JMS transaction when running * outside of a managed transaction, and a synchronized local JMS * transaction in case of a managed transaction (other than an XA * transaction) being present. This has the effect of a local JMS * transaction being managed alongside the main transaction (which might * be a native JDBC transaction), with the JMS transaction committing * right after the main transaction. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: transaction * * @param transactedInOut the value to set * @return the dsl builder */ default AmqpComponentBuilder transactedInOut(boolean transactedInOut) { doSetProperty("transactedInOut", transactedInOut); return this; } /** * If true, Camel will create a JmsTransactionManager, if there is no * transactionManager injected when option transacted=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: transaction (advanced) * * @param lazyCreateTransactionManager the value to set * @return the dsl builder */ default AmqpComponentBuilder lazyCreateTransactionManager( boolean lazyCreateTransactionManager) { doSetProperty("lazyCreateTransactionManager", lazyCreateTransactionManager); return this; } /** * The Spring transaction manager to use. * * The option is a: * &lt;code&gt;org.springframework.transaction.PlatformTransactionManager&lt;/code&gt; type. * * Group: transaction (advanced) * * @param transactionManager the value to set * @return the dsl builder */ default AmqpComponentBuilder transactionManager( org.springframework.transaction.PlatformTransactionManager transactionManager) { doSetProperty("transactionManager", transactionManager); return this; } /** * The name of the transaction to use. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: transaction (advanced) * * @param transactionName the value to set * @return the dsl builder */ default AmqpComponentBuilder transactionName( java.lang.String transactionName) { doSetProperty("transactionName", transactionName); return this; } /** * The timeout value of the transaction (in seconds), if using * transacted mode. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: -1 * Group: transaction (advanced) * * @param transactionTimeout the value to set * @return the dsl builder */ default AmqpComponentBuilder transactionTimeout(int transactionTimeout) { doSetProperty("transactionTimeout", transactionTimeout); return this; } } class AmqpComponentBuilderImpl extends AbstractComponentBuilder<AMQPComponent> implements AmqpComponentBuilder { @Override protected AMQPComponent buildConcreteComponent() { return new AMQPComponent(); } private org.apache.camel.component.jms.JmsConfiguration getOrCreateConfiguration( org.apache.camel.component.amqp.AMQPComponent component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.jms.JmsConfiguration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "clientId": getOrCreateConfiguration((AMQPComponent) component).setClientId((java.lang.String) value); return true; case "connectionFactory": getOrCreateConfiguration((AMQPComponent) component).setConnectionFactory((javax.jms.ConnectionFactory) value); return true; case "disableReplyTo": getOrCreateConfiguration((AMQPComponent) component).setDisableReplyTo((boolean) value); return true; case "durableSubscriptionName": getOrCreateConfiguration((AMQPComponent) component).setDurableSubscriptionName((java.lang.String) value); return true; case "includeAmqpAnnotations": ((AMQPComponent) component).setIncludeAmqpAnnotations((boolean) value); return true; case "jmsMessageType": getOrCreateConfiguration((AMQPComponent) component).setJmsMessageType((org.apache.camel.component.jms.JmsMessageType) value); return true; case "replyTo": getOrCreateConfiguration((AMQPComponent) component).setReplyTo((java.lang.String) value); return true; case "testConnectionOnStartup": getOrCreateConfiguration((AMQPComponent) component).setTestConnectionOnStartup((boolean) value); return true; case "acknowledgementModeName": getOrCreateConfiguration((AMQPComponent) component).setAcknowledgementModeName((java.lang.String) value); return true; case "artemisConsumerPriority": getOrCreateConfiguration((AMQPComponent) component).setArtemisConsumerPriority((int) value); return true; case "asyncConsumer": getOrCreateConfiguration((AMQPComponent) component).setAsyncConsumer((boolean) value); return true; case "autoStartup": getOrCreateConfiguration((AMQPComponent) component).setAutoStartup((boolean) value); return true; case "cacheLevel": getOrCreateConfiguration((AMQPComponent) component).setCacheLevel((int) value); return true; case "cacheLevelName": getOrCreateConfiguration((AMQPComponent) component).setCacheLevelName((java.lang.String) value); return true; case "concurrentConsumers": getOrCreateConfiguration((AMQPComponent) component).setConcurrentConsumers((int) value); return true; case "maxConcurrentConsumers": getOrCreateConfiguration((AMQPComponent) component).setMaxConcurrentConsumers((int) value); return true; case "replyToDeliveryPersistent": getOrCreateConfiguration((AMQPComponent) component).setReplyToDeliveryPersistent((boolean) value); return true; case "selector": getOrCreateConfiguration((AMQPComponent) component).setSelector((java.lang.String) value); return true; case "subscriptionDurable": getOrCreateConfiguration((AMQPComponent) component).setSubscriptionDurable((boolean) value); return true; case "subscriptionName": getOrCreateConfiguration((AMQPComponent) component).setSubscriptionName((java.lang.String) value); return true; case "subscriptionShared": getOrCreateConfiguration((AMQPComponent) component).setSubscriptionShared((boolean) value); return true; case "acceptMessagesWhileStopping": getOrCreateConfiguration((AMQPComponent) component).setAcceptMessagesWhileStopping((boolean) value); return true; case "allowReplyManagerQuickStop": getOrCreateConfiguration((AMQPComponent) component).setAllowReplyManagerQuickStop((boolean) value); return true; case "consumerType": getOrCreateConfiguration((AMQPComponent) component).setConsumerType((org.apache.camel.component.jms.ConsumerType) value); return true; case "defaultTaskExecutorType": getOrCreateConfiguration((AMQPComponent) component).setDefaultTaskExecutorType((org.apache.camel.component.jms.DefaultTaskExecutorType) value); return true; case "eagerLoadingOfProperties": getOrCreateConfiguration((AMQPComponent) component).setEagerLoadingOfProperties((boolean) value); return true; case "eagerPoisonBody": getOrCreateConfiguration((AMQPComponent) component).setEagerPoisonBody((java.lang.String) value); return true; case "exposeListenerSession": getOrCreateConfiguration((AMQPComponent) component).setExposeListenerSession((boolean) value); return true; case "replyToSameDestinationAllowed": getOrCreateConfiguration((AMQPComponent) component).setReplyToSameDestinationAllowed((boolean) value); return true; case "taskExecutor": getOrCreateConfiguration((AMQPComponent) component).setTaskExecutor((org.springframework.core.task.TaskExecutor) value); return true; case "deliveryDelay": getOrCreateConfiguration((AMQPComponent) component).setDeliveryDelay((long) value); return true; case "deliveryMode": getOrCreateConfiguration((AMQPComponent) component).setDeliveryMode((java.lang.Integer) value); return true; case "deliveryPersistent": getOrCreateConfiguration((AMQPComponent) component).setDeliveryPersistent((boolean) value); return true; case "explicitQosEnabled": getOrCreateConfiguration((AMQPComponent) component).setExplicitQosEnabled((java.lang.Boolean) value); return true; case "formatDateHeadersToIso8601": getOrCreateConfiguration((AMQPComponent) component).setFormatDateHeadersToIso8601((boolean) value); return true; case "lazyStartProducer": ((AMQPComponent) component).setLazyStartProducer((boolean) value); return true; case "preserveMessageQos": getOrCreateConfiguration((AMQPComponent) component).setPreserveMessageQos((boolean) value); return true; case "priority": getOrCreateConfiguration((AMQPComponent) component).setPriority((int) value); return true; case "replyToConcurrentConsumers": getOrCreateConfiguration((AMQPComponent) component).setReplyToConcurrentConsumers((int) value); return true; case "replyToMaxConcurrentConsumers": getOrCreateConfiguration((AMQPComponent) component).setReplyToMaxConcurrentConsumers((int) value); return true; case "replyToOnTimeoutMaxConcurrentConsumers": getOrCreateConfiguration((AMQPComponent) component).setReplyToOnTimeoutMaxConcurrentConsumers((int) value); return true; case "replyToOverride": getOrCreateConfiguration((AMQPComponent) component).setReplyToOverride((java.lang.String) value); return true; case "replyToType": getOrCreateConfiguration((AMQPComponent) component).setReplyToType((org.apache.camel.component.jms.ReplyToType) value); return true; case "requestTimeout": getOrCreateConfiguration((AMQPComponent) component).setRequestTimeout((long) value); return true; case "timeToLive": getOrCreateConfiguration((AMQPComponent) component).setTimeToLive((long) value); return true; case "allowAdditionalHeaders": getOrCreateConfiguration((AMQPComponent) component).setAllowAdditionalHeaders((java.lang.String) value); return true; case "allowNullBody": getOrCreateConfiguration((AMQPComponent) component).setAllowNullBody((boolean) value); return true; case "alwaysCopyMessage": getOrCreateConfiguration((AMQPComponent) component).setAlwaysCopyMessage((boolean) value); return true; case "correlationProperty": getOrCreateConfiguration((AMQPComponent) component).setCorrelationProperty((java.lang.String) value); return true; case "disableTimeToLive": getOrCreateConfiguration((AMQPComponent) component).setDisableTimeToLive((boolean) value); return true; case "forceSendOriginalMessage": getOrCreateConfiguration((AMQPComponent) component).setForceSendOriginalMessage((boolean) value); return true; case "includeSentJMSMessageID": getOrCreateConfiguration((AMQPComponent) component).setIncludeSentJMSMessageID((boolean) value); return true; case "replyToCacheLevelName": getOrCreateConfiguration((AMQPComponent) component).setReplyToCacheLevelName((java.lang.String) value); return true; case "replyToDestinationSelectorName": getOrCreateConfiguration((AMQPComponent) component).setReplyToDestinationSelectorName((java.lang.String) value); return true; case "streamMessageTypeEnabled": getOrCreateConfiguration((AMQPComponent) component).setStreamMessageTypeEnabled((boolean) value); return true; case "allowAutoWiredConnectionFactory": ((AMQPComponent) component).setAllowAutoWiredConnectionFactory((boolean) value); return true; case "allowAutoWiredDestinationResolver": ((AMQPComponent) component).setAllowAutoWiredDestinationResolver((boolean) value); return true; case "allowSerializedHeaders": getOrCreateConfiguration((AMQPComponent) component).setAllowSerializedHeaders((boolean) value); return true; case "artemisStreamingEnabled": getOrCreateConfiguration((AMQPComponent) component).setArtemisStreamingEnabled((boolean) value); return true; case "asyncStartListener": getOrCreateConfiguration((AMQPComponent) component).setAsyncStartListener((boolean) value); return true; case "asyncStopListener": getOrCreateConfiguration((AMQPComponent) component).setAsyncStopListener((boolean) value); return true; case "autowiredEnabled": ((AMQPComponent) component).setAutowiredEnabled((boolean) value); return true; case "configuration": ((AMQPComponent) component).setConfiguration((org.apache.camel.component.jms.JmsConfiguration) value); return true; case "destinationResolver": getOrCreateConfiguration((AMQPComponent) component).setDestinationResolver((org.springframework.jms.support.destination.DestinationResolver) value); return true; case "errorHandler": getOrCreateConfiguration((AMQPComponent) component).setErrorHandler((org.springframework.util.ErrorHandler) value); return true; case "exceptionListener": getOrCreateConfiguration((AMQPComponent) component).setExceptionListener((javax.jms.ExceptionListener) value); return true; case "idleConsumerLimit": getOrCreateConfiguration((AMQPComponent) component).setIdleConsumerLimit((int) value); return true; case "idleTaskExecutionLimit": getOrCreateConfiguration((AMQPComponent) component).setIdleTaskExecutionLimit((int) value); return true; case "includeAllJMSXProperties": getOrCreateConfiguration((AMQPComponent) component).setIncludeAllJMSXProperties((boolean) value); return true; case "jmsKeyFormatStrategy": getOrCreateConfiguration((AMQPComponent) component).setJmsKeyFormatStrategy((org.apache.camel.component.jms.JmsKeyFormatStrategy) value); return true; case "mapJmsMessage": getOrCreateConfiguration((AMQPComponent) component).setMapJmsMessage((boolean) value); return true; case "maxMessagesPerTask": getOrCreateConfiguration((AMQPComponent) component).setMaxMessagesPerTask((int) value); return true; case "messageConverter": getOrCreateConfiguration((AMQPComponent) component).setMessageConverter((org.springframework.jms.support.converter.MessageConverter) value); return true; case "messageCreatedStrategy": getOrCreateConfiguration((AMQPComponent) component).setMessageCreatedStrategy((org.apache.camel.component.jms.MessageCreatedStrategy) value); return true; case "messageIdEnabled": getOrCreateConfiguration((AMQPComponent) component).setMessageIdEnabled((boolean) value); return true; case "messageListenerContainerFactory": getOrCreateConfiguration((AMQPComponent) component).setMessageListenerContainerFactory((org.apache.camel.component.jms.MessageListenerContainerFactory) value); return true; case "messageTimestampEnabled": getOrCreateConfiguration((AMQPComponent) component).setMessageTimestampEnabled((boolean) value); return true; case "pubSubNoLocal": getOrCreateConfiguration((AMQPComponent) component).setPubSubNoLocal((boolean) value); return true; case "queueBrowseStrategy": ((AMQPComponent) component).setQueueBrowseStrategy((org.apache.camel.component.jms.QueueBrowseStrategy) value); return true; case "receiveTimeout": getOrCreateConfiguration((AMQPComponent) component).setReceiveTimeout((long) value); return true; case "recoveryInterval": getOrCreateConfiguration((AMQPComponent) component).setRecoveryInterval((long) value); return true; case "requestTimeoutCheckerInterval": getOrCreateConfiguration((AMQPComponent) component).setRequestTimeoutCheckerInterval((long) value); return true; case "synchronous": getOrCreateConfiguration((AMQPComponent) component).setSynchronous((boolean) value); return true; case "transferException": getOrCreateConfiguration((AMQPComponent) component).setTransferException((boolean) value); return true; case "transferExchange": getOrCreateConfiguration((AMQPComponent) component).setTransferExchange((boolean) value); return true; case "useMessageIDAsCorrelationID": getOrCreateConfiguration((AMQPComponent) component).setUseMessageIDAsCorrelationID((boolean) value); return true; case "waitForProvisionCorrelationToBeUpdatedCounter": getOrCreateConfiguration((AMQPComponent) component).setWaitForProvisionCorrelationToBeUpdatedCounter((int) value); return true; case "waitForProvisionCorrelationToBeUpdatedThreadSleepingTime": getOrCreateConfiguration((AMQPComponent) component).setWaitForProvisionCorrelationToBeUpdatedThreadSleepingTime((long) value); return true; case "headerFilterStrategy": ((AMQPComponent) component).setHeaderFilterStrategy((org.apache.camel.spi.HeaderFilterStrategy) value); return true; case "errorHandlerLoggingLevel": getOrCreateConfiguration((AMQPComponent) component).setErrorHandlerLoggingLevel((org.apache.camel.LoggingLevel) value); return true; case "errorHandlerLogStackTrace": getOrCreateConfiguration((AMQPComponent) component).setErrorHandlerLogStackTrace((boolean) value); return true; case "password": getOrCreateConfiguration((AMQPComponent) component).setPassword((java.lang.String) value); return true; case "username": getOrCreateConfiguration((AMQPComponent) component).setUsername((java.lang.String) value); return true; case "transacted": getOrCreateConfiguration((AMQPComponent) component).setTransacted((boolean) value); return true; case "transactedInOut": getOrCreateConfiguration((AMQPComponent) component).setTransactedInOut((boolean) value); return true; case "lazyCreateTransactionManager": getOrCreateConfiguration((AMQPComponent) component).setLazyCreateTransactionManager((boolean) value); return true; case "transactionManager": getOrCreateConfiguration((AMQPComponent) component).setTransactionManager((org.springframework.transaction.PlatformTransactionManager) value); return true; case "transactionName": getOrCreateConfiguration((AMQPComponent) component).setTransactionName((java.lang.String) value); return true; case "transactionTimeout": getOrCreateConfiguration((AMQPComponent) component).setTransactionTimeout((int) value); return true; default: return false; } } } }
apache-2.0
apache/wink
wink-itests/wink-itest/wink-itest-context/src/main/java/org/apache/wink/itest/securitycontext/SecurityContextBeanResource.java
1522
/* * 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.wink.itest.securitycontext; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.SecurityContext; import org.apache.wink.itest.securitycontext.xml.SecurityContextInfo; @Path("/context/securitycontext/bean") @Produces(MediaType.APPLICATION_XML) public class SecurityContextBeanResource { private SecurityContext s = null; @GET public SecurityContextInfo requestSecurityInfo() { return SecurityContextUtils.securityContextToJSON(s); } @Context public void setSecurityInfo(SecurityContext secContext) { this.s = secContext; } }
apache-2.0
alexholmes/hiped2
src/main/java/hip/ch3/thrift/Stock.java
23514
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING */ package hip.ch3.thrift; import org.apache.thrift.*; import org.apache.thrift.meta_data.*; import org.apache.thrift.protocol.*; import java.util.*; public class Stock implements TBase<Stock, Stock._Fields>, java.io.Serializable, Cloneable { private static final TStruct STRUCT_DESC = new TStruct("Stock"); private static final TField SYMBOL_FIELD_DESC = new TField("symbol", TType.STRING, (short)1); private static final TField DATE_FIELD_DESC = new TField("date", TType.STRING, (short)2); private static final TField OPEN_FIELD_DESC = new TField("open", TType.DOUBLE, (short)3); private static final TField HIGH_FIELD_DESC = new TField("high", TType.DOUBLE, (short)4); private static final TField LOW_FIELD_DESC = new TField("low", TType.DOUBLE, (short)5); private static final TField CLOSE_FIELD_DESC = new TField("close", TType.DOUBLE, (short)6); private static final TField VOLUME_FIELD_DESC = new TField("volume", TType.I32, (short)7); private static final TField ADJ_CLOSE_FIELD_DESC = new TField("adjClose", TType.DOUBLE, (short)8); private String symbol; private String date; private double open; private double high; private double low; private double close; private int volume; private double adjClose; /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements TFieldIdEnum { SYMBOL((short)1, "symbol"), DATE((short)2, "date"), OPEN((short)3, "open"), HIGH((short)4, "high"), LOW((short)5, "low"), CLOSE((short)6, "close"), VOLUME((short)7, "volume"), ADJ_CLOSE((short)8, "adjClose"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // SYMBOL return SYMBOL; case 2: // DATE return DATE; case 3: // OPEN return OPEN; case 4: // HIGH return HIGH; case 5: // LOW return LOW; case 6: // CLOSE return CLOSE; case 7: // VOLUME return VOLUME; case 8: // ADJ_CLOSE return ADJ_CLOSE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __OPEN_ISSET_ID = 0; private static final int __HIGH_ISSET_ID = 1; private static final int __LOW_ISSET_ID = 2; private static final int __CLOSE_ISSET_ID = 3; private static final int __VOLUME_ISSET_ID = 4; private static final int __ADJCLOSE_ISSET_ID = 5; private BitSet __isset_bit_vector = new BitSet(6); public static final Map<_Fields, FieldMetaData> metaDataMap; static { Map<_Fields, FieldMetaData> tmpMap = new EnumMap<_Fields, FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SYMBOL, new FieldMetaData("symbol", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.STRING))); tmpMap.put(_Fields.DATE, new FieldMetaData("date", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.STRING))); tmpMap.put(_Fields.OPEN, new FieldMetaData("open", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.DOUBLE))); tmpMap.put(_Fields.HIGH, new FieldMetaData("high", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.DOUBLE))); tmpMap.put(_Fields.LOW, new FieldMetaData("low", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.DOUBLE))); tmpMap.put(_Fields.CLOSE, new FieldMetaData("close", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.DOUBLE))); tmpMap.put(_Fields.VOLUME, new FieldMetaData("volume", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.I32))); tmpMap.put(_Fields.ADJ_CLOSE, new FieldMetaData("adjClose", TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.DOUBLE))); metaDataMap = Collections.unmodifiableMap(tmpMap); FieldMetaData.addStructMetaDataMap(Stock.class, metaDataMap); } public Stock() { } public Stock( String symbol, String date, double open, double high, double low, double close, int volume, double adjClose) { this(); this.symbol = symbol; this.date = date; this.open = open; setOpenIsSet(true); this.high = high; setHighIsSet(true); this.low = low; setLowIsSet(true); this.close = close; setCloseIsSet(true); this.volume = volume; setVolumeIsSet(true); this.adjClose = adjClose; setAdjCloseIsSet(true); } /** * Performs a deep copy on <i>other</i>. */ public Stock(Stock other) { __isset_bit_vector.clear(); __isset_bit_vector.or(other.__isset_bit_vector); if (other.isSetSymbol()) { this.symbol = other.symbol; } if (other.isSetDate()) { this.date = other.date; } this.open = other.open; this.high = other.high; this.low = other.low; this.close = other.close; this.volume = other.volume; this.adjClose = other.adjClose; } public Stock deepCopy() { return new Stock(this); } @Override public void clear() { this.symbol = null; this.date = null; setOpenIsSet(false); this.open = 0.0; setHighIsSet(false); this.high = 0.0; setLowIsSet(false); this.low = 0.0; setCloseIsSet(false); this.close = 0.0; setVolumeIsSet(false); this.volume = 0; setAdjCloseIsSet(false); this.adjClose = 0.0; } public String getSymbol() { return this.symbol; } public Stock setSymbol(String symbol) { this.symbol = symbol; return this; } public void unsetSymbol() { this.symbol = null; } /** Returns true if field symbol is set (has been asigned a value) and false otherwise */ public boolean isSetSymbol() { return this.symbol != null; } public void setSymbolIsSet(boolean value) { if (!value) { this.symbol = null; } } public String getDate() { return this.date; } public Stock setDate(String date) { this.date = date; return this; } public void unsetDate() { this.date = null; } /** Returns true if field date is set (has been asigned a value) and false otherwise */ public boolean isSetDate() { return this.date != null; } public void setDateIsSet(boolean value) { if (!value) { this.date = null; } } public double getOpen() { return this.open; } public Stock setOpen(double open) { this.open = open; setOpenIsSet(true); return this; } public void unsetOpen() { __isset_bit_vector.clear(__OPEN_ISSET_ID); } /** Returns true if field open is set (has been asigned a value) and false otherwise */ public boolean isSetOpen() { return __isset_bit_vector.get(__OPEN_ISSET_ID); } public void setOpenIsSet(boolean value) { __isset_bit_vector.set(__OPEN_ISSET_ID, value); } public double getHigh() { return this.high; } public Stock setHigh(double high) { this.high = high; setHighIsSet(true); return this; } public void unsetHigh() { __isset_bit_vector.clear(__HIGH_ISSET_ID); } /** Returns true if field high is set (has been asigned a value) and false otherwise */ public boolean isSetHigh() { return __isset_bit_vector.get(__HIGH_ISSET_ID); } public void setHighIsSet(boolean value) { __isset_bit_vector.set(__HIGH_ISSET_ID, value); } public double getLow() { return this.low; } public Stock setLow(double low) { this.low = low; setLowIsSet(true); return this; } public void unsetLow() { __isset_bit_vector.clear(__LOW_ISSET_ID); } /** Returns true if field low is set (has been asigned a value) and false otherwise */ public boolean isSetLow() { return __isset_bit_vector.get(__LOW_ISSET_ID); } public void setLowIsSet(boolean value) { __isset_bit_vector.set(__LOW_ISSET_ID, value); } public double getClose() { return this.close; } public Stock setClose(double close) { this.close = close; setCloseIsSet(true); return this; } public void unsetClose() { __isset_bit_vector.clear(__CLOSE_ISSET_ID); } /** Returns true if field close is set (has been asigned a value) and false otherwise */ public boolean isSetClose() { return __isset_bit_vector.get(__CLOSE_ISSET_ID); } public void setCloseIsSet(boolean value) { __isset_bit_vector.set(__CLOSE_ISSET_ID, value); } public int getVolume() { return this.volume; } public Stock setVolume(int volume) { this.volume = volume; setVolumeIsSet(true); return this; } public void unsetVolume() { __isset_bit_vector.clear(__VOLUME_ISSET_ID); } /** Returns true if field volume is set (has been asigned a value) and false otherwise */ public boolean isSetVolume() { return __isset_bit_vector.get(__VOLUME_ISSET_ID); } public void setVolumeIsSet(boolean value) { __isset_bit_vector.set(__VOLUME_ISSET_ID, value); } public double getAdjClose() { return this.adjClose; } public Stock setAdjClose(double adjClose) { this.adjClose = adjClose; setAdjCloseIsSet(true); return this; } public void unsetAdjClose() { __isset_bit_vector.clear(__ADJCLOSE_ISSET_ID); } /** Returns true if field adjClose is set (has been asigned a value) and false otherwise */ public boolean isSetAdjClose() { return __isset_bit_vector.get(__ADJCLOSE_ISSET_ID); } public void setAdjCloseIsSet(boolean value) { __isset_bit_vector.set(__ADJCLOSE_ISSET_ID, value); } public void setFieldValue(_Fields field, Object value) { switch (field) { case SYMBOL: if (value == null) { unsetSymbol(); } else { setSymbol((String)value); } break; case DATE: if (value == null) { unsetDate(); } else { setDate((String)value); } break; case OPEN: if (value == null) { unsetOpen(); } else { setOpen((Double)value); } break; case HIGH: if (value == null) { unsetHigh(); } else { setHigh((Double)value); } break; case LOW: if (value == null) { unsetLow(); } else { setLow((Double)value); } break; case CLOSE: if (value == null) { unsetClose(); } else { setClose((Double)value); } break; case VOLUME: if (value == null) { unsetVolume(); } else { setVolume((Integer)value); } break; case ADJ_CLOSE: if (value == null) { unsetAdjClose(); } else { setAdjClose((Double)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SYMBOL: return getSymbol(); case DATE: return getDate(); case OPEN: return new Double(getOpen()); case HIGH: return new Double(getHigh()); case LOW: return new Double(getLow()); case CLOSE: return new Double(getClose()); case VOLUME: return new Integer(getVolume()); case ADJ_CLOSE: return new Double(getAdjClose()); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been asigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SYMBOL: return isSetSymbol(); case DATE: return isSetDate(); case OPEN: return isSetOpen(); case HIGH: return isSetHigh(); case LOW: return isSetLow(); case CLOSE: return isSetClose(); case VOLUME: return isSetVolume(); case ADJ_CLOSE: return isSetAdjClose(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof Stock) return this.equals((Stock)that); return false; } public boolean equals(Stock that) { if (that == null) return false; boolean this_present_symbol = true && this.isSetSymbol(); boolean that_present_symbol = true && that.isSetSymbol(); if (this_present_symbol || that_present_symbol) { if (!(this_present_symbol && that_present_symbol)) return false; if (!this.symbol.equals(that.symbol)) return false; } boolean this_present_date = true && this.isSetDate(); boolean that_present_date = true && that.isSetDate(); if (this_present_date || that_present_date) { if (!(this_present_date && that_present_date)) return false; if (!this.date.equals(that.date)) return false; } boolean this_present_open = true; boolean that_present_open = true; if (this_present_open || that_present_open) { if (!(this_present_open && that_present_open)) return false; if (this.open != that.open) return false; } boolean this_present_high = true; boolean that_present_high = true; if (this_present_high || that_present_high) { if (!(this_present_high && that_present_high)) return false; if (this.high != that.high) return false; } boolean this_present_low = true; boolean that_present_low = true; if (this_present_low || that_present_low) { if (!(this_present_low && that_present_low)) return false; if (this.low != that.low) return false; } boolean this_present_close = true; boolean that_present_close = true; if (this_present_close || that_present_close) { if (!(this_present_close && that_present_close)) return false; if (this.close != that.close) return false; } boolean this_present_volume = true; boolean that_present_volume = true; if (this_present_volume || that_present_volume) { if (!(this_present_volume && that_present_volume)) return false; if (this.volume != that.volume) return false; } boolean this_present_adjClose = true; boolean that_present_adjClose = true; if (this_present_adjClose || that_present_adjClose) { if (!(this_present_adjClose && that_present_adjClose)) return false; if (this.adjClose != that.adjClose) return false; } return true; } @Override public int hashCode() { return 0; } public int compareTo(Stock other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; Stock typedOther = (Stock)other; lastComparison = Boolean.valueOf(isSetSymbol()).compareTo(typedOther.isSetSymbol()); if (lastComparison != 0) { return lastComparison; } if (isSetSymbol()) { lastComparison = TBaseHelper.compareTo(this.symbol, typedOther.symbol); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDate()).compareTo(typedOther.isSetDate()); if (lastComparison != 0) { return lastComparison; } if (isSetDate()) { lastComparison = TBaseHelper.compareTo(this.date, typedOther.date); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetOpen()).compareTo(typedOther.isSetOpen()); if (lastComparison != 0) { return lastComparison; } if (isSetOpen()) { lastComparison = TBaseHelper.compareTo(this.open, typedOther.open); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetHigh()).compareTo(typedOther.isSetHigh()); if (lastComparison != 0) { return lastComparison; } if (isSetHigh()) { lastComparison = TBaseHelper.compareTo(this.high, typedOther.high); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLow()).compareTo(typedOther.isSetLow()); if (lastComparison != 0) { return lastComparison; } if (isSetLow()) { lastComparison = TBaseHelper.compareTo(this.low, typedOther.low); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetClose()).compareTo(typedOther.isSetClose()); if (lastComparison != 0) { return lastComparison; } if (isSetClose()) { lastComparison = TBaseHelper.compareTo(this.close, typedOther.close); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetVolume()).compareTo(typedOther.isSetVolume()); if (lastComparison != 0) { return lastComparison; } if (isSetVolume()) { lastComparison = TBaseHelper.compareTo(this.volume, typedOther.volume); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetAdjClose()).compareTo(typedOther.isSetAdjClose()); if (lastComparison != 0) { return lastComparison; } if (isSetAdjClose()) { lastComparison = TBaseHelper.compareTo(this.adjClose, typedOther.adjClose); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(TProtocol iprot) throws TException { TField field; iprot.readStructBegin(); while (true) { field = iprot.readFieldBegin(); if (field.type == TType.STOP) { break; } switch (field.id) { case 1: // SYMBOL if (field.type == TType.STRING) { this.symbol = iprot.readString(); } else { TProtocolUtil.skip(iprot, field.type); } break; case 2: // DATE if (field.type == TType.STRING) { this.date = iprot.readString(); } else { TProtocolUtil.skip(iprot, field.type); } break; case 3: // OPEN if (field.type == TType.DOUBLE) { this.open = iprot.readDouble(); setOpenIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; case 4: // HIGH if (field.type == TType.DOUBLE) { this.high = iprot.readDouble(); setHighIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; case 5: // LOW if (field.type == TType.DOUBLE) { this.low = iprot.readDouble(); setLowIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; case 6: // CLOSE if (field.type == TType.DOUBLE) { this.close = iprot.readDouble(); setCloseIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; case 7: // VOLUME if (field.type == TType.I32) { this.volume = iprot.readI32(); setVolumeIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; case 8: // ADJ_CLOSE if (field.type == TType.DOUBLE) { this.adjClose = iprot.readDouble(); setAdjCloseIsSet(true); } else { TProtocolUtil.skip(iprot, field.type); } break; default: TProtocolUtil.skip(iprot, field.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method validate(); } public void write(TProtocol oprot) throws TException { validate(); oprot.writeStructBegin(STRUCT_DESC); if (this.symbol != null) { oprot.writeFieldBegin(SYMBOL_FIELD_DESC); oprot.writeString(this.symbol); oprot.writeFieldEnd(); } if (this.date != null) { oprot.writeFieldBegin(DATE_FIELD_DESC); oprot.writeString(this.date); oprot.writeFieldEnd(); } oprot.writeFieldBegin(OPEN_FIELD_DESC); oprot.writeDouble(this.open); oprot.writeFieldEnd(); oprot.writeFieldBegin(HIGH_FIELD_DESC); oprot.writeDouble(this.high); oprot.writeFieldEnd(); oprot.writeFieldBegin(LOW_FIELD_DESC); oprot.writeDouble(this.low); oprot.writeFieldEnd(); oprot.writeFieldBegin(CLOSE_FIELD_DESC); oprot.writeDouble(this.close); oprot.writeFieldEnd(); oprot.writeFieldBegin(VOLUME_FIELD_DESC); oprot.writeI32(this.volume); oprot.writeFieldEnd(); oprot.writeFieldBegin(ADJ_CLOSE_FIELD_DESC); oprot.writeDouble(this.adjClose); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } @Override public String toString() { StringBuilder sb = new StringBuilder("Stock("); boolean first = true; sb.append("symbol:"); if (this.symbol == null) { sb.append("null"); } else { sb.append(this.symbol); } first = false; if (!first) sb.append(", "); sb.append("date:"); if (this.date == null) { sb.append("null"); } else { sb.append(this.date); } first = false; if (!first) sb.append(", "); sb.append("open:"); sb.append(this.open); first = false; if (!first) sb.append(", "); sb.append("high:"); sb.append(this.high); first = false; if (!first) sb.append(", "); sb.append("low:"); sb.append(this.low); first = false; if (!first) sb.append(", "); sb.append("close:"); sb.append(this.close); first = false; if (!first) sb.append(", "); sb.append("volume:"); sb.append(this.volume); first = false; if (!first) sb.append(", "); sb.append("adjClose:"); sb.append(this.adjClose); first = false; sb.append(")"); return sb.toString(); } public void validate() throws TException { // check for required fields } }
apache-2.0
ern/elasticsearch
x-pack/plugin/transform/qa/multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/continuous/ContinuousTestCase.java
6183
/* * 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; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.transform.integration.continuous; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.transform.transforms.SettingsConfig; import org.elasticsearch.client.transform.transforms.SyncConfig; import org.elasticsearch.client.transform.transforms.TimeSyncConfig; import org.elasticsearch.client.transform.transforms.TransformConfig; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.core.TimeValue; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.test.rest.ESRestTestCase; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; public abstract class ContinuousTestCase extends ESRestTestCase { public static final TimeValue SYNC_DELAY = new TimeValue(1, TimeUnit.SECONDS); public static final int METRIC_TREND = 5000; public static final String CONTINUOUS_EVENTS_SOURCE_INDEX = "test-transform-continuous-events"; public static final String INGEST_PIPELINE = "transform-ingest"; public static final String MAX_RUN_FIELD = "run.max"; public static final String INGEST_RUN_FIELD = "run_ingest"; // mixture of fields to choose from, indexed and runtime public static final Set<String> METRIC_FIELDS = Set.of("metric", "metric-rt-2x"); public static final Set<String> METRIC_TIMESTAMP_FIELDS = Set.of("metric-timestamp", "metric-timestamp-5m-earlier"); public static final Set<String> TERMS_FIELDS = Set.of("event", "event-upper"); public static final Set<String> TIMESTAMP_FIELDS = Set.of("timestamp", "timestamp-at-runtime"); public static final Set<String> OTHER_TIMESTAMP_FIELDS = Set.of("some-timestamp", "some-timestamp-10m-earlier"); public static final DateTimeFormatter STRICT_DATE_OPTIONAL_TIME_PRINTER_NANOS = new DateTimeFormatterBuilder().parseCaseInsensitive() .append(ISO_LOCAL_DATE) .appendLiteral('T') .appendValue(HOUR_OF_DAY, 2) .appendLiteral(':') .appendValue(MINUTE_OF_HOUR, 2) .appendLiteral(':') .appendValue(SECOND_OF_MINUTE, 2) .appendFraction(NANO_OF_SECOND, 3, 9, true) .appendOffsetId() .toFormatter(Locale.ROOT); /** * Get the name of the transform/test * * @return name of the transform(used for start/stop) */ public abstract String getName(); /** * Create the transform configuration for the test. * * @return the transform configuration */ public abstract TransformConfig createConfig(); /** * Test results after 1 iteration in the test runner. * * @param iteration the current iteration * @param modifiedEvents set of events modified in the current iteration */ public abstract void testIteration(int iteration, Set<String> modifiedEvents) throws IOException; protected TransformConfig.Builder addCommonBuilderParameters(TransformConfig.Builder builder) { return builder.setSyncConfig(getSyncConfig()) .setSettings(addCommonSetings(new SettingsConfig.Builder()).build()) .setFrequency(SYNC_DELAY); } protected AggregatorFactories.Builder addCommonAggregations(AggregatorFactories.Builder builder) { builder.addAggregator(AggregationBuilders.max(MAX_RUN_FIELD).field("run")) .addAggregator(AggregationBuilders.count("count").field("run")) .addAggregator(AggregationBuilders.max("time.max").field("timestamp")); return builder; } protected SettingsConfig.Builder addCommonSetings(SettingsConfig.Builder builder) { // enforce paging, to see we run through all of the options builder.setMaxPageSearchSize(10); return builder; } protected SearchResponse search(SearchRequest searchRequest) throws IOException { try (RestHighLevelClient restClient = new TestRestHighLevelClient()) { return restClient.search(searchRequest, RequestOptions.DEFAULT); } catch (Exception e) { logger.error("Search failed with an exception.", e); throw e; } } @Override protected Settings restClientSettings() { final String token = "Basic " + Base64.getEncoder().encodeToString(("x_pack_rest_user:x-pack-test-password").getBytes(StandardCharsets.UTF_8)); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } private static class TestRestHighLevelClient extends RestHighLevelClient { private static final List<NamedXContentRegistry.Entry> X_CONTENT_ENTRIES = new SearchModule(Settings.EMPTY, Collections.emptyList()) .getNamedXContents(); TestRestHighLevelClient() { super(client(), restClient -> {}, X_CONTENT_ENTRIES); } } private SyncConfig getSyncConfig() { return TimeSyncConfig.builder().setField("timestamp").setDelay(SYNC_DELAY).build(); } }
apache-2.0
emeroad/pinpoint
thrift/src/main/java/com/navercorp/pinpoint/io/request/DefaultServerRequest.java
1951
/* * Copyright 2018 NAVER Corp. * * 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.navercorp.pinpoint.io.request; import com.navercorp.pinpoint.io.header.Header; import com.navercorp.pinpoint.io.header.HeaderEntity; import java.util.Objects; /** * @author Woonduk Kang(emeroad) */ public class DefaultServerRequest<T> extends DefaultAttributeMap implements ServerRequest<T> { private final Message<T> message; private final String remoteAddress; private final int remotePort; public DefaultServerRequest(Message<T> message, String remoteAddress, int remotePort) { this.message = Objects.requireNonNull(message, "message"); this.remoteAddress = Objects.requireNonNull(remoteAddress, "remoteAddress"); this.remotePort = remotePort; } @Override public Header getHeader() { return message.getHeader(); } @Override public HeaderEntity getHeaderEntity() { return message.getHeaderEntity(); } @Override public T getData() { return message.getData(); } @Override public String getRemoteAddress() { return remoteAddress; } @Override public int getRemotePort() { return remotePort; } @Override public String toString() { return "DefaultServerRequest{" + "message=" + message + ", remoteAddress='" + remoteAddress + '\'' + ", remotePort=" + remotePort + '}'; } }
apache-2.0
oscarceballos/flink-1.3.2
flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/history/HistoryServerStaticFileServerHandler.java
9764
/* * 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.webmonitor.history; /***************************************************************************** * This code is based on the "HttpStaticFileServerHandler" from the * Netty project's HTTP server example. * * See http://netty.io and * https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java *****************************************************************************/ import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.DefaultFileRegion; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.router.Routed; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedFile; import org.apache.flink.runtime.webmonitor.files.StaticFileServerHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static io.netty.handler.codec.http.HttpHeaders.Names.IF_MODIFIED_SINCE; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static org.apache.flink.util.Preconditions.checkNotNull; /** * Simple file server handler used by the {@link HistoryServer} that serves requests to web frontend's static files, * such as HTML, CSS, JS or JSON files. * * This code is based on the "HttpStaticFileServerHandler" from the Netty project's HTTP server * example. * * This class is a copy of the {@link StaticFileServerHandler}. The differences are that the request path is * modified to end on ".json" if it does not have a filename extension; when "index.html" is requested we load * "index_hs.html" instead to inject the modified HistoryServer WebInterface and that the caching of the "/joboverview" * page is prevented. */ @ChannelHandler.Sharable public class HistoryServerStaticFileServerHandler extends SimpleChannelInboundHandler<Routed> { /** Default logger, if none is specified */ private static final Logger LOG = LoggerFactory.getLogger(HistoryServerStaticFileServerHandler.class); // ------------------------------------------------------------------------ /** The path in which the static documents are */ private final File rootPath; public HistoryServerStaticFileServerHandler(File rootPath) throws IOException { this.rootPath = checkNotNull(rootPath).getCanonicalFile(); } // ------------------------------------------------------------------------ // Responses to requests // ------------------------------------------------------------------------ @Override public void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception { String requestPath = routed.path(); respondWithFile(ctx, routed.request(), requestPath); } /** * Response when running with leading JobManager. */ private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException { // make sure we request the "index.html" in case there is a directory request if (requestPath.endsWith("/")) { requestPath = requestPath + "index.html"; } if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js requestPath = requestPath + ".json"; } // convert to absolute path final File file = new File(rootPath, requestPath); if (!file.exists()) { // file does not exist. Try to load it with the classloader ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader(); String pathToLoad = requestPath.replace("index.html", "index_hs.html"); try (InputStream resourceStream = cl.getResourceAsStream("web" + pathToLoad)) { boolean success = false; try { if (resourceStream != null) { URL root = cl.getResource("web"); URL requested = cl.getResource("web" + pathToLoad); if (root != null && requested != null) { URI rootURI = new URI(root.getPath()).normalize(); URI requestedURI = new URI(requested.getPath()).normalize(); // Check that we don't load anything from outside of the // expected scope. if (!rootURI.relativize(requestedURI).equals(requestedURI)) { LOG.debug("Loading missing file from classloader: {}", pathToLoad); // ensure that directory to file exists. file.getParentFile().mkdirs(); Files.copy(resourceStream, file.toPath()); success = true; } } } } catch (Throwable t) { LOG.error("error while responding", t); } finally { if (!success) { LOG.debug("Unable to load requested file {} from classloader", pathToLoad); StaticFileServerHandler.sendError(ctx, NOT_FOUND); return; } } } } if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) { StaticFileServerHandler.sendError(ctx, NOT_FOUND); return; } if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) { StaticFileServerHandler.sendError(ctx, NOT_FOUND); return; } // cache validation final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { if (LOG.isDebugEnabled()) { LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\''); } StaticFileServerHandler.sendNotModified(ctx); return; } } if (LOG.isDebugEnabled()) { LOG.debug("Responding with file '" + file.getAbsolutePath() + '\''); } // Don't need to close this manually. Netty's DefaultFileRegion will take care of it. final RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException e) { StaticFileServerHandler.sendError(ctx, NOT_FOUND); return; } try { long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); StaticFileServerHandler.setContentTypeHeader(response, file); // the job overview should be updated as soon as possible if (!requestPath.equals("/joboverview.json")) { StaticFileServerHandler.setDateAndCacheHeaders(response, file); } if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } HttpHeaders.setContentLength(response, fileLength); // write the initial line and the header. ctx.write(response); // write the content. ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. } // close the connection, if no keep-alive is needed if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } catch (Exception e) { raf.close(); LOG.error("Failed to serve file.", e); StaticFileServerHandler.sendError(ctx, INTERNAL_SERVER_ERROR); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (ctx.channel().isActive()) { LOG.error("Caught exception", cause); StaticFileServerHandler.sendError(ctx, INTERNAL_SERVER_ERROR); } } }
apache-2.0
ivankelly/bookkeeper
stream/storage/impl/src/main/java/org/apache/bookkeeper/stream/storage/impl/sc/StorageContainer404.java
1842
/* * 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.bookkeeper.stream.storage.impl.sc; import io.grpc.Channel; import java.util.concurrent.CompletableFuture; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.stream.storage.api.sc.StorageContainer; /** * A storage container that always responds {@link io.grpc.Status#NOT_FOUND}. */ final class StorageContainer404 implements StorageContainer { static StorageContainer404 of() { return INSTANCE; } private static final StorageContainer404 INSTANCE = new StorageContainer404(); private StorageContainer404() {} @Override public long getId() { return -404; } @Override public Channel getChannel() { return Channel404.of(); } @Override public CompletableFuture<StorageContainer> start() { return FutureUtils.value(this); } @Override public CompletableFuture<Void> stop() { return FutureUtils.Void(); } @Override public void close() { // no-op } }
apache-2.0
kuujo/onos
apps/vtn/sfcmgr/src/test/java/org/onosproject/sfc/util/VtnRscAdapter.java
2478
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.sfc.util; import java.util.Iterator; import org.onlab.packet.MacAddress; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.Host; import org.onosproject.net.HostId; import org.onosproject.vtnrsc.SegmentationId; import org.onosproject.vtnrsc.TenantId; import org.onosproject.vtnrsc.TenantRouter; import org.onosproject.vtnrsc.VirtualPortId; import org.onosproject.vtnrsc.event.VtnRscListener; import org.onosproject.vtnrsc.service.VtnRscService; /** * Provides implementation of the VtnRsc service. */ public class VtnRscAdapter implements VtnRscService { @Override public void addListener(VtnRscListener listener) { } @Override public void removeListener(VtnRscListener listener) { } @Override public SegmentationId getL3vni(TenantId tenantId) { return null; } @Override public Iterator<Device> getClassifierOfTenant(TenantId tenantId) { return null; } @Override public Iterator<Device> getSffOfTenant(TenantId tenantId) { return null; } @Override public MacAddress getGatewayMac(HostId hostId) { return null; } @Override public boolean isServiceFunction(VirtualPortId portId) { return false; } @Override public DeviceId getSfToSffMaping(VirtualPortId portId) { return DeviceId.deviceId("of:000000000000001"); } @Override public void addDeviceIdOfOvsMap(VirtualPortId virtualPortId, TenantId tenantId, DeviceId deviceId) { } @Override public void removeDeviceIdOfOvsMap(Host host, TenantId tenantId, DeviceId deviceId) { } @Override public SegmentationId getL3vni(TenantRouter tenantRouter) { return null; } }
apache-2.0
guozhangwang/kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorAdapter.java
3298
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.processor.internals; import org.apache.kafka.streams.processor.api.Processor; import org.apache.kafka.streams.processor.api.ProcessorContext; import org.apache.kafka.streams.processor.api.Record; @SuppressWarnings("deprecation") // Old PAPI compatibility public final class ProcessorAdapter<KIn, VIn, KOut, VOut> implements Processor<KIn, VIn, KOut, VOut> { private final org.apache.kafka.streams.processor.Processor<KIn, VIn> delegate; private InternalProcessorContext context; public static <KIn, VIn, KOut, VOut> Processor<KIn, VIn, KOut, VOut> adapt(final org.apache.kafka.streams.processor.Processor<KIn, VIn> delegate) { if (delegate == null) { return null; } else { return new ProcessorAdapter<>(delegate); } } @SuppressWarnings({"rawtypes", "unchecked"}) public static <KIn, VIn, KOut, VOut> Processor<KIn, VIn, KOut, VOut> adaptRaw(final org.apache.kafka.streams.processor.Processor delegate) { if (delegate == null) { return null; } else { return new ProcessorAdapter<>(delegate); } } private ProcessorAdapter(final org.apache.kafka.streams.processor.Processor<KIn, VIn> delegate) { this.delegate = delegate; } @Override public void init(final ProcessorContext<KOut, VOut> context) { // It only makes sense to use this adapter internally to Streams, in which case // all contexts are implementations of InternalProcessorContext. // This would fail if someone were to use this adapter in a unit test where // the context only implements api.ProcessorContext. this.context = (InternalProcessorContext) context; delegate.init((org.apache.kafka.streams.processor.ProcessorContext) context); } @Override public void process(final Record<KIn, VIn> record) { final ProcessorRecordContext processorRecordContext = context.recordContext(); try { context.setRecordContext(new ProcessorRecordContext( record.timestamp(), context.offset(), context.partition(), context.topic(), record.headers() )); delegate.process(record.key(), record.value()); } finally { context.setRecordContext(processorRecordContext); } } @Override public void close() { delegate.close(); } }
apache-2.0
ern/elasticsearch
server/src/main/java/org/elasticsearch/action/update/UpdateHelper.java
20072
/* * 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.action.update; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.Requests; import org.elasticsearch.core.Nullable; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.core.Tuple; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.index.engine.DocumentSourceMissingException; import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.RoutingFieldMapper; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.UpdateScript; import org.elasticsearch.search.lookup.SourceLookup; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.LongSupplier; /** * Helper for translating an update request to an index, delete request or update response. */ public class UpdateHelper { private static final Logger logger = LogManager.getLogger(UpdateHelper.class); private final ScriptService scriptService; public UpdateHelper(ScriptService scriptService) { this.scriptService = scriptService; } /** * Prepares an update request by converting it into an index or delete request or an update response (no action). */ public Result prepare(UpdateRequest request, IndexShard indexShard, LongSupplier nowInMillis) { final GetResult getResult = indexShard.getService().getForUpdate( request.id(), request.ifSeqNo(), request.ifPrimaryTerm()); return prepare(indexShard.shardId(), request, getResult, nowInMillis); } /** * Prepares an update request by converting it into an index or delete request or an update response (no action, in the event of a * noop). */ protected Result prepare(ShardId shardId, UpdateRequest request, final GetResult getResult, LongSupplier nowInMillis) { if (getResult.isExists() == false) { // If the document didn't exist, execute the update request as an upsert return prepareUpsert(shardId, request, getResult, nowInMillis); } else if (getResult.internalSourceRef() == null) { // no source, we can't do anything, throw a failure... throw new DocumentSourceMissingException(shardId, request.id()); } else if (request.script() == null && request.doc() != null) { // The request has no script, it is a new doc that should be merged with the old document return prepareUpdateIndexRequest(shardId, request, getResult, request.detectNoop()); } else { // The request has a script (or empty script), execute the script and prepare a new index request return prepareUpdateScriptRequest(shardId, request, getResult, nowInMillis); } } /** * Execute a scripted upsert, where there is an existing upsert document and a script to be executed. The script is executed and a new * Tuple of operation and updated {@code _source} is returned. */ Tuple<UpdateOpType, Map<String, Object>> executeScriptedUpsert(Map<String, Object> upsertDoc, Script script, LongSupplier nowInMillis) { Map<String, Object> ctx = new HashMap<>(3); // Tell the script that this is a create and not an update ctx.put(ContextFields.OP, UpdateOpType.CREATE.toString()); ctx.put(ContextFields.SOURCE, upsertDoc); ctx.put(ContextFields.NOW, nowInMillis.getAsLong()); ctx = executeScript(script, ctx); UpdateOpType operation = UpdateOpType.lenientFromString((String) ctx.get(ContextFields.OP), logger, script.getIdOrCode()); @SuppressWarnings("unchecked") Map<String, Object> newSource = (Map<String, Object>) ctx.get(ContextFields.SOURCE); if (operation != UpdateOpType.CREATE && operation != UpdateOpType.NONE) { // Only valid options for an upsert script are "create" (the default) or "none", meaning abort upsert logger.warn("Invalid upsert operation [{}] for script [{}], doing nothing...", operation, script.getIdOrCode()); operation = UpdateOpType.NONE; } return new Tuple<>(operation, newSource); } /** * Prepare the request for upsert, executing the upsert script if present, and returning a {@code Result} containing a new * {@code IndexRequest} to be executed on the primary and replicas. */ Result prepareUpsert(ShardId shardId, UpdateRequest request, final GetResult getResult, LongSupplier nowInMillis) { if (request.upsertRequest() == null && request.docAsUpsert() == false) { throw new DocumentMissingException(shardId, request.id()); } IndexRequest indexRequest = request.docAsUpsert() ? request.doc() : request.upsertRequest(); if (request.scriptedUpsert() && request.script() != null) { // Run the script to perform the create logic IndexRequest upsert = request.upsertRequest(); Tuple<UpdateOpType, Map<String, Object>> upsertResult = executeScriptedUpsert(upsert.sourceAsMap(), request.script, nowInMillis); switch (upsertResult.v1()) { case CREATE: indexRequest = Requests.indexRequest(request.index()).source(upsertResult.v2()); break; case NONE: UpdateResponse update = new UpdateResponse(shardId, getResult.getId(), getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), DocWriteResponse.Result.NOOP); update.setGetResult(getResult); return new Result(update, DocWriteResponse.Result.NOOP, upsertResult.v2(), XContentType.JSON); default: // It's fine to throw an exception here, the leniency is handled/logged by `executeScriptedUpsert` throw new IllegalArgumentException("unknown upsert operation, got: " + upsertResult.v1()); } } indexRequest.index(request.index()) .id(request.id()).setRefreshPolicy(request.getRefreshPolicy()).routing(request.routing()) .timeout(request.timeout()).waitForActiveShards(request.waitForActiveShards()) // it has to be a "create!" .create(true); if (request.versionType() != VersionType.INTERNAL) { // in all but the internal versioning mode, we want to create the new document using the given version. indexRequest.version(request.version()).versionType(request.versionType()); } return new Result(indexRequest, DocWriteResponse.Result.CREATED, null, null); } /** * Calculate a routing value to be used, either the included index request's routing, or retrieved document's routing when defined. */ @Nullable static String calculateRouting(GetResult getResult, @Nullable IndexRequest updateIndexRequest) { if (updateIndexRequest != null && updateIndexRequest.routing() != null) { return updateIndexRequest.routing(); } else if (getResult.getFields().containsKey(RoutingFieldMapper.NAME)) { return getResult.field(RoutingFieldMapper.NAME).getValue().toString(); } else { return null; } } /** * Prepare the request for merging the existing document with a new one, can optionally detect a noop change. Returns a {@code Result} * containing a new {@code IndexRequest} to be executed on the primary and replicas. */ Result prepareUpdateIndexRequest(ShardId shardId, UpdateRequest request, GetResult getResult, boolean detectNoop) { final IndexRequest currentRequest = request.doc(); final String routing = calculateRouting(getResult, currentRequest); final Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true); final XContentType updateSourceContentType = sourceAndContent.v1(); final Map<String, Object> updatedSourceAsMap = sourceAndContent.v2(); final boolean noop = XContentHelper.update(updatedSourceAsMap, currentRequest.sourceAsMap(), detectNoop) == false; // We can only actually turn the update into a noop if detectNoop is true to preserve backwards compatibility and to handle cases // where users repopulating multi-fields or adding synonyms, etc. if (detectNoop && noop) { UpdateResponse update = new UpdateResponse(shardId, getResult.getId(), getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), DocWriteResponse.Result.NOOP); update.setGetResult(extractGetResult(request, request.index(), getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), updatedSourceAsMap, updateSourceContentType, getResult.internalSourceRef())); return new Result(update, DocWriteResponse.Result.NOOP, updatedSourceAsMap, updateSourceContentType); } else { final IndexRequest finalIndexRequest = Requests.indexRequest(request.index()) .id(request.id()).routing(routing) .source(updatedSourceAsMap, updateSourceContentType) .setIfSeqNo(getResult.getSeqNo()).setIfPrimaryTerm(getResult.getPrimaryTerm()) .waitForActiveShards(request.waitForActiveShards()).timeout(request.timeout()) .setRefreshPolicy(request.getRefreshPolicy()); return new Result(finalIndexRequest, DocWriteResponse.Result.UPDATED, updatedSourceAsMap, updateSourceContentType); } } /** * Prepare the request for updating an existing document using a script. Executes the script and returns a {@code Result} containing * either a new {@code IndexRequest} or {@code DeleteRequest} (depending on the script's returned "op" value) to be executed on the * primary and replicas. */ Result prepareUpdateScriptRequest(ShardId shardId, UpdateRequest request, GetResult getResult, LongSupplier nowInMillis) { final IndexRequest currentRequest = request.doc(); final String routing = calculateRouting(getResult, currentRequest); final Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true); final XContentType updateSourceContentType = sourceAndContent.v1(); final Map<String, Object> sourceAsMap = sourceAndContent.v2(); Map<String, Object> ctx = new HashMap<>(16); ctx.put(ContextFields.OP, UpdateOpType.INDEX.toString()); // The default operation is "index" ctx.put(ContextFields.INDEX, getResult.getIndex()); ctx.put(ContextFields.TYPE, MapperService.SINGLE_MAPPING_NAME); ctx.put(ContextFields.ID, getResult.getId()); ctx.put(ContextFields.VERSION, getResult.getVersion()); ctx.put(ContextFields.ROUTING, routing); ctx.put(ContextFields.SOURCE, sourceAsMap); ctx.put(ContextFields.NOW, nowInMillis.getAsLong()); ctx = executeScript(request.script, ctx); UpdateOpType operation = UpdateOpType.lenientFromString((String) ctx.get(ContextFields.OP), logger, request.script.getIdOrCode()); @SuppressWarnings("unchecked") final Map<String, Object> updatedSourceAsMap = (Map<String, Object>) ctx.get(ContextFields.SOURCE); switch (operation) { case INDEX: final IndexRequest indexRequest = Requests.indexRequest(request.index()) .id(request.id()).routing(routing) .source(updatedSourceAsMap, updateSourceContentType) .setIfSeqNo(getResult.getSeqNo()).setIfPrimaryTerm(getResult.getPrimaryTerm()) .waitForActiveShards(request.waitForActiveShards()).timeout(request.timeout()) .setRefreshPolicy(request.getRefreshPolicy()); return new Result(indexRequest, DocWriteResponse.Result.UPDATED, updatedSourceAsMap, updateSourceContentType); case DELETE: DeleteRequest deleteRequest = Requests.deleteRequest(request.index()) .id(request.id()).routing(routing) .setIfSeqNo(getResult.getSeqNo()).setIfPrimaryTerm(getResult.getPrimaryTerm()) .waitForActiveShards(request.waitForActiveShards()) .timeout(request.timeout()).setRefreshPolicy(request.getRefreshPolicy()); return new Result(deleteRequest, DocWriteResponse.Result.DELETED, updatedSourceAsMap, updateSourceContentType); default: // If it was neither an INDEX or DELETE operation, treat it as a noop UpdateResponse update = new UpdateResponse(shardId, getResult.getId(), getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), DocWriteResponse.Result.NOOP); update.setGetResult(extractGetResult(request, request.index(), getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), updatedSourceAsMap, updateSourceContentType, getResult.internalSourceRef())); return new Result(update, DocWriteResponse.Result.NOOP, updatedSourceAsMap, updateSourceContentType); } } private Map<String, Object> executeScript(Script script, Map<String, Object> ctx) { try { if (scriptService != null) { UpdateScript.Factory factory = scriptService.compile(script, UpdateScript.CONTEXT); UpdateScript executableScript = factory.newInstance(script.getParams(), ctx); executableScript.execute(); } } catch (Exception e) { throw new IllegalArgumentException("failed to execute script", e); } return ctx; } /** * Applies {@link UpdateRequest#fetchSource()} to the _source of the updated document to be returned in a update response. */ public static GetResult extractGetResult(final UpdateRequest request, String concreteIndex, long seqNo, long primaryTerm, long version, final Map<String, Object> source, XContentType sourceContentType, @Nullable final BytesReference sourceAsBytes) { if (request.fetchSource() == null || request.fetchSource().fetchSource() == false) { return null; } BytesReference sourceFilteredAsBytes = sourceAsBytes; if (request.fetchSource().includes().length > 0 || request.fetchSource().excludes().length > 0) { SourceLookup sourceLookup = new SourceLookup(); sourceLookup.setSource(source); Object value = sourceLookup.filter(request.fetchSource()); try { final int initialCapacity = sourceAsBytes != null ? Math.min(1024, sourceAsBytes.length()) : 1024; BytesStreamOutput streamOutput = new BytesStreamOutput(initialCapacity); try (XContentBuilder builder = new XContentBuilder(sourceContentType.xContent(), streamOutput)) { builder.value(value); sourceFilteredAsBytes = BytesReference.bytes(builder); } } catch (IOException e) { throw new ElasticsearchException("Error filtering source", e); } } // TODO when using delete/none, we can still return the source as bytes by generating it (using the sourceContentType) return new GetResult(concreteIndex, request.id(), seqNo, primaryTerm, version, true, sourceFilteredAsBytes, Collections.emptyMap(), Collections.emptyMap()); } public static class Result { private final Writeable action; private final DocWriteResponse.Result result; private final Map<String, Object> updatedSourceAsMap; private final XContentType updateSourceContentType; public Result(Writeable action, DocWriteResponse.Result result, Map<String, Object> updatedSourceAsMap, XContentType updateSourceContentType) { this.action = action; this.result = result; this.updatedSourceAsMap = updatedSourceAsMap; this.updateSourceContentType = updateSourceContentType; } @SuppressWarnings("unchecked") public <T extends Writeable> T action() { return (T) action; } public DocWriteResponse.Result getResponseResult() { return result; } public Map<String, Object> updatedSourceAsMap() { return updatedSourceAsMap; } public XContentType updateSourceContentType() { return updateSourceContentType; } } /** * After executing the script, this is the type of operation that will be used for subsequent actions. This corresponds to the "ctx.op" * variable inside of scripts. */ enum UpdateOpType { CREATE("create"), INDEX("index"), DELETE("delete"), NONE("none"); private final String name; UpdateOpType(String name) { this.name = name; } public static UpdateOpType lenientFromString(String operation, Logger logger, String scriptId) { switch (operation) { case "create": return UpdateOpType.CREATE; case "index": return UpdateOpType.INDEX; case "delete": return UpdateOpType.DELETE; case "none": return UpdateOpType.NONE; default: // TODO: can we remove this leniency yet?? logger.warn("Used upsert operation [{}] for script [{}], doing nothing...", operation, scriptId); return UpdateOpType.NONE; } } @Override public String toString() { return name; } } /** * Field names used to populate the script context */ public static class ContextFields { public static final String CTX = "ctx"; public static final String OP = "op"; public static final String SOURCE = "_source"; public static final String NOW = "_now"; public static final String INDEX = "_index"; public static final String TYPE = "_type"; public static final String ID = "_id"; public static final String VERSION = "_version"; public static final String ROUTING = "_routing"; } }
apache-2.0
bhav0904/eclipse-collections
unit-tests-java8/src/test/java/org/eclipse/collections/test/LazyNoIteratorTestCase.java
1526
/* * Copyright (c) 2015 Goldman Sachs. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.eclipse.collections.test; import org.eclipse.collections.api.list.ListIterable; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.test.list.TransformsToListTrait; import org.junit.Test; public interface LazyNoIteratorTestCase extends NoIteratorTestCase, RichIterableWithDuplicatesTestCase, TransformsToListTrait { @Override default <T> ListIterable<T> getExpectedFiltered(T... elements) { return Lists.immutable.with(elements); } @Override default <T> MutableList<T> newMutableForFilter(T... elements) { return Lists.mutable.with(elements); } @Override default <T> ListIterable<T> getExpectedTransformed(T... elements) { return Lists.immutable.with(elements); } @Override @Test default void Object_PostSerializedEqualsAndHashCode() { // Not applicable } @Override @Test default void Object_equalsAndHashCode() { // Not applicable } }
bsd-3-clause
bhav0904/eclipse-collections
serialization-tests/src/test/java/org/eclipse/collections/impl/map/immutable/primitive/ImmutableLongCharEmptyMapSerializationTest.java
1002
/* * Copyright (c) 2015 Goldman Sachs. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.eclipse.collections.impl.map.immutable.primitive; import org.eclipse.collections.impl.test.Verify; import org.junit.Test; public class ImmutableLongCharEmptyMapSerializationTest { @Test public void serializedForm() { Verify.assertSerializedForm( 1L, "rO0ABXNyAE5vcmcuZWNsaXBzZS5jb2xsZWN0aW9ucy5pbXBsLm1hcC5pbW11dGFibGUucHJpbWl0\n" + "aXZlLkltbXV0YWJsZUxvbmdDaGFyRW1wdHlNYXAAAAAAAAAAAQIAAHhw", new ImmutableLongCharEmptyMap()); } }
bsd-3-clause
diego4522/dyn4j
src/org/dyn4j/dynamics/joint/JointEdge.java
2724
/* * Copyright (c) 2010-2014 William Bittle http://www.dyn4j.org/ * 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 dyn4j 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 org.dyn4j.dynamics.joint; import org.dyn4j.dynamics.Body; /** * Represents a link from one {@link Body} to another over a {@link Joint}. * @author William Bittle * @version 3.0.2 * @since 1.0.0 */ public class JointEdge { /** The linked body */ protected Body other; /** The {@link Joint} */ protected Joint joint; /** * Full constructor. * @param other the linked {@link Body} * @param joint the {@link Joint} */ public JointEdge(Body other, Joint joint) { this.other = other; this.joint = joint; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("JointEdge[Joint=").append(this.joint) .append("|ConnectedBody=").append(this.other) .append("]"); return sb.toString(); } /** * Returns the linked {@link Body}. * @return {@link Body} */ public Body getOther() { return other; } /** * Returns the {@link Joint}. * @return {@link Joint} */ public Joint getJoint() { return joint; } }
bsd-3-clause
pravin02/dyn4j
sandbox/org/dyn4j/sandbox/panels/ForcePanel.java
5137
/* * Copyright (c) 2010-2014 William Bittle http://www.dyn4j.org/ * 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 dyn4j 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 org.dyn4j.sandbox.panels; import java.awt.Window; import java.text.DecimalFormat; import java.text.MessageFormat; import javax.swing.GroupLayout; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import org.dyn4j.geometry.Vector2; import org.dyn4j.sandbox.icons.Icons; import org.dyn4j.sandbox.listeners.SelectTextFocusListener; import org.dyn4j.sandbox.resources.Messages; import org.dyn4j.sandbox.utilities.ControlUtilities; /** * Panel used to apply a force to a body. * @author William Bittle * @version 1.0.1 * @since 1.0.0 */ public class ForcePanel extends JPanel implements InputPanel { /** The version id */ private static final long serialVersionUID = 2359226860458900772L; /** The x value of the force input */ private JFormattedTextField txtX; /** The y value of the force input */ private JFormattedTextField txtY; /** * Default constructor. */ public ForcePanel() { GroupLayout layout = new GroupLayout(this); this.setLayout(layout); JLabel lblForce = new JLabel(Messages.getString("panel.force"), Icons.INFO, JLabel.LEFT); lblForce.setToolTipText(MessageFormat.format(Messages.getString("panel.force.tooltip"), Messages.getString("unit.force"))); JLabel lblX = new JLabel(Messages.getString("x")); JLabel lblY = new JLabel(Messages.getString("y")); this.txtX = new JFormattedTextField(new DecimalFormat(Messages.getString("panel.force.format"))); this.txtY = new JFormattedTextField(new DecimalFormat(Messages.getString("panel.force.format"))); this.txtX.addFocusListener(new SelectTextFocusListener(this.txtX)); this.txtY.addFocusListener(new SelectTextFocusListener(this.txtY)); this.txtX.setColumns(7); this.txtY.setColumns(7); this.txtX.setValue(0.0); this.txtY.setValue(0.0); JLabel lblFiller = new JLabel(); layout.setAutoCreateContainerGaps(true); layout.setAutoCreateGaps(true); layout.setHorizontalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(lblForce) .addComponent(lblFiller)) .addGroup(layout.createParallelGroup() .addComponent(this.txtX) .addComponent(this.txtY)) .addGroup(layout.createParallelGroup() .addComponent(lblX) .addComponent(lblY))); layout.setVerticalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(lblForce) .addComponent(this.txtX, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblX)) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(lblFiller) .addComponent(this.txtY, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblY))); } /** * Returns the force given by the user. * @return Vector2 */ public Vector2 getForce() { Vector2 f = new Vector2( ControlUtilities.getDoubleValue(this.txtX), ControlUtilities.getDoubleValue(this.txtY)); return f; } /* (non-Javadoc) * @see org.dyn4j.sandbox.panels.InputPanel#isValidInput() */ @Override public boolean isValidInput() { return true; } /* (non-Javadoc) * @see org.dyn4j.sandbox.panels.InputPanel#showInvalidInputMessage(java.awt.Window) */ @Override public void showInvalidInputMessage(Window owner) {} }
bsd-3-clause
MarinnaCole/LightZone
lightcrafts/src/com/lightcrafts/ui/operation/drag/StackLayer.java
4408
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.ui.operation.drag; import javax.swing.*; import java.awt.*; class StackLayer extends JPanel { private DraggableStack draggableStack; private JComponent dragComp; private JComponent placeholderComp; private boolean isDragSwappable; // Take a DraggableStack so we can notify swapOccurred() on it: StackLayer(DraggableStack draggableStack) { this.draggableStack = draggableStack; setLayout(null); setOpaque(false); } void setDragComponent(JComponent comp, boolean isSwappable) { if (dragComp == comp) { return; } if (comp != null) { placeholderComp = new JPanel(); placeholderComp.setOpaque(false); Dimension size = comp.getPreferredSize(); placeholderComp.setPreferredSize(size); int index = getIndexOf(comp); remove(comp); add(placeholderComp, index); } else { int index = getIndexOf(placeholderComp); remove(placeholderComp); add(dragComp, index); placeholderComp = null; } dragComp = comp; isDragSwappable = isSwappable; validate(); repaint(); } public void doLayout() { Dimension size = getSize(); Component[] comps = getComponents(); if (comps.length == 0) { return; } int y = 0; int midX = size.width / 2; for (int n=comps.length-1; n>=0; n--) { Component comp = comps[n]; Dimension pref = comp.getPreferredSize(); int width = pref.width; int height = pref.height; int x = midX - width / 2; if (x < 0) { x = 0; width = size.width; } comp.setLocation(x, y); comp.setSize(width, height); y += height; } } public Dimension getPreferredSize() { Component[] comps = getComponents(); int width = 0; int height = 0; for (int n=0; n<comps.length; n++) { Component comp = comps[n]; Dimension pref = comp.getPreferredSize(); width = Math.max(width, pref.width); height += pref.height; } return new Dimension(width, height); } // See whether the current drag height crosses the threshold to swap // Component layout: void dragTo(int dragTop) { if (! isDragSwappable) { return; } int index = getIndexOf(placeholderComp); Rectangle phBounds = placeholderComp.getBounds(); int phTop = phBounds.y; int dragBottom = dragTop + phBounds.height; if (dragTop <= phTop) { if (index < getComponentCount() - 1) { Component upper = getComponent(index + 1); if (! ((StackableComponent) upper).isSwappable()) { return; } int upperMidY = upper.getY() + upper.getHeight() / 2; if (dragTop < upperMidY) { remove(placeholderComp); remove(upper); add(upper, index); add(placeholderComp, index + 1); notifySwap(index); } } } else { if (index > 0) { Component lower = getComponent(index - 1); if (! ((StackableComponent) lower).isSwappable()) { return; } int lowerMidY = lower.getY() + lower.getHeight() / 2; if (dragBottom > lowerMidY) { remove(lower); remove(placeholderComp); add(placeholderComp, index - 1); add(lower, index); notifySwap(index - 1); } } } } private void notifySwap(int index) { draggableStack.swapOccurred(index); validate(); repaint(); } private int getIndexOf(Component comp) { Component[] comps = getComponents(); for (int n=0; n<comps.length; n++) { if (comp == comps[n]) { return n; } } return -1; } }
bsd-3-clause
MarinnaCole/LightZone
lightcrafts/src/com/lightcrafts/ui/datatips/xswing/TreeDataTipListener.java
2120
/* Copyright (C) 2005-2011 Fabio Riccardi */ /* * Copyright (c) 2002 - 2005, Stephen Kelvin Friedrich. 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 copyright holder 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 com.lightcrafts.ui.datatips.xswing; import javax.swing.*; import java.awt.*; class TreeDataTipListener extends DataTipListener { TreeDataTipListener() { } DataTipCell getCell(JComponent component, Point point) { JTree tree = (JTree) component; int rowIndex = tree.getRowForLocation(point.x, point.y); if (rowIndex < 0) { return DataTipCell.NONE; } return new TreeDataTipCell(tree, rowIndex); } }
bsd-3-clause
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/main/java/org/elasticsearch/rest/action/admin/indices/RestIndicesAliasesAction.java
3439
/* * 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.rest.action.admin.indices; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.ParseFieldMatcherSupplier; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.AcknowledgedRestListener; import static org.elasticsearch.rest.RestRequest.Method.POST; public class RestIndicesAliasesAction extends BaseRestHandler { static final ObjectParser<IndicesAliasesRequest, ParseFieldMatcherSupplier> PARSER = new ObjectParser<>("aliases"); static { PARSER.declareObjectArray((request, actions) -> { for (AliasActions action: actions) { request.addAliasAction(action); } }, AliasActions.PARSER, new ParseField("actions")); } @Inject public RestIndicesAliasesAction(Settings settings, RestController controller) { super(settings); controller.registerHandler(POST, "/_aliases", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) throws Exception { IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest(); indicesAliasesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout())); indicesAliasesRequest.timeout(request.paramAsTime("timeout", indicesAliasesRequest.timeout())); try (XContentParser parser = XContentFactory.xContent(request.content()).createParser(request.content())) { PARSER.parse(parser, indicesAliasesRequest, () -> ParseFieldMatcher.STRICT); } if (indicesAliasesRequest.getAliasActions().isEmpty()) { throw new IllegalArgumentException("No action specified"); } client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<IndicesAliasesResponse>(channel)); } }
bsd-3-clause
ylfonline/ormlite-core
src/main/java/com/j256/ormlite/stmt/query/In.java
1649
package com.j256.ormlite.stmt.query; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.stmt.ArgumentHolder; import com.j256.ormlite.stmt.Where; /** * Internal class handling the SQL 'in' query part. Used by {@link Where#in}. * * @author graywatson */ public class In extends BaseComparison { private Iterable<?> objects; private final boolean in; public In(String columnName, FieldType fieldType, Iterable<?> objects, boolean in) throws SQLException { super(columnName, fieldType, null, true); this.objects = objects; this.in = in; } public In(String columnName, FieldType fieldType, Object[] objects, boolean in) throws SQLException { super(columnName, fieldType, null, true); // grrrr, Object[] should be Iterable this.objects = Arrays.asList(objects); this.in = in; } @Override public void appendOperation(StringBuilder sb) { if (in) { sb.append("IN "); } else { sb.append("NOT IN "); } } @Override public void appendValue(DatabaseType databaseType, StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException { sb.append('('); boolean first = true; for (Object value : objects) { if (value == null) { throw new IllegalArgumentException("one of the IN values for '" + columnName + "' is null"); } if (first) { first = false; } else { sb.append(','); } // for each of our arguments, add it to the output super.appendArgOrValue(databaseType, fieldType, sb, columnArgList, value); } sb.append(") "); } }
isc
zhangf911/common
test/resources/geom_java/Triangulo.java
353
package dummy.geom.primitives; public class Triangulo { float lado; float altura; public Triangulo() { this.lado = 10; this.altura = 15; } public Triangulo(float lado, float altura) { this.lado = lado; this.altura = altura; } public float Superficie() { float superficie = (this.lado * this.altura)/2; return superficie; } }
mit
bryan10328/java-m3g
build/linux/Sample-13-background/src/org/karlsland/m3g/sample/MainActivity.java
1066
package org.karlsland.m3g.sample; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GLCanvas; import javax.swing.JFrame; public class MainActivity { JFrame frame; GLCanvas canvas; M3GRenderer renderer; public MainActivity () { frame = new JFrame (); canvas = new GLCanvas (); renderer = new M3GRenderer (); canvas.addGLEventListener(renderer); frame.add(canvas); frame.setSize(300, 300); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { renderer.update (e.getKeyChar()); } }); frame.setVisible(true); } public static void main(String[] args) { new MainActivity(); } }
mit
sk89q/CommandHelper
src/main/java/com/laytonsmith/abstraction/entities/MCFishHook.java
101
package com.laytonsmith.abstraction.entities; public interface MCFishHook extends MCProjectile { }
mit
sedstef/openhab
bundles/binding/org.openhab.binding.mochadx10/src/main/java/org/openhab/binding/mochadx10/internal/MochadX10Binding.java
19106
/** * Copyright (c) 2010-2016, openHAB.org 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 */ package org.openhab.binding.mochadx10.internal; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.openhab.binding.mochadx10.MochadX10BindingProvider; import org.openhab.binding.mochadx10.commands.MochadX10Address; import org.openhab.binding.mochadx10.commands.MochadX10Command; import org.openhab.core.binding.AbstractBinding; import org.openhab.core.library.items.DimmerItem; import org.openhab.core.library.items.RollershutterItem; import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.StopMoveType; import org.openhab.core.library.types.UpDownType; import org.openhab.core.types.Command; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This binding is able to do the following tasks with the mochad X10 System: * * <ul> * <li>X10 Appliance modules: switch on, switch off.</li> * <li>X10 Dimmer modules: switch on, switch off, dim</li> * <li>X10 Shutter modules: open, close, stop, move</li> * </ul> * * @author Jack Sleuters * @since 1.7.0 */ public class MochadX10Binding extends AbstractBinding<MochadX10BindingProvider>implements ManagedService { static final Logger logger = LoggerFactory.getLogger(MochadX10Binding.class); /** * The ip address of the Mochad X10 host (default 127.0.0.1) */ private String hostIp = "127.0.0.1"; /** * The port number of the Mochad X10 host (default 1099) */ private int hostPort = 1099; /** * To implement the stop command for x10 modules like Rollershutters, it is required * to know whether the last issued command was a 'dim' or a 'bright' command. If it * was a 'dim' command, the 'bright' command has to be issued to realize stop functionality. * If it was a 'bright' command, the 'dim' command has to be issued. * * This map keeps track of the last issued command per X10 address */ private Map<String, Command> lastIssuedCommand = new HashMap<String, Command>(); // required to determine the X10 // command for STOP /** * Not every X10 module keeps its state. Furthermore, some X10 commands like 'dim' or 'bright' change the * brightness level in a relative way. Therefore, it is required to keep the absolute level of such module. * According to discussions on the openhab forums, it is bad practice to use the item registry to retrieve * the current level of a module. Therefore, it is stored internally in this binding. * * 'currentLevel' maps an X10 address string on a level value * * One could initialize this map with all possible X10 addresses and a default level value. However, * in practice a lot less than 256 X10 modules will be connected. To keep memory usage as low as possible, * the map is not initialized. When the current level of a module with an address that is not yet in the map * is requested, a value of '-1' will be returned. */ private Map<String, Integer> currentLevel = new HashMap<String, Integer>(); /** * The socket used to communicate with the Mochad X10 host */ private Socket client; /** * Used to receive messages from the Mochad X10 host */ private BufferedReader in; /** * Used to send commands to the Mochad X10 host */ private DataOutputStream out; /** * Receiving of messages from the Mochad X10 host is asynchronous. To make sure we * capture incoming message, a separate receive thread is used. */ private ReceiveThread receiveThread; /** * Keeps track of the latest used X10 address. This is required because the following messages * can be received from the Mochad X10 server. The first message specifies the full address 'D1' * the second message only specifies the 'houseCode' part of the address. This means that * the unitCode of the previous X10 address should be used. * * 03/11 22:08:01 Rx PL HouseUnit: D1 * 03/11 22:08:40 Rx PL House: D Func: Bright(1) * */ private MochadX10Address previousX10Address; /** * The regular expression to check whether the ip address of the host is correct */ private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; /** * This thread asynchronously receives messages from the Mochad X10 Host. It * parses the message and posts the appropriate event on the openHAB event bus. * * @author Jack Sleuters * @since 1.7.0 * */ private class ReceiveThread extends Thread { private MochadX10Binding binding; /** * The command parser parses messages received from the host and transforms them * into MochadX10Commands. */ private MochadX10CommandParser commandParser = new MochadX10CommandParser(eventPublisher); /** * Constructor * * @param binding This binding */ public ReceiveThread(MochadX10Binding binding) { this.binding = binding; } /** * Process a message received by the Mochad X10 host * * @param msg string containing the received message */ private void processIncomingMessage(String msg) { logger.debug("Received message: " + msg); MochadX10Command command = commandParser.parse(msg); if (command != null) { logger.debug("Command: " + command.toString()); String itemName = getItemNameForAddress(command.getAddress()); if (itemName != null) { command.postCommand(itemName, getCurrentLevel(command.getAddress().toString())); logger.debug("Address " + command.getAddress() + " level set to " + command.getLevel()); binding.previousX10Address = command.getAddress(); logger.debug("ReceiveThread: previous X10 address set to " + previousX10Address.toString()); } } } /** * Run method. Runs the actual receiving process. */ @Override public void run() { String msg = null; logger.debug("Starting Mochad X10 Receive thread"); while (!interrupted()) { try { // Blocking read, reading messages coming from Mochad X10 host msg = in.readLine(); if (msg != null) { processIncomingMessage(msg); } else { logger.error("Received a \"null\" message"); reconnectToMochadX10Server(); } } catch (IOException e) { logger.trace("Caught IOException " + e.getMessage()); reconnectToMochadX10Server(); } } logger.debug("Stopped Mochad X10 Receive thread"); } } protected void addBindingProvider(MochadX10BindingProvider bindingProvider) { super.addBindingProvider(bindingProvider); } protected void removeBindingProvider(MochadX10BindingProvider bindingProvider) { super.removeBindingProvider(bindingProvider); } @Override public void updated(Dictionary<String, ?> properties) throws ConfigurationException { if (properties != null) { String ip = (String) properties.get("hostIp"); if (StringUtils.isNotBlank(ip)) { if (isValidIpAddress(ip)) { this.hostIp = ip; } else { throw new ConfigurationException(hostIp, "The specified hostIp address \"" + ip + "\" is not a valid ip address"); } } String port = (String) properties.get("hostPort"); if (StringUtils.isNotBlank(port)) { if (isValidPort(port)) { this.hostPort = Integer.parseInt(port); } else { throw new ConfigurationException(port, "The specified port \"" + port + "\" is not a valid port number."); } } initializeBinding(); } } @Override public void deactivate() { // Close the connection with the Mochad X10 Server disconnectFromMochadX10Server(); super.deactivate(); } /** * Initialize the binding. Connection to the Mochad X10 host is established and after that * the receive thread is started. */ private void initializeBinding() { previousX10Address = new MochadX10Address("a1"); connectToMochadX10Server(); receiveThread = new ReceiveThread(this); receiveThread.start(); } /** * Connect to the Mochad X10 host */ private void connectToMochadX10Server() { try { client = new Socket(hostIp, hostPort); in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new DataOutputStream(client.getOutputStream()); logger.debug("Connected to Mochad X10 server"); } catch (UnknownHostException e) { logger.error("Unknown host: " + hostIp + ":" + hostPort); } catch (IOException e) { logger.error("IOException: " + e.getMessage() + " while trying to connect to Mochad X10 host: " + hostIp + ":" + hostPort); } } /** * Disconnect from the Mochad X10 host. This method is required to clean up the connection * after the binding was disconnected from the host. */ private void disconnectFromMochadX10Server() { try { in.close(); out.close(); client.close(); logger.debug("Disconnected from Mochad X10 server"); } catch (IOException e) { logger.error("IOException: " + e.getMessage() + " while trying to disconnect from Mochad X10 host: " + hostIp + ":" + hostPort); } } /** * Reconnect to the Mochad X10 host after the connection to it was lost. */ private void reconnectToMochadX10Server() { disconnectFromMochadX10Server(); connectToMochadX10Server(); logger.debug("Reconnected to Mochad X10 server"); } /** * Check if the specified port number is a valid. * * @param port The port number to check * @return true when valid, false otherwise */ private boolean isValidPort(String port) { try { int portNumber = Integer.parseInt(port); if ((portNumber >= 1024) && (portNumber <= 65535)) { return true; } } catch (NumberFormatException e) { return false; } return false; } /** * Check if the specified ip address is a valid. * * @param hostIp The ip address to check to check * @return true when valid, false otherwise */ private boolean isValidIpAddress(String hostIp) { if (hostIp.matches(IPADDRESS_PATTERN)) { return true; } return false; } /** * Given an X10 address (<houseCode><unitCode>) find the name of the * corresponding bounded item * * @param address The X10 address * @return The name of the corresponding item, null if no corresponding * item could be found. */ private String getItemNameForAddress(MochadX10Address address) { for (MochadX10BindingProvider provider : this.providers) { Collection<String> itemNames = provider.getItemNames(); for (String itemName : itemNames) { MochadX10BindingConfig bindingConfig = provider.getItemConfig(itemName); if (bindingConfig.getAddress().equals(address.toString())) { return bindingConfig.getItemName(); } } } logger.warn("No item name found for address '" + address.toString() + "'"); return null; } /** * Lookup of the configuration of the named item. * * @param itemName * @return The configuration, null otherwise. */ private MochadX10BindingConfig getConfigForItemName(String itemName) { for (MochadX10BindingProvider provider : this.providers) { if (provider.getItemConfig(itemName) != null) { return provider.getItemConfig(itemName); } } logger.warn("No configuration found for item '" + itemName + "'"); return null; } @Override protected void internalReceiveCommand(String itemName, Command command) { MochadX10BindingConfig deviceConfig = getConfigForItemName(itemName); if (deviceConfig == null) { return; } String address = deviceConfig.getAddress(); String tm = deviceConfig.getTransmitMethod(); String commandStr = "none"; Command previousCommand = lastIssuedCommand.get(address); int level = -1; if (command instanceof OnOffType) { commandStr = OnOffType.ON.equals(command) ? "on" : "off"; level = OnOffType.ON.equals(command) ? 100 : 0; } else if (command instanceof UpDownType) { commandStr = UpDownType.UP.equals(command) ? "bright" : "dim"; level = UpDownType.UP.equals(command) ? 100 : 0; } else if (command instanceof StopMoveType) { if (StopMoveType.STOP.equals(command)) { commandStr = UpDownType.UP.equals(previousCommand) ? "dim" : "bright"; } else { // Move not supported yet commandStr = "none"; } } else if (command instanceof PercentType) { if (deviceConfig.getItemType() == DimmerItem.class) { level = ((PercentType) command).intValue(); if (((PercentType) command).intValue() == 0) { // If percent value equals 0 the x10 "off" command is used instead of the dim command commandStr = "off"; } else { long dim_value = 0; if (deviceConfig.getDimMethod().equals("xdim")) { // 100% maps to value (XDIM_LEVELS - 1) so we need to do scaling dim_value = Math.round( ((PercentType) command).doubleValue() * (MochadX10Command.XDIM_LEVELS - 1) / 100); commandStr = "xdim " + dim_value; } else { // 100% maps to value (DIM_LEVELS - 1) so we need to do scaling Integer currentValue = currentLevel.get(address); if (currentValue == null) { currentValue = 0; } logger.debug("Address " + address + " current level " + currentValue); int newValue = ((PercentType) command).intValue(); int relativeValue; if (newValue > currentValue) { relativeValue = (int) Math .round((newValue - currentValue) * ((MochadX10Command.DIM_LEVELS - 1) * 1.0 / 100)); commandStr = "bright " + relativeValue; } else if (currentValue > newValue) { relativeValue = (int) Math .round((currentValue - newValue) * ((MochadX10Command.DIM_LEVELS - 1) * 1.0 / 100)); commandStr = "dim " + relativeValue; } else { // If there is no change in state, do nothing commandStr = "none"; } } } } else if (deviceConfig.getItemType() == RollershutterItem.class) { level = ((PercentType) command).intValue(); Double invert_level = 100 - ((PercentType) command).doubleValue(); long newlevel = Math.round(invert_level * 25.0 / 100); commandStr = "extended_code_1 0 1 " + newlevel; } } else if (command instanceof IncreaseDecreaseType) { // Increase decrease not yet supported commandStr = "none"; } try { if (!commandStr.equals("none")) { out.writeBytes(tm + " " + address + " " + commandStr + "\n"); logger.debug(tm + " " + address + " " + commandStr); out.flush(); previousX10Address.setAddress(address); logger.debug("Previous X10 address set to " + previousX10Address.toString()); if (level != -1) { currentLevel.put(address, level); logger.debug("Address " + address + " level set to " + level); } } } catch (IOException e) { reconnectToMochadX10Server(); logger.error("IOException: " + e.getMessage() + " while trying to send a command to Mochad X10 host: " + hostIp + ":" + hostPort); } lastIssuedCommand.put(address, command); } /** * Retrieve the current level [0..100] of the X10 module identified by 'address' * * @param address the X10 address * @return if the level was stored at least once, the current level otherwise -1 */ private int getCurrentLevel(String address) { if (currentLevel.get(address) == null) { return -1; } return currentLevel.get(address); } /** * Retrieve the output stream of the established socket connection * * @return the output stream */ public DataOutputStream getOut() { return out; } }
epl-1.0
TheNetStriker/openhab
bundles/binding/org.openhab.binding.fht/src/main/java/org/openhab/binding/fht/FHTBindingConfig.java
2035
/** * Copyright (c) 2010-2019 by the respective copyright holders. * * 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 */ package org.openhab.binding.fht; import org.openhab.core.binding.BindingConfig; import org.openhab.core.items.Item; /** * This class represents FHT based devices. These can be FHT-80b, FHT-8v or the * window sensor. * * @author Till Klocke * @since 1.4.0 */ public class FHTBindingConfig implements BindingConfig { /** * This enum represents the available data types of the FHT devices. Not all * datapoints are available in all devices. Refer to your FHT manual to know * which to use. * * @author Till Klocke * */ public static enum Datapoint { MEASURED_TEMP, DESIRED_TEMP, BATTERY, WINDOW, VALVE; } /** * The housecode in hexadecimal notation */ private String housecode; /** * The address in hexadecimal notation. Not needed in FHT-80b. */ private String address; private Datapoint datapoint; private Item item; public FHTBindingConfig(Item item, String housecode, String address, Datapoint datapoint) { this.housecode = housecode; this.address = address; this.datapoint = datapoint; this.item = item; } public String getHousecode() { return housecode; } public String getAddress() { return address; } public Datapoint getDatapoint() { return datapoint; } /** * Return the full address needed to address the device via rf. * * @return */ public String getFullAddress() { if (address != null) { return housecode + address; } return housecode; } public Item getItem() { return item; } }
epl-1.0
PatrickSHYee/idecore
com.salesforce.ide.core/src/com/salesforce/ide/core/services/ServiceLocator.java
3296
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * 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: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.core.services; import com.salesforce.ide.core.factories.FactoryLocator; public class ServiceLocator { protected MetadataService metadataService = null; protected PackageDeployService packageDeployService = null; protected PackageRetrieveService packageRetrieveService = null; protected ProjectService projectService = null; protected LoggingService loggingService = null; protected ApexService apexService = null; protected ToolingDeployService toolingDeployService = null; protected ToolingService toolingService = null; protected FactoryLocator factoryLocator = null; // C O N S T R U C T O R public ServiceLocator() { super(); } // M E T H O D S public MetadataService getMetadataService() { return metadataService; } public void setMetadataService(MetadataService metadataService) { this.metadataService = metadataService; } public PackageDeployService getPackageDeployService() { return packageDeployService; } public void setPackageDeployService(PackageDeployService packageDeployService) { this.packageDeployService = packageDeployService; } public PackageRetrieveService getPackageRetrieveService() { return packageRetrieveService; } public void setPackageRetrieveService(PackageRetrieveService packageRetrieveService) { this.packageRetrieveService = packageRetrieveService; } public ProjectService getProjectService() { return projectService; } public void setProjectService(ProjectService projectService) { this.projectService = projectService; } public LoggingService getLoggingService() { return loggingService ; } public void setLoggingService(LoggingService loggingService) { this.loggingService = loggingService; } public ApexService getApexService() { return apexService; } public void setApexService(ApexService apexService) { this.apexService = apexService; } public ToolingDeployService getToolingDeployService() { return toolingDeployService; } public void setToolingDeployService(ToolingDeployService toolingDeployService) { this.toolingDeployService = toolingDeployService; } public ToolingService getToolingService() { return toolingService; } public void setToolingService(ToolingService toolingService) { this.toolingService = toolingService; } // factories public FactoryLocator getFactoryLocator() { return factoryLocator; } public void setFactoryLocator(FactoryLocator factoryLocator) { this.factoryLocator = factoryLocator; } }
epl-1.0
openjdk-mirror/jdk7u-jdk
src/share/classes/sun/security/ssl/SSLContextImpl.java
42221
/* * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.ssl; import java.net.Socket; import java.io.*; import java.util.*; import java.security.*; import java.security.cert.*; import java.security.cert.Certificate; import javax.net.ssl.*; import sun.security.provider.certpath.AlgorithmChecker; public abstract class SSLContextImpl extends SSLContextSpi { private static final Debug debug = Debug.getInstance("ssl"); private final EphemeralKeyManager ephemeralKeyManager; private final SSLSessionContextImpl clientCache; private final SSLSessionContextImpl serverCache; private boolean isInitialized; private X509ExtendedKeyManager keyManager; private X509TrustManager trustManager; private SecureRandom secureRandom; // The default algrithm constraints private AlgorithmConstraints defaultAlgorithmConstraints = new SSLAlgorithmConstraints(null); // supported and default protocols private ProtocolList defaultServerProtocolList; private ProtocolList defaultClientProtocolList; private ProtocolList supportedProtocolList; // supported and default cipher suites private CipherSuiteList defaultServerCipherSuiteList; private CipherSuiteList defaultClientCipherSuiteList; private CipherSuiteList supportedCipherSuiteList; SSLContextImpl() { ephemeralKeyManager = new EphemeralKeyManager(); clientCache = new SSLSessionContextImpl(); serverCache = new SSLSessionContextImpl(); } protected void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr) throws KeyManagementException { isInitialized = false; keyManager = chooseKeyManager(km); if (tm == null) { try { TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore)null); tm = tmf.getTrustManagers(); } catch (Exception e) { // eat } } trustManager = chooseTrustManager(tm); if (sr == null) { secureRandom = JsseJce.getSecureRandom(); } else { if (SunJSSE.isFIPS() && (sr.getProvider() != SunJSSE.cryptoProvider)) { throw new KeyManagementException ("FIPS mode: SecureRandom must be from provider " + SunJSSE.cryptoProvider.getName()); } secureRandom = sr; } /* * The initial delay of seeding the random number generator * could be long enough to cause the initial handshake on our * first connection to timeout and fail. Make sure it is * primed and ready by getting some initial output from it. */ if (debug != null && Debug.isOn("sslctx")) { System.out.println("trigger seeding of SecureRandom"); } secureRandom.nextInt(); if (debug != null && Debug.isOn("sslctx")) { System.out.println("done seeding SecureRandom"); } isInitialized = true; } private X509TrustManager chooseTrustManager(TrustManager[] tm) throws KeyManagementException { // We only use the first instance of X509TrustManager passed to us. for (int i = 0; tm != null && i < tm.length; i++) { if (tm[i] instanceof X509TrustManager) { if (SunJSSE.isFIPS() && !(tm[i] instanceof X509TrustManagerImpl)) { throw new KeyManagementException ("FIPS mode: only SunJSSE TrustManagers may be used"); } if (tm[i] instanceof X509ExtendedTrustManager) { return (X509TrustManager)tm[i]; } else { return new AbstractTrustManagerWrapper( (X509TrustManager)tm[i]); } } } // nothing found, return a dummy X509TrustManager. return DummyX509TrustManager.INSTANCE; } private X509ExtendedKeyManager chooseKeyManager(KeyManager[] kms) throws KeyManagementException { for (int i = 0; kms != null && i < kms.length; i++) { KeyManager km = kms[i]; if (km instanceof X509KeyManager == false) { continue; } if (SunJSSE.isFIPS()) { // In FIPS mode, require that one of SunJSSE's own keymanagers // is used. Otherwise, we cannot be sure that only keys from // the FIPS token are used. if ((km instanceof X509KeyManagerImpl) || (km instanceof SunX509KeyManagerImpl)) { return (X509ExtendedKeyManager)km; } else { // throw exception, we don't want to silently use the // dummy keymanager without telling the user. throw new KeyManagementException ("FIPS mode: only SunJSSE KeyManagers may be used"); } } if (km instanceof X509ExtendedKeyManager) { return (X509ExtendedKeyManager)km; } if (debug != null && Debug.isOn("sslctx")) { System.out.println( "X509KeyManager passed to " + "SSLContext.init(): need an " + "X509ExtendedKeyManager for SSLEngine use"); } return new AbstractKeyManagerWrapper((X509KeyManager)km); } // nothing found, return a dummy X509ExtendedKeyManager return DummyX509KeyManager.INSTANCE; } protected SSLSocketFactory engineGetSocketFactory() { if (!isInitialized) { throw new IllegalStateException( "SSLContextImpl is not initialized"); } return new SSLSocketFactoryImpl(this); } protected SSLServerSocketFactory engineGetServerSocketFactory() { if (!isInitialized) { throw new IllegalStateException("SSLContext is not initialized"); } return new SSLServerSocketFactoryImpl(this); } protected SSLEngine engineCreateSSLEngine() { if (!isInitialized) { throw new IllegalStateException( "SSLContextImpl is not initialized"); } return new SSLEngineImpl(this); } protected SSLEngine engineCreateSSLEngine(String host, int port) { if (!isInitialized) { throw new IllegalStateException( "SSLContextImpl is not initialized"); } return new SSLEngineImpl(this, host, port); } protected SSLSessionContext engineGetClientSessionContext() { return clientCache; } protected SSLSessionContext engineGetServerSessionContext() { return serverCache; } SecureRandom getSecureRandom() { return secureRandom; } X509ExtendedKeyManager getX509KeyManager() { return keyManager; } X509TrustManager getX509TrustManager() { return trustManager; } EphemeralKeyManager getEphemeralKeyManager() { return ephemeralKeyManager; } abstract SSLParameters getDefaultServerSSLParams(); abstract SSLParameters getDefaultClientSSLParams(); abstract SSLParameters getSupportedSSLParams(); // Get suported ProtoclList. ProtocolList getSuportedProtocolList() { if (supportedProtocolList == null) { supportedProtocolList = new ProtocolList(getSupportedSSLParams().getProtocols()); } return supportedProtocolList; } // Get default ProtoclList. ProtocolList getDefaultProtocolList(boolean roleIsServer) { if (roleIsServer) { if (defaultServerProtocolList == null) { defaultServerProtocolList = new ProtocolList( getDefaultServerSSLParams().getProtocols()); } return defaultServerProtocolList; } else { if (defaultClientProtocolList == null) { defaultClientProtocolList = new ProtocolList( getDefaultClientSSLParams().getProtocols()); } return defaultClientProtocolList; } } // Get suported CipherSuiteList. CipherSuiteList getSuportedCipherSuiteList() { // Clear cache of available ciphersuites. clearAvailableCache(); if (supportedCipherSuiteList == null) { supportedCipherSuiteList = getApplicableCipherSuiteList(getSuportedProtocolList(), false); } return supportedCipherSuiteList; } // Get default CipherSuiteList. CipherSuiteList getDefaultCipherSuiteList(boolean roleIsServer) { // Clear cache of available ciphersuites. clearAvailableCache(); if (roleIsServer) { if (defaultServerCipherSuiteList == null) { defaultServerCipherSuiteList = getApplicableCipherSuiteList( getDefaultProtocolList(true), true); } return defaultServerCipherSuiteList; } else { if (defaultClientCipherSuiteList == null) { defaultClientCipherSuiteList = getApplicableCipherSuiteList( getDefaultProtocolList(false), true); } return defaultClientCipherSuiteList; } } /** * Return whether a protocol list is the original default enabled * protocols. See: SSLSocket/SSLEngine.setEnabledProtocols() */ boolean isDefaultProtocolList(ProtocolList protocols) { return (protocols == defaultServerProtocolList) || (protocols == defaultClientProtocolList); } /* * Return the list of all available CipherSuites with a priority of * minPriority or above. */ private CipherSuiteList getApplicableCipherSuiteList( ProtocolList protocols, boolean onlyEnabled) { int minPriority = CipherSuite.SUPPORTED_SUITES_PRIORITY; if (onlyEnabled) { minPriority = CipherSuite.DEFAULT_SUITES_PRIORITY; } Collection<CipherSuite> allowedCipherSuites = CipherSuite.allowedCipherSuites(); ArrayList<CipherSuite> suites = new ArrayList<>(); if (!(protocols.collection().isEmpty()) && protocols.min.v != ProtocolVersion.NONE.v) { for (CipherSuite suite : allowedCipherSuites) { if (suite.allowed == false || suite.priority < minPriority) { continue; } if (suite.isAvailable() && suite.obsoleted > protocols.min.v && suite.supported <= protocols.max.v) { if (defaultAlgorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) { suites.add(suite); } } else if (debug != null && Debug.isOn("sslctx") && Debug.isOn("verbose")) { if (suite.obsoleted <= protocols.min.v) { System.out.println( "Ignoring obsoleted cipher suite: " + suite); } else if (suite.supported > protocols.max.v) { System.out.println( "Ignoring unsupported cipher suite: " + suite); } else { System.out.println( "Ignoring unavailable cipher suite: " + suite); } } } } return new CipherSuiteList(suites); } /** * Clear cache of available ciphersuites. If we support all ciphers * internally, there is no need to clear the cache and calling this * method has no effect. */ synchronized void clearAvailableCache() { if (CipherSuite.DYNAMIC_AVAILABILITY) { supportedCipherSuiteList = null; defaultServerCipherSuiteList = null; defaultClientCipherSuiteList = null; CipherSuite.BulkCipher.clearAvailableCache(); JsseJce.clearEcAvailable(); } } /* * The SSLContext implementation for TLS/SSL algorithm * * SSL/TLS protocols specify the forward compatibility and version * roll-back attack protections, however, a number of SSL/TLS server * vendors did not implement these aspects properly, and some current * SSL/TLS servers may refuse to talk to a TLS 1.1 or later client. * * Considering above interoperability issues, SunJSSE will not set * TLS 1.1 and TLS 1.2 as the enabled protocols for client by default. * * For SSL/TLS servers, there is no such interoperability issues as * SSL/TLS clients. In SunJSSE, TLS 1.1 or later version will be the * enabled protocols for server by default. * * We may change the behavior when popular TLS/SSL vendors support TLS * forward compatibility properly. * * SSLv2Hello is no longer necessary. This interoperability option was * put in place in the late 90's when SSLv3/TLS1.0 were relatively new * and there were a fair number of SSLv2-only servers deployed. Because * of the security issues in SSLv2, it is rarely (if ever) used, as * deployments should now be using SSLv3 and TLSv1. * * Considering the issues of SSLv2Hello, we should not enable SSLv2Hello * by default. Applications still can use it by enabling SSLv2Hello with * the series of setEnabledProtocols APIs. */ /* * The conservative SSLContext implementation for TLS, SSL, SSLv3 and * TLS10 algorithm. * * This is a super class of DefaultSSLContext and TLS10Context. * * @see SSLContext */ private static class ConservativeSSLContext extends SSLContextImpl { // parameters private static SSLParameters defaultServerSSLParams; private static SSLParameters defaultClientSSLParams; private static SSLParameters supportedSSLParams; static { if (SunJSSE.isFIPS()) { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name }); } else { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.SSL20Hello.name, ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name }); } } SSLParameters getDefaultServerSSLParams() { return defaultServerSSLParams; } SSLParameters getDefaultClientSSLParams() { return defaultClientSSLParams; } SSLParameters getSupportedSSLParams() { return supportedSSLParams; } } /* * The SSLContext implementation for default algorithm * * @see SSLContext */ public static final class DefaultSSLContext extends ConservativeSSLContext { private static final String NONE = "NONE"; private static final String P11KEYSTORE = "PKCS11"; private static volatile SSLContextImpl defaultImpl; private static TrustManager[] defaultTrustManagers; private static KeyManager[] defaultKeyManagers; public DefaultSSLContext() throws Exception { try { super.engineInit(getDefaultKeyManager(), getDefaultTrustManager(), null); } catch (Exception e) { if (debug != null && Debug.isOn("defaultctx")) { System.out.println("default context init failed: " + e); } throw e; } if (defaultImpl == null) { defaultImpl = this; } } protected void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr) throws KeyManagementException { throw new KeyManagementException ("Default SSLContext is initialized automatically"); } static synchronized SSLContextImpl getDefaultImpl() throws Exception { if (defaultImpl == null) { new DefaultSSLContext(); } return defaultImpl; } private static synchronized TrustManager[] getDefaultTrustManager() throws Exception { if (defaultTrustManagers != null) { return defaultTrustManagers; } KeyStore ks = TrustManagerFactoryImpl.getCacertsKeyStore("defaultctx"); TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); defaultTrustManagers = tmf.getTrustManagers(); return defaultTrustManagers; } private static synchronized KeyManager[] getDefaultKeyManager() throws Exception { if (defaultKeyManagers != null) { return defaultKeyManagers; } final Map<String,String> props = new HashMap<>(); AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { props.put("keyStore", System.getProperty( "javax.net.ssl.keyStore", "")); props.put("keyStoreType", System.getProperty( "javax.net.ssl.keyStoreType", KeyStore.getDefaultType())); props.put("keyStoreProvider", System.getProperty( "javax.net.ssl.keyStoreProvider", "")); props.put("keyStorePasswd", System.getProperty( "javax.net.ssl.keyStorePassword", "")); return null; } }); final String defaultKeyStore = props.get("keyStore"); String defaultKeyStoreType = props.get("keyStoreType"); String defaultKeyStoreProvider = props.get("keyStoreProvider"); if (debug != null && Debug.isOn("defaultctx")) { System.out.println("keyStore is : " + defaultKeyStore); System.out.println("keyStore type is : " + defaultKeyStoreType); System.out.println("keyStore provider is : " + defaultKeyStoreProvider); } if (P11KEYSTORE.equals(defaultKeyStoreType) && !NONE.equals(defaultKeyStore)) { throw new IllegalArgumentException("if keyStoreType is " + P11KEYSTORE + ", then keyStore must be " + NONE); } FileInputStream fs = null; if (defaultKeyStore.length() != 0 && !NONE.equals(defaultKeyStore)) { fs = AccessController.doPrivileged( new PrivilegedExceptionAction<FileInputStream>() { public FileInputStream run() throws Exception { return new FileInputStream(defaultKeyStore); } }); } String defaultKeyStorePassword = props.get("keyStorePasswd"); char[] passwd = null; if (defaultKeyStorePassword.length() != 0) { passwd = defaultKeyStorePassword.toCharArray(); } /** * Try to initialize key store. */ KeyStore ks = null; if ((defaultKeyStoreType.length()) != 0) { if (debug != null && Debug.isOn("defaultctx")) { System.out.println("init keystore"); } if (defaultKeyStoreProvider.length() == 0) { ks = KeyStore.getInstance(defaultKeyStoreType); } else { ks = KeyStore.getInstance(defaultKeyStoreType, defaultKeyStoreProvider); } // if defaultKeyStore is NONE, fs will be null ks.load(fs, passwd); } if (fs != null) { fs.close(); fs = null; } /* * Try to initialize key manager. */ if (debug != null && Debug.isOn("defaultctx")) { System.out.println("init keymanager of type " + KeyManagerFactory.getDefaultAlgorithm()); } KeyManagerFactory kmf = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); if (P11KEYSTORE.equals(defaultKeyStoreType)) { kmf.init(ks, null); // do not pass key passwd if using token } else { kmf.init(ks, passwd); } defaultKeyManagers = kmf.getKeyManagers(); return defaultKeyManagers; } } /* * The SSLContext implementation for TLS, SSL, SSLv3 and TLS10 algorithm * * @see SSLContext */ public static final class TLS10Context extends ConservativeSSLContext { // use the default constructor and methods } /* * The SSLContext implementation for TLS11 algorithm * * @see SSLContext */ public static final class TLS11Context extends SSLContextImpl { // parameters private static SSLParameters defaultServerSSLParams; private static SSLParameters defaultClientSSLParams; private static SSLParameters supportedSSLParams; static { if (SunJSSE.isFIPS()) { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name }); } else { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.SSL20Hello.name, ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name }); } } SSLParameters getDefaultServerSSLParams() { return defaultServerSSLParams; } SSLParameters getDefaultClientSSLParams() { return defaultClientSSLParams; } SSLParameters getSupportedSSLParams() { return supportedSSLParams; } } /* * The SSLContext implementation for TLS12 algorithm * * @see SSLContext */ public static final class TLS12Context extends SSLContextImpl { // parameters private static SSLParameters defaultServerSSLParams; private static SSLParameters defaultClientSSLParams; private static SSLParameters supportedSSLParams; static { if (SunJSSE.isFIPS()) { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); } else { supportedSSLParams = new SSLParameters(); supportedSSLParams.setProtocols(new String[] { ProtocolVersion.SSL20Hello.name, ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); defaultServerSSLParams = supportedSSLParams; defaultClientSSLParams = new SSLParameters(); defaultClientSSLParams.setProtocols(new String[] { ProtocolVersion.SSL30.name, ProtocolVersion.TLS10.name, ProtocolVersion.TLS11.name, ProtocolVersion.TLS12.name }); } } SSLParameters getDefaultServerSSLParams() { return defaultServerSSLParams; } SSLParameters getDefaultClientSSLParams() { return defaultClientSSLParams; } SSLParameters getSupportedSSLParams() { return supportedSSLParams; } } } final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager implements X509TrustManager { // the delegated trust manager private final X509TrustManager tm; AbstractTrustManagerWrapper(X509TrustManager tm) { this.tm = tm; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { tm.checkClientTrusted(chain, authType); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { tm.checkServerTrusted(chain, authType); } @Override public X509Certificate[] getAcceptedIssuers() { return tm.getAcceptedIssuers(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { tm.checkClientTrusted(chain, authType); checkAdditionalTrust(chain, authType, socket, true); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { tm.checkServerTrusted(chain, authType); checkAdditionalTrust(chain, authType, socket, false); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { tm.checkClientTrusted(chain, authType); checkAdditionalTrust(chain, authType, engine, true); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { tm.checkServerTrusted(chain, authType); checkAdditionalTrust(chain, authType, engine, false); } private void checkAdditionalTrust(X509Certificate[] chain, String authType, Socket socket, boolean isClient) throws CertificateException { if (socket != null && socket.isConnected() && socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket)socket; SSLSession session = sslSocket.getHandshakeSession(); if (session == null) { throw new CertificateException("No handshake session"); } // check endpoint identity String identityAlg = sslSocket.getSSLParameters(). getEndpointIdentificationAlgorithm(); if (identityAlg != null && identityAlg.length() != 0) { String hostname = session.getPeerHost(); X509TrustManagerImpl.checkIdentity( hostname, chain[0], identityAlg); } // try the best to check the algorithm constraints ProtocolVersion protocolVersion = ProtocolVersion.valueOf(session.getProtocol()); AlgorithmConstraints constraints = null; if (protocolVersion.v >= ProtocolVersion.TLS12.v) { if (session instanceof ExtendedSSLSession) { ExtendedSSLSession extSession = (ExtendedSSLSession)session; String[] peerSupportedSignAlgs = extSession.getLocalSupportedSignatureAlgorithms(); constraints = new SSLAlgorithmConstraints( sslSocket, peerSupportedSignAlgs, true); } else { constraints = new SSLAlgorithmConstraints(sslSocket, true); } } else { constraints = new SSLAlgorithmConstraints(sslSocket, true); } checkAlgorithmConstraints(chain, constraints); } } private void checkAdditionalTrust(X509Certificate[] chain, String authType, SSLEngine engine, boolean isClient) throws CertificateException { if (engine != null) { SSLSession session = engine.getHandshakeSession(); if (session == null) { throw new CertificateException("No handshake session"); } // check endpoint identity String identityAlg = engine.getSSLParameters(). getEndpointIdentificationAlgorithm(); if (identityAlg != null && identityAlg.length() != 0) { String hostname = session.getPeerHost(); X509TrustManagerImpl.checkIdentity( hostname, chain[0], identityAlg); } // try the best to check the algorithm constraints ProtocolVersion protocolVersion = ProtocolVersion.valueOf(session.getProtocol()); AlgorithmConstraints constraints = null; if (protocolVersion.v >= ProtocolVersion.TLS12.v) { if (session instanceof ExtendedSSLSession) { ExtendedSSLSession extSession = (ExtendedSSLSession)session; String[] peerSupportedSignAlgs = extSession.getLocalSupportedSignatureAlgorithms(); constraints = new SSLAlgorithmConstraints( engine, peerSupportedSignAlgs, true); } else { constraints = new SSLAlgorithmConstraints(engine, true); } } else { constraints = new SSLAlgorithmConstraints(engine, true); } checkAlgorithmConstraints(chain, constraints); } } private void checkAlgorithmConstraints(X509Certificate[] chain, AlgorithmConstraints constraints) throws CertificateException { try { // Does the certificate chain end with a trusted certificate? int checkedLength = chain.length - 1; Collection<X509Certificate> trustedCerts = new HashSet<>(); X509Certificate[] certs = tm.getAcceptedIssuers(); if ((certs != null) && (certs.length > 0)){ Collections.addAll(trustedCerts, certs); } if (trustedCerts.contains(chain[checkedLength])) { checkedLength--; } // A forward checker, need to check from trust to target if (checkedLength >= 0) { AlgorithmChecker checker = new AlgorithmChecker(constraints); checker.init(false); for (int i = checkedLength; i >= 0; i--) { Certificate cert = chain[i]; // We don't care about the unresolved critical extensions. checker.check(cert, Collections.<String>emptySet()); } } } catch (CertPathValidatorException cpve) { throw new CertificateException( "Certificates does not conform to algorithm constraints"); } } } // Dummy X509TrustManager implementation, rejects all peer certificates. // Used if the application did not specify a proper X509TrustManager. final class DummyX509TrustManager extends X509ExtendedTrustManager implements X509TrustManager { static final X509TrustManager INSTANCE = new DummyX509TrustManager(); private DummyX509TrustManager() { // empty } /* * Given the partial or complete certificate chain * provided by the peer, build a certificate path * to a trusted root and return if it can be * validated and is trusted for client SSL authentication. * If not, it throws an exception. */ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation avaiable"); } /* * Given the partial or complete certificate chain * provided by the peer, build a certificate path * to a trusted root and return if it can be * validated and is trusted for server SSL authentication. * If not, it throws an exception. */ @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation available"); } /* * Return an array of issuer certificates which are trusted * for authenticating peers. */ @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation available"); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation available"); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation available"); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { throw new CertificateException( "No X509TrustManager implementation available"); } } /* * A wrapper class to turn a X509KeyManager into an X509ExtendedKeyManager */ final class AbstractKeyManagerWrapper extends X509ExtendedKeyManager { private final X509KeyManager km; AbstractKeyManagerWrapper(X509KeyManager km) { this.km = km; } public String[] getClientAliases(String keyType, Principal[] issuers) { return km.getClientAliases(keyType, issuers); } public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return km.chooseClientAlias(keyType, issuers, socket); } public String[] getServerAliases(String keyType, Principal[] issuers) { return km.getServerAliases(keyType, issuers); } public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return km.chooseServerAlias(keyType, issuers, socket); } public X509Certificate[] getCertificateChain(String alias) { return km.getCertificateChain(alias); } public PrivateKey getPrivateKey(String alias) { return km.getPrivateKey(alias); } // Inherit chooseEngineClientAlias() and chooseEngineServerAlias() from // X509ExtendedKeymanager. It defines them to return null; } // Dummy X509KeyManager implementation, never returns any certificates/keys. // Used if the application did not specify a proper X509TrustManager. final class DummyX509KeyManager extends X509ExtendedKeyManager { static final X509ExtendedKeyManager INSTANCE = new DummyX509KeyManager(); private DummyX509KeyManager() { // empty } /* * Get the matching aliases for authenticating the client side of a secure * socket given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String[] getClientAliases(String keyType, Principal[] issuers) { return null; } /* * Choose an alias to authenticate the client side of a secure * socket given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { return null; } /* * Choose an alias to authenticate the client side of an * engine given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String chooseEngineClientAlias( String[] keyTypes, Principal[] issuers, SSLEngine engine) { return null; } /* * Get the matching aliases for authenticating the server side of a secure * socket given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String[] getServerAliases(String keyType, Principal[] issuers) { return null; } /* * Choose an alias to authenticate the server side of a secure * socket given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return null; } /* * Choose an alias to authenticate the server side of an engine * given the public key type and the list of * certificate issuer authorities recognized by the peer (if any). */ public String chooseEngineServerAlias( String keyType, Principal[] issuers, SSLEngine engine) { return null; } /** * Returns the certificate chain associated with the given alias. * * @param alias the alias name * * @return the certificate chain (ordered with the user's certificate first * and the root certificate authority last) */ public X509Certificate[] getCertificateChain(String alias) { return null; } /* * Returns the key associated with the given alias, using the given * password to recover it. * * @param alias the alias name * * @return the requested key */ public PrivateKey getPrivateKey(String alias) { return null; } }
gpl-2.0
Taichi-SHINDO/jdk9-jdk
test/java/awt/Modal/ToBack/ToBackTKModal5Test.java
1698
/* * Copyright (c) 2007, 2014, 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.awt.Dialog; /* * @test * @bug 8054143 * @summary Check whether a toolkit modal dialog having a visible Frame * constructor still stays on top of the blocked windows even * after calling toBack for the dialog. * * @library ../helpers ../../../../lib/testlibrary/ * @build ExtendedRobot * @build Flag * @build TestDialog * @build TestFrame * @run main ToBackTKModal5Test */ public class ToBackTKModal5Test { public static void main(String[] args) throws Exception { (new ToBackFDFTest(Dialog.ModalityType.TOOLKIT_MODAL, ToBackFDFTest.DialogOwner.FRAME)).doTest(); } }
gpl-2.0
dschultzca/RomRaider
src/main/java/com/romraider/io/protocol/ssm/iso15765/SSMResponseProcessor.java
4954
/* * RomRaider Open-Source Tuning, Logging and Reflashing * Copyright (C) 2006-2015 RomRaider.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.romraider.io.protocol.ssm.iso15765; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.module; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.ECU_INIT_RESPONSE; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.ECU_NRC; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.READ_ADDRESS_RESPONSE; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.READ_MEMORY_RESPONSE; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.RESPONSE_NON_DATA_BYTES; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.WRITE_ADDRESS_RESPONSE; import static com.romraider.io.protocol.ssm.iso15765.SSMProtocol.WRITE_MEMORY_RESPONSE; import static com.romraider.util.ByteUtil.asUnsignedInt; import static com.romraider.util.HexUtil.asHex; import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; import com.romraider.logger.ecu.comms.manager.PollingState; import com.romraider.logger.ecu.exception.InvalidResponseException; public final class SSMResponseProcessor { private SSMResponseProcessor() { throw new UnsupportedOperationException(); } public static byte[] filterRequestFromResponse(byte[] request, byte[] response, PollingState pollState) { checkNotNullOrEmpty(response, "response"); return response; } public static void validateResponse(byte[] response) { assertTrue(response.length > RESPONSE_NON_DATA_BYTES, "Invalid response length"); assertEquals(module.getAddress(), response, "Invalid " + module.getName() + " id"); if (response[4] == ECU_NRC) { assertNrc(ECU_NRC, response[4], response[5], response[6],"Request type not supported"); } assertOneOf(new byte[]{ECU_INIT_RESPONSE, READ_ADDRESS_RESPONSE, READ_MEMORY_RESPONSE, WRITE_ADDRESS_RESPONSE, WRITE_MEMORY_RESPONSE}, response[4], "Invalid response code"); } public static byte[] extractResponseData(byte[] response) { checkNotNullOrEmpty(response, "response"); // 0x00 0x00 0x07 0xe0 response_command response_data validateResponse(response); final byte[] data = new byte[response.length - RESPONSE_NON_DATA_BYTES]; System.arraycopy(response, (RESPONSE_NON_DATA_BYTES), data, 0, data.length); return data; } private static void assertTrue(boolean condition, String msg) { if (!condition) { throw new InvalidResponseException(msg); } } private static void assertNrc(byte expected, byte actual, byte command, byte code, String msg) { if (actual == expected) { String ec = " unsupported parameter."; if (code == 0x13) { ec = " invalid format or length."; } if (code == 0x22) { ec = " address not allowed."; } throw new InvalidResponseException( msg + ". Command: " + asHex(new byte[]{command}) + ec); } } private static void assertEquals(byte[] expected, byte[] actual, String msg) { final byte[] idBytes = new byte[4]; System.arraycopy(actual, 0, idBytes, 0, 4); final int idExpected = asUnsignedInt(expected); final int idActual = asUnsignedInt(idBytes); if (idActual != idExpected) { throw new InvalidResponseException(msg + ". Expected: " + asHex(expected) + ". Actual: " + asHex(idBytes) + "."); } } private static void assertOneOf(byte[] validOptions, byte actual, String msg) { for (byte option : validOptions) { if (option == actual) { return; } } StringBuilder builder = new StringBuilder(); for (int i = 0; i < validOptions.length; i++) { if (i > 0) { builder.append(", "); } builder.append(asHex(new byte[]{validOptions[i]})); } throw new InvalidResponseException(msg + ". Expected one of [" + builder.toString() + "]. Actual: " + asHex(new byte[]{actual}) + "."); } }
gpl-2.0
mdaniel/svn-caucho-com-resin
artifacts/netbeans/src/com/caucho/netbeans/Console.java
3545
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.netbeans; import com.caucho.netbeans.PluginLogger; import com.caucho.netbeans.util.LogSupport; import org.netbeans.modules.j2ee.deployment.plugins.api.UISupport; import org.openide.ErrorManager; import org.openide.windows.InputOutput; import org.openide.windows.OutputWriter; import java.io.IOException; import java.io.Reader; import java.util.logging.Level; public final class Console { private static final PluginLogger log = new PluginLogger(Console.class); private final String _uri; private final InputOutput _inputOutput; private final OutputWriter _writer; private final OutputWriter _errorWriter; private final LogSupport _logSupport = new LogSupport(); private ConsoleRedirector _consoleRedirector; public Console(String uri) { _uri = uri; _inputOutput = UISupport.getServerIO(uri); try { _inputOutput.getOut().reset(); } catch (IOException e) { log.log(Level.INFO, e); } _writer = _inputOutput.getOut(); _errorWriter = _inputOutput.getErr(); _inputOutput.select(); } public String getUri() { return _uri; } public void println() { _writer.println(); } public void println(String line) { LogSupport.LineInfo lineInfo = _logSupport.analyzeLine(line); if (lineInfo.isError()) { if (lineInfo.isAccessible()) { try { _errorWriter.println(line, _logSupport.getLink(lineInfo.message(), lineInfo.path(), lineInfo.line())); } catch (IOException ex) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } else { _errorWriter.println(line); } takeFocus(); } else { _writer.println(line); } } public void start(Reader in, Reader err) { if (_consoleRedirector != null) throw new IllegalStateException(); _consoleRedirector = new ConsoleRedirector(this, in, err); } void flush() { _writer.flush(); _errorWriter.flush(); } public void takeFocus() { _inputOutput.select(); } public void stop() { ConsoleRedirector consoleRedirector = _consoleRedirector; _consoleRedirector = null; if (consoleRedirector != null) consoleRedirector.destroy(); } public void destroy() { try { stop(); } finally { _logSupport.detachAnnotation(); } } }
gpl-2.0
xor-freenet/fred-staging
src/freenet/client/async/USKFetcherWrapper.java
3268
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.client.async; import java.util.List; import freenet.client.ClientMetadata; import freenet.client.FetchException; import freenet.client.InsertContext.CompatibilityMode; import freenet.crypt.HashResult; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.node.RequestClient; import freenet.support.compress.Compressor; import freenet.support.io.ResumeFailedException; /** * Wrapper for a backgrounded USKFetcher. */ public class USKFetcherWrapper extends BaseClientGetter { private static final long serialVersionUID = -6416069493740293035L; final USK usk; public USKFetcherWrapper(USK usk, short prio, final RequestClient client) { super(prio, new ClientBaseCallback() { @Override public void onResume(ClientContext context) { throw new IllegalStateException(); } @Override public RequestClient getRequestClient() { return client; } }); this.usk = usk; } @Override public FreenetURI getURI() { return usk.getURI(); } @Override public boolean isFinished() { return false; } @Override protected void innerNotifyClients(ClientContext context) { // Do nothing } @Override public void onSuccess(StreamGenerator streamGenerator, ClientMetadata clientMetadata, List<? extends Compressor> decompressors, ClientGetState state, ClientContext context) { // Ignore; we don't do anything with it because we are running in the background. } @Override public void onFailure(FetchException e, ClientGetState state, ClientContext context) { // Ignore } @Override public void onBlockSetFinished(ClientGetState state, ClientContext context) { // Ignore } @Override public void onTransition(ClientGetState oldState, ClientGetState newState, ClientContext context) { // Ignore } @Override public String toString() { return super.toString()+ ':' +usk; } @Override public void onExpectedMIME(ClientMetadata meta, ClientContext context) { // Ignore } @Override public void onExpectedSize(long size, ClientContext context) { // Ignore } @Override public void onFinalizedMetadata() { // Ignore } @Override public void cancel(ClientContext context) { super.cancel(); } @Override protected void innerToNetwork(ClientContext context) { // Ignore } @Override public void onExpectedTopSize(long size, long compressed, int blocksReq, int blocksTotal, ClientContext context) { // Ignore } @Override public void onSplitfileCompatibilityMode(CompatibilityMode min, CompatibilityMode max, byte[] splitfileKey, boolean compressed, boolean bottomLayer, boolean definitiveAnyway, ClientContext context) { // Ignore } @Override public void onHashes(HashResult[] hashes, ClientContext context) { // Ignore } @Override public void innerOnResume(ClientContext context) throws ResumeFailedException { super.innerOnResume(context); } @Override protected ClientBaseCallback getCallback() { return null; } }
gpl-2.0
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/antadapter/org/eclipse/jdt/core/BuildJarIndex.java
2016
/******************************************************************************* * Copyright (c) 2011 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core; import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.eclipse.jdt.core.index.JavaIndexer; import org.eclipse.jdt.internal.antadapter.AntAdapterMessages; /** * <p> * An Ant task to generate the index file for the given jar path. * </p> * <p> * <code>&lt;eclipse.buildJarIndex jarPath="Test.jar" indexPath="Test.index"/&gt;</code> * </p> * <p> * For more information on Ant check out the website at http://jakarta.apache.org/ant/ . * </p> * <p> * This is not intended to be subclassed by users. * </p> * @since 3.8 */ public class BuildJarIndex extends Task { private String jarPath; private String indexPath; @Override public void execute() throws BuildException { if (this.jarPath == null) { throw new BuildException(AntAdapterMessages.getString("buildJarIndex.jarFile.cannot.be.null")); //$NON-NLS-1$ } if (this.indexPath == null) { throw new BuildException(AntAdapterMessages.getString("buildJarIndex.indexFile.cannot.be.null")); //$NON-NLS-1$ } try { JavaIndexer.generateIndexForJar(this.jarPath, this.indexPath); } catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("buildJarIndex.ioexception.occured", e.getLocalizedMessage()), e); //$NON-NLS-1$ } } public void setJarPath(String path) { this.jarPath = path; } public void setIndexPath(String path) { this.indexPath = path; } }
gpl-3.0
elta/GetProductMsg
src/main/Main.java
38
package main; public class Main { }
gpl-3.0
Mazdallier/AncientWarfare2
z_unused/shadowmage/ancient_framework/common/utils/DamageType.java
2763
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare 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 3 of the License, or (at your option) any later version. Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_framework.common.utils; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ChatMessageComponent; import net.minecraft.util.DamageSource; public class DamageType extends DamageSource { Entity ent; public static DamageType fireMissile = (DamageType) new DamageType("dmg.firemissile").setFireDamage().setProjectile(); public static DamageType explosiveMissile = (DamageType) new DamageType("dmg.explosivemissile").setFireDamage().setProjectile(); public static DamageType genericMissile = (DamageType) new DamageType("dmg.genericmissile").setProjectile(); public static DamageType piercingMissile = (DamageType) new DamageType("dmg.piercingmissile").setDamageBypassesArmor().setProjectile(); public static DamageType batteringDamage = (DamageType) new DamageType("dmg.battering"); /** * @param par1Str */ protected DamageType(String par1Str) { super(par1Str); } protected DamageType(String type, Entity source) { super(type); this.ent = source; } @Override public Entity getEntity() { return ent; } public static DamageSource causeEntityMissileDamage(Entity attacker , boolean fire, boolean expl) { DamageType t = new DamageType("AWMissile", attacker); t.setProjectile(); if(fire) { t.setFireDamage(); } if(expl) { t.setExplosion(); } return t; } @Override public ChatMessageComponent getDeathMessage(EntityLivingBase par1EntityLiving) { EntityLivingBase entityliving1 = par1EntityLiving.func_94060_bK(); String name = entityliving1==null? "No Entity" : entityliving1.getEntityName(); ChatMessageComponent chat = ChatMessageComponent.createFromText(name + " was killed by Missile Damage"); return chat; } }
gpl-3.0
sanjupolus/kc-coeus-1508.3
coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/print/CurrentOrPendingReportAction.java
6949
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.print; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.coeus.common.framework.print.PrintConstants; import org.kuali.coeus.common.proposal.framework.report.CurrentAndPendingReportService; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.common.web.struts.form.ReportHelperBean; import org.kuali.kra.common.web.struts.form.ReportHelperBeanContainer; import org.kuali.kra.infrastructure.Constants; import org.kuali.coeus.common.framework.print.AttachmentDataSource; import org.kuali.rice.kns.util.WebUtils; import org.kuali.rice.kns.web.struts.action.KualiAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class CurrentOrPendingReportAction extends KualiAction{ private static final Log LOG = LogFactory.getLog(CurrentOrPendingReportAction.class); private CurrentAndPendingReportService currentAndPendingReportService; protected CurrentAndPendingReportService getCurrentAndPendingReportService (){ if (currentAndPendingReportService == null) currentAndPendingReportService = KcServiceLocator.getService (CurrentAndPendingReportService.class); return currentAndPendingReportService; } /** * Prepare current report (i.e. Awards that selected person is on) * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward printCurrentReportPdf(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CurrentAndPendingReportService currentAndPendingReportService = getCurrentAndPendingReportService(); ReportHelperBean helper = ((ReportHelperBeanContainer) form).getReportHelperBean(); Map<String, Object> reportParameters = new HashMap<String, Object>(); reportParameters.put(PrintConstants.PERSON_ID_KEY, helper.getPersonId()); reportParameters.put(PrintConstants.REPORT_PERSON_NAME_KEY, helper.getTargetPersonName()); AttachmentDataSource dataStream = currentAndPendingReportService.printCurrentReport(reportParameters); streamToResponse(dataStream.getData(), dataStream.getName(), null, response); return null; } /** * Prepare pending report (i.e. InstitutionalProposals that selected person is on) {@inheritDoc} */ public ActionForward printPendingReportPdf(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CurrentAndPendingReportService currentAndPendingReportService = getCurrentAndPendingReportService(); ReportHelperBean helper = ((ReportHelperBeanContainer) form).getReportHelperBean(); Map<String, Object> reportParameters = new HashMap<String, Object>(); reportParameters.put(PrintConstants.PERSON_ID_KEY, helper.getPersonId()); reportParameters.put(PrintConstants.REPORT_PERSON_NAME_KEY, helper.getTargetPersonName()); AttachmentDataSource dataStream = currentAndPendingReportService.printPendingReport(reportParameters); streamToResponse(dataStream.getData(), dataStream.getName(), null, response); return null; } /** * Prepare current report (i.e. Awards that selected person is on) * {@inheritDoc} */ public ActionForward prepareCurrentReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ReportHelperBean helper = ((ReportHelperBeanContainer)form).getReportHelperBean(); request.setAttribute(PrintConstants.CURRENT_REPORT_ROWS_KEY, helper.prepareCurrentReport()); request.setAttribute(PrintConstants.REPORT_PERSON_NAME_KEY, helper.getTargetPersonName()); return mapping.findForward(Constants.MAPPING_BASIC); } /** * Prepare pending report (i.e. InstitutionalProposals that selected person is on) * {@inheritDoc} */ public ActionForward preparePendingReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ReportHelperBean helper = ((ReportHelperBeanContainer)form).getReportHelperBean(); request.setAttribute(PrintConstants.PENDING_REPORT_ROWS_KEY, helper.preparePendingReport()); request.setAttribute(PrintConstants.REPORT_PERSON_NAME_KEY, helper.getTargetPersonName()); return mapping.findForward(Constants.MAPPING_BASIC); } /** * * Handy method to stream the byte array to response object * @param fileContents * @param fileName * @param fileContentType * @param response * @throws Exception */ protected void streamToResponse(byte[] fileContents, String fileName, String fileContentType,HttpServletResponse response) throws Exception{ ByteArrayOutputStream baos = null; try{ baos = new ByteArrayOutputStream(fileContents.length); baos.write(fileContents); WebUtils.saveMimeOutputStreamAsFile(response, fileContentType, baos, fileName); }finally{ try{ if(baos!=null){ baos.close(); baos = null; } }catch(IOException ioEx){ LOG.error("Error while downloading attachment"); throw new RuntimeException("IOException occurred while downloading attachment", ioEx); } } } }
agpl-3.0
cswhite2000/ProjectAres
PGM/src/main/java/tc/oc/pgm/xml/parser/AttributeParser.java
626
package tc.oc.pgm.xml.parser; import org.bukkit.attribute.Attribute; import tc.oc.pgm.xml.InvalidXMLException; import tc.oc.pgm.xml.Node; public class AttributeParser extends PrimitiveParser<Attribute> { @Override protected Attribute parseInternal(Node node, String text) throws FormatException, InvalidXMLException { Attribute attribute = Attribute.byName(text); if(attribute != null) return attribute; attribute = Attribute.byName("generic." + text); if(attribute != null) return attribute; throw new InvalidXMLException("Unknown attribute '" + text + "'", node); } }
agpl-3.0
sanjupolus/KC6.oLatest
coeus-it/src/test/java/org/kuali/kra/KcClasspathSuite.java
4298
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter; public class KcClasspathSuite extends Suite { public KcClasspathSuite(Class<?> suiteClass, RunnerBuilder builder) throws InitializationError, ClassNotFoundException { super(builder, getTestClasses(suiteClass)); } protected static Class<?>[] getTestClasses(Class<?> suiteClass) throws ClassNotFoundException { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new MethodAnnotationTypeFilter(Test.class)); List<Class<?>> classes = new ArrayList<Class<?>>(); for (BeanDefinition bd : scanner.findCandidateComponents(suiteClass.getPackage().getName())) { System.out.println("Found test - " + bd.getBeanClassName()); classes.add(Class.forName(bd.getBeanClassName())); } for (BeanDefinition bd : scanner.findCandidateComponents("org.kuali.coeus")) { System.out.println("Found test - " + bd.getBeanClassName()); classes.add(Class.forName(bd.getBeanClassName())); } Class<?>[] classArray = new Class<?>[classes.size()]; return (Class<?>[]) classes.toArray(classArray); } /** * Based on AnnotationTypeFilter with changes. Major one is we cannot use * AbstractTypeHierarchyTraversingFilter superClass features due to the real possiblity our * parent classes exist in jar files and the metadata readers have troubles processing those files * so instead once we have a class we do simple reflection based getMethod.hasAnnotation scanning of parent * classes. * @author dpace * */ protected static class MethodAnnotationTypeFilter extends AbstractTypeHierarchyTraversingFilter { private Class<? extends Annotation> methodAnnotation; public MethodAnnotationTypeFilter(Class<? extends Annotation> annotationType) { super(false, true); this.methodAnnotation = annotationType; } @Override protected boolean matchSelf(MetadataReader metadataReader) { AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); if (metadata.hasAnnotatedMethods(methodAnnotation.getName())) { return true; } else if (metadata.hasSuperClass()) { return matchSuperClass(metadata.getSuperClassName()); } else { return false; } } @Override protected Boolean matchSuperClass(String superClassName) { if (Object.class.getName().equals(superClassName)) { return Boolean.FALSE; } else { try { Class<?> clazz = getClass().getClassLoader().loadClass(superClassName); for (Method method : clazz.getMethods()) { if (method.getAnnotation(methodAnnotation) != null) { return Boolean.TRUE; } } return matchSuperClass(clazz.getSuperclass().getCanonicalName()); } catch (ClassNotFoundException ex) { // Class not found - can't determine a match that way. } } return Boolean.FALSE; } } }
agpl-3.0
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/coeus/common/questionnaire/impl/question/QuestionAuthorizationServiceImpl.java
2915
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.common.questionnaire.impl.question; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.common.framework.auth.UnitAuthorizationService; import org.kuali.coeus.sys.framework.gv.GlobalVariableService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("questionAuthorizationService") public class QuestionAuthorizationServiceImpl implements QuestionAuthorizationService { @Autowired @Qualifier("unitAuthorizationService") private UnitAuthorizationService unitAuthorizationService; @Autowired @Qualifier("kcPersonService") private KcPersonService kcPersonService; @Autowired @Qualifier("globalVariableService") private GlobalVariableService globalVariableService; public boolean hasPermission(String permissionName) { KcPerson person = kcPersonService.getKcPersonByUserName(getUserName()); return unitAuthorizationService.hasPermission(person.getPersonId(), "KC-QUESTIONNAIRE", permissionName); } protected String getUserName() { return globalVariableService.getUserSession().getPerson().getPrincipalName(); } public void setUnitAuthorizationService(UnitAuthorizationService unitAuthorizationService) { this.unitAuthorizationService = unitAuthorizationService; } public void setKcPersonService(KcPersonService kcPersonService) { this.kcPersonService = kcPersonService; } public UnitAuthorizationService getUnitAuthorizationService() { return unitAuthorizationService; } public KcPersonService getKcPersonService() { return kcPersonService; } public GlobalVariableService getGlobalVariableService() { return globalVariableService; } public void setGlobalVariableService(GlobalVariableService globalVariableService) { this.globalVariableService = globalVariableService; } }
agpl-3.0
jstourac/wildfly
metrics/src/main/java/org/wildfly/extension/metrics/WildFlyMetricRegistry.java
2956
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.metrics; import static java.util.Objects.requireNonNull; import java.io.Closeable; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class WildFlyMetricRegistry implements Closeable, MetricRegistry { /* Key is the metric name */ private Map<String, MetricMetadata> metadataMap = new HashMap(); private Map<MetricID, Metric> metricMap = new TreeMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); @Override public void close() { lock.writeLock().lock(); try { metricMap.clear(); metadataMap.clear(); } finally { lock.writeLock().unlock(); } } Map<MetricID, Metric> getMetrics() { return metricMap; } Map<String, MetricMetadata> getMetricMetadata() { return metadataMap; } @Override public synchronized void registerMetric(Metric metric, MetricMetadata metadata) { requireNonNull(metadata); requireNonNull(metric); lock.writeLock().lock(); try { MetricID metricID = metadata.getMetricID(); if (!metadataMap.containsKey(metadata.getMetricName())) { metadataMap.put(metadata.getMetricName(), metadata); } metricMap.put(metricID, metric); } finally { lock.writeLock().unlock(); } } @Override public void unregister(MetricID metricID) { lock.writeLock().lock(); try { metricMap.remove(metricID); } finally { lock.writeLock().unlock(); } } @Override public void readLock() { lock.readLock().lock(); } @Override public void unlock() { lock.readLock().unlock(); } }
lgpl-2.1
rockmkd/datacollector
commonlib/src/test/java/com/streamsets/pipeline/lib/util/ExtensionsProto.java
63125
/* * Copyright 2017 StreamSets 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Extensions.proto package com.streamsets.pipeline.lib.util; public final class ExtensionsProto { private ExtensionsProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.stringField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.doubleField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.floatField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.boolField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.intField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.longField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.bytesField); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.residenceAddress); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.factoryAddress); registry.add(com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.officeAddress); } public interface PersonExtensionOrBuilder extends com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code util.PersonExtension} */ public static final class PersonExtension extends com.google.protobuf.GeneratedMessage implements PersonExtensionOrBuilder { // Use PersonExtension.newBuilder() to construct. private PersonExtension(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private PersonExtension(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final PersonExtension defaultInstance; public static PersonExtension getDefaultInstance() { return defaultInstance; } public PersonExtension getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private PersonExtension( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.Builder.class); } public static com.google.protobuf.Parser<PersonExtension> PARSER = new com.google.protobuf.AbstractParser<PersonExtension>() { public PersonExtension parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new PersonExtension(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<PersonExtension> getParserForType() { return PARSER; } public interface NestedPersonExtensionOrBuilder extends com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code util.PersonExtension.NestedPersonExtension} */ public static final class NestedPersonExtension extends com.google.protobuf.GeneratedMessage implements NestedPersonExtensionOrBuilder { // Use NestedPersonExtension.newBuilder() to construct. private NestedPersonExtension(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private NestedPersonExtension(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final NestedPersonExtension defaultInstance; public static NestedPersonExtension getDefaultInstance() { return defaultInstance; } public NestedPersonExtension getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private NestedPersonExtension( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_NestedPersonExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_NestedPersonExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.Builder.class); } public static com.google.protobuf.Parser<NestedPersonExtension> PARSER = new com.google.protobuf.AbstractParser<NestedPersonExtension>() { public NestedPersonExtension parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new NestedPersonExtension(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<NestedPersonExtension> getParserForType() { return PARSER; } private void initFields() { } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code util.PersonExtension.NestedPersonExtension} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtensionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_NestedPersonExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_NestedPersonExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.Builder.class); } // Construct using com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_NestedPersonExtension_descriptor; } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension getDefaultInstanceForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.getDefaultInstance(); } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension build() { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension buildPartial() { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension result = new com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension(this); onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension) { return mergeFrom((com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension other) { if (other == com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } // @@protoc_insertion_point(builder_scope:util.PersonExtension.NestedPersonExtension) } static { defaultInstance = new NestedPersonExtension(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:util.PersonExtension.NestedPersonExtension) public static final int RESIDENCEADDRESS_FIELD_NUMBER = 101; /** * <code>extend .util.Person { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.PersonProto.Person, java.lang.String> residenceAddress = com.google.protobuf.GeneratedMessage .newMessageScopedGeneratedExtension( com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.NestedPersonExtension.getDefaultInstance(), 0, java.lang.String.class, null); } private void initFields() { } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code util.PersonExtension} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtensionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.Builder.class); } // Construct using com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_PersonExtension_descriptor; } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension getDefaultInstanceForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.getDefaultInstance(); } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension build() { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension buildPartial() { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension result = new com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension(this); onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension) { return mergeFrom((com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension other) { if (other == com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.streamsets.pipeline.lib.util.ExtensionsProto.PersonExtension) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } // @@protoc_insertion_point(builder_scope:util.PersonExtension) } static { defaultInstance = new PersonExtension(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:util.PersonExtension) } public interface EngineerExtensionOrBuilder extends com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code util.EngineerExtension} */ public static final class EngineerExtension extends com.google.protobuf.GeneratedMessage implements EngineerExtensionOrBuilder { // Use EngineerExtension.newBuilder() to construct. private EngineerExtension(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private EngineerExtension(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final EngineerExtension defaultInstance; public static EngineerExtension getDefaultInstance() { return defaultInstance; } public EngineerExtension getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private EngineerExtension( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_EngineerExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_EngineerExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.Builder.class); } public static com.google.protobuf.Parser<EngineerExtension> PARSER = new com.google.protobuf.AbstractParser<EngineerExtension>() { public EngineerExtension parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new EngineerExtension(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<EngineerExtension> getParserForType() { return PARSER; } private void initFields() { } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code util.EngineerExtension} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtensionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_EngineerExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_EngineerExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.Builder.class); } // Construct using com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_EngineerExtension_descriptor; } public com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension getDefaultInstanceForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.getDefaultInstance(); } public com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension build() { com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension buildPartial() { com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension result = new com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension(this); onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension) { return mergeFrom((com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension other) { if (other == com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } // @@protoc_insertion_point(builder_scope:util.EngineerExtension) } static { defaultInstance = new EngineerExtension(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:util.EngineerExtension) public static final int FACTORYADDRESS_FIELD_NUMBER = 201; /** * <code>extend .util.Engineer { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EngineerProto.Engineer, java.lang.String> factoryAddress = com.google.protobuf.GeneratedMessage .newMessageScopedGeneratedExtension( com.streamsets.pipeline.lib.util.ExtensionsProto.EngineerExtension.getDefaultInstance(), 0, java.lang.String.class, null); } public interface ExecutiveExtensionOrBuilder extends com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code util.ExecutiveExtension} */ public static final class ExecutiveExtension extends com.google.protobuf.GeneratedMessage implements ExecutiveExtensionOrBuilder { // Use ExecutiveExtension.newBuilder() to construct. private ExecutiveExtension(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private ExecutiveExtension(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final ExecutiveExtension defaultInstance; public static ExecutiveExtension getDefaultInstance() { return defaultInstance; } public ExecutiveExtension getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ExecutiveExtension( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_ExecutiveExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_ExecutiveExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.Builder.class); } public static com.google.protobuf.Parser<ExecutiveExtension> PARSER = new com.google.protobuf.AbstractParser<ExecutiveExtension>() { public ExecutiveExtension parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ExecutiveExtension(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ExecutiveExtension> getParserForType() { return PARSER; } private void initFields() { } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code util.ExecutiveExtension} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtensionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_ExecutiveExtension_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_ExecutiveExtension_fieldAccessorTable .ensureFieldAccessorsInitialized( com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.class, com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.Builder.class); } // Construct using com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.internal_static_util_ExecutiveExtension_descriptor; } public com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension getDefaultInstanceForType() { return com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.getDefaultInstance(); } public com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension build() { com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension buildPartial() { com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension result = new com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension(this); onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension) { return mergeFrom((com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension other) { if (other == com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } // @@protoc_insertion_point(builder_scope:util.ExecutiveExtension) } static { defaultInstance = new ExecutiveExtension(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:util.ExecutiveExtension) public static final int OFFICEADDRESS_FIELD_NUMBER = 301; /** * <code>extend .util.Executive { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.ExecutiveProto.Executive, java.lang.String> officeAddress = com.google.protobuf.GeneratedMessage .newMessageScopedGeneratedExtension( com.streamsets.pipeline.lib.util.ExtensionsProto.ExecutiveExtension.getDefaultInstance(), 0, java.lang.String.class, null); } public static final int STRINGFIELD_FIELD_NUMBER = 401; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.String> stringField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.String.class, null); public static final int DOUBLEFIELD_FIELD_NUMBER = 402; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.Double> doubleField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.Double.class, null); public static final int FLOATFIELD_FIELD_NUMBER = 403; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.Float> floatField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.Float.class, null); public static final int BOOLFIELD_FIELD_NUMBER = 404; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.Boolean> boolField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.Boolean.class, null); public static final int INTFIELD_FIELD_NUMBER = 405; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.Integer> intField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.Integer.class, null); public static final int LONGFIELD_FIELD_NUMBER = 406; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, java.lang.Long> longField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( java.lang.Long.class, null); public static final int BYTESFIELD_FIELD_NUMBER = 407; /** * <code>extend .util.Employee { ... }</code> */ public static final com.google.protobuf.GeneratedMessage.GeneratedExtension< com.streamsets.pipeline.lib.util.EmployeeProto.Employee, com.google.protobuf.ByteString> bytesField = com.google.protobuf.GeneratedMessage .newFileScopedGeneratedExtension( com.google.protobuf.ByteString.class, null); private static com.google.protobuf.Descriptors.Descriptor internal_static_util_PersonExtension_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_util_PersonExtension_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_util_PersonExtension_NestedPersonExtension_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_util_PersonExtension_NestedPersonExtension_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_util_EngineerExtension_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_util_EngineerExtension_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_util_ExecutiveExtension_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_util_ExecutiveExtension_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\020Extensions.proto\022\004util\032\014Person.proto\032\016" + "Engineer.proto\032\017Executive.proto\032\016Employe" + "e.proto\"R\n\017PersonExtension\032?\n\025NestedPers" + "onExtension2&\n\020residenceAddress\022\014.util.P" + "erson\030e \001(\t\"<\n\021EngineerExtension2\'\n\016fact" + "oryAddress\022\016.util.Engineer\030\311\001 \001(\t\"=\n\022Exe" + "cutiveExtension2\'\n\rofficeAddress\022\017.util." + "Executive\030\255\002 \001(\t:(\n\013stringField\022\016.util.E" + "mployee\030\221\003 \001(\t:\002NY:.\n\013doubleField\022\016.util" + ".Employee\030\222\003 \001(\001:\0103534.234:+\n\nfloatField", "\022\016.util.Employee\030\223\003 \001(\002:\006343.34:(\n\tboolF" + "ield\022\016.util.Employee\030\224\003 \001(\010:\004true:(\n\010int" + "Field\022\016.util.Employee\030\225\003 \001(\005:\00543243:.\n\tl" + "ongField\022\016.util.Employee\030\226\003 \001(\003:\n2343254" + "354:,\n\nbytesField\022\016.util.Employee\030\227\003 \001(\014" + ":\007NewYorkB3\n com.streamsets.pipeline.lib" + ".utilB\017ExtensionsProto" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_util_PersonExtension_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_util_PersonExtension_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_util_PersonExtension_descriptor, new java.lang.String[] { }); internal_static_util_PersonExtension_NestedPersonExtension_descriptor = internal_static_util_PersonExtension_descriptor.getNestedTypes().get(0); internal_static_util_PersonExtension_NestedPersonExtension_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_util_PersonExtension_NestedPersonExtension_descriptor, new java.lang.String[] { }); internal_static_util_EngineerExtension_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_util_EngineerExtension_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_util_EngineerExtension_descriptor, new java.lang.String[] { }); internal_static_util_ExecutiveExtension_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_util_ExecutiveExtension_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_util_ExecutiveExtension_descriptor, new java.lang.String[] { }); stringField.internalInit(descriptor.getExtensions().get(0)); doubleField.internalInit(descriptor.getExtensions().get(1)); floatField.internalInit(descriptor.getExtensions().get(2)); boolField.internalInit(descriptor.getExtensions().get(3)); intField.internalInit(descriptor.getExtensions().get(4)); longField.internalInit(descriptor.getExtensions().get(5)); bytesField.internalInit(descriptor.getExtensions().get(6)); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.streamsets.pipeline.lib.util.PersonProto.getDescriptor(), com.streamsets.pipeline.lib.util.EngineerProto.getDescriptor(), com.streamsets.pipeline.lib.util.ExecutiveProto.getDescriptor(), com.streamsets.pipeline.lib.util.EmployeeProto.getDescriptor(), }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
facebook/buck
src/com/facebook/buck/apple/LibtoolStep.java
2851
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.apple; import com.facebook.buck.core.build.execution.context.ExecutionContext; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.shell.ShellStep; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.nio.file.Path; /** ShellStep for calling libtool. */ public class LibtoolStep extends ShellStep { /** Style of library to be created, static or dynamic. */ public enum Style { STATIC, DYNAMIC, } private final ProjectFilesystem filesystem; private final ImmutableMap<String, String> environment; private final ImmutableList<String> libtoolCommand; private final Path argsfile; private final Path output; private final ImmutableList<String> flags; private final LibtoolStep.Style style; public LibtoolStep( ProjectFilesystem filesystem, ImmutableMap<String, String> environment, ImmutableList<String> libtoolCommand, Path argsfile, Path output, ImmutableList<String> flags, LibtoolStep.Style style) { super(filesystem.getRootPath()); this.filesystem = filesystem; this.environment = environment; this.libtoolCommand = libtoolCommand; this.argsfile = argsfile; this.output = output; this.flags = ImmutableList.copyOf(flags); this.style = style; } @Override protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { ImmutableList.Builder<String> commandBuilder = ImmutableList.builder(); commandBuilder.addAll(libtoolCommand); switch (style) { case STATIC: commandBuilder.add("-static"); break; case DYNAMIC: commandBuilder.add("-dynamic"); break; } commandBuilder.add("-o"); commandBuilder.add(filesystem.resolve(output).toString()); commandBuilder.add("-filelist"); commandBuilder.add(filesystem.resolve(argsfile).toString()); commandBuilder.addAll(flags); return commandBuilder.build(); } @Override public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) { return environment; } @Override public String getShortName() { return "libtool"; } }
apache-2.0
NSAmelchev/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheStatisticsModeChangeTask.java
1921
/* * 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; import org.apache.ignite.internal.processors.security.SecurityContext; import org.apache.ignite.internal.util.typedef.internal.S; /** * Cache statistics mode change task for exchange worker. */ public class CacheStatisticsModeChangeTask extends AbstractCachePartitionExchangeWorkerTask { /** Discovery message. */ private final CacheStatisticsModeChangeMessage msg; /** * @param secCtx Security context in which current task must be executed. * @param msg Message. */ public CacheStatisticsModeChangeTask(SecurityContext secCtx, CacheStatisticsModeChangeMessage msg) { super(secCtx); assert msg != null; this.msg = msg; } /** {@inheritDoc} */ @Override public boolean skipForExchangeMerge() { return false; } /** * @return Message. */ public CacheStatisticsModeChangeMessage message() { return msg; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(CacheStatisticsModeChangeTask.class, this); } }
apache-2.0
mghosh4/druid
server/src/main/java/org/apache/druid/server/coordinator/rules/BroadcastDistributionRule.java
6016
/* * 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.druid.server.coordinator.rules; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import org.apache.druid.java.util.emitter.EmittingLogger; import org.apache.druid.server.coordination.ServerType; import org.apache.druid.server.coordinator.CoordinatorStats; import org.apache.druid.server.coordinator.DruidCluster; import org.apache.druid.server.coordinator.DruidCoordinator; import org.apache.druid.server.coordinator.DruidCoordinatorRuntimeParams; import org.apache.druid.server.coordinator.SegmentReplicantLookup; import org.apache.druid.server.coordinator.ServerHolder; import org.apache.druid.timeline.DataSegment; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public abstract class BroadcastDistributionRule implements Rule { private static final EmittingLogger log = new EmittingLogger(BroadcastDistributionRule.class); @Override public CoordinatorStats run(DruidCoordinator coordinator, DruidCoordinatorRuntimeParams params, DataSegment segment) { final Set<ServerHolder> dropServerHolders = new HashSet<>(); // Find servers where we need to load the broadcast segments final Set<ServerHolder> loadServerHolders = params.getDruidCluster().getAllServers() .stream() .filter( (serverHolder) -> { ServerType serverType = serverHolder.getServer().getType(); if (!serverType.isSegmentBroadcastTarget()) { return false; } final boolean isServingSegment = serverHolder.isServingSegment(segment); if (serverHolder.isDecommissioning()) { if (isServingSegment && !serverHolder.isDroppingSegment(segment)) { dropServerHolders.add(serverHolder); } return false; } return !isServingSegment && !serverHolder.isLoadingSegment(segment); } ) .collect(Collectors.toSet()); final CoordinatorStats stats = new CoordinatorStats(); return stats.accumulate(assign(loadServerHolders, segment)) .accumulate(drop(dropServerHolders, segment)); } @Override public boolean canLoadSegments() { return true; } @Override public void updateUnderReplicated( Map<String, Object2LongMap<String>> underReplicatedPerTier, SegmentReplicantLookup segmentReplicantLookup, DataSegment segment ) { Object2LongMap<String> underReplicatedBroadcastTiers = segmentReplicantLookup.getBroadcastUnderReplication(segment.getId()); for (final Object2LongMap.Entry<String> entry : underReplicatedBroadcastTiers.object2LongEntrySet()) { final String tier = entry.getKey(); final long underReplicatedCount = entry.getLongValue(); underReplicatedPerTier.compute(tier, (_tier, existing) -> { Object2LongMap<String> underReplicationPerDataSource = existing; if (existing == null) { underReplicationPerDataSource = new Object2LongOpenHashMap<>(); } underReplicationPerDataSource.compute( segment.getDataSource(), (_datasource, count) -> count != null ? count + underReplicatedCount : underReplicatedCount ); return underReplicationPerDataSource; }); } } @Override public void updateUnderReplicatedWithClusterView( Map<String, Object2LongMap<String>> underReplicatedPerTier, SegmentReplicantLookup segmentReplicantLookup, DruidCluster cluster, DataSegment segment ) { updateUnderReplicated( underReplicatedPerTier, segmentReplicantLookup, segment ); } private CoordinatorStats assign( final Set<ServerHolder> serverHolders, final DataSegment segment ) { final CoordinatorStats stats = new CoordinatorStats(); stats.addToGlobalStat(LoadRule.ASSIGNED_COUNT, 0); for (ServerHolder holder : serverHolders) { if (segment.getSize() > holder.getAvailableSize()) { log.makeAlert("Failed to broadcast segment for [%s]", segment.getDataSource()) .addData("segmentId", segment.getId()) .addData("segmentSize", segment.getSize()) .addData("hostName", holder.getServer().getHost()) .addData("availableSize", holder.getAvailableSize()) .emit(); } else { if (!holder.isLoadingSegment(segment)) { holder.getPeon().loadSegment( segment, null ); stats.addToGlobalStat(LoadRule.ASSIGNED_COUNT, 1); } } } return stats; } private CoordinatorStats drop( final Set<ServerHolder> serverHolders, final DataSegment segment ) { CoordinatorStats stats = new CoordinatorStats(); for (ServerHolder holder : serverHolders) { holder.getPeon().dropSegment(segment, null); stats.addToGlobalStat(LoadRule.DROPPED_COUNT, 1); } return stats; } }
apache-2.0
Team-OctOS/host_gerrit
gerrit-server/src/main/java/com/google/gerrit/server/change/GetChange.java
1984
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.change; import com.google.gerrit.extensions.common.ListChangesOption; import com.google.gerrit.extensions.restapi.CacheControl; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.server.change.ChangeJson.ChangeInfo; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import org.kohsuke.args4j.Option; import java.util.concurrent.TimeUnit; public class GetChange implements RestReadView<ChangeResource> { private final ChangeJson json; @Option(name = "-o", usage = "Output options") void addOption(ListChangesOption o) { json.addOption(o); } @Option(name = "-O", usage = "Output option flags, in hex") void setOptionFlagsHex(String hex) { json.addOptions(ListChangesOption.fromBits(Integer.parseInt(hex, 16))); } @Inject GetChange(ChangeJson json) { this.json = json; } @Override public Response<ChangeInfo> apply(ChangeResource rsrc) throws OrmException { return cache(json.format(rsrc)); } Response<ChangeInfo> apply(RevisionResource rsrc) throws OrmException { return cache(json.format(rsrc)); } private Response<ChangeInfo> cache(ChangeInfo res) { return Response.ok(res) .caching(CacheControl.PRIVATE(0, TimeUnit.SECONDS).setMustRevalidate()); } }
apache-2.0
Ant-Droid/android_frameworks_base_OLD
packages/SystemUI/src/com/android/systemui/recents/views/ViewPool.java
2784
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.recents.views; import android.content.Context; import java.util.Iterator; import java.util.LinkedList; /* A view pool to manage more views than we can visibly handle */ public class ViewPool<V, T> { /* An interface to the consumer of a view pool */ public interface ViewPoolConsumer<V, T> { public V createView(Context context); public void prepareViewToEnterPool(V v); public void prepareViewToLeavePool(V v, T prepareData, boolean isNewView); public boolean hasPreferredData(V v, T preferredData); } Context mContext; ViewPoolConsumer<V, T> mViewCreator; LinkedList<V> mPool = new LinkedList<V>(); /** Initializes the pool with a fixed predetermined pool size */ public ViewPool(Context context, ViewPoolConsumer<V, T> viewCreator) { mContext = context; mViewCreator = viewCreator; } /** Returns a view into the pool */ void returnViewToPool(V v) { mViewCreator.prepareViewToEnterPool(v); mPool.push(v); } /** Gets a view from the pool and prepares it */ V pickUpViewFromPool(T preferredData, T prepareData) { V v = null; boolean isNewView = false; if (mPool.isEmpty()) { v = mViewCreator.createView(mContext); isNewView = true; } else { // Try and find a preferred view Iterator<V> iter = mPool.iterator(); while (iter.hasNext()) { V vpv = iter.next(); if (mViewCreator.hasPreferredData(vpv, preferredData)) { v = vpv; iter.remove(); break; } } // Otherwise, just grab the first view if (v == null) { v = mPool.pop(); } } mViewCreator.prepareViewToLeavePool(v, prepareData, isNewView); return v; } /** Returns an iterator to the list of the views in the pool. */ Iterator<V> poolViewIterator() { if (mPool != null) { return mPool.iterator(); } return null; } }
apache-2.0
gh351135612/presto
presto-memory/src/test/java/com/facebook/presto/plugin/memory/TestMemorySmoke.java
7108
/* * 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.plugin.memory; import com.facebook.presto.metadata.QualifiedObjectName; import com.facebook.presto.testing.MaterializedResult; import com.facebook.presto.testing.MaterializedRow; import com.facebook.presto.tests.AbstractTestQueryFramework; import org.intellij.lang.annotations.Language; import org.testng.annotations.Test; import java.sql.SQLException; import java.util.List; import static com.facebook.presto.plugin.memory.MemoryQueryRunner.CATALOG; import static com.facebook.presto.testing.assertions.Assert.assertEquals; import static java.lang.String.format; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestMemorySmoke extends AbstractTestQueryFramework { public TestMemorySmoke() { super(MemoryQueryRunner::createQueryRunner); } @Test public void testCreateAndDropTable() throws SQLException { int tablesBeforeCreate = listMemoryTables().size(); assertUpdate("CREATE TABLE test AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertEquals(listMemoryTables().size(), tablesBeforeCreate + 1); assertUpdate("DROP TABLE test"); assertEquals(listMemoryTables().size(), tablesBeforeCreate); } // it has to be RuntimeException as FailureInfo$FailureException is private @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists") public void testCreateTableWhenTableIsAlreadyCreated() throws SQLException { @Language("SQL") String createTableSql = "CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation"; assertUpdate(createTableSql); } @Test public void testSelect() throws SQLException { assertUpdate("CREATE TABLE test_select AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertQuery("SELECT * FROM test_select ORDER BY nationkey", "SELECT * FROM nation ORDER BY nationkey"); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_select", 75L); } @Test public void testCreateTableWithNoData() throws SQLException { assertUpdate("CREATE TABLE test_empty (a BIGINT)"); assertQueryResult("SELECT count(*) FROM test_empty", 0L); assertQueryResult("INSERT INTO test_empty SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_empty", 25L); } @Test public void testCreateFilteredOutTable() throws SQLException { assertUpdate("CREATE TABLE filtered_out AS SELECT nationkey FROM tpch.tiny.nation WHERE nationkey < 0", "SELECT count(nationkey) FROM nation WHERE nationkey < 0"); assertQueryResult("SELECT count(*) FROM filtered_out", 0L); assertQueryResult("INSERT INTO filtered_out SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM filtered_out", 25L); } @Test public void testSelectFromEmptyTable() throws SQLException { assertUpdate("CREATE TABLE test_select_empty AS SELECT * FROM tpch.tiny.nation WHERE nationkey > 1000", "SELECT count(*) FROM nation WHERE nationkey > 1000"); assertQueryResult("SELECT count(*) FROM test_select_empty", 0L); } @Test public void testSelectSingleRow() { assertQuery("SELECT * FROM tpch.tiny.nation WHERE nationkey = 1", "SELECT * FROM nation WHERE nationkey = 1"); } @Test public void testSelectColumnsSubset() throws SQLException { assertQuery("SELECT nationkey, regionkey FROM tpch.tiny.nation ORDER BY nationkey", "SELECT nationkey, regionkey FROM nation ORDER BY nationkey"); } @Test public void testCreateTableInNonDefaultSchema() { assertUpdate(format("CREATE SCHEMA %s.schema1", CATALOG)); assertUpdate(format("CREATE SCHEMA %s.schema2", CATALOG)); assertQueryResult(format("SHOW SCHEMAS FROM %s", CATALOG), "default", "information_schema", "schema1", "schema2"); assertUpdate(format("CREATE TABLE %s.schema1.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey %% 2 = 0", CATALOG), "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 0"); assertUpdate(format("CREATE TABLE %s.schema2.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey %% 2 = 1", CATALOG), "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 1"); assertQueryResult(format("SELECT count(*) FROM %s.schema1.nation", CATALOG), 13L); assertQueryResult(format("SELECT count(*) FROM %s.schema2.nation", CATALOG), 12L); } @Test public void testViews() { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view AS SELECT 123 x"); assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query); assertQueryFails("CREATE TABLE test_view (x date)", "View \\[default.test_view] already exists"); assertQueryFails("CREATE VIEW test_view AS SELECT 123 x", "View already exists: default.test_view"); assertQuery("SELECT * FROM test_view", query); assertTrue(computeActual("SHOW TABLES").getOnlyColumnAsSet().contains("test_view")); assertUpdate("DROP VIEW test_view"); assertQueryFails("DROP VIEW test_view", "line 1:1: View 'memory.default.test_view' does not exist"); } private List<QualifiedObjectName> listMemoryTables() { return getQueryRunner().listTables(getSession(), "memory", "default"); } private void assertQueryResult(@Language("SQL") String sql, Object... expected) { MaterializedResult rows = computeActual(sql); assertEquals(rows.getRowCount(), expected.length); for (int i = 0; i < expected.length; i++) { MaterializedRow materializedRow = rows.getMaterializedRows().get(i); int fieldCount = materializedRow.getFieldCount(); assertTrue(fieldCount == 1, format("Expected only one column, but got '%d'", fieldCount)); Object value = materializedRow.getField(0); assertEquals(value, expected[i]); assertTrue(materializedRow.getFieldCount() == 1); } } }
apache-2.0
svn2github/pixels
src/main/java/com/jhlabs/composite/DarkenComposite.java
2072
/* Copyright 2006 Jerry Huxtable 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.jhlabs.composite; import java.awt.*; import java.awt.image.*; public final class DarkenComposite extends RGBComposite { public DarkenComposite( float alpha ) { super( alpha ); } public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints ) { return new Context( extraAlpha, srcColorModel, dstColorModel ); } static class Context extends RGBCompositeContext { public Context( float alpha, ColorModel srcColorModel, ColorModel dstColorModel ) { super( alpha, srcColorModel, dstColorModel ); } public void composeRGB( int[] src, int[] dst, float alpha ) { int w = src.length; for ( int i = 0; i < w; i += 4 ) { int sr = src[i]; int dir = dst[i]; int sg = src[i+1]; int dig = dst[i+1]; int sb = src[i+2]; int dib = dst[i+2]; int sa = src[i+3]; int dia = dst[i+3]; int dor, dog, dob; dor = dir < sr ? dir : sr; dog = dig < sg ? dig : sg; dob = dib < sb ? dib : sb; float a = alpha*sa/255f; float ac = 1-a; dst[i] = (int)(a*dor + ac*dir); dst[i+1] = (int)(a*dog + ac*dig); dst[i+2] = (int)(a*dob + ac*dib); dst[i+3] = (int)(sa*alpha + dia*ac); } } } }
apache-2.0
prasi-in/geode
geode-core/src/test/java/org/apache/geode/internal/cache/Bug34179TooManyFilesOpenJUnitTest.java
3252
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache; import java.io.File; import java.util.Arrays; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.LogWriter; import org.apache.geode.test.junit.categories.IntegrationTest; /** * Disk region perf test for Persist only with Async writes and Buffer. Set Rolling oplog to true * and setMaxOplogSize to 10240 * * If more than some number of files are open, an Exception is thrown. This ia JDK 1.4 bug. This * test should be run after transition to JDK 1.5 to verify that the bug does not exceed. * * The disk properties will ensure that very many oplog files are created. * * This test is currently not being executed and is marked with an underscore */ @Category(IntegrationTest.class) public class Bug34179TooManyFilesOpenJUnitTest extends DiskRegionTestingBase { private static int ENTRY_SIZE = 1024; private static int OP_COUNT = 100000; private LogWriter log = null; private DiskRegionProperties diskProps = new DiskRegionProperties(); @Override protected final void postSetUp() throws Exception { File file1 = new File("testingDirectory/" + getName() + "1"); file1.mkdir(); file1.deleteOnExit(); dirs = new File[1]; dirs[0] = file1; diskProps.setDiskDirs(dirs); diskProps.setPersistBackup(true); diskProps.setTimeInterval(15000l); diskProps.setBytesThreshold(10000l); diskProps.setRolling(true); // set max oplog size as 10 kb diskProps.setMaxOplogSize(10240); region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskProps); log = ds.getLogWriter(); } /** * currently not being executed for congo but after transition to JDK 1.5, this test should be * executed. */ @Ignore("TODO: test is disabled") @Test public void testPopulate1kbwrites() { final byte[] value = new byte[ENTRY_SIZE]; Arrays.fill(value, (byte) 77); for (int i = 0; i < OP_COUNT; i++) { region.put(new Integer(i), value); } closeDown(); // closes disk file which will flush all buffers } /** * cleans all the directory of all the files present in them */ protected static void deleteFiles() { for (int i = 0; i < dirs.length; i++) { File[] files = dirs[i].listFiles(); for (int j = 0; j < files.length; j++) { files[j].delete(); } } } }// end of Bug34179TooManyFilesOpenJUnitTest
apache-2.0
lukecwik/incubator-beam
sdks/java/extensions/sql/src/test/java/org/apache/beam/sdk/extensions/sql/impl/planner/NodeStatsTest.java
3793
/* * 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.beam.sdk.extensions.sql.impl.planner; import org.apache.beam.sdk.extensions.sql.impl.rel.BaseRelTest; import org.apache.beam.sdk.extensions.sql.impl.rel.BeamSqlRelUtils; import org.apache.beam.sdk.extensions.sql.meta.provider.test.TestBoundedTable; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelOptCluster; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelTraitSet; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.volcano.RelSubset; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.RelNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.SingleRel; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** This tests the NodeStats Metadata handler and the estimations. */ public class NodeStatsTest extends BaseRelTest { static class UnknownRel extends SingleRel { protected UnknownRel(RelOptCluster cluster, RelTraitSet traits, RelNode input) { super(cluster, traits, input); } } public static final TestBoundedTable ORDER_DETAILS1 = TestBoundedTable.of( Schema.FieldType.INT32, "order_id", Schema.FieldType.INT32, "site_id", Schema.FieldType.INT32, "price") .addRows(1, 2, 3, 2, 3, 3, 3, 4, 5); public static final TestBoundedTable ORDER_DETAILS2 = TestBoundedTable.of( Schema.FieldType.INT32, "order_id", Schema.FieldType.INT32, "site_id", Schema.FieldType.INT32, "price") .addRows(1, 2, 3, 2, 3, 3, 3, 4, 5); @BeforeClass public static void prepare() { registerTable("ORDER_DETAILS1", ORDER_DETAILS1); registerTable("ORDER_DETAILS2", ORDER_DETAILS2); } @Test public void testUnknownRel() { String sql = " select * from ORDER_DETAILS1 "; RelNode root = env.parseQuery(sql); RelNode unknown = new UnknownRel(root.getCluster(), null, null); NodeStats nodeStats = unknown .metadata(NodeStatsMetadata.class, unknown.getCluster().getMetadataQuery()) .getNodeStats(); Assert.assertTrue(nodeStats.isUnknown()); } @Test public void testKnownRel() { String sql = " select * from ORDER_DETAILS1 "; RelNode root = env.parseQuery(sql); NodeStats nodeStats = root.metadata(NodeStatsMetadata.class, root.getCluster().getMetadataQuery()).getNodeStats(); Assert.assertFalse(nodeStats.isUnknown()); } @Test public void testSubsetHavingBest() { String sql = " select * from ORDER_DETAILS1 "; RelNode root = env.parseQuery(sql); root = root.getCluster().getPlanner().getRoot(); // tests if we are actually testing what we want. Assert.assertTrue(root instanceof RelSubset); NodeStats estimates = BeamSqlRelUtils.getNodeStats(root, root.getCluster().getMetadataQuery()); Assert.assertFalse(estimates.isUnknown()); } }
apache-2.0
yinkaf/robovm-samples
ContractRFX/core/src/main/java/org/robovm/samples/contractr/core/service/ConnectionPool.java
811
/* * Copyright (C) 2014 RoboVM AB * * 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.robovm.samples.contractr.core.service; import java.sql.Connection; import java.sql.SQLException; /** * */ public interface ConnectionPool { Connection getConnection() throws SQLException; }
apache-2.0
asedunov/intellij-community
jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java
18700
/* * Copyright 2000-2017 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 org.jetbrains.jps.model.serialization; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.concurrency.BoundedTaskExecutor; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.TimingLog; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsElement; import org.jetbrains.jps.model.JpsElementFactory; import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.java.JpsJavaModuleType; import org.jetbrains.jps.model.library.sdk.JpsSdkType; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.model.serialization.artifact.JpsArtifactSerializer; import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer; import org.jetbrains.jps.model.serialization.impl.JpsModuleSerializationDataExtensionImpl; import org.jetbrains.jps.model.serialization.impl.JpsProjectSerializationDataExtensionImpl; import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer; import org.jetbrains.jps.model.serialization.library.JpsSdkTableSerializer; import org.jetbrains.jps.model.serialization.module.JpsModuleClasspathSerializer; import org.jetbrains.jps.model.serialization.module.JpsModulePropertiesSerializer; import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer; import org.jetbrains.jps.model.serialization.runConfigurations.JpsRunConfigurationSerializer; import org.jetbrains.jps.service.SharedThreadPool; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.Future; import java.util.stream.Stream; /** * @author nik */ public class JpsProjectLoader extends JpsLoaderBase { private static final Logger LOG = Logger.getInstance(JpsProjectLoader.class); private static final BoundedTaskExecutor ourThreadPool = new BoundedTaskExecutor("JpsProjectLoader pool",SharedThreadPool.getInstance(), Runtime.getRuntime().availableProcessors()); public static final String CLASSPATH_ATTRIBUTE = "classpath"; public static final String CLASSPATH_DIR_ATTRIBUTE = "classpath-dir"; private final JpsProject myProject; private final Map<String, String> myPathVariables; private JpsProjectLoader(JpsProject project, Map<String, String> pathVariables, Path baseDir) { super(createProjectMacroExpander(pathVariables, baseDir)); myProject = project; myPathVariables = pathVariables; myProject.getContainer().setChild(JpsProjectSerializationDataExtensionImpl.ROLE, new JpsProjectSerializationDataExtensionImpl(baseDir)); } static JpsMacroExpander createProjectMacroExpander(Map<String, String> pathVariables, @NotNull Path baseDir) { final JpsMacroExpander expander = new JpsMacroExpander(pathVariables); expander.addFileHierarchyReplacements(PathMacroUtil.PROJECT_DIR_MACRO_NAME, baseDir.toFile()); return expander; } public static void loadProject(final JpsProject project, Map<String, String> pathVariables, String projectPath) throws IOException { Path file = Paths.get(FileUtil.toCanonicalPath(projectPath)); if (Files.isRegularFile(file) && projectPath.endsWith(".ipr")) { new JpsProjectLoader(project, pathVariables, file.getParent()).loadFromIpr(file); } else { Path dotIdea = file.resolve(PathMacroUtil.DIRECTORY_STORE_NAME); Path directory; if (Files.isDirectory(dotIdea)) { directory = dotIdea; } else if (Files.isDirectory(file) && file.endsWith(PathMacroUtil.DIRECTORY_STORE_NAME)) { directory = file; } else { throw new IOException("Cannot find IntelliJ IDEA project files at " + projectPath); } new JpsProjectLoader(project, pathVariables, directory.getParent()).loadFromDirectory(directory); } } @NotNull public static String getDirectoryBaseProjectName(@NotNull Path dir) { try (Stream<String> stream = Files.lines(dir.resolve(".name"))) { String value = stream.findFirst().map(String::trim).orElse(null); if (value != null) { return value; } } catch (IOException ignored) { } return dir.getParent().getFileName().toString(); } private void loadFromDirectory(@NotNull Path dir) { myProject.setName(getDirectoryBaseProjectName(dir)); Path defaultConfigFile = dir.resolve("misc.xml"); JpsSdkType<?> projectSdkType = loadProjectRoot(loadRootElement(defaultConfigFile)); for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) { loadComponents(dir, defaultConfigFile, serializer, myProject); } } Path workspaceFile = dir.resolve("workspace.xml"); loadModules(loadRootElement(dir.resolve("modules.xml")), projectSdkType, workspaceFile); Runnable timingLog = TimingLog.startActivity("loading project libraries"); for (Path libraryFile : listXmlFiles(dir.resolve("libraries"))) { loadProjectLibraries(loadRootElement(libraryFile)); } Path externalConfigDir = resolveExternalProjectConfig("project"); if (externalConfigDir != null) { LOG.info("External project config dir is used: " + externalConfigDir); loadProjectLibraries(loadRootElement(externalConfigDir.resolve("libraries.xml"))); } timingLog.run(); Runnable artifactsTimingLog = TimingLog.startActivity("loading artifacts"); for (Path artifactFile : listXmlFiles(dir.resolve("artifacts"))) { loadArtifacts(loadRootElement(artifactFile)); } artifactsTimingLog.run(); if (hasRunConfigurationSerializers()) { Runnable runConfTimingLog = TimingLog.startActivity("loading run configurations"); for (Path configurationFile : listXmlFiles(dir.resolve("runConfigurations"))) { JpsRunConfigurationSerializer.loadRunConfigurations(myProject, loadRootElement(configurationFile)); } JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(loadRootElement(workspaceFile), "RunManager")); runConfTimingLog.run(); } } private static boolean hasRunConfigurationSerializers() { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { if (!extension.getRunConfigurationPropertiesSerializers().isEmpty()) { return true; } } return false; } @NotNull private static List<Path> listXmlFiles(@NotNull Path dir) { try { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, it -> it.getFileName().toString().endsWith(".xml") && Files.isRegularFile(it))) { return ContainerUtil.collect(stream.iterator()); } } catch (IOException e) { return Collections.emptyList(); } } private void loadFromIpr(@NotNull Path iprFile) { final Element iprRoot = loadRootElement(iprFile); String projectName = FileUtil.getNameWithoutExtension(iprFile.getFileName().toString()); myProject.setName(projectName); Path iwsFile = iprFile.getParent().resolve(projectName + ".iws"); Element iwsRoot = loadRootElement(iwsFile); JpsSdkType<?> projectSdkType = loadProjectRoot(iprRoot); for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) { Element rootTag = JpsProjectExtensionSerializer.WORKSPACE_FILE.equals(serializer.getConfigFileName()) ? iwsRoot : iprRoot; Element component = JDomSerializationUtil.findComponent(rootTag, serializer.getComponentName()); if (component != null) { serializer.loadExtension(myProject, component); } else { serializer.loadExtensionWithDefaultSettings(myProject); } } } loadModules(iprRoot, projectSdkType, iwsFile); loadProjectLibraries(JDomSerializationUtil.findComponent(iprRoot, "libraryTable")); loadArtifacts(JDomSerializationUtil.findComponent(iprRoot, "ArtifactManager")); if (hasRunConfigurationSerializers()) { JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iprRoot, "ProjectRunConfigurationManager")); JpsRunConfigurationSerializer.loadRunConfigurations(myProject, JDomSerializationUtil.findComponent(iwsRoot, "RunManager")); } } private void loadArtifacts(@Nullable Element artifactManagerComponent) { JpsArtifactSerializer.loadArtifacts(myProject, artifactManagerComponent); } @Nullable private JpsSdkType<?> loadProjectRoot(@Nullable Element root) { JpsSdkType<?> sdkType = null; Element rootManagerElement = JDomSerializationUtil.findComponent(root, "ProjectRootManager"); if (rootManagerElement != null) { String sdkName = rootManagerElement.getAttributeValue("project-jdk-name"); String sdkTypeId = rootManagerElement.getAttributeValue("project-jdk-type"); if (sdkName != null) { sdkType = JpsSdkTableSerializer.getSdkType(sdkTypeId); JpsSdkTableSerializer.setSdkReference(myProject.getSdkReferencesTable(), sdkName, sdkType); } } return sdkType; } private void loadProjectLibraries(@Nullable Element libraryTableElement) { JpsLibraryTableSerializer.loadLibraries(libraryTableElement, myProject.getLibraryCollection()); } private void loadModules(@Nullable Element root, final @Nullable JpsSdkType<?> projectSdkType, Path workspaceFile) { Runnable timingLog = TimingLog.startActivity("loading modules"); Element componentRoot = JDomSerializationUtil.findComponent(root, "ProjectModuleManager"); if (componentRoot == null) return; Set<String> unloadedModules = new HashSet<>(); if (Files.exists(workspaceFile)) { Element unloadedModulesList = JDomSerializationUtil.findComponent(loadRootElement(workspaceFile), "UnloadedModulesList"); for (Element element : JDOMUtil.getChildren(unloadedModulesList, "module")) { unloadedModules.add(element.getAttributeValue("name")); } } final Set<Path> foundFiles = new THashSet<>(); final List<Path> moduleFiles = new ArrayList<>(); for (Element moduleElement : JDOMUtil.getChildren(componentRoot.getChild("modules"), "module")) { final String path = moduleElement.getAttributeValue("filepath"); final Path file = Paths.get(path); if (foundFiles.add(file) && !unloadedModules.contains(getModuleName(file))) { moduleFiles.add(file); } } List<JpsModule> modules = loadModules(moduleFiles, projectSdkType, myPathVariables); for (JpsModule module : modules) { myProject.addModule(module); } timingLog.run(); } @Nullable private static Path resolveExternalProjectConfig(@NotNull String subDirName) { String externalProjectConfigDir = System.getProperty("external.project.config"); return StringUtil.isEmptyOrSpaces(externalProjectConfigDir) ? null : Paths.get(externalProjectConfigDir, subDirName); } @NotNull public static List<JpsModule> loadModules(@NotNull List<Path> moduleFiles, @Nullable final JpsSdkType<?> projectSdkType, @NotNull final Map<String, String> pathVariables) { List<JpsModule> modules = new ArrayList<>(); List<Future<Pair<Path, Element>>> futureModuleFilesContents = new ArrayList<>(); Path externalModuleDir = resolveExternalProjectConfig("modules"); if (externalModuleDir != null) { LOG.info("External project config dir is used for modules: " + externalModuleDir); } for (Path file : moduleFiles) { futureModuleFilesContents.add(ourThreadPool.submit(() -> { final JpsMacroExpander expander = createModuleMacroExpander(pathVariables, file); Element data = loadRootElement(file, expander); Path externalPath = externalModuleDir == null ? null : externalModuleDir.resolve(FileUtilRt.getNameWithoutExtension(file.getFileName().toString()) + ".xml"); Element externalData = externalPath == null ? null : loadRootElement(externalPath, expander); if (externalData != null) { if (data == null) { data = externalData; } else { JDOMUtil.merge(data, externalData); } } if (data == null) { LOG.info("Module '" + getModuleName(file) + "' is skipped: " + file.toAbsolutePath() + " doesn't exist"); } return Pair.create(file, data); })); } try { final List<String> classpathDirs = new ArrayList<>(); for (Future<Pair<Path, Element>> moduleFile : futureModuleFilesContents) { Element rootElement = moduleFile.get().getSecond(); if (rootElement != null) { final String classpathDir = rootElement.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE); if (classpathDir != null) { classpathDirs.add(classpathDir); } } } List<Future<JpsModule>> futures = new ArrayList<>(); for (final Future<Pair<Path, Element>> futureModuleFile : futureModuleFilesContents) { final Pair<Path, Element> moduleFile = futureModuleFile.get(); if (moduleFile.getSecond() != null) { futures.add(ourThreadPool.submit( () -> loadModule(moduleFile.getFirst(), moduleFile.getSecond(), classpathDirs, projectSdkType, pathVariables))); } } for (Future<JpsModule> future : futures) { JpsModule module = future.get(); if (module != null) { modules.add(module); } } return modules; } catch (Exception e) { throw new RuntimeException(e); } } @NotNull private static JpsModule loadModule(@NotNull Path file, @NotNull Element moduleRoot, List<String> paths, @Nullable JpsSdkType<?> projectSdkType, Map<String, String> pathVariables) { String name = getModuleName(file); final String typeId = moduleRoot.getAttributeValue("type"); final JpsModulePropertiesSerializer<?> serializer = getModulePropertiesSerializer(typeId); final JpsModule module = createModule(name, moduleRoot, serializer); module.getContainer().setChild(JpsModuleSerializationDataExtensionImpl.ROLE, new JpsModuleSerializationDataExtensionImpl(file.getParent())); for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { extension.loadModuleOptions(module, moduleRoot); } String baseModulePath = FileUtil.toSystemIndependentName(file.getParent().toString()); String classpath = moduleRoot.getAttributeValue(CLASSPATH_ATTRIBUTE); if (classpath == null) { JpsModuleRootModelSerializer.loadRootModel(module, JDomSerializationUtil.findComponent(moduleRoot, "NewModuleRootManager"), projectSdkType); } else { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { JpsModuleClasspathSerializer classpathSerializer = extension.getClasspathSerializer(); if (classpathSerializer != null && classpathSerializer.getClasspathId().equals(classpath)) { String classpathDir = moduleRoot.getAttributeValue(CLASSPATH_DIR_ATTRIBUTE); final JpsMacroExpander expander = createModuleMacroExpander(pathVariables, file); classpathSerializer.loadClasspath(module, classpathDir, baseModulePath, expander, paths, projectSdkType); } } } JpsFacetSerializer.loadFacets(module, JDomSerializationUtil.findComponent(moduleRoot, "FacetManager")); return module; } @NotNull private static String getModuleName(@NotNull Path file) { return FileUtil.getNameWithoutExtension(file.getFileName().toString()); } static JpsMacroExpander createModuleMacroExpander(final Map<String, String> pathVariables, @NotNull Path moduleFile) { final JpsMacroExpander expander = new JpsMacroExpander(pathVariables); String moduleDirPath = PathMacroUtil.getModuleDir(moduleFile.toAbsolutePath().toString()); if (moduleDirPath != null) { expander.addFileHierarchyReplacements(PathMacroUtil.MODULE_DIR_MACRO_NAME, new File(FileUtil.toSystemDependentName(moduleDirPath))); } return expander; } private static <P extends JpsElement> JpsModule createModule(String name, Element moduleRoot, JpsModulePropertiesSerializer<P> loader) { String componentName = loader.getComponentName(); Element component = componentName != null ? JDomSerializationUtil.findComponent(moduleRoot, componentName) : null; return JpsElementFactory.getInstance().createModule(name, loader.getType(), loader.loadProperties(component)); } private static JpsModulePropertiesSerializer<?> getModulePropertiesSerializer(@Nullable String typeId) { for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsModulePropertiesSerializer<?> loader : extension.getModulePropertiesSerializers()) { if (loader.getTypeId().equals(typeId)) { return loader; } } } return new JpsModulePropertiesSerializer<JpsDummyElement>(JpsJavaModuleType.INSTANCE, "JAVA_MODULE", null) { @Override public JpsDummyElement loadProperties(@Nullable Element componentElement) { return JpsElementFactory.getInstance().createDummyElement(); } @Override public void saveProperties(@NotNull JpsDummyElement properties, @NotNull Element componentElement) { } }; } }
apache-2.0
darina/omim
android/src/com/mapswithme/maps/ChartController.java
9370
package com.mapswithme.maps; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.MarkerView; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.formatter.ValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.mapswithme.maps.base.Hideable; import com.mapswithme.maps.base.Initializable; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.ElevationInfo; import com.mapswithme.maps.widget.placepage.AxisValueFormatter; import com.mapswithme.maps.widget.placepage.CurrentLocationMarkerView; import com.mapswithme.maps.widget.placepage.FloatingMarkerView; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; public class ChartController implements OnChartValueSelectedListener, Initializable<View>, BookmarkManager.OnElevationActivePointChangedListener, BookmarkManager.OnElevationCurrentPositionChangedListener, Hideable { private static final int CHART_Y_LABEL_COUNT = 3; private static final int CHART_X_LABEL_COUNT = 6; private static final int CHART_ANIMATION_DURATION = 1500; private static final int CHART_FILL_ALPHA = (int) (0.12 * 255); private static final int CHART_AXIS_GRANULARITY = 100; private static final float CUBIC_INTENSITY = 0.2f; private static final int CURRENT_POSITION_OUT_OF_TRACK = -1; @SuppressWarnings("NullableProblems") @NonNull private LineChart mChart; @SuppressWarnings("NullableProblems") @NonNull private FloatingMarkerView mFloatingMarkerView; @SuppressWarnings("NullableProblems") @NonNull private MarkerView mCurrentLocationMarkerView; @SuppressWarnings("NullableProblems") @NonNull private TextView mMaxAltitude; @SuppressWarnings("NullableProblems") @NonNull private TextView mMinAltitude; @NonNull private final Context mContext; private long mTrackId = Utils.INVALID_ID; private boolean mCurrentPositionOutOfTrack = true; public ChartController(@NonNull Context context) { mContext = context; } @Override public void initialize(@Nullable View view) { Objects.requireNonNull(view); BookmarkManager.INSTANCE.setElevationActivePointChangedListener(this); BookmarkManager.INSTANCE.setElevationCurrentPositionChangedListener(this); final Resources resources = mContext.getResources(); mChart = view.findViewById(R.id.elevation_profile_chart); mFloatingMarkerView = view.findViewById(R.id.floating_marker); mCurrentLocationMarkerView = new CurrentLocationMarkerView(mContext); mFloatingMarkerView.setChartView(mChart); mCurrentLocationMarkerView.setChartView(mChart); mMaxAltitude = view.findViewById(R.id.highest_altitude); mMinAltitude = view.findViewById(R.id.lowest_altitude); mChart.setBackgroundColor(ThemeUtils.getColor(mContext, R.attr.cardBackground)); mChart.setTouchEnabled(true); mChart.setOnChartValueSelectedListener(this); mChart.setDrawGridBackground(false); mChart.setScaleXEnabled(true); mChart.setScaleYEnabled(false); mChart.setExtraTopOffset(0); int sideOffset = resources.getDimensionPixelSize(R.dimen.margin_base); int topOffset = 0; mChart.setViewPortOffsets(sideOffset, topOffset, sideOffset, resources.getDimensionPixelSize(R.dimen.margin_base_plus_quarter)); mChart.getDescription().setEnabled(false); mChart.setDrawBorders(false); Legend l = mChart.getLegend(); l.setEnabled(false); initAxises(); } @Override public void destroy() { BookmarkManager.INSTANCE.setElevationActivePointChangedListener(null); BookmarkManager.INSTANCE.setElevationCurrentPositionChangedListener(null); } private void highlightChartCurrentLocation() { mChart.highlightValues(Collections.singletonList(getCurrentPosHighlight()), Collections.singletonList(mCurrentLocationMarkerView)); } private void initAxises() { XAxis x = mChart.getXAxis(); x.setLabelCount(CHART_X_LABEL_COUNT, false); x.setDrawGridLines(false); x.setGranularity(CHART_AXIS_GRANULARITY); x.setGranularityEnabled(true); x.setTextColor(ThemeUtils.getColor(mContext, R.attr.elevationProfileAxisLabelColor)); x.setPosition(XAxis.XAxisPosition.BOTTOM); x.setAxisLineColor(ThemeUtils.getColor(mContext, R.attr.dividerHorizontal)); x.setAxisLineWidth(mContext.getResources().getDimensionPixelSize(R.dimen.divider_height)); ValueFormatter xAxisFormatter = new AxisValueFormatter(mChart); x.setValueFormatter(xAxisFormatter); YAxis y = mChart.getAxisLeft(); y.setLabelCount(CHART_Y_LABEL_COUNT, false); y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); y.setDrawGridLines(true); y.setGridColor(mContext.getResources().getColor(R.color.black_12)); y.setEnabled(true); y.setTextColor(Color.TRANSPARENT); y.setAxisLineColor(Color.TRANSPARENT); int lineLength = mContext.getResources().getDimensionPixelSize(R.dimen.margin_eighth); y.enableGridDashedLine(lineLength, 2 * lineLength, 0); mChart.getAxisRight().setEnabled(false); } public void setData(@NonNull ElevationInfo info) { mTrackId = info.getId(); List<Entry> values = new ArrayList<>(); for (ElevationInfo.Point point: info.getPoints()) values.add(new Entry((float) point.getDistance(), point.getAltitude())); LineDataSet set = new LineDataSet(values, "Elevation_profile_points"); set.setMode(LineDataSet.Mode.CUBIC_BEZIER); set.setCubicIntensity(CUBIC_INTENSITY); set.setDrawFilled(true); set.setDrawCircles(false); int lineThickness = mContext.getResources().getDimensionPixelSize(R.dimen.divider_width); set.setLineWidth(lineThickness); int color = ThemeUtils.getColor(mContext, R.attr.elevationProfileColor); set.setCircleColor(color); set.setColor(color); set.setFillAlpha(CHART_FILL_ALPHA); set.setFillColor(color); set.setDrawHorizontalHighlightIndicator(false); set.setHighlightLineWidth(lineThickness); set.setHighLightColor(mContext.getResources().getColor(R.color.base_accent_transparent)); LineData data = new LineData(set); data.setValueTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.text_size_icon_title)); data.setDrawValues(false); mChart.setData(data); mChart.animateX(CHART_ANIMATION_DURATION); mMinAltitude.setText(Framework.nativeFormatAltitude(info.getMinAltitude())); mMaxAltitude.setText(Framework.nativeFormatAltitude(info.getMaxAltitude())); highlightActivePointManually(); } @Override public void onValueSelected(Entry e, Highlight h) { mFloatingMarkerView.updateOffsets(e, h); Highlight curPos = getCurrentPosHighlight(); if (mCurrentPositionOutOfTrack) mChart.highlightValues(Collections.singletonList(h), Collections.singletonList(mFloatingMarkerView)); else mChart.highlightValues(Arrays.asList(curPos, h), Arrays.asList(mCurrentLocationMarkerView, mFloatingMarkerView)); if (mTrackId == Utils.INVALID_ID) return; BookmarkManager.INSTANCE.setElevationActivePoint(mTrackId, e.getX()); } @NonNull private Highlight getCurrentPosHighlight() { double activeX = BookmarkManager.INSTANCE.getElevationCurPositionDistance(mTrackId); return new Highlight((float) activeX, 0f, 0); } @Override public void onNothingSelected() { if (mCurrentPositionOutOfTrack) return; highlightChartCurrentLocation(); } @Override public void onCurrentPositionChanged() { if (mTrackId == Utils.INVALID_ID) return; double distance = BookmarkManager.INSTANCE.getElevationCurPositionDistance(mTrackId); mCurrentPositionOutOfTrack = distance == CURRENT_POSITION_OUT_OF_TRACK; highlightActivePointManually(); } @Override public void onElevationActivePointChanged() { if (mTrackId == Utils.INVALID_ID) return; highlightActivePointManually(); } private void highlightActivePointManually() { Highlight highlight = getActivePoint(); mChart.highlightValue(highlight, true); } @NonNull private Highlight getActivePoint() { double activeX = BookmarkManager.INSTANCE.getElevationActivePointDistance(mTrackId); return new Highlight((float) activeX, 0f, 0); } @Override public void onHide() { mChart.fitScreen(); mTrackId = Utils.INVALID_ID; } }
apache-2.0
nutzam/nutz
test/org/nutz/dao/test/meta/other/UpdateClobBlobBean.java
746
package org.nutz.dao.test.meta.other; import java.sql.Blob; import java.sql.Clob; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; @Table("t_update_clob_blob") public class UpdateClobBlobBean { @Id private int id; private Clob manytext; private Blob manybinary; public int getId() { return id; } public void setId(int id) { this.id = id; } public Clob getManytext() { return manytext; } public void setManytext(Clob manytext) { this.manytext = manytext; } public Blob getManybinary() { return manybinary; } public void setManybinary(Blob manybinary) { this.manybinary = manybinary; } }
apache-2.0
stoksey69/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201408/ObjectFactory.java
94549
package com.google.api.ads.dfp.jaxws.v201408; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.google.api.ads.dfp.jaxws.v201408 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _ResponseHeader_QNAME = new QName("https://www.google.com/apis/ads/publisher/v201408", "ResponseHeader"); private final static QName _ApiExceptionFault_QNAME = new QName("https://www.google.com/apis/ads/publisher/v201408", "ApiExceptionFault"); private final static QName _RequestHeader_QNAME = new QName("https://www.google.com/apis/ads/publisher/v201408", "RequestHeader"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.google.api.ads.dfp.jaxws.v201408 * */ public ObjectFactory() { } /** * Create an instance of {@link SoapResponseHeader } * */ public SoapResponseHeader createSoapResponseHeader() { return new SoapResponseHeader(); } /** * Create an instance of {@link GetAdUnitSizesByStatementResponse } * */ public GetAdUnitSizesByStatementResponse createGetAdUnitSizesByStatementResponse() { return new GetAdUnitSizesByStatementResponse(); } /** * Create an instance of {@link AdUnitSize } * */ public AdUnitSize createAdUnitSize() { return new AdUnitSize(); } /** * Create an instance of {@link UpdateAdUnitsResponse } * */ public UpdateAdUnitsResponse createUpdateAdUnitsResponse() { return new UpdateAdUnitsResponse(); } /** * Create an instance of {@link AdUnit } * */ public AdUnit createAdUnit() { return new AdUnit(); } /** * Create an instance of {@link GetAdUnitSizesByStatement } * */ public GetAdUnitSizesByStatement createGetAdUnitSizesByStatement() { return new GetAdUnitSizesByStatement(); } /** * Create an instance of {@link Statement } * */ public Statement createStatement() { return new Statement(); } /** * Create an instance of {@link ApiException } * */ public ApiException createApiException() { return new ApiException(); } /** * Create an instance of {@link PerformAdUnitActionResponse } * */ public PerformAdUnitActionResponse createPerformAdUnitActionResponse() { return new PerformAdUnitActionResponse(); } /** * Create an instance of {@link UpdateResult } * */ public UpdateResult createUpdateResult() { return new UpdateResult(); } /** * Create an instance of {@link GetAdUnitsByStatement } * */ public GetAdUnitsByStatement createGetAdUnitsByStatement() { return new GetAdUnitsByStatement(); } /** * Create an instance of {@link PerformAdUnitAction } * */ public PerformAdUnitAction createPerformAdUnitAction() { return new PerformAdUnitAction(); } /** * Create an instance of {@link GetAdUnitsByStatementResponse } * */ public GetAdUnitsByStatementResponse createGetAdUnitsByStatementResponse() { return new GetAdUnitsByStatementResponse(); } /** * Create an instance of {@link AdUnitPage } * */ public AdUnitPage createAdUnitPage() { return new AdUnitPage(); } /** * Create an instance of {@link CreateAdUnits } * */ public CreateAdUnits createCreateAdUnits() { return new CreateAdUnits(); } /** * Create an instance of {@link SoapRequestHeader } * */ public SoapRequestHeader createSoapRequestHeader() { return new SoapRequestHeader(); } /** * Create an instance of {@link UpdateAdUnits } * */ public UpdateAdUnits createUpdateAdUnits() { return new UpdateAdUnits(); } /** * Create an instance of {@link CreateAdUnitsResponse } * */ public CreateAdUnitsResponse createCreateAdUnitsResponse() { return new CreateAdUnitsResponse(); } /** * Create an instance of {@link TemplateCreative } * */ public TemplateCreative createTemplateCreative() { return new TemplateCreative(); } /** * Create an instance of {@link ReserveAndOverbookLineItems } * */ public ReserveAndOverbookLineItems createReserveAndOverbookLineItems() { return new ReserveAndOverbookLineItems(); } /** * Create an instance of {@link VastRedirectCreative } * */ public VastRedirectCreative createVastRedirectCreative() { return new VastRedirectCreative(); } /** * Create an instance of {@link ReportDownloadOptions } * */ public ReportDownloadOptions createReportDownloadOptions() { return new ReportDownloadOptions(); } /** * Create an instance of {@link ExchangeRateError } * */ public ExchangeRateError createExchangeRateError() { return new ExchangeRateError(); } /** * Create an instance of {@link Size } * */ public Size createSize() { return new Size(); } /** * Create an instance of {@link Product } * */ public Product createProduct() { return new Product(); } /** * Create an instance of {@link UnarchiveOrders } * */ public UnarchiveOrders createUnarchiveOrders() { return new UnarchiveOrders(); } /** * Create an instance of {@link AvailableBillingError } * */ public AvailableBillingError createAvailableBillingError() { return new AvailableBillingError(); } /** * Create an instance of {@link ProposalPage } * */ public ProposalPage createProposalPage() { return new ProposalPage(); } /** * Create an instance of {@link SubmitOrdersForApproval } * */ public SubmitOrdersForApproval createSubmitOrdersForApproval() { return new SubmitOrdersForApproval(); } /** * Create an instance of {@link VideoPositionWithinPod } * */ public VideoPositionWithinPod createVideoPositionWithinPod() { return new VideoPositionWithinPod(); } /** * Create an instance of {@link InternalRedirectCreative } * */ public InternalRedirectCreative createInternalRedirectCreative() { return new InternalRedirectCreative(); } /** * Create an instance of {@link ResultSet } * */ public ResultSet createResultSet() { return new ResultSet(); } /** * Create an instance of {@link ActivityGroup } * */ public ActivityGroup createActivityGroup() { return new ActivityGroup(); } /** * Create an instance of {@link LineItemCreativeAssociationError } * */ public LineItemCreativeAssociationError createLineItemCreativeAssociationError() { return new LineItemCreativeAssociationError(); } /** * Create an instance of {@link CreativeSet } * */ public CreativeSet createCreativeSet() { return new CreativeSet(); } /** * Create an instance of {@link OperatingSystemVersionTargeting } * */ public OperatingSystemVersionTargeting createOperatingSystemVersionTargeting() { return new OperatingSystemVersionTargeting(); } /** * Create an instance of {@link PackageActionError } * */ public PackageActionError createPackageActionError() { return new PackageActionError(); } /** * Create an instance of {@link ReportQuery } * */ public ReportQuery createReportQuery() { return new ReportQuery(); } /** * Create an instance of {@link CreativeTemplate } * */ public CreativeTemplate createCreativeTemplate() { return new CreativeTemplate(); } /** * Create an instance of {@link TemplateInstantiatedCreativeError } * */ public TemplateInstantiatedCreativeError createTemplateInstantiatedCreativeError() { return new TemplateInstantiatedCreativeError(); } /** * Create an instance of {@link SalespersonSplit } * */ public SalespersonSplit createSalespersonSplit() { return new SalespersonSplit(); } /** * Create an instance of {@link AudienceSegmentPremiumFeature } * */ public AudienceSegmentPremiumFeature createAudienceSegmentPremiumFeature() { return new AudienceSegmentPremiumFeature(); } /** * Create an instance of {@link AssignAdUnitsToPlacement } * */ public AssignAdUnitsToPlacement createAssignAdUnitsToPlacement() { return new AssignAdUnitsToPlacement(); } /** * Create an instance of {@link ReconciliationReportPage } * */ public ReconciliationReportPage createReconciliationReportPage() { return new ReconciliationReportPage(); } /** * Create an instance of {@link PublisherQueryLanguageContextError } * */ public PublisherQueryLanguageContextError createPublisherQueryLanguageContextError() { return new PublisherQueryLanguageContextError(); } /** * Create an instance of {@link ContentMetadataTargetingError } * */ public ContentMetadataTargetingError createContentMetadataTargetingError() { return new ContentMetadataTargetingError(); } /** * Create an instance of {@link ActivateLineItems } * */ public ActivateLineItems createActivateLineItems() { return new ActivateLineItems(); } /** * Create an instance of {@link NoPoddingAdRuleSlot } * */ public NoPoddingAdRuleSlot createNoPoddingAdRuleSlot() { return new NoPoddingAdRuleSlot(); } /** * Create an instance of {@link DeactivateAdUnits } * */ public DeactivateAdUnits createDeactivateAdUnits() { return new DeactivateAdUnits(); } /** * Create an instance of {@link UnsupportedCreative } * */ public UnsupportedCreative createUnsupportedCreative() { return new UnsupportedCreative(); } /** * Create an instance of {@link ProductActionError } * */ public ProductActionError createProductActionError() { return new ProductActionError(); } /** * Create an instance of {@link ContentMetadataKeyHierarchyPage } * */ public ContentMetadataKeyHierarchyPage createContentMetadataKeyHierarchyPage() { return new ContentMetadataKeyHierarchyPage(); } /** * Create an instance of {@link AdMobBackfillCreative } * */ public AdMobBackfillCreative createAdMobBackfillCreative() { return new AdMobBackfillCreative(); } /** * Create an instance of {@link DeactivateRateCards } * */ public DeactivateRateCards createDeactivateRateCards() { return new DeactivateRateCards(); } /** * Create an instance of {@link CustomFieldError } * */ public CustomFieldError createCustomFieldError() { return new CustomFieldError(); } /** * Create an instance of {@link AdSenseAccountError } * */ public AdSenseAccountError createAdSenseAccountError() { return new AdSenseAccountError(); } /** * Create an instance of {@link PlacementTargeting } * */ public PlacementTargeting createPlacementTargeting() { return new PlacementTargeting(); } /** * Create an instance of {@link DeleteLineItems } * */ public DeleteLineItems createDeleteLineItems() { return new DeleteLineItems(); } /** * Create an instance of {@link DeleteAdRules } * */ public DeleteAdRules createDeleteAdRules() { return new DeleteAdRules(); } /** * Create an instance of {@link ActivateCustomFields } * */ public ActivateCustomFields createActivateCustomFields() { return new ActivateCustomFields(); } /** * Create an instance of {@link ProposalCompanyAssociation } * */ public ProposalCompanyAssociation createProposalCompanyAssociation() { return new ProposalCompanyAssociation(); } /** * Create an instance of {@link DeviceManufacturerPremiumFeature } * */ public DeviceManufacturerPremiumFeature createDeviceManufacturerPremiumFeature() { return new DeviceManufacturerPremiumFeature(); } /** * Create an instance of {@link UnknownAdRuleSlot } * */ public UnknownAdRuleSlot createUnknownAdRuleSlot() { return new UnknownAdRuleSlot(); } /** * Create an instance of {@link TechnologyTargeting } * */ public TechnologyTargeting createTechnologyTargeting() { return new TechnologyTargeting(); } /** * Create an instance of {@link UnknownPremiumFeature } * */ public UnknownPremiumFeature createUnknownPremiumFeature() { return new UnknownPremiumFeature(); } /** * Create an instance of {@link CreativeTemplateError } * */ public CreativeTemplateError createCreativeTemplateError() { return new CreativeTemplateError(); } /** * Create an instance of {@link FlashRedirectCreative } * */ public FlashRedirectCreative createFlashRedirectCreative() { return new FlashRedirectCreative(); } /** * Create an instance of {@link MobileDeviceTargeting } * */ public MobileDeviceTargeting createMobileDeviceTargeting() { return new MobileDeviceTargeting(); } /** * Create an instance of {@link PlacementError } * */ public PlacementError createPlacementError() { return new PlacementError(); } /** * Create an instance of {@link ProposalActionError } * */ public ProposalActionError createProposalActionError() { return new ProposalActionError(); } /** * Create an instance of {@link SuggestedAdUnitPage } * */ public SuggestedAdUnitPage createSuggestedAdUnitPage() { return new SuggestedAdUnitPage(); } /** * Create an instance of {@link ReconciliationReportRow } * */ public ReconciliationReportRow createReconciliationReportRow() { return new ReconciliationReportRow(); } /** * Create an instance of {@link MobileDeviceSubmodelTargeting } * */ public MobileDeviceSubmodelTargeting createMobileDeviceSubmodelTargeting() { return new MobileDeviceSubmodelTargeting(); } /** * Create an instance of {@link VpaidLinearCreative } * */ public VpaidLinearCreative createVpaidLinearCreative() { return new VpaidLinearCreative(); } /** * Create an instance of {@link SwiffyConversionError } * */ public SwiffyConversionError createSwiffyConversionError() { return new SwiffyConversionError(); } /** * Create an instance of {@link CreativeAsset } * */ public CreativeAsset createCreativeAsset() { return new CreativeAsset(); } /** * Create an instance of {@link FlashRedirectOverlayCreative } * */ public FlashRedirectOverlayCreative createFlashRedirectOverlayCreative() { return new FlashRedirectOverlayCreative(); } /** * Create an instance of {@link ActivityError } * */ public ActivityError createActivityError() { return new ActivityError(); } /** * Create an instance of {@link UserTeamAssociation } * */ public UserTeamAssociation createUserTeamAssociation() { return new UserTeamAssociation(); } /** * Create an instance of {@link PopulateAudienceSegments } * */ public PopulateAudienceSegments createPopulateAudienceSegments() { return new PopulateAudienceSegments(); } /** * Create an instance of {@link SubmitReconciliationOrderReports } * */ public SubmitReconciliationOrderReports createSubmitReconciliationOrderReports() { return new SubmitReconciliationOrderReports(); } /** * Create an instance of {@link ForecastError } * */ public ForecastError createForecastError() { return new ForecastError(); } /** * Create an instance of {@link ActivityPage } * */ public ActivityPage createActivityPage() { return new ActivityPage(); } /** * Create an instance of {@link ArchiveProductTemplates } * */ public ArchiveProductTemplates createArchiveProductTemplates() { return new ArchiveProductTemplates(); } /** * Create an instance of {@link LabelError } * */ public LabelError createLabelError() { return new LabelError(); } /** * Create an instance of {@link ArchiveLineItems } * */ public ArchiveLineItems createArchiveLineItems() { return new ArchiveLineItems(); } /** * Create an instance of {@link PauseOrders } * */ public PauseOrders createPauseOrders() { return new PauseOrders(); } /** * Create an instance of {@link DropDownCustomField } * */ public DropDownCustomField createDropDownCustomField() { return new DropDownCustomField(); } /** * Create an instance of {@link RuleBasedFirstPartyAudienceSegment } * */ public RuleBasedFirstPartyAudienceSegment createRuleBasedFirstPartyAudienceSegment() { return new RuleBasedFirstPartyAudienceSegment(); } /** * Create an instance of {@link RevertReconciliationOrderReports } * */ public RevertReconciliationOrderReports createRevertReconciliationOrderReports() { return new RevertReconciliationOrderReports(); } /** * Create an instance of {@link NullError } * */ public NullError createNullError() { return new NullError(); } /** * Create an instance of {@link ActivateUsers } * */ public ActivateUsers createActivateUsers() { return new ActivateUsers(); } /** * Create an instance of {@link DateTimeRangeTargetingError } * */ public DateTimeRangeTargetingError createDateTimeRangeTargetingError() { return new DateTimeRangeTargetingError(); } /** * Create an instance of {@link Placement } * */ public Placement createPlacement() { return new Placement(); } /** * Create an instance of {@link ApiVersionError } * */ public ApiVersionError createApiVersionError() { return new ApiVersionError(); } /** * Create an instance of {@link SubmitOrdersForApprovalAndOverbook } * */ public SubmitOrdersForApprovalAndOverbook createSubmitOrdersForApprovalAndOverbook() { return new SubmitOrdersForApprovalAndOverbook(); } /** * Create an instance of {@link ReconciliationOrderReport } * */ public ReconciliationOrderReport createReconciliationOrderReport() { return new ReconciliationOrderReport(); } /** * Create an instance of {@link ProductTemplateError } * */ public ProductTemplateError createProductTemplateError() { return new ProductTemplateError(); } /** * Create an instance of {@link ProgrammaticSettings } * */ public ProgrammaticSettings createProgrammaticSettings() { return new ProgrammaticSettings(); } /** * Create an instance of {@link CreativeSetPage } * */ public CreativeSetPage createCreativeSetPage() { return new CreativeSetPage(); } /** * Create an instance of {@link StringLengthError } * */ public StringLengthError createStringLengthError() { return new StringLengthError(); } /** * Create an instance of {@link CollectionSizeError } * */ public CollectionSizeError createCollectionSizeError() { return new CollectionSizeError(); } /** * Create an instance of {@link GenericTargetingError } * */ public GenericTargetingError createGenericTargetingError() { return new GenericTargetingError(); } /** * Create an instance of {@link ActivateAdRules } * */ public ActivateAdRules createActivateAdRules() { return new ActivateAdRules(); } /** * Create an instance of {@link DateTimeValue } * */ public DateTimeValue createDateTimeValue() { return new DateTimeValue(); } /** * Create an instance of {@link ServerError } * */ public ServerError createServerError() { return new ServerError(); } /** * Create an instance of {@link ImageRedirectOverlayCreative } * */ public ImageRedirectOverlayCreative createImageRedirectOverlayCreative() { return new ImageRedirectOverlayCreative(); } /** * Create an instance of {@link ActivityGroupPage } * */ public ActivityGroupPage createActivityGroupPage() { return new ActivityGroupPage(); } /** * Create an instance of {@link DeleteUserTeamAssociations } * */ public DeleteUserTeamAssociations createDeleteUserTeamAssociations() { return new DeleteUserTeamAssociations(); } /** * Create an instance of {@link Role } * */ public Role createRole() { return new Role(); } /** * Create an instance of {@link LabelPage } * */ public LabelPage createLabelPage() { return new LabelPage(); } /** * Create an instance of {@link DeviceCapabilityPremiumFeature } * */ public DeviceCapabilityPremiumFeature createDeviceCapabilityPremiumFeature() { return new DeviceCapabilityPremiumFeature(); } /** * Create an instance of {@link Stats } * */ public Stats createStats() { return new Stats(); } /** * Create an instance of {@link PrecisionError } * */ public PrecisionError createPrecisionError() { return new PrecisionError(); } /** * Create an instance of {@link RichMediaStudioCreative } * */ public RichMediaStudioCreative createRichMediaStudioCreative() { return new RichMediaStudioCreative(); } /** * Create an instance of {@link InvalidEmailError } * */ public InvalidEmailError createInvalidEmailError() { return new InvalidEmailError(); } /** * Create an instance of {@link FeatureError } * */ public FeatureError createFeatureError() { return new FeatureError(); } /** * Create an instance of {@link GrpSettingsError } * */ public GrpSettingsError createGrpSettingsError() { return new GrpSettingsError(); } /** * Create an instance of {@link OperatingSystem } * */ public OperatingSystem createOperatingSystem() { return new OperatingSystem(); } /** * Create an instance of {@link TokenError } * */ public TokenError createTokenError() { return new TokenError(); } /** * Create an instance of {@link ReleaseLineItems } * */ public ReleaseLineItems createReleaseLineItems() { return new ReleaseLineItems(); } /** * Create an instance of {@link AudienceSegmentPage } * */ public AudienceSegmentPage createAudienceSegmentPage() { return new AudienceSegmentPage(); } /** * Create an instance of {@link RateCard } * */ public RateCard createRateCard() { return new RateCard(); } /** * Create an instance of {@link Money } * */ public Money createMoney() { return new Money(); } /** * Create an instance of {@link CustomTargetingValue } * */ public CustomTargetingValue createCustomTargetingValue() { return new CustomTargetingValue(); } /** * Create an instance of {@link AdRuleFrequencyCapError } * */ public AdRuleFrequencyCapError createAdRuleFrequencyCapError() { return new AdRuleFrequencyCapError(); } /** * Create an instance of {@link CustomFieldOption } * */ public CustomFieldOption createCustomFieldOption() { return new CustomFieldOption(); } /** * Create an instance of {@link CreativeWrapperHtmlSnippet } * */ public CreativeWrapperHtmlSnippet createCreativeWrapperHtmlSnippet() { return new CreativeWrapperHtmlSnippet(); } /** * Create an instance of {@link ArchiveProducts } * */ public ArchiveProducts createArchiveProducts() { return new ArchiveProducts(); } /** * Create an instance of {@link ApproveOrdersWithoutReservationChanges } * */ public ApproveOrdersWithoutReservationChanges createApproveOrdersWithoutReservationChanges() { return new ApproveOrdersWithoutReservationChanges(); } /** * Create an instance of {@link ProductTemplate } * */ public ProductTemplate createProductTemplate() { return new ProductTemplate(); } /** * Create an instance of {@link PremiumRateValue } * */ public PremiumRateValue createPremiumRateValue() { return new PremiumRateValue(); } /** * Create an instance of {@link DisapproveOrders } * */ public DisapproveOrders createDisapproveOrders() { return new DisapproveOrders(); } /** * Create an instance of {@link RequiredError } * */ public RequiredError createRequiredError() { return new RequiredError(); } /** * Create an instance of {@link OrderActionError } * */ public OrderActionError createOrderActionError() { return new OrderActionError(); } /** * Create an instance of {@link PlacementPremiumFeature } * */ public PlacementPremiumFeature createPlacementPremiumFeature() { return new PlacementPremiumFeature(); } /** * Create an instance of {@link UserDomainTargetingError } * */ public UserDomainTargetingError createUserDomainTargetingError() { return new UserDomainTargetingError(); } /** * Create an instance of {@link DayPart } * */ public DayPart createDayPart() { return new DayPart(); } /** * Create an instance of {@link SizeStringMapEntry } * */ public SizeStringMapEntry createSizeStringMapEntry() { return new SizeStringMapEntry(); } /** * Create an instance of {@link SwiffyFallbackAsset } * */ public SwiffyFallbackAsset createSwiffyFallbackAsset() { return new SwiffyFallbackAsset(); } /** * Create an instance of {@link ProductTemplateBaseRate } * */ public ProductTemplateBaseRate createProductTemplateBaseRate() { return new ProductTemplateBaseRate(); } /** * Create an instance of {@link OrderError } * */ public OrderError createOrderError() { return new OrderError(); } /** * Create an instance of {@link ResumeLineItems } * */ public ResumeLineItems createResumeLineItems() { return new ResumeLineItems(); } /** * Create an instance of {@link CustomCreativeError } * */ public CustomCreativeError createCustomCreativeError() { return new CustomCreativeError(); } /** * Create an instance of {@link RequiredSizeError } * */ public RequiredSizeError createRequiredSizeError() { return new RequiredSizeError(); } /** * Create an instance of {@link DeleteExchangeRates } * */ public DeleteExchangeRates createDeleteExchangeRates() { return new DeleteExchangeRates(); } /** * Create an instance of {@link FlashCreative } * */ public FlashCreative createFlashCreative() { return new FlashCreative(); } /** * Create an instance of {@link CrossSellError } * */ public CrossSellError createCrossSellError() { return new CrossSellError(); } /** * Create an instance of {@link DateTime } * */ public DateTime createDateTime() { return new DateTime(); } /** * Create an instance of {@link ContentBundle } * */ public ContentBundle createContentBundle() { return new ContentBundle(); } /** * Create an instance of {@link VideoCreative } * */ public VideoCreative createVideoCreative() { return new VideoCreative(); } /** * Create an instance of {@link ReconciliationReport } * */ public ReconciliationReport createReconciliationReport() { return new ReconciliationReport(); } /** * Create an instance of {@link AdUnitTargeting } * */ public AdUnitTargeting createAdUnitTargeting() { return new AdUnitTargeting(); } /** * Create an instance of {@link ActivateLineItemCreativeAssociations } * */ public ActivateLineItemCreativeAssociations createActivateLineItemCreativeAssociations() { return new ActivateLineItemCreativeAssociations(); } /** * Create an instance of {@link BrowserLanguage } * */ public BrowserLanguage createBrowserLanguage() { return new BrowserLanguage(); } /** * Create an instance of {@link BooleanValue } * */ public BooleanValue createBooleanValue() { return new BooleanValue(); } /** * Create an instance of {@link DeleteOrders } * */ public DeleteOrders createDeleteOrders() { return new DeleteOrders(); } /** * Create an instance of {@link RequiredCollectionError } * */ public RequiredCollectionError createRequiredCollectionError() { return new RequiredCollectionError(); } /** * Create an instance of {@link DeviceCategory } * */ public DeviceCategory createDeviceCategory() { return new DeviceCategory(); } /** * Create an instance of {@link InventoryTargetingError } * */ public InventoryTargetingError createInventoryTargetingError() { return new InventoryTargetingError(); } /** * Create an instance of {@link ProposalLineItemActionError } * */ public ProposalLineItemActionError createProposalLineItemActionError() { return new ProposalLineItemActionError(); } /** * Create an instance of {@link ApproveAndOverbookOrders } * */ public ApproveAndOverbookOrders createApproveAndOverbookOrders() { return new ApproveAndOverbookOrders(); } /** * Create an instance of {@link ApproveOrders } * */ public ApproveOrders createApproveOrders() { return new ApproveOrders(); } /** * Create an instance of {@link DayPartTargetingError } * */ public DayPartTargetingError createDayPartTargetingError() { return new DayPartTargetingError(); } /** * Create an instance of {@link LineItemOperationError } * */ public LineItemOperationError createLineItemOperationError() { return new LineItemOperationError(); } /** * Create an instance of {@link CustomTargetingError } * */ public CustomTargetingError createCustomTargetingError() { return new CustomTargetingError(); } /** * Create an instance of {@link TextValue } * */ public TextValue createTextValue() { return new TextValue(); } /** * Create an instance of {@link ContentPartnerError } * */ public ContentPartnerError createContentPartnerError() { return new ContentPartnerError(); } /** * Create an instance of {@link FirstPartyAudienceSegmentRule } * */ public FirstPartyAudienceSegmentRule createFirstPartyAudienceSegmentRule() { return new FirstPartyAudienceSegmentRule(); } /** * Create an instance of {@link CreativePage } * */ public CreativePage createCreativePage() { return new CreativePage(); } /** * Create an instance of {@link ProductTemplateTargeting } * */ public ProductTemplateTargeting createProductTemplateTargeting() { return new ProductTemplateTargeting(); } /** * Create an instance of {@link WorkflowValidationError } * */ public WorkflowValidationError createWorkflowValidationError() { return new WorkflowValidationError(); } /** * Create an instance of {@link WorkflowRequestPage } * */ public WorkflowRequestPage createWorkflowRequestPage() { return new WorkflowRequestPage(); } /** * Create an instance of {@link ProductTemplatePage } * */ public ProductTemplatePage createProductTemplatePage() { return new ProductTemplatePage(); } /** * Create an instance of {@link AssetError } * */ public AssetError createAssetError() { return new AssetError(); } /** * Create an instance of {@link CreativeSetError } * */ public CreativeSetError createCreativeSetError() { return new CreativeSetError(); } /** * Create an instance of {@link AdRule } * */ public AdRule createAdRule() { return new AdRule(); } /** * Create an instance of {@link ApproveWorkflowApprovalRequests } * */ public ApproveWorkflowApprovalRequests createApproveWorkflowApprovalRequests() { return new ApproveWorkflowApprovalRequests(); } /** * Create an instance of {@link FrequencyCap } * */ public FrequencyCap createFrequencyCap() { return new FrequencyCap(); } /** * Create an instance of {@link InvalidUrlError } * */ public InvalidUrlError createInvalidUrlError() { return new InvalidUrlError(); } /** * Create an instance of {@link UserDomainPremiumFeature } * */ public UserDomainPremiumFeature createUserDomainPremiumFeature() { return new UserDomainPremiumFeature(); } /** * Create an instance of {@link AdSenseSettingsInheritedProperty } * */ public AdSenseSettingsInheritedProperty createAdSenseSettingsInheritedProperty() { return new AdSenseSettingsInheritedProperty(); } /** * Create an instance of {@link LongCreativeTemplateVariableValue } * */ public LongCreativeTemplateVariableValue createLongCreativeTemplateVariableValue() { return new LongCreativeTemplateVariableValue(); } /** * Create an instance of {@link EntityChildrenLimitReachedError } * */ public EntityChildrenLimitReachedError createEntityChildrenLimitReachedError() { return new EntityChildrenLimitReachedError(); } /** * Create an instance of {@link NumberValue } * */ public NumberValue createNumberValue() { return new NumberValue(); } /** * Create an instance of {@link CompanyCreditStatusError } * */ public CompanyCreditStatusError createCompanyCreditStatusError() { return new CompanyCreditStatusError(); } /** * Create an instance of {@link LineItemCreativeAssociationPage } * */ public LineItemCreativeAssociationPage createLineItemCreativeAssociationPage() { return new LineItemCreativeAssociationPage(); } /** * Create an instance of {@link OperatingSystemTargeting } * */ public OperatingSystemTargeting createOperatingSystemTargeting() { return new OperatingSystemTargeting(); } /** * Create an instance of {@link ReconciliationImportError } * */ public ReconciliationImportError createReconciliationImportError() { return new ReconciliationImportError(); } /** * Create an instance of {@link CmsContent } * */ public CmsContent createCmsContent() { return new CmsContent(); } /** * Create an instance of {@link CreativeWrapper } * */ public CreativeWrapper createCreativeWrapper() { return new CreativeWrapper(); } /** * Create an instance of {@link CustomFieldValueError } * */ public CustomFieldValueError createCustomFieldValueError() { return new CustomFieldValueError(); } /** * Create an instance of {@link RichMediaStudioCreativeError } * */ public RichMediaStudioCreativeError createRichMediaStudioCreativeError() { return new RichMediaStudioCreativeError(); } /** * Create an instance of {@link CustomTargetingKey } * */ public CustomTargetingKey createCustomTargetingKey() { return new CustomTargetingKey(); } /** * Create an instance of {@link LineItemError } * */ public LineItemError createLineItemError() { return new LineItemError(); } /** * Create an instance of {@link CreativeWrapperPage } * */ public CreativeWrapperPage createCreativeWrapperPage() { return new CreativeWrapperPage(); } /** * Create an instance of {@link ClickTrackingCreative } * */ public ClickTrackingCreative createClickTrackingCreative() { return new ClickTrackingCreative(); } /** * Create an instance of {@link SuggestedAdUnit } * */ public SuggestedAdUnit createSuggestedAdUnit() { return new SuggestedAdUnit(); } /** * Create an instance of {@link UrlCreativeTemplateVariableValue } * */ public UrlCreativeTemplateVariableValue createUrlCreativeTemplateVariableValue() { return new UrlCreativeTemplateVariableValue(); } /** * Create an instance of {@link ContactError } * */ public ContactError createContactError() { return new ContactError(); } /** * Create an instance of {@link LiveStreamEventPage } * */ public LiveStreamEventPage createLiveStreamEventPage() { return new LiveStreamEventPage(); } /** * Create an instance of {@link ActivateProductTemplates } * */ public ActivateProductTemplates createActivateProductTemplates() { return new ActivateProductTemplates(); } /** * Create an instance of {@link ApplicationException } * */ public ApplicationException createApplicationException() { return new ApplicationException(); } /** * Create an instance of {@link DeleteCustomTargetingValues } * */ public DeleteCustomTargetingValues createDeleteCustomTargetingValues() { return new DeleteCustomTargetingValues(); } /** * Create an instance of {@link ActivateContentBundles } * */ public ActivateContentBundles createActivateContentBundles() { return new ActivateContentBundles(); } /** * Create an instance of {@link AdUnitTypeError } * */ public AdUnitTypeError createAdUnitTypeError() { return new AdUnitTypeError(); } /** * Create an instance of {@link BrowserTargeting } * */ public BrowserTargeting createBrowserTargeting() { return new BrowserTargeting(); } /** * Create an instance of {@link ConversionEventTrackingUrlsMapEntry } * */ public ConversionEventTrackingUrlsMapEntry createConversionEventTrackingUrlsMapEntry() { return new ConversionEventTrackingUrlsMapEntry(); } /** * Create an instance of {@link ProductPage } * */ public ProductPage createProductPage() { return new ProductPage(); } /** * Create an instance of {@link ActivatePlacements } * */ public ActivatePlacements createActivatePlacements() { return new ActivatePlacements(); } /** * Create an instance of {@link LongCreativeTemplateVariable } * */ public LongCreativeTemplateVariable createLongCreativeTemplateVariable() { return new LongCreativeTemplateVariable(); } /** * Create an instance of {@link ThirdPartyAudienceSegment } * */ public ThirdPartyAudienceSegment createThirdPartyAudienceSegment() { return new ThirdPartyAudienceSegment(); } /** * Create an instance of {@link BandwidthGroupTargeting } * */ public BandwidthGroupTargeting createBandwidthGroupTargeting() { return new BandwidthGroupTargeting(); } /** * Create an instance of {@link InventoryUnitError } * */ public InventoryUnitError createInventoryUnitError() { return new InventoryUnitError(); } /** * Create an instance of {@link ThirdPartyCreative } * */ public ThirdPartyCreative createThirdPartyCreative() { return new ThirdPartyCreative(); } /** * Create an instance of {@link AssetCreativeTemplateVariable } * */ public AssetCreativeTemplateVariable createAssetCreativeTemplateVariable() { return new AssetCreativeTemplateVariable(); } /** * Create an instance of {@link CustomTargetingPremiumFeature } * */ public CustomTargetingPremiumFeature createCustomTargetingPremiumFeature() { return new CustomTargetingPremiumFeature(); } /** * Create an instance of {@link QuotaError } * */ public QuotaError createQuotaError() { return new QuotaError(); } /** * Create an instance of {@link ReconciliationError } * */ public ReconciliationError createReconciliationError() { return new ReconciliationError(); } /** * Create an instance of {@link FlashOverlayCreative } * */ public FlashOverlayCreative createFlashOverlayCreative() { return new FlashOverlayCreative(); } /** * Create an instance of {@link WorkflowActionError } * */ public WorkflowActionError createWorkflowActionError() { return new WorkflowActionError(); } /** * Create an instance of {@link CompanyPage } * */ public CompanyPage createCompanyPage() { return new CompanyPage(); } /** * Create an instance of {@link InvalidColorError } * */ public InvalidColorError createInvalidColorError() { return new InvalidColorError(); } /** * Create an instance of {@link ArchiveLiveStreamEvents } * */ public ArchiveLiveStreamEvents createArchiveLiveStreamEvents() { return new ArchiveLiveStreamEvents(); } /** * Create an instance of {@link LineItemTemplatePage } * */ public LineItemTemplatePage createLineItemTemplatePage() { return new LineItemTemplatePage(); } /** * Create an instance of {@link BrowserLanguageTargeting } * */ public BrowserLanguageTargeting createBrowserLanguageTargeting() { return new BrowserLanguageTargeting(); } /** * Create an instance of {@link ContentMetadataKeyHierarchyLevel } * */ public ContentMetadataKeyHierarchyLevel createContentMetadataKeyHierarchyLevel() { return new ContentMetadataKeyHierarchyLevel(); } /** * Create an instance of {@link ReconciliationReportRowPage } * */ public ReconciliationReportRowPage createReconciliationReportRowPage() { return new ReconciliationReportRowPage(); } /** * Create an instance of {@link SharedAudienceSegment } * */ public SharedAudienceSegment createSharedAudienceSegment() { return new SharedAudienceSegment(); } /** * Create an instance of {@link SiteTargetingInfo } * */ public SiteTargetingInfo createSiteTargetingInfo() { return new SiteTargetingInfo(); } /** * Create an instance of {@link ArchiveProposalLineItems } * */ public ArchiveProposalLineItems createArchiveProposalLineItems() { return new ArchiveProposalLineItems(); } /** * Create an instance of {@link CreativeWrapperError } * */ public CreativeWrapperError createCreativeWrapperError() { return new CreativeWrapperError(); } /** * Create an instance of {@link CustomCriteriaSet } * */ public CustomCriteriaSet createCustomCriteriaSet() { return new CustomCriteriaSet(); } /** * Create an instance of {@link ApproveSuggestedAdUnit } * */ public ApproveSuggestedAdUnit createApproveSuggestedAdUnit() { return new ApproveSuggestedAdUnit(); } /** * Create an instance of {@link BrowserLanguagePremiumFeature } * */ public BrowserLanguagePremiumFeature createBrowserLanguagePremiumFeature() { return new BrowserLanguagePremiumFeature(); } /** * Create an instance of {@link Forecast } * */ public Forecast createForecast() { return new Forecast(); } /** * Create an instance of {@link DeviceManufacturer } * */ public DeviceManufacturer createDeviceManufacturer() { return new DeviceManufacturer(); } /** * Create an instance of {@link ReserveLineItems } * */ public ReserveLineItems createReserveLineItems() { return new ReserveLineItems(); } /** * Create an instance of {@link Row } * */ public Row createRow() { return new Row(); } /** * Create an instance of {@link RejectWorkflowApprovalRequests } * */ public RejectWorkflowApprovalRequests createRejectWorkflowApprovalRequests() { return new RejectWorkflowApprovalRequests(); } /** * Create an instance of {@link ExchangeRatePage } * */ public ExchangeRatePage createExchangeRatePage() { return new ExchangeRatePage(); } /** * Create an instance of {@link MobileCarrier } * */ public MobileCarrier createMobileCarrier() { return new MobileCarrier(); } /** * Create an instance of {@link BrowserPremiumFeature } * */ public BrowserPremiumFeature createBrowserPremiumFeature() { return new BrowserPremiumFeature(); } /** * Create an instance of {@link PremiumRatePage } * */ public PremiumRatePage createPremiumRatePage() { return new PremiumRatePage(); } /** * Create an instance of {@link PauseLiveStreamEvents } * */ public PauseLiveStreamEvents createPauseLiveStreamEvents() { return new PauseLiveStreamEvents(); } /** * Create an instance of {@link ClickTrackingLineItemError } * */ public ClickTrackingLineItemError createClickTrackingLineItemError() { return new ClickTrackingLineItemError(); } /** * Create an instance of {@link ResumeOrders } * */ public ResumeOrders createResumeOrders() { return new ResumeOrders(); } /** * Create an instance of {@link ProposalLineItemPage } * */ public ProposalLineItemPage createProposalLineItemPage() { return new ProposalLineItemPage(); } /** * Create an instance of {@link ListStringCreativeTemplateVariableVariableChoice } * */ public ListStringCreativeTemplateVariableVariableChoice createListStringCreativeTemplateVariableVariableChoice() { return new ListStringCreativeTemplateVariableVariableChoice(); } /** * Create an instance of {@link ParseError } * */ public ParseError createParseError() { return new ParseError(); } /** * Create an instance of {@link TrackingUrls } * */ public TrackingUrls createTrackingUrls() { return new TrackingUrls(); } /** * Create an instance of {@link InventoryUnitSizesError } * */ public InventoryUnitSizesError createInventoryUnitSizesError() { return new InventoryUnitSizesError(); } /** * Create an instance of {@link MobileCarrierPremiumFeature } * */ public MobileCarrierPremiumFeature createMobileCarrierPremiumFeature() { return new MobileCarrierPremiumFeature(); } /** * Create an instance of {@link SubmitOrdersForApprovalWithoutReservationChanges } * */ public SubmitOrdersForApprovalWithoutReservationChanges createSubmitOrdersForApprovalWithoutReservationChanges() { return new SubmitOrdersForApprovalWithoutReservationChanges(); } /** * Create an instance of {@link DeactivateContentBundles } * */ public DeactivateContentBundles createDeactivateContentBundles() { return new DeactivateContentBundles(); } /** * Create an instance of {@link ArchivePlacements } * */ public ArchivePlacements createArchivePlacements() { return new ArchivePlacements(); } /** * Create an instance of {@link CreativePlaceholder } * */ public CreativePlaceholder createCreativePlaceholder() { return new CreativePlaceholder(); } /** * Create an instance of {@link ListStringCreativeTemplateVariable } * */ public ListStringCreativeTemplateVariable createListStringCreativeTemplateVariable() { return new ListStringCreativeTemplateVariable(); } /** * Create an instance of {@link VideoPositionTarget } * */ public VideoPositionTarget createVideoPositionTarget() { return new VideoPositionTarget(); } /** * Create an instance of {@link ProposalLineItemError } * */ public ProposalLineItemError createProposalLineItemError() { return new ProposalLineItemError(); } /** * Create an instance of {@link RetractProposals } * */ public RetractProposals createRetractProposals() { return new RetractProposals(); } /** * Create an instance of {@link PackageError } * */ public PackageError createPackageError() { return new PackageError(); } /** * Create an instance of {@link CommonError } * */ public CommonError createCommonError() { return new CommonError(); } /** * Create an instance of {@link SetValue } * */ public SetValue createSetValue() { return new SetValue(); } /** * Create an instance of {@link AudienceSegmentError } * */ public AudienceSegmentError createAudienceSegmentError() { return new AudienceSegmentError(); } /** * Create an instance of {@link ReconciliationOrderReportPage } * */ public ReconciliationOrderReportPage createReconciliationOrderReportPage() { return new ReconciliationOrderReportPage(); } /** * Create an instance of {@link AdRuleDateError } * */ public AdRuleDateError createAdRuleDateError() { return new AdRuleDateError(); } /** * Create an instance of {@link PremiumRate } * */ public PremiumRate createPremiumRate() { return new PremiumRate(); } /** * Create an instance of {@link TeamError } * */ public TeamError createTeamError() { return new TeamError(); } /** * Create an instance of {@link RemoveAdUnitsFromPlacement } * */ public RemoveAdUnitsFromPlacement createRemoveAdUnitsFromPlacement() { return new RemoveAdUnitsFromPlacement(); } /** * Create an instance of {@link GeoTargetingError } * */ public GeoTargetingError createGeoTargetingError() { return new GeoTargetingError(); } /** * Create an instance of {@link Activity } * */ public Activity createActivity() { return new Activity(); } /** * Create an instance of {@link LiveStreamEventActionError } * */ public LiveStreamEventActionError createLiveStreamEventActionError() { return new LiveStreamEventActionError(); } /** * Create an instance of {@link OperatingSystemVersion } * */ public OperatingSystemVersion createOperatingSystemVersion() { return new OperatingSystemVersion(); } /** * Create an instance of {@link DeactivateLineItemCreativeAssociations } * */ public DeactivateLineItemCreativeAssociations createDeactivateLineItemCreativeAssociations() { return new DeactivateLineItemCreativeAssociations(); } /** * Create an instance of {@link ActivateCreativeWrappers } * */ public ActivateCreativeWrappers createActivateCreativeWrappers() { return new ActivateCreativeWrappers(); } /** * Create an instance of {@link DayPartTargeting } * */ public DayPartTargeting createDayPartTargeting() { return new DayPartTargeting(); } /** * Create an instance of {@link AudienceSegmentCriteria } * */ public AudienceSegmentCriteria createAudienceSegmentCriteria() { return new AudienceSegmentCriteria(); } /** * Create an instance of {@link ProductSegmentation } * */ public ProductSegmentation createProductSegmentation() { return new ProductSegmentation(); } /** * Create an instance of {@link UserTeamAssociationPage } * */ public UserTeamAssociationPage createUserTeamAssociationPage() { return new UserTeamAssociationPage(); } /** * Create an instance of {@link CustomTargetingKeyPage } * */ public CustomTargetingKeyPage createCustomTargetingKeyPage() { return new CustomTargetingKeyPage(); } /** * Create an instance of {@link DeactivateAudienceSegments } * */ public DeactivateAudienceSegments createDeactivateAudienceSegments() { return new DeactivateAudienceSegments(); } /** * Create an instance of {@link ProgrammaticError } * */ public ProgrammaticError createProgrammaticError() { return new ProgrammaticError(); } /** * Create an instance of {@link CustomCreativeAsset } * */ public CustomCreativeAsset createCustomCreativeAsset() { return new CustomCreativeAsset(); } /** * Create an instance of {@link VideoRedirectAsset } * */ public VideoRedirectAsset createVideoRedirectAsset() { return new VideoRedirectAsset(); } /** * Create an instance of {@link ProposalLineItemPremium } * */ public ProposalLineItemPremium createProposalLineItemPremium() { return new ProposalLineItemPremium(); } /** * Create an instance of {@link StandardPoddingAdRuleSlot } * */ public StandardPoddingAdRuleSlot createStandardPoddingAdRuleSlot() { return new StandardPoddingAdRuleSlot(); } /** * Create an instance of {@link CompanyError } * */ public CompanyError createCompanyError() { return new CompanyError(); } /** * Create an instance of {@link UserDomainTargeting } * */ public UserDomainTargeting createUserDomainTargeting() { return new UserDomainTargeting(); } /** * Create an instance of {@link LineItemCreativeAssociationStats } * */ public LineItemCreativeAssociationStats createLineItemCreativeAssociationStats() { return new LineItemCreativeAssociationStats(); } /** * Create an instance of {@link AudienceSegmentDataProvider } * */ public AudienceSegmentDataProvider createAudienceSegmentDataProvider() { return new AudienceSegmentDataProvider(); } /** * Create an instance of {@link VpaidLinearRedirectCreative } * */ public VpaidLinearRedirectCreative createVpaidLinearRedirectCreative() { return new VpaidLinearRedirectCreative(); } /** * Create an instance of {@link TypeError } * */ public TypeError createTypeError() { return new TypeError(); } /** * Create an instance of {@link ContentMetadataKeyHierarchyError } * */ public ContentMetadataKeyHierarchyError createContentMetadataKeyHierarchyError() { return new ContentMetadataKeyHierarchyError(); } /** * Create an instance of {@link FileError } * */ public FileError createFileError() { return new FileError(); } /** * Create an instance of {@link Targeting } * */ public Targeting createTargeting() { return new Targeting(); } /** * Create an instance of {@link StringCreativeTemplateVariableValue } * */ public StringCreativeTemplateVariableValue createStringCreativeTemplateVariableValue() { return new StringCreativeTemplateVariableValue(); } /** * Create an instance of {@link ResumeAndOverbookOrders } * */ public ResumeAndOverbookOrders createResumeAndOverbookOrders() { return new ResumeAndOverbookOrders(); } /** * Create an instance of {@link LegacyDfpMobileCreative } * */ public LegacyDfpMobileCreative createLegacyDfpMobileCreative() { return new LegacyDfpMobileCreative(); } /** * Create an instance of {@link StringValueMapEntry } * */ public StringValueMapEntry createStringValueMapEntry() { return new StringValueMapEntry(); } /** * Create an instance of {@link InvalidPhoneNumberError } * */ public InvalidPhoneNumberError createInvalidPhoneNumberError() { return new InvalidPhoneNumberError(); } /** * Create an instance of {@link DateValue } * */ public DateValue createDateValue() { return new DateValue(); } /** * Create an instance of {@link ProductTemplateActionError } * */ public ProductTemplateActionError createProductTemplateActionError() { return new ProductTemplateActionError(); } /** * Create an instance of {@link Team } * */ public Team createTeam() { return new Team(); } /** * Create an instance of {@link ReportError } * */ public ReportError createReportError() { return new ReportError(); } /** * Create an instance of {@link LiveStreamEventDateTimeError } * */ public LiveStreamEventDateTimeError createLiveStreamEventDateTimeError() { return new LiveStreamEventDateTimeError(); } /** * Create an instance of {@link CreativeTemplatePage } * */ public CreativeTemplatePage createCreativeTemplatePage() { return new CreativeTemplatePage(); } /** * Create an instance of {@link SkipWorkflowExternalConditionRequests } * */ public SkipWorkflowExternalConditionRequests createSkipWorkflowExternalConditionRequests() { return new SkipWorkflowExternalConditionRequests(); } /** * Create an instance of {@link AdRuleSlotError } * */ public AdRuleSlotError createAdRuleSlotError() { return new AdRuleSlotError(); } /** * Create an instance of {@link VideoRedirectCreative } * */ public VideoRedirectCreative createVideoRedirectCreative() { return new VideoRedirectCreative(); } /** * Create an instance of {@link VideoPositionTargeting } * */ public VideoPositionTargeting createVideoPositionTargeting() { return new VideoPositionTargeting(); } /** * Create an instance of {@link AdUnitCodeError } * */ public AdUnitCodeError createAdUnitCodeError() { return new AdUnitCodeError(); } /** * Create an instance of {@link DeviceCategoryTargeting } * */ public DeviceCategoryTargeting createDeviceCategoryTargeting() { return new DeviceCategoryTargeting(); } /** * Create an instance of {@link AdSenseCreative } * */ public AdSenseCreative createAdSenseCreative() { return new AdSenseCreative(); } /** * Create an instance of {@link DeactivatePlacements } * */ public DeactivatePlacements createDeactivatePlacements() { return new DeactivatePlacements(); } /** * Create an instance of {@link EntityLimitReachedError } * */ public EntityLimitReachedError createEntityLimitReachedError() { return new EntityLimitReachedError(); } /** * Create an instance of {@link DeviceCapability } * */ public DeviceCapability createDeviceCapability() { return new DeviceCapability(); } /** * Create an instance of {@link ColumnType } * */ public ColumnType createColumnType() { return new ColumnType(); } /** * Create an instance of {@link Label } * */ public Label createLabel() { return new Label(); } /** * Create an instance of {@link DeactivateCreativeWrappers } * */ public DeactivateCreativeWrappers createDeactivateCreativeWrappers() { return new DeactivateCreativeWrappers(); } /** * Create an instance of {@link IncludeContentInContentBundle } * */ public IncludeContentInContentBundle createIncludeContentInContentBundle() { return new IncludeContentInContentBundle(); } /** * Create an instance of {@link InventoryUnitPartnerAssociationError } * */ public InventoryUnitPartnerAssociationError createInventoryUnitPartnerAssociationError() { return new InventoryUnitPartnerAssociationError(); } /** * Create an instance of {@link FrequencyCapError } * */ public FrequencyCapError createFrequencyCapError() { return new FrequencyCapError(); } /** * Create an instance of {@link RequiredNumberError } * */ public RequiredNumberError createRequiredNumberError() { return new RequiredNumberError(); } /** * Create an instance of {@link UnarchiveLineItems } * */ public UnarchiveLineItems createUnarchiveLineItems() { return new UnarchiveLineItems(); } /** * Create an instance of {@link ActivateRateCards } * */ public ActivateRateCards createActivateRateCards() { return new ActivateRateCards(); } /** * Create an instance of {@link DeactivateUsers } * */ public DeactivateUsers createDeactivateUsers() { return new DeactivateUsers(); } /** * Create an instance of {@link CustomCriteria } * */ public CustomCriteria createCustomCriteria() { return new CustomCriteria(); } /** * Create an instance of {@link BaseContact } * */ public BaseContact createBaseContact() { return new BaseContact(); } /** * Create an instance of {@link ProposalError } * */ public ProposalError createProposalError() { return new ProposalError(); } /** * Create an instance of {@link RejectAudienceSegments } * */ public RejectAudienceSegments createRejectAudienceSegments() { return new RejectAudienceSegments(); } /** * Create an instance of {@link ProductError } * */ public ProductError createProductError() { return new ProductError(); } /** * Create an instance of {@link TriggerWorkflowExternalConditionRequests } * */ public TriggerWorkflowExternalConditionRequests createTriggerWorkflowExternalConditionRequests() { return new TriggerWorkflowExternalConditionRequests(); } /** * Create an instance of {@link ActivateAdUnits } * */ public ActivateAdUnits createActivateAdUnits() { return new ActivateAdUnits(); } /** * Create an instance of {@link GeographyPremiumFeature } * */ public GeographyPremiumFeature createGeographyPremiumFeature() { return new GeographyPremiumFeature(); } /** * Create an instance of {@link PremiumRateError } * */ public PremiumRateError createPremiumRateError() { return new PremiumRateError(); } /** * Create an instance of {@link ArchiveOrders } * */ public ArchiveOrders createArchiveOrders() { return new ArchiveOrders(); } /** * Create an instance of {@link ContentPage } * */ public ContentPage createContentPage() { return new ContentPage(); } /** * Create an instance of {@link DeactivateCustomFields } * */ public DeactivateCustomFields createDeactivateCustomFields() { return new DeactivateCustomFields(); } /** * Create an instance of {@link DeviceCapabilityTargeting } * */ public DeviceCapabilityTargeting createDeviceCapabilityTargeting() { return new DeviceCapabilityTargeting(); } /** * Create an instance of {@link ExchangeRate } * */ public ExchangeRate createExchangeRate() { return new ExchangeRate(); } /** * Create an instance of {@link OrderPage } * */ public OrderPage createOrderPage() { return new OrderPage(); } /** * Create an instance of {@link TeamPage } * */ public TeamPage createTeamPage() { return new TeamPage(); } /** * Create an instance of {@link AppliedLabel } * */ public AppliedLabel createAppliedLabel() { return new AppliedLabel(); } /** * Create an instance of {@link WorkflowApprovalRequest } * */ public WorkflowApprovalRequest createWorkflowApprovalRequest() { return new WorkflowApprovalRequest(); } /** * Create an instance of {@link CreativeAssetMacroError } * */ public CreativeAssetMacroError createCreativeAssetMacroError() { return new CreativeAssetMacroError(); } /** * Create an instance of {@link ActivateLabels } * */ public ActivateLabels createActivateLabels() { return new ActivateLabels(); } /** * Create an instance of {@link MobileDevice } * */ public MobileDevice createMobileDevice() { return new MobileDevice(); } /** * Create an instance of {@link CustomCreative } * */ public CustomCreative createCustomCreative() { return new CustomCreative(); } /** * Create an instance of {@link BandwidthPremiumFeature } * */ public BandwidthPremiumFeature createBandwidthPremiumFeature() { return new BandwidthPremiumFeature(); } /** * Create an instance of {@link BaseRatePage } * */ public BaseRatePage createBaseRatePage() { return new BaseRatePage(); } /** * Create an instance of {@link DeactivateAdRules } * */ public DeactivateAdRules createDeactivateAdRules() { return new DeactivateAdRules(); } /** * Create an instance of {@link AdUnitHierarchyError } * */ public AdUnitHierarchyError createAdUnitHierarchyError() { return new AdUnitHierarchyError(); } /** * Create an instance of {@link DeactivateProducts } * */ public DeactivateProducts createDeactivateProducts() { return new DeactivateProducts(); } /** * Create an instance of {@link AdUnitAfcSizeError } * */ public AdUnitAfcSizeError createAdUnitAfcSizeError() { return new AdUnitAfcSizeError(); } /** * Create an instance of {@link AdSenseSettings } * */ public AdSenseSettings createAdSenseSettings() { return new AdSenseSettings(); } /** * Create an instance of {@link UserPage } * */ public UserPage createUserPage() { return new UserPage(); } /** * Create an instance of {@link VideoPosition } * */ public VideoPosition createVideoPosition() { return new VideoPosition(); } /** * Create an instance of {@link ImageError } * */ public ImageError createImageError() { return new ImageError(); } /** * Create an instance of {@link StatementError } * */ public StatementError createStatementError() { return new StatementError(); } /** * Create an instance of {@link ContendingLineItem } * */ public ContendingLineItem createContendingLineItem() { return new ContendingLineItem(); } /** * Create an instance of {@link RegExError } * */ public RegExError createRegExError() { return new RegExError(); } /** * Create an instance of {@link ImageOverlayCreative } * */ public ImageOverlayCreative createImageOverlayCreative() { return new ImageOverlayCreative(); } /** * Create an instance of {@link BandwidthGroup } * */ public BandwidthGroup createBandwidthGroup() { return new BandwidthGroup(); } /** * Create an instance of {@link Location } * */ public Location createLocation() { return new Location(); } /** * Create an instance of {@link PauseLineItems } * */ public PauseLineItems createPauseLineItems() { return new PauseLineItems(); } /** * Create an instance of {@link PoddingError } * */ public PoddingError createPoddingError() { return new PoddingError(); } /** * Create an instance of {@link LineItemSummary } * */ public LineItemSummary createLineItemSummary() { return new LineItemSummary(); } /** * Create an instance of {@link AdUnitParent } * */ public AdUnitParent createAdUnitParent() { return new AdUnitParent(); } /** * Create an instance of {@link DeleteContentMetadataKeyHierarchies } * */ public DeleteContentMetadataKeyHierarchies createDeleteContentMetadataKeyHierarchies() { return new DeleteContentMetadataKeyHierarchies(); } /** * Create an instance of {@link PlacementPage } * */ public PlacementPage createPlacementPage() { return new PlacementPage(); } /** * Create an instance of {@link Goal } * */ public Goal createGoal() { return new Goal(); } /** * Create an instance of {@link PauseLiveStreamEventAds } * */ public PauseLiveStreamEventAds createPauseLiveStreamEventAds() { return new PauseLiveStreamEventAds(); } /** * Create an instance of {@link ResumeAndOverbookLineItems } * */ public ResumeAndOverbookLineItems createResumeAndOverbookLineItems() { return new ResumeAndOverbookLineItems(); } /** * Create an instance of {@link Network } * */ public Network createNetwork() { return new Network(); } /** * Create an instance of {@link UniqueError } * */ public UniqueError createUniqueError() { return new UniqueError(); } /** * Create an instance of {@link DisapproveOrdersWithoutReservationChanges } * */ public DisapproveOrdersWithoutReservationChanges createDisapproveOrdersWithoutReservationChanges() { return new DisapproveOrdersWithoutReservationChanges(); } /** * Create an instance of {@link AuthenticationError } * */ public AuthenticationError createAuthenticationError() { return new AuthenticationError(); } /** * Create an instance of {@link SuggestedAdUnitUpdateResult } * */ public SuggestedAdUnitUpdateResult createSuggestedAdUnitUpdateResult() { return new SuggestedAdUnitUpdateResult(); } /** * Create an instance of {@link PermissionError } * */ public PermissionError createPermissionError() { return new PermissionError(); } /** * Create an instance of {@link LineItemTemplate } * */ public LineItemTemplate createLineItemTemplate() { return new LineItemTemplate(); } /** * Create an instance of {@link WorkflowExternalConditionRequest } * */ public WorkflowExternalConditionRequest createWorkflowExternalConditionRequest() { return new WorkflowExternalConditionRequest(); } /** * Create an instance of {@link ReservationDetailsError } * */ public ReservationDetailsError createReservationDetailsError() { return new ReservationDetailsError(); } /** * Create an instance of {@link ContentTargeting } * */ public ContentTargeting createContentTargeting() { return new ContentTargeting(); } /** * Create an instance of {@link InternalApiError } * */ public InternalApiError createInternalApiError() { return new InternalApiError(); } /** * Create an instance of {@link CreativeError } * */ public CreativeError createCreativeError() { return new CreativeError(); } /** * Create an instance of {@link UserRecord } * */ public UserRecord createUserRecord() { return new UserRecord(); } /** * Create an instance of {@link LineItemFlightDateError } * */ public LineItemFlightDateError createLineItemFlightDateError() { return new LineItemFlightDateError(); } /** * Create an instance of {@link DeviceCategoryPremiumFeature } * */ public DeviceCategoryPremiumFeature createDeviceCategoryPremiumFeature() { return new DeviceCategoryPremiumFeature(); } /** * Create an instance of {@link ContentMetadataKeyHierarchy } * */ public ContentMetadataKeyHierarchy createContentMetadataKeyHierarchy() { return new ContentMetadataKeyHierarchy(); } /** * Create an instance of {@link Browser } * */ public Browser createBrowser() { return new Browser(); } /** * Create an instance of {@link StringCreativeTemplateVariable } * */ public StringCreativeTemplateVariable createStringCreativeTemplateVariable() { return new StringCreativeTemplateVariable(); } /** * Create an instance of {@link LongStatsMapEntry } * */ public LongStatsMapEntry createLongStatsMapEntry() { return new LongStatsMapEntry(); } /** * Create an instance of {@link MobileDeviceSubmodel } * */ public MobileDeviceSubmodel createMobileDeviceSubmodel() { return new MobileDeviceSubmodel(); } /** * Create an instance of {@link PublisherQueryLanguageSyntaxError } * */ public PublisherQueryLanguageSyntaxError createPublisherQueryLanguageSyntaxError() { return new PublisherQueryLanguageSyntaxError(); } /** * Create an instance of {@link AspectRatioImageCreative } * */ public AspectRatioImageCreative createAspectRatioImageCreative() { return new AspectRatioImageCreative(); } /** * Create an instance of {@link UnarchiveProposals } * */ public UnarchiveProposals createUnarchiveProposals() { return new UnarchiveProposals(); } /** * Create an instance of {@link NonRuleBasedFirstPartyAudienceSegment } * */ public NonRuleBasedFirstPartyAudienceSegment createNonRuleBasedFirstPartyAudienceSegment() { return new NonRuleBasedFirstPartyAudienceSegment(); } /** * Create an instance of {@link LineItemPage } * */ public LineItemPage createLineItemPage() { return new LineItemPage(); } /** * Create an instance of {@link ProgrammaticCreative } * */ public ProgrammaticCreative createProgrammaticCreative() { return new ProgrammaticCreative(); } /** * Create an instance of {@link AdExchangeCreative } * */ public AdExchangeCreative createAdExchangeCreative() { return new AdExchangeCreative(); } /** * Create an instance of {@link RuleBasedFirstPartyAudienceSegmentSummary } * */ public RuleBasedFirstPartyAudienceSegmentSummary createRuleBasedFirstPartyAudienceSegmentSummary() { return new RuleBasedFirstPartyAudienceSegmentSummary(); } /** * Create an instance of {@link ActivateProducts } * */ public ActivateProducts createActivateProducts() { return new ActivateProducts(); } /** * Create an instance of {@link ContentBundlePage } * */ public ContentBundlePage createContentBundlePage() { return new ContentBundlePage(); } /** * Create an instance of {@link DeliveryIndicator } * */ public DeliveryIndicator createDeliveryIndicator() { return new DeliveryIndicator(); } /** * Create an instance of {@link UrlCreativeTemplateVariable } * */ public UrlCreativeTemplateVariable createUrlCreativeTemplateVariable() { return new UrlCreativeTemplateVariable(); } /** * Create an instance of {@link GrpSettings } * */ public GrpSettings createGrpSettings() { return new GrpSettings(); } /** * Create an instance of {@link ApproveAudienceSegments } * */ public ApproveAudienceSegments createApproveAudienceSegments() { return new ApproveAudienceSegments(); } /** * Create an instance of {@link DeviceManufacturerTargeting } * */ public DeviceManufacturerTargeting createDeviceManufacturerTargeting() { return new DeviceManufacturerTargeting(); } /** * Create an instance of {@link LegacyDfpCreative } * */ public LegacyDfpCreative createLegacyDfpCreative() { return new LegacyDfpCreative(); } /** * Create an instance of {@link RichMediaStudioChildAssetProperty } * */ public RichMediaStudioChildAssetProperty createRichMediaStudioChildAssetProperty() { return new RichMediaStudioChildAssetProperty(); } /** * Create an instance of {@link AdUnitPremiumFeature } * */ public AdUnitPremiumFeature createAdUnitPremiumFeature() { return new AdUnitPremiumFeature(); } /** * Create an instance of {@link CustomFieldPage } * */ public CustomFieldPage createCustomFieldPage() { return new CustomFieldPage(); } /** * Create an instance of {@link BaseRateActionError } * */ public BaseRateActionError createBaseRateActionError() { return new BaseRateActionError(); } /** * Create an instance of {@link FrequencyCapPremiumFeature } * */ public FrequencyCapPremiumFeature createFrequencyCapPremiumFeature() { return new FrequencyCapPremiumFeature(); } /** * Create an instance of {@link ContactPage } * */ public ContactPage createContactPage() { return new ContactPage(); } /** * Create an instance of {@link MobileCarrierTargeting } * */ public MobileCarrierTargeting createMobileCarrierTargeting() { return new MobileCarrierTargeting(); } /** * Create an instance of {@link AudienceSegment } * */ public AudienceSegment createAudienceSegment() { return new AudienceSegment(); } /** * Create an instance of {@link CustomFieldValue } * */ public CustomFieldValue createCustomFieldValue() { return new CustomFieldValue(); } /** * Create an instance of {@link Company } * */ public Company createCompany() { return new Company(); } /** * Create an instance of {@link NotNullError } * */ public NotNullError createNotNullError() { return new NotNullError(); } /** * Create an instance of {@link Technology } * */ public Technology createTechnology() { return new Technology(); } /** * Create an instance of {@link ImageRedirectCreative } * */ public ImageRedirectCreative createImageRedirectCreative() { return new ImageRedirectCreative(); } /** * Create an instance of {@link DeleteBaseRates } * */ public DeleteBaseRates createDeleteBaseRates() { return new DeleteBaseRates(); } /** * Create an instance of {@link ImageCreative } * */ public ImageCreative createImageCreative() { return new ImageCreative(); } /** * Create an instance of {@link WorkflowRequestError } * */ public WorkflowRequestError createWorkflowRequestError() { return new WorkflowRequestError(); } /** * Create an instance of {@link ActivateAudienceSegments } * */ public ActivateAudienceSegments createActivateAudienceSegments() { return new ActivateAudienceSegments(); } /** * Create an instance of {@link OperatingSystemPremiumFeature } * */ public OperatingSystemPremiumFeature createOperatingSystemPremiumFeature() { return new OperatingSystemPremiumFeature(); } /** * Create an instance of {@link CustomTargetingValuePage } * */ public CustomTargetingValuePage createCustomTargetingValuePage() { return new CustomTargetingValuePage(); } /** * Create an instance of {@link AdRulePriorityError } * */ public AdRulePriorityError createAdRulePriorityError() { return new AdRulePriorityError(); } /** * Create an instance of {@link DeactivateLabels } * */ public DeactivateLabels createDeactivateLabels() { return new DeactivateLabels(); } /** * Create an instance of {@link Order } * */ public Order createOrder() { return new Order(); } /** * Create an instance of {@link DaypartPremiumFeature } * */ public DaypartPremiumFeature createDaypartPremiumFeature() { return new DaypartPremiumFeature(); } /** * Create an instance of {@link TechnologyTargetingError } * */ public TechnologyTargetingError createTechnologyTargetingError() { return new TechnologyTargetingError(); } /** * Create an instance of {@link NetworkError } * */ public NetworkError createNetworkError() { return new NetworkError(); } /** * Create an instance of {@link UnknownBaseRate } * */ public UnknownBaseRate createUnknownBaseRate() { return new UnknownBaseRate(); } /** * Create an instance of {@link ReportJob } * */ public ReportJob createReportJob() { return new ReportJob(); } /** * Create an instance of {@link InventoryTargeting } * */ public InventoryTargeting createInventoryTargeting() { return new InventoryTargeting(); } /** * Create an instance of {@link GeoTargeting } * */ public GeoTargeting createGeoTargeting() { return new GeoTargeting(); } /** * Create an instance of {@link BaseRateError } * */ public BaseRateError createBaseRateError() { return new BaseRateError(); } /** * Create an instance of {@link CustomFieldAction } * */ public CustomFieldAction createCustomFieldAction() { return new CustomFieldAction(); } /** * Create an instance of {@link AdRulePage } * */ public AdRulePage createAdRulePage() { return new AdRulePage(); } /** * Create an instance of {@link ProposalLineItem } * */ public ProposalLineItem createProposalLineItem() { return new ProposalLineItem(); } /** * Create an instance of {@link Content } * */ public Content createContent() { return new Content(); } /** * Create an instance of {@link SubmitProposalsForApproval } * */ public SubmitProposalsForApproval createSubmitProposalsForApproval() { return new SubmitProposalsForApproval(); } /** * Create an instance of {@link DeliveryData } * */ public DeliveryData createDeliveryData() { return new DeliveryData(); } /** * Create an instance of {@link DeleteCustomTargetingKeys } * */ public DeleteCustomTargetingKeys createDeleteCustomTargetingKeys() { return new DeleteCustomTargetingKeys(); } /** * Create an instance of {@link Proposal } * */ public Proposal createProposal() { return new Proposal(); } /** * Create an instance of {@link DropDownCustomFieldValue } * */ public DropDownCustomFieldValue createDropDownCustomFieldValue() { return new DropDownCustomFieldValue(); } /** * Create an instance of {@link User } * */ public User createUser() { return new User(); } /** * Create an instance of {@link ArchiveAdUnits } * */ public ArchiveAdUnits createArchiveAdUnits() { return new ArchiveAdUnits(); } /** * Create an instance of {@link RateCardActionError } * */ public RateCardActionError createRateCardActionError() { return new RateCardActionError(); } /** * Create an instance of {@link ArchiveProposals } * */ public ArchiveProposals createArchiveProposals() { return new ArchiveProposals(); } /** * Create an instance of {@link AudienceExtensionError } * */ public AudienceExtensionError createAudienceExtensionError() { return new AudienceExtensionError(); } /** * Create an instance of {@link RangeError } * */ public RangeError createRangeError() { return new RangeError(); } /** * Create an instance of {@link LiveStreamEvent } * */ public LiveStreamEvent createLiveStreamEvent() { return new LiveStreamEvent(); } /** * Create an instance of {@link RetractOrders } * */ public RetractOrders createRetractOrders() { return new RetractOrders(); } /** * Create an instance of {@link AssetCreativeTemplateVariableValue } * */ public AssetCreativeTemplateVariableValue createAssetCreativeTemplateVariableValue() { return new AssetCreativeTemplateVariableValue(); } /** * Create an instance of {@link RetractOrdersWithoutReservationChanges } * */ public RetractOrdersWithoutReservationChanges createRetractOrdersWithoutReservationChanges() { return new RetractOrdersWithoutReservationChanges(); } /** * Create an instance of {@link TimeOfDay } * */ public TimeOfDay createTimeOfDay() { return new TimeOfDay(); } /** * Create an instance of {@link ActivateLiveStreamEvents } * */ public ActivateLiveStreamEvents createActivateLiveStreamEvents() { return new ActivateLiveStreamEvents(); } /** * Create an instance of {@link LabelEntityAssociationError } * */ public LabelEntityAssociationError createLabelEntityAssociationError() { return new LabelEntityAssociationError(); } /** * Create an instance of {@link ContentMetadataKeyHierarchyTargeting } * */ public ContentMetadataKeyHierarchyTargeting createContentMetadataKeyHierarchyTargeting() { return new ContentMetadataKeyHierarchyTargeting(); } /** * Create an instance of {@link LineItem } * */ public LineItem createLineItem() { return new LineItem(); } /** * Create an instance of {@link Date } * */ public Date createDate() { return new Date(); } /** * Create an instance of {@link Contact } * */ public Contact createContact() { return new Contact(); } /** * Create an instance of {@link BillingError } * */ public BillingError createBillingError() { return new BillingError(); } /** * Create an instance of {@link RateCardPage } * */ public RateCardPage createRateCardPage() { return new RateCardPage(); } /** * Create an instance of {@link LineItemCreativeAssociation } * */ public LineItemCreativeAssociation createLineItemCreativeAssociation() { return new LineItemCreativeAssociation(); } /** * Create an instance of {@link RateCardError } * */ public RateCardError createRateCardError() { return new RateCardError(); } /** * Create an instance of {@link ProductBaseRate } * */ public ProductBaseRate createProductBaseRate() { return new ProductBaseRate(); } /** * Create an instance of {@link CustomField } * */ public CustomField createCustomField() { return new CustomField(); } /** * Create an instance of {@link OptimizedPoddingAdRuleSlot } * */ public OptimizedPoddingAdRuleSlot createOptimizedPoddingAdRuleSlot() { return new OptimizedPoddingAdRuleSlot(); } /** * Create an instance of {@link ExcludeContentFromContentBundle } * */ public ExcludeContentFromContentBundle createExcludeContentFromContentBundle() { return new ExcludeContentFromContentBundle(); } /** * Create an instance of {@link DeactivateProductTemplates } * */ public DeactivateProductTemplates createDeactivateProductTemplates() { return new DeactivateProductTemplates(); } /** * Create an instance of {@link LabelFrequencyCap } * */ public LabelFrequencyCap createLabelFrequencyCap() { return new LabelFrequencyCap(); } /** * Create an instance of {@link LineItemCreativeAssociationOperationError } * */ public LineItemCreativeAssociationOperationError createLineItemCreativeAssociationOperationError() { return new LineItemCreativeAssociationOperationError(); } /** * Create an instance of {@link UnarchiveProposalLineItems } * */ public UnarchiveProposalLineItems createUnarchiveProposalLineItems() { return new UnarchiveProposalLineItems(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SoapResponseHeader }{@code >}} * */ @XmlElementDecl(namespace = "https://www.google.com/apis/ads/publisher/v201408", name = "ResponseHeader") public JAXBElement<SoapResponseHeader> createResponseHeader(SoapResponseHeader value) { return new JAXBElement<SoapResponseHeader>(_ResponseHeader_QNAME, SoapResponseHeader.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ApiException }{@code >}} * */ @XmlElementDecl(namespace = "https://www.google.com/apis/ads/publisher/v201408", name = "ApiExceptionFault") public JAXBElement<ApiException> createApiExceptionFault(ApiException value) { return new JAXBElement<ApiException>(_ApiExceptionFault_QNAME, ApiException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SoapRequestHeader }{@code >}} * */ @XmlElementDecl(namespace = "https://www.google.com/apis/ads/publisher/v201408", name = "RequestHeader") public JAXBElement<SoapRequestHeader> createRequestHeader(SoapRequestHeader value) { return new JAXBElement<SoapRequestHeader>(_RequestHeader_QNAME, SoapRequestHeader.class, null, value); } }
apache-2.0
salyh/elasticsearch
src/main/java/org/elasticsearch/rest/action/admin/indices/alias/head/RestAliasesExistAction.java
3512
/* * 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.rest.action.admin.indices.alias.head; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.indices.alias.exists.AliasesExistResponse; import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.Client; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.*; import static org.elasticsearch.rest.RestRequest.Method.HEAD; import static org.elasticsearch.rest.RestStatus.NOT_FOUND; import static org.elasticsearch.rest.RestStatus.OK; /** */ public class RestAliasesExistAction extends BaseRestHandler { @Inject public RestAliasesExistAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(HEAD, "/_alias/{name}", this); controller.registerHandler(HEAD, "/{index}/_alias/{name}", this); controller.registerHandler(HEAD, "/{index}/_alias", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel) { String[] aliases = request.paramAsStringArray("name", Strings.EMPTY_ARRAY); final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases); getAliasesRequest.indices(indices); getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions())); getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local())); client.admin().indices().aliasesExist(getAliasesRequest, new ActionListener<AliasesExistResponse>() { @Override public void onResponse(AliasesExistResponse response) { try { if (response.isExists()) { channel.sendResponse(new BytesRestResponse(OK)); } else { channel.sendResponse(new BytesRestResponse(NOT_FOUND)); } } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e))); } catch (Exception e1) { logger.error("Failed to send failure response", e1); } } }); } }
apache-2.0
rasheedamir/jimfs
jimfs/src/main/java/com/google/common/jimfs/Name.java
3978
/* * 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 com.google.common.jimfs; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.collect.Ordering; import javax.annotation.Nullable; /** * Immutable representation of a file name. Used both for the name components of paths and as the * keys for directory entries. * * <p>A name has both a display string (used in the {@code toString()} form of a {@code Path} as * well as for {@code Path} equality and sort ordering) and a canonical string, which is used for * determining equality of the name during file lookup. * * <p>Note: all factory methods return a constant name instance when given the original string "." * or "..", ensuring that those names can be accessed statically elsewhere in the code while still * being equal to any names created for those values, regardless of normalization settings. * * @author Colin Decker */ final class Name { /** The empty name. */ static final Name EMPTY = new Name("", ""); /** The name to use for a link from a directory to itself. */ public static final Name SELF = new Name(".", "."); /** The name to use for a link from a directory to its parent directory. */ public static final Name PARENT = new Name("..", ".."); /** * Creates a new name with no normalization done on the given string. */ @VisibleForTesting static Name simple(String name) { switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } } /** * Creates a name with the given display representation and the given canonical representation. */ public static Name create(String display, String canonical) { return new Name(display, canonical); } private final String display; private final String canonical; private Name(String display, String canonical) { this.display = checkNotNull(display); this.canonical = checkNotNull(canonical); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof Name) { Name other = (Name) obj; return canonical.equals(other.canonical); } return false; } @Override public int hashCode() { return Util.smearHash(canonical.hashCode()); } @Override public String toString() { return display; } /** * Returns an ordering that orders names by their display representation. */ public static Ordering<Name> displayOrdering() { return DISPLAY_ORDERING; } /** * Returns an ordering that orders names by their canonical representation. */ public static Ordering<Name> canonicalOrdering() { return CANONICAL_ORDERING; } private static final Ordering<Name> DISPLAY_ORDERING = Ordering.natural() .onResultOf( new Function<Name, String>() { @Override public String apply(Name name) { return name.display; } }); private static final Ordering<Name> CANONICAL_ORDERING = Ordering.natural() .onResultOf( new Function<Name, String>() { @Override public String apply(Name name) { return name.canonical; } }); }
apache-2.0
gkatsikas/onos
core/api/src/main/java/org/onosproject/net/intent/constraint/NonDisruptiveConstraint.java
1975
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.intent.constraint; import org.onosproject.net.intent.ConnectivityIntent; import org.onosproject.net.intent.Intent; /** * Constraint to request a non-disruptive intent reallocation. */ public final class NonDisruptiveConstraint extends MarkerConstraint { private static final NonDisruptiveConstraint NON_DISRUPTIVE_CONSTRAINT = new NonDisruptiveConstraint(); protected NonDisruptiveConstraint() { } /** * Determines whether the intent requires a non-disruptive reallocation. * * @param intent intent to be inspected * @return whether the intent has a NonDisruptiveConstraint */ public static boolean requireNonDisruptive(Intent intent) { if (intent instanceof ConnectivityIntent) { ConnectivityIntent connectivityIntent = (ConnectivityIntent) intent; return connectivityIntent.constraints().stream() .anyMatch(p -> p instanceof NonDisruptiveConstraint); } return false; } /** * Returns the nonDisruptiveConstraint. * * @return non-disruptive constraint */ public static NonDisruptiveConstraint nonDisruptive() { return NON_DISRUPTIVE_CONSTRAINT; } @Override public String toString() { return "Non-disruptive reallocation required"; } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/cluster/MembershipAdapter.java
1039
/* * Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.cluster; /** * Adapter for MembershipListener. All the methods are implemented and only override the relevant methods * * @see MembershipListener */ public class MembershipAdapter implements MembershipListener { @Override public void memberAdded(MembershipEvent membershipEvent) { } @Override public void memberRemoved(MembershipEvent membershipEvent) { } }
apache-2.0
anishek/hive
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMDropMappingRequest.java
12338
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class WMDropMappingRequest implements org.apache.thrift.TBase<WMDropMappingRequest, WMDropMappingRequest._Fields>, java.io.Serializable, Cloneable, Comparable<WMDropMappingRequest> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("WMDropMappingRequest"); private static final org.apache.thrift.protocol.TField MAPPING_FIELD_DESC = new org.apache.thrift.protocol.TField("mapping", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new WMDropMappingRequestStandardSchemeFactory()); schemes.put(TupleScheme.class, new WMDropMappingRequestTupleSchemeFactory()); } private WMMapping mapping; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { MAPPING((short)1, "mapping"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // MAPPING return MAPPING; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.MAPPING}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.MAPPING, new org.apache.thrift.meta_data.FieldMetaData("mapping", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, WMMapping.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(WMDropMappingRequest.class, metaDataMap); } public WMDropMappingRequest() { } /** * Performs a deep copy on <i>other</i>. */ public WMDropMappingRequest(WMDropMappingRequest other) { if (other.isSetMapping()) { this.mapping = new WMMapping(other.mapping); } } public WMDropMappingRequest deepCopy() { return new WMDropMappingRequest(this); } @Override public void clear() { this.mapping = null; } public WMMapping getMapping() { return this.mapping; } public void setMapping(WMMapping mapping) { this.mapping = mapping; } public void unsetMapping() { this.mapping = null; } /** Returns true if field mapping is set (has been assigned a value) and false otherwise */ public boolean isSetMapping() { return this.mapping != null; } public void setMappingIsSet(boolean value) { if (!value) { this.mapping = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case MAPPING: if (value == null) { unsetMapping(); } else { setMapping((WMMapping)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case MAPPING: return getMapping(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case MAPPING: return isSetMapping(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof WMDropMappingRequest) return this.equals((WMDropMappingRequest)that); return false; } public boolean equals(WMDropMappingRequest that) { if (that == null) return false; boolean this_present_mapping = true && this.isSetMapping(); boolean that_present_mapping = true && that.isSetMapping(); if (this_present_mapping || that_present_mapping) { if (!(this_present_mapping && that_present_mapping)) return false; if (!this.mapping.equals(that.mapping)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_mapping = true && (isSetMapping()); list.add(present_mapping); if (present_mapping) list.add(mapping); return list.hashCode(); } @Override public int compareTo(WMDropMappingRequest other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetMapping()).compareTo(other.isSetMapping()); if (lastComparison != 0) { return lastComparison; } if (isSetMapping()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.mapping, other.mapping); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("WMDropMappingRequest("); boolean first = true; if (isSetMapping()) { sb.append("mapping:"); if (this.mapping == null) { sb.append("null"); } else { sb.append(this.mapping); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (mapping != null) { mapping.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class WMDropMappingRequestStandardSchemeFactory implements SchemeFactory { public WMDropMappingRequestStandardScheme getScheme() { return new WMDropMappingRequestStandardScheme(); } } private static class WMDropMappingRequestStandardScheme extends StandardScheme<WMDropMappingRequest> { public void read(org.apache.thrift.protocol.TProtocol iprot, WMDropMappingRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // MAPPING if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.mapping = new WMMapping(); struct.mapping.read(iprot); struct.setMappingIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, WMDropMappingRequest struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.mapping != null) { if (struct.isSetMapping()) { oprot.writeFieldBegin(MAPPING_FIELD_DESC); struct.mapping.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class WMDropMappingRequestTupleSchemeFactory implements SchemeFactory { public WMDropMappingRequestTupleScheme getScheme() { return new WMDropMappingRequestTupleScheme(); } } private static class WMDropMappingRequestTupleScheme extends TupleScheme<WMDropMappingRequest> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, WMDropMappingRequest struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetMapping()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetMapping()) { struct.mapping.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, WMDropMappingRequest struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.mapping = new WMMapping(); struct.mapping.read(iprot); struct.setMappingIsSet(true); } } } }
apache-2.0
ieure/mina-sshd
sshd-core/src/main/java/org/apache/sshd/agent/SshAgent.java
1460
/* * 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.sshd.agent; import java.io.IOException; import java.security.KeyPair; import java.security.PublicKey; import java.util.List; import org.apache.sshd.common.util.Pair; /** * SSH key agent server */ public interface SshAgent extends java.nio.channels.Channel { String SSH_AUTHSOCKET_ENV_NAME = "SSH_AUTH_SOCK"; List<Pair<PublicKey, String>> getIdentities() throws IOException; byte[] sign(PublicKey key, byte[] data) throws IOException; void addIdentity(KeyPair key, String comment) throws IOException; void removeIdentity(PublicKey key) throws IOException; void removeAllIdentities() throws IOException; }
apache-2.0
JSDemos/android-sdk-20
src/java/util/concurrent/ConcurrentLinkedQueue.java
29821
/* * Written by Doug Lea and Martin Buchholz with assistance from members of * JCP JSR-166 Expert Group and released to the public domain, as explained * at http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.AbstractQueue; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; // BEGIN android-note // removed link to collections framework docs // END android-note /** * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes. * This queue orders elements FIFO (first-in-first-out). * The <em>head</em> of the queue is that element that has been on the * queue the longest time. * The <em>tail</em> of the queue is that element that has been on the * queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * A {@code ConcurrentLinkedQueue} is an appropriate choice when * many threads will share access to a common collection. * Like most other concurrent collection implementations, this class * does not permit the use of {@code null} elements. * * <p>This implementation employs an efficient <em>non-blocking</em> * algorithm based on one described in <a * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple, * Fast, and Practical Non-Blocking and Blocking Concurrent Queue * Algorithms</a> by Maged M. Michael and Michael L. Scott. * * <p>Iterators are <i>weakly consistent</i>, returning elements * reflecting the state of the queue at some point at or since the * creation of the iterator. They do <em>not</em> throw {@link * java.util.ConcurrentModificationException}, and may proceed concurrently * with other operations. Elements contained in the queue since the creation * of the iterator will be returned exactly once. * * <p>Beware that, unlike in most collections, the {@code size} method * is <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current number * of elements requires a traversal of the elements, and so may report * inaccurate results if this collection is modified during traversal. * Additionally, the bulk operations {@code addAll}, * {@code removeAll}, {@code retainAll}, {@code containsAll}, * {@code equals}, and {@code toArray} are <em>not</em> guaranteed * to be performed atomically. For example, an iterator operating * concurrently with an {@code addAll} operation might view only some * of the added elements. * * <p>This class and its iterator implement all of the <em>optional</em> * methods of the {@link Queue} and {@link Iterator} interfaces. * * <p>Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code ConcurrentLinkedQueue} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code ConcurrentLinkedQueue} in another thread. * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> implements Queue<E>, java.io.Serializable { private static final long serialVersionUID = 196745693267521676L; /* * This is a modification of the Michael & Scott algorithm, * adapted for a garbage-collected environment, with support for * interior node deletion (to support remove(Object)). For * explanation, read the paper. * * Note that like most non-blocking algorithms in this package, * this implementation relies on the fact that in garbage * collected systems, there is no possibility of ABA problems due * to recycled nodes, so there is no need to use "counted * pointers" or related techniques seen in versions used in * non-GC'ed settings. * * The fundamental invariants are: * - There is exactly one (last) Node with a null next reference, * which is CASed when enqueueing. This last Node can be * reached in O(1) time from tail, but tail is merely an * optimization - it can always be reached in O(N) time from * head as well. * - The elements contained in the queue are the non-null items in * Nodes that are reachable from head. CASing the item * reference of a Node to null atomically removes it from the * queue. Reachability of all elements from head must remain * true even in the case of concurrent modifications that cause * head to advance. A dequeued Node may remain in use * indefinitely due to creation of an Iterator or simply a * poll() that has lost its time slice. * * The above might appear to imply that all Nodes are GC-reachable * from a predecessor dequeued Node. That would cause two problems: * - allow a rogue Iterator to cause unbounded memory retention * - cause cross-generational linking of old Nodes to new Nodes if * a Node was tenured while live, which generational GCs have a * hard time dealing with, causing repeated major collections. * However, only non-deleted Nodes need to be reachable from * dequeued Nodes, and reachability does not necessarily have to * be of the kind understood by the GC. We use the trick of * linking a Node that has just been dequeued to itself. Such a * self-link implicitly means to advance to head. * * Both head and tail are permitted to lag. In fact, failing to * update them every time one could is a significant optimization * (fewer CASes). As with LinkedTransferQueue (see the internal * documentation for that class), we use a slack threshold of two; * that is, we update head/tail when the current pointer appears * to be two or more steps away from the first/last node. * * Since head and tail are updated concurrently and independently, * it is possible for tail to lag behind head (why not)? * * CASing a Node's item reference to null atomically removes the * element from the queue. Iterators skip over Nodes with null * items. Prior implementations of this class had a race between * poll() and remove(Object) where the same element would appear * to be successfully removed by two concurrent operations. The * method remove(Object) also lazily unlinks deleted Nodes, but * this is merely an optimization. * * When constructing a Node (before enqueuing it) we avoid paying * for a volatile write to item by using Unsafe.putObject instead * of a normal write. This allows the cost of enqueue to be * "one-and-a-half" CASes. * * Both head and tail may or may not point to a Node with a * non-null item. If the queue is empty, all items must of course * be null. Upon creation, both head and tail refer to a dummy * Node with null item. Both head and tail are only updated using * CAS, so they never regress, although again this is merely an * optimization. */ private static class Node<E> { volatile E item; volatile Node<E> next; /** * Constructs a new node. Uses relaxed write because item can * only be seen after publication via casNext. */ Node(E item) { UNSAFE.putObject(this, itemOffset, item); } boolean casItem(E cmp, E val) { return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val); } void lazySetNext(Node<E> val) { UNSAFE.putOrderedObject(this, nextOffset, val); } boolean casNext(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long itemOffset; private static final long nextOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = Node.class; itemOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("item")); nextOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("next")); } catch (Exception e) { throw new Error(e); } } } /** * A node from which the first live (non-deleted) node (if any) * can be reached in O(1) time. * Invariants: * - all live nodes are reachable from head via succ() * - head != null * - (tmp = head).next != tmp || tmp != head * Non-invariants: * - head.item may or may not be null. * - it is permitted for tail to lag behind head, that is, for tail * to not be reachable from head! */ private transient volatile Node<E> head; /** * A node from which the last node on list (that is, the unique * node with node.next == null) can be reached in O(1) time. * Invariants: * - the last node is always reachable from tail via succ() * - tail != null * Non-invariants: * - tail.item may or may not be null. * - it is permitted for tail to lag behind head, that is, for tail * to not be reachable from head! * - tail.next may or may not be self-pointing to tail. */ private transient volatile Node<E> tail; /** * Creates a {@code ConcurrentLinkedQueue} that is initially empty. */ public ConcurrentLinkedQueue() { head = tail = new Node<E>(null); } /** * Creates a {@code ConcurrentLinkedQueue} * initially containing the elements of the given collection, * added in traversal order of the collection's iterator. * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public ConcurrentLinkedQueue(Collection<? extends E> c) { Node<E> h = null, t = null; for (E e : c) { checkNotNull(e); Node<E> newNode = new Node<E>(e); if (h == null) h = t = newNode; else { t.lazySetNext(newNode); t = newNode; } } if (h == null) h = t = new Node<E>(null); head = h; tail = t; } // Have to override just to update the javadoc /** * Inserts the specified element at the tail of this queue. * As the queue is unbounded, this method will never throw * {@link IllegalStateException} or return {@code false}. * * @return {@code true} (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return offer(e); } /** * Tries to CAS head to p. If successful, repoint old head to itself * as sentinel for succ(), below. */ final void updateHead(Node<E> h, Node<E> p) { if (h != p && casHead(h, p)) h.lazySetNext(h); } /** * Returns the successor of p, or the head node if p.next has been * linked to self, which will only be true if traversing with a * stale pointer that is now off the list. */ final Node<E> succ(Node<E> p) { Node<E> next = p.next; return (p == next) ? head : next; } /** * Inserts the specified element at the tail of this queue. * As the queue is unbounded, this method will never return {@code false}. * * @return {@code true} (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { checkNotNull(e); final Node<E> newNode = new Node<E>(e); for (Node<E> t = tail, p = t;;) { Node<E> q = p.next; if (q == null) { // p is last node if (p.casNext(null, newNode)) { // Successful CAS is the linearization point // for e to become an element of this queue, // and for newNode to become "live". if (p != t) // hop two nodes at a time casTail(t, newNode); // Failure is OK. return true; } // Lost CAS race to another thread; re-read next } else if (p == q) // We have fallen off list. If tail is unchanged, it // will also be off-list, in which case we need to // jump to head, from which all live nodes are always // reachable. Else the new tail is a better bet. p = (t != (t = tail)) ? t : head; else // Check for tail updates after two hops. p = (p != t && t != (t = tail)) ? t : q; } } public E poll() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; if (item != null && p.casItem(item, null)) { // Successful CAS is the linearization point // for item to be removed from this queue. if (p != h) // hop two nodes at a time updateHead(h, ((q = p.next) != null) ? q : p); return item; } else if ((q = p.next) == null) { updateHead(h, p); return null; } else if (p == q) continue restartFromHead; else p = q; } } } public E peek() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; if (item != null || (q = p.next) == null) { updateHead(h, p); return item; } else if (p == q) continue restartFromHead; else p = q; } } } /** * Returns the first live (non-deleted) node on list, or null if none. * This is yet another variant of poll/peek; here returning the * first node, not element. We could make peek() a wrapper around * first(), but that would cost an extra volatile read of item, * and the need to add a retry loop to deal with the possibility * of losing a race to a concurrent poll(). */ Node<E> first() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { boolean hasItem = (p.item != null); if (hasItem || (q = p.next) == null) { updateHead(h, p); return hasItem ? p : null; } else if (p == q) continue restartFromHead; else p = q; } } } /** * Returns {@code true} if this queue contains no elements. * * @return {@code true} if this queue contains no elements */ public boolean isEmpty() { return first() == null; } /** * Returns the number of elements in this queue. If this queue * contains more than {@code Integer.MAX_VALUE} elements, returns * {@code Integer.MAX_VALUE}. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these queues, determining the current * number of elements requires an O(n) traversal. * Additionally, if elements are added or removed during execution * of this method, the returned result may be inaccurate. Thus, * this method is typically not very useful in concurrent * applications. * * @return the number of elements in this queue */ public int size() { int count = 0; for (Node<E> p = first(); p != null; p = succ(p)) if (p.item != null) // Collection.size() spec says to max out if (++count == Integer.MAX_VALUE) break; return count; } /** * Returns {@code true} if this queue contains the specified element. * More formally, returns {@code true} if and only if this queue contains * at least one element {@code e} such that {@code o.equals(e)}. * * @param o object to be checked for containment in this queue * @return {@code true} if this queue contains the specified element */ public boolean contains(Object o) { if (o == null) return false; for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null && o.equals(item)) return true; } return false; } /** * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element {@code e} such * that {@code o.equals(e)}, if this queue contains one or more such * elements. * Returns {@code true} if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * * @param o element to be removed from this queue, if present * @return {@code true} if this queue changed as a result of the call */ public boolean remove(Object o) { if (o == null) return false; Node<E> pred = null; for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null && o.equals(item) && p.casItem(item, null)) { Node<E> next = succ(p); if (pred != null && next != null) pred.casNext(p, next); return true; } pred = p; } return false; } /** * Appends all of the elements in the specified collection to the end of * this queue, in the order that they are returned by the specified * collection's iterator. Attempts to {@code addAll} of a queue to * itself result in {@code IllegalArgumentException}. * * @param c the elements to be inserted into this queue * @return {@code true} if this queue changed as a result of the call * @throws NullPointerException if the specified collection or any * of its elements are null * @throws IllegalArgumentException if the collection is this queue */ public boolean addAll(Collection<? extends E> c) { if (c == this) // As historically specified in AbstractQueue#addAll throw new IllegalArgumentException(); // Copy c into a private chain of Nodes Node<E> beginningOfTheEnd = null, last = null; for (E e : c) { checkNotNull(e); Node<E> newNode = new Node<E>(e); if (beginningOfTheEnd == null) beginningOfTheEnd = last = newNode; else { last.lazySetNext(newNode); last = newNode; } } if (beginningOfTheEnd == null) return false; // Atomically append the chain at the tail of this collection for (Node<E> t = tail, p = t;;) { Node<E> q = p.next; if (q == null) { // p is last node if (p.casNext(null, beginningOfTheEnd)) { // Successful CAS is the linearization point // for all elements to be added to this queue. if (!casTail(t, last)) { // Try a little harder to update tail, // since we may be adding many elements. t = tail; if (last.next == null) casTail(t, last); } return true; } // Lost CAS race to another thread; re-read next } else if (p == q) // We have fallen off list. If tail is unchanged, it // will also be off-list, in which case we need to // jump to head, from which all live nodes are always // reachable. Else the new tail is a better bet. p = (t != (t = tail)) ? t : head; else // Check for tail updates after two hops. p = (p != t && t != (t = tail)) ? t : q; } } /** * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this queue */ public Object[] toArray() { // Use ArrayList to deal with resizing. ArrayList<E> al = new ArrayList<E>(); for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) al.add(item); } return al.toArray(); } /** * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * {@code null}. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose {@code x} is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of {@code String}: * * <pre> {@code String[] y = x.toArray(new String[0]);}</pre> * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // try to use sent-in array int k = 0; Node<E> p; for (p = first(); p != null && k < a.length; p = succ(p)) { E item = p.item; if (item != null) a[k++] = (T)item; } if (p == null) { if (k < a.length) a[k] = null; return a; } // If won't fit, use ArrayList version ArrayList<E> al = new ArrayList<E>(); for (Node<E> q = first(); q != null; q = succ(q)) { E item = q.item; if (item != null) al.add(item); } return al.toArray(a); } /** * Returns an iterator over the elements in this queue in proper sequence. * The elements will be returned in order from first (head) to last (tail). * * <p>The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException * ConcurrentModificationException}, and guarantees to traverse * elements as they existed upon construction of the iterator, and * may (but is not guaranteed to) reflect any modifications * subsequent to construction. * * @return an iterator over the elements in this queue in proper sequence */ public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { /** * Next node to return item for. */ private Node<E> nextNode; /** * nextItem holds on to item fields because once we claim * that an element exists in hasNext(), we must return it in * the following next() call even if it was in the process of * being removed when hasNext() was called. */ private E nextItem; /** * Node of the last returned item, to support remove. */ private Node<E> lastRet; Itr() { advance(); } /** * Moves to next valid node and returns item to return for * next(), or null if no such. */ private E advance() { lastRet = nextNode; E x = nextItem; Node<E> pred, p; if (nextNode == null) { p = first(); pred = null; } else { pred = nextNode; p = succ(nextNode); } for (;;) { if (p == null) { nextNode = null; nextItem = null; return x; } E item = p.item; if (item != null) { nextNode = p; nextItem = item; return x; } else { // skip over nulls Node<E> next = succ(p); if (pred != null && next != null) pred.casNext(p, next); p = next; } } } public boolean hasNext() { return nextNode != null; } public E next() { if (nextNode == null) throw new NoSuchElementException(); return advance(); } public void remove() { Node<E> l = lastRet; if (l == null) throw new IllegalStateException(); // rely on a future traversal to relink. l.item = null; lastRet = null; } } /** * Saves this queue to a stream (that is, serializes it). * * @serialData All of the elements (each an {@code E}) in * the proper order, followed by a null */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden stuff s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = first(); p != null; p = succ(p)) { Object item = p.item; if (item != null) s.writeObject(item); } // Use trailing null as sentinel s.writeObject(null); } /** * Reconstitutes this queue from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in elements until trailing null sentinel found Node<E> h = null, t = null; Object item; while ((item = s.readObject()) != null) { @SuppressWarnings("unchecked") Node<E> newNode = new Node<E>((E) item); if (h == null) h = t = newNode; else { t.lazySetNext(newNode); t = newNode; } } if (h == null) h = t = new Node<E>(null); head = h; tail = t; } /** * Throws NullPointerException if argument is null. * * @param v the element */ private static void checkNotNull(Object v) { if (v == null) throw new NullPointerException(); } private boolean casTail(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); } private boolean casHead(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long headOffset; private static final long tailOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = ConcurrentLinkedQueue.class; headOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("head")); tailOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("tail")); } catch (Exception e) { throw new Error(e); } } }
apache-2.0
10045125/retrofit
retrofit/src/main/java/retrofit/http/PartMap.java
1919
/* * Copyright (C) 2014 Square, 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 retrofit.http; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static retrofit.mime.MultipartTypedOutput.DEFAULT_TRANSFER_ENCODING; /** * Denotes name and value parts of a multi-part request * <p> * Values of the map on which this annotation exists will be processed in one of three ways: * <ul> * <li>If the type implements {@link retrofit.mime.TypedOutput TypedOutput} the headers and * body will be used directly.</li> * <li>If the type is {@link String} the value will also be used directly with a {@code text/plain} * content type.</li> * <li>Other object types will be converted to an appropriate representation by calling {@link * retrofit.converter.Converter#toBody(Object)}.</li> * </ul> * <p> * <pre> * &#64;Multipart * &#64;POST("/upload") * void upload(&#64;Part("file") TypedFile file, &#64;PartMap Map&lt;String, String&gt; params); * </pre> * <p> * * @see Multipart * @see Part */ @Documented @Target(PARAMETER) @Retention(RUNTIME) public @interface PartMap { /** The {@code Content-Transfer-Encoding} of this part. */ String encoding() default DEFAULT_TRANSFER_ENCODING; }
apache-2.0
henakamaMSFT/elasticsearch
core/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSourceAggregationBuilder.java
13052
/* * 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.support; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.script.Script; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AggregationInitializationException; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.AggregatorFactories.Builder; import org.elasticsearch.search.aggregations.AggregatorFactory; import org.elasticsearch.search.aggregations.InternalAggregation.Type; import org.elasticsearch.search.internal.SearchContext; import org.joda.time.DateTimeZone; import java.io.IOException; import java.util.Objects; public abstract class ValuesSourceAggregationBuilder<VS extends ValuesSource, AB extends ValuesSourceAggregationBuilder<VS, AB>> extends AbstractAggregationBuilder<AB> { public abstract static class LeafOnly<VS extends ValuesSource, AB extends ValuesSourceAggregationBuilder<VS, AB>> extends ValuesSourceAggregationBuilder<VS, AB> { protected LeafOnly(String name, Type type, ValuesSourceType valuesSourceType, ValueType targetValueType) { super(name, type, valuesSourceType, targetValueType); } /** * Read an aggregation from a stream that does not serialize its targetValueType. This should be used by most subclasses. */ protected LeafOnly(StreamInput in, Type type, ValuesSourceType valuesSourceType, ValueType targetValueType) throws IOException { super(in, type, valuesSourceType, targetValueType); } /** * Read an aggregation from a stream that serializes its targetValueType. This should only be used by subclasses that override * {@link #serializeTargetValueType()} to return true. */ protected LeafOnly(StreamInput in, Type type, ValuesSourceType valuesSourceType) throws IOException { super(in, type, valuesSourceType); } @Override public AB subAggregations(Builder subFactories) { throw new AggregationInitializationException("Aggregator [" + name + "] of type [" + type + "] cannot accept sub-aggregations"); } } private final ValuesSourceType valuesSourceType; private final ValueType targetValueType; private String field = null; private Script script = null; private ValueType valueType = null; private String format = null; private Object missing = null; private DateTimeZone timeZone = null; protected ValuesSourceConfig<VS> config; protected ValuesSourceAggregationBuilder(String name, Type type, ValuesSourceType valuesSourceType, ValueType targetValueType) { super(name, type); if (valuesSourceType == null) { throw new IllegalArgumentException("[valuesSourceType] must not be null: [" + name + "]"); } this.valuesSourceType = valuesSourceType; this.targetValueType = targetValueType; } /** * Read an aggregation from a stream that does not serialize its targetValueType. This should be used by most subclasses. */ protected ValuesSourceAggregationBuilder(StreamInput in, Type type, ValuesSourceType valuesSourceType, ValueType targetValueType) throws IOException { super(in, type); assert false == serializeTargetValueType() : "Wrong read constructor called for subclass that provides its targetValueType"; this.valuesSourceType = valuesSourceType; this.targetValueType = targetValueType; read(in); } /** * Read an aggregation from a stream that serializes its targetValueType. This should only be used by subclasses that override * {@link #serializeTargetValueType()} to return true. */ protected ValuesSourceAggregationBuilder(StreamInput in, Type type, ValuesSourceType valuesSourceType) throws IOException { super(in, type); assert serializeTargetValueType() : "Wrong read constructor called for subclass that serializes its targetValueType"; this.valuesSourceType = valuesSourceType; this.targetValueType = in.readOptionalWriteable(ValueType::readFromStream); read(in); } /** * Read from a stream. */ private void read(StreamInput in) throws IOException { field = in.readOptionalString(); if (in.readBoolean()) { script = new Script(in); } if (in.readBoolean()) { valueType = ValueType.readFromStream(in); } format = in.readOptionalString(); missing = in.readGenericValue(); if (in.readBoolean()) { timeZone = DateTimeZone.forID(in.readString()); } } @Override protected final void doWriteTo(StreamOutput out) throws IOException { if (serializeTargetValueType()) { out.writeOptionalWriteable(targetValueType); } out.writeOptionalString(field); boolean hasScript = script != null; out.writeBoolean(hasScript); if (hasScript) { script.writeTo(out); } boolean hasValueType = valueType != null; out.writeBoolean(hasValueType); if (hasValueType) { valueType.writeTo(out); } out.writeOptionalString(format); out.writeGenericValue(missing); boolean hasTimeZone = timeZone != null; out.writeBoolean(hasTimeZone); if (hasTimeZone) { out.writeString(timeZone.getID()); } innerWriteTo(out); } /** * Write subclass's state to the stream. */ protected abstract void innerWriteTo(StreamOutput out) throws IOException; /** * Should this builder serialize its targetValueType? Defaults to false. All subclasses that override this to true should use the three * argument read constructor rather than the four argument version. */ protected boolean serializeTargetValueType() { return false; } /** * Sets the field to use for this aggregation. */ @SuppressWarnings("unchecked") public AB field(String field) { if (field == null) { throw new IllegalArgumentException("[field] must not be null: [" + name + "]"); } this.field = field; return (AB) this; } /** * Gets the field to use for this aggregation. */ public String field() { return field; } /** * Sets the script to use for this aggregation. */ @SuppressWarnings("unchecked") public AB script(Script script) { if (script == null) { throw new IllegalArgumentException("[script] must not be null: [" + name + "]"); } this.script = script; return (AB) this; } /** * Gets the script to use for this aggregation. */ public Script script() { return script; } /** * Sets the {@link ValueType} for the value produced by this aggregation */ @SuppressWarnings("unchecked") public AB valueType(ValueType valueType) { if (valueType == null) { throw new IllegalArgumentException("[valueType] must not be null: [" + name + "]"); } this.valueType = valueType; return (AB) this; } /** * Gets the {@link ValueType} for the value produced by this aggregation */ public ValueType valueType() { return valueType; } /** * Sets the format to use for the output of the aggregation. */ @SuppressWarnings("unchecked") public AB format(String format) { if (format == null) { throw new IllegalArgumentException("[format] must not be null: [" + name + "]"); } this.format = format; return (AB) this; } /** * Gets the format to use for the output of the aggregation. */ public String format() { return format; } /** * Sets the value to use when the aggregation finds a missing value in a * document */ @SuppressWarnings("unchecked") public AB missing(Object missing) { if (missing == null) { throw new IllegalArgumentException("[missing] must not be null: [" + name + "]"); } this.missing = missing; return (AB) this; } /** * Gets the value to use when the aggregation finds a missing value in a * document */ public Object missing() { return missing; } /** * Sets the time zone to use for this aggregation */ @SuppressWarnings("unchecked") public AB timeZone(DateTimeZone timeZone) { if (timeZone == null) { throw new IllegalArgumentException("[timeZone] must not be null: [" + name + "]"); } this.timeZone = timeZone; return (AB) this; } /** * Gets the time zone to use for this aggregation */ public DateTimeZone timeZone() { return timeZone; } @Override protected final ValuesSourceAggregatorFactory<VS, ?> doBuild(SearchContext context, AggregatorFactory<?> parent, AggregatorFactories.Builder subFactoriesBuilder) throws IOException { ValuesSourceConfig<VS> config = resolveConfig(context); ValuesSourceAggregatorFactory<VS, ?> factory = innerBuild(context, config, parent, subFactoriesBuilder); return factory; } protected ValuesSourceConfig<VS> resolveConfig(SearchContext context) { ValueType valueType = this.valueType != null ? this.valueType : targetValueType; return ValuesSourceConfig.resolve(context.getQueryShardContext(), valueType, field, script, missing, timeZone, format); } protected abstract ValuesSourceAggregatorFactory<VS, ?> innerBuild(SearchContext context, ValuesSourceConfig<VS> config, AggregatorFactory<?> parent, AggregatorFactories.Builder subFactoriesBuilder) throws IOException; @Override public final XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (field != null) { builder.field("field", field); } if (script != null) { builder.field("script", script); } if (missing != null) { builder.field("missing", missing); } if (format != null) { builder.field("format", format); } if (timeZone != null) { builder.field("time_zone", timeZone); } if (valueType != null) { builder.field("value_type", valueType.getPreferredName()); } doXContentBody(builder, params); builder.endObject(); return builder; } protected abstract XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException; @Override protected final int doHashCode() { return Objects.hash(field, format, missing, script, targetValueType, timeZone, valueType, valuesSourceType, innerHashCode()); } protected abstract int innerHashCode(); @Override protected final boolean doEquals(Object obj) { ValuesSourceAggregationBuilder<?, ?> other = (ValuesSourceAggregationBuilder<?, ?>) obj; if (!Objects.equals(field, other.field)) return false; if (!Objects.equals(format, other.format)) return false; if (!Objects.equals(missing, other.missing)) return false; if (!Objects.equals(script, other.script)) return false; if (!Objects.equals(targetValueType, other.targetValueType)) return false; if (!Objects.equals(timeZone, other.timeZone)) return false; if (!Objects.equals(valueType, other.valueType)) return false; if (!Objects.equals(valuesSourceType, other.valuesSourceType)) return false; return innerEquals(obj); } protected abstract boolean innerEquals(Object obj); }
apache-2.0
LegNeato/buck
src/com/facebook/buck/cxx/AbstractElfSharedLibraryInterfaceFactory.java
3228
/* * Copyright 2016-present Facebook, 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.facebook.buck.cxx; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.toolchain.toolprovider.ToolProvider; import com.facebook.buck.core.util.immutables.BuckStylePackageVisibleTuple; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.ElfSharedLibraryInterfaceParams; import com.facebook.buck.cxx.toolchain.SharedLibraryInterfaceFactory; import com.facebook.buck.cxx.toolchain.linker.Linker; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.args.Arg; import com.google.common.collect.ImmutableList; import org.immutables.value.Value; @Value.Immutable @BuckStylePackageVisibleTuple abstract class AbstractElfSharedLibraryInterfaceFactory implements SharedLibraryInterfaceFactory { abstract ToolProvider getObjcopy(); abstract boolean isRemoveUndefinedSymbols(); @Override public final BuildRule createSharedInterfaceLibraryFromLibrary( BuildTarget target, ProjectFilesystem projectFilesystem, BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CxxPlatform cxxPlatform, SourcePath library) { return ElfSharedLibraryInterface.from( target, projectFilesystem, pathResolver, ruleFinder, getObjcopy().resolve(resolver), library, isRemoveUndefinedSymbols()); } @Override public final BuildRule createSharedInterfaceLibraryFromLinkableInput( BuildTarget target, ProjectFilesystem projectFilesystem, BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, String libName, Linker linker, ImmutableList<Arg> args) { return ElfSharedLibraryInterface.from( target, projectFilesystem, ruleFinder, getObjcopy().resolve(resolver), libName, linker, args, isRemoveUndefinedSymbols()); } @Override public Iterable<BuildTarget> getParseTimeDeps() { return getObjcopy().getParseTimeDeps(); } public static ElfSharedLibraryInterfaceFactory from(ElfSharedLibraryInterfaceParams params) { return ElfSharedLibraryInterfaceFactory.of( params.getObjcopy(), params.isRemoveUndefinedSymbols()); } }
apache-2.0
arehart13/smile
core/src/test/java/smile/wavelet/CoifletWaveletTest.java
1862
/******************************************************************************* * Copyright (c) 2010 Haifeng Li * * 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 smile.wavelet; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Haifeng Li */ public class CoifletWaveletTest { public CoifletWaveletTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testFilter() { System.out.println("filter"); for (int p = 6; p <= 30; p += 6) { System.out.format("p = %d\n", p); double[] a = {.2, -.4, -.6, -.5, -.8, -.4, -.9, 0, -.2, .1, -.1, .1, .7, .9, 0, .3}; double[] b = a.clone(); Wavelet instance = new CoifletWavelet(p); instance.transform(a); instance.inverse(a); for (int i = 0; i < a.length; i++) { assertEquals(b[i], a[i], 1E-6); } } } }
apache-2.0
floodlight/floodlight
src/test/java/net/floodlightcontroller/hasupport/topology/TopoFilterQueueTest.java
3364
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.hasupport.topology; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sdnplatform.sync.IStoreClient; public class TopoFilterQueueTest { protected static IStoreClient<String, String> storeTopo; protected static String controllerID = "none"; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testDequeueForward() { TopoFilterQueue Topof2 = new TopoFilterQueue(storeTopo, controllerID); String testJson = new String("{\"src\":\"00:00:00:00:00:00:00:05\",\"operation\":\"Switch Removed\"}"); assertEquals(Topof2.enqueueForward(testJson), true); Topof2.dequeueForward(); assertEquals(TopoFilterQueue.filterQueue.size(), 0); TopoFilterQueue.myMap.clear(); TopoFilterQueue.filterQueue.clear(); } @Test public void testDequeueForward2() { TopoFilterQueue Topof2 = new TopoFilterQueue(storeTopo, controllerID); assertEquals(Topof2.dequeueForward(), false); } @Test public void testEnqueueForward() { TopoFilterQueue tf = new TopoFilterQueue(storeTopo, controllerID); assertEquals(tf.enqueueForward("cat"), true); assertEquals(TopoFilterQueue.myMap.get("d077f244def8a70e5ea758bd8352fcd8"), "cat"); TopoFilterQueue.myMap.clear(); TopoFilterQueue.filterQueue.clear(); } @Test public void testEnqueueForward2() { TopoFilterQueue Topof2 = new TopoFilterQueue(storeTopo, controllerID); String testJson = new String("{\"src\":\"00:00:00:00:00:00:00:05\",\"operation\":\"Switch Removed\"}"); assertEquals(Topof2.enqueueForward(testJson), true); assertEquals(TopoFilterQueue.myMap.get("f6816a638cbd1fcec9dcd88ebc2cfcb0"), testJson); assertEquals(TopoFilterQueue.myMap.get("f6816a638cbd1fcec9dcd88bc2cfcb0"), null); assertEquals(TopoFilterQueue.myMap.size(), 1); TopoFilterQueue.myMap.clear(); TopoFilterQueue.filterQueue.clear(); } @Test public void testReverse() { TopoFilterQueue Topof2 = new TopoFilterQueue(storeTopo, controllerID); String testJson = new String("{\"src\":\"00:00:00:00:00:00:00:05\",\"operation\":\"Switch Removed\"}"); assertEquals(Topof2.enqueueReverse(testJson), true); Topof2.dequeueReverse(); assertEquals(TopoFilterQueue.reverseFilterQueue.size(), 0); TopoFilterQueue.reverseFilterQueue.clear(); } @Test public void testReverse2() { TopoFilterQueue Topof2 = new TopoFilterQueue(storeTopo, controllerID); String testJson = new String("cat{\"src\":\"00:00:00:00:00:00::\"Switch Removed\"}"); assertEquals(Topof2.enqueueReverse(testJson), true); Topof2.dequeueReverse(); assertEquals(TopoFilterQueue.reverseFilterQueue.size(), 0); TopoFilterQueue.reverseFilterQueue.clear(); } }
apache-2.0
pascalrobert/aribaweb
src/util/src/main/java/ariba/util/formatter/SecureStringFormatter.java
5700
/* Copyright 1996-2008 Ariba, 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. $Id: //ariba/platform/util/core/ariba/util/formatter/SecureStringFormatter.java#6 $ */ package ariba.util.formatter; import ariba.util.core.Assert; import ariba.util.core.FastStringBuffer; import ariba.util.core.ResourceService; import ariba.util.core.StringUtil; /** Formats strings such that certain characters are "blocked out". For example, the string "1234" can be formatted to display "XX34". This formatter uses a format string to format string values. This format string supports the following syntax: D - display a character as is X - replaces the character with the cross out character The string value is right justified relative to the format. Any excess characters are trimmed away. If the format string is longer than the value, then the value will be padded by the format string's characters. So, for example, if the format "XXD" with blockoutChar "*" is applied to "12345", the user will see "**5". @aribaapi documented */ public class SecureStringFormatter extends StringFormatter { /*----------------------------------------------------------------------- Constants -----------------------------------------------------------------------*/ /** The class name of this formatter. @aribaapi private */ public static final String ClassName = "ariba.util.formatter.SecureStringFormatter"; // String resources private static final String StringTable = "ariba.util.core"; private static final String DefaultBlockoutChar = "BlockoutChar"; /*----------------------------------------------------------------------- Constructor -----------------------------------------------------------------------*/ /** Creates a <code>SecureStringFormatter</code>. @aribaapi private */ public SecureStringFormatter () { } /*----------------------------------------------------------------------- Static methods -----------------------------------------------------------------------*/ /** Returns a string formatted according to the <code>format</code> and <code>blockoutString</code> parameters. @param value The value to format. @param format The format string that controls which characters of the value get blocked out. @param blockoutString A string of length 1 that contains the If the <code>blockoutString</code> is null, then we'll use the default blockout character in the string resources. @return Returns a string formatted according to the format and blockoutString parameters. @aribaapi documented */ public static String getStringValue (Object value, String format, String blockoutString) { String strValue = getStringValue(value); char blockoutChar = getBlockoutChar(blockoutString); if (StringUtil.nullOrEmptyOrBlankString(format)) { Assert.assertNonFatal(false, "SecureTextFieldViewer: must specify a format property"); return strValue; } FastStringBuffer buf = new FastStringBuffer(strValue); int i,j; for (i = format.length()-1, j = buf.length()-1; i >= 0; i--, j--) { char curChar = format.charAt(i); // If we found the 'D' format character, then let the // character pass through unchanged. if (curChar == 'D') { continue; } if (curChar == 'X') { // If we found any other character, then // replace the digit with the cross out character. if (j >= 0) { buf.setCharAt(j, blockoutChar); } else { buf.insert(blockoutChar, 0); } continue; } // Otherwise, insert the character into // the return string. j++; int k = Math.max(0, j); buf.insert(curChar, k); } // If we got to the beginning of the format before getting to the // beginning of the number, then strip away the remaining digits. if (i < j) { j++; strValue = buf.substring(j, buf.length()); } else { strValue = buf.toString(); } return strValue; } /* Returns the blockoutChar from the field properties. */ private static char getBlockoutChar (String blockoutString) { if (StringUtil.nullOrEmptyString(blockoutString)) { String str = ResourceService.getString(StringTable, DefaultBlockoutChar); return str.charAt(0); } else { return blockoutString.charAt(0); } } }
apache-2.0
allotria/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/highlighter/custom/CustomFileTypeWordSelectionTest.java
980
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.highlighter.custom; import com.intellij.testFramework.fixtures.CodeInsightTestUtil; import com.intellij.testFramework.fixtures.BasePlatformTestCase; /** * @author yole */ public class CustomFileTypeWordSelectionTest extends BasePlatformTestCase { public void testCustomFileTypeBraces() { doTest(); } public void testCustomFileTypeQuotes() { doTest(); } public void testCustomFileTypeQuotesWithEscapes() { doTest(); } public void testCustomFileTypeSkipMatchedPair() { doTest(); } @Override protected boolean isCommunity() { return true; } @Override protected String getBasePath() { return "/platform/platform-tests/testData/selectWord/"; } private void doTest() { CodeInsightTestUtil.doWordSelectionTestOnDirectory(myFixture, getTestName(true), "cs"); } }
apache-2.0
leafclick/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/IntentionUtils.java
8567
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.base; import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils; import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodFromUsageFix; import com.intellij.codeInsight.template.*; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyLanguage; import org.jetbrains.plugins.groovy.actions.GroovyTemplates; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint; import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil; import org.jetbrains.plugins.groovy.lang.psi.util.GroovyModifiersUtil; import org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression; import org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression; import org.jetbrains.plugins.groovy.template.expressions.StringParameterNameExpression; public class IntentionUtils { private static final Logger LOG = Logger.getInstance(IntentionUtils.class); public static void createTemplateForMethod(ChooseTypeExpression[] paramTypesExpressions, PsiMethod method, PsiClass owner, TypeConstraint[] constraints, boolean isConstructor, @NotNull final PsiElement context) { ParameterNameExpression[] nameExpressions = new ParameterNameExpression[paramTypesExpressions.length]; for (int i = 0; i < nameExpressions.length; i++) { nameExpressions[i] = StringParameterNameExpression.Companion.getEMPTY(); } ChooseTypeExpression returnTypeExpression = new ChooseTypeExpression( constraints, owner.getManager(), context.getResolveScope(), method.getLanguage() == GroovyLanguage.INSTANCE ); createTemplateForMethod(paramTypesExpressions, nameExpressions, method, owner, returnTypeExpression, isConstructor, context); } public static void createTemplateForMethod(ChooseTypeExpression[] paramTypesExpressions, ParameterNameExpression[] paramNameExpressions, PsiMethod method, PsiClass owner, ChooseTypeExpression returnTypeExpression, boolean isConstructor, @Nullable final PsiElement context) { final Project project = owner.getProject(); PsiTypeElement typeElement = method.getReturnTypeElement(); TemplateBuilderImpl builder = new TemplateBuilderImpl(method); if (!isConstructor) { assert typeElement != null; builder.replaceElement(typeElement, returnTypeExpression); } PsiParameter[] parameters = method.getParameterList().getParameters(); for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; PsiTypeElement parameterTypeElement = parameter.getTypeElement(); builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]); builder.replaceElement(parameter.getNameIdentifier(), paramNameExpressions[i]); } PsiCodeBlock body = method.getBody(); if (body != null) { PsiElement lbrace = body.getLBrace(); assert lbrace != null; builder.setEndVariableAfter(lbrace); } else { builder.setEndVariableAfter(method.getParameterList()); } method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method); Template template = builder.buildTemplate(); final PsiFile targetFile = owner.getContainingFile(); final Editor newEditor = positionCursor(project, targetFile, method); TextRange range = method.getTextRange(); newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); TemplateManager manager = TemplateManager.getInstance(project); TemplateEditingListener templateListener = new TemplateEditingAdapter() { @Override public void templateFinished(@NotNull Template template, boolean brokenOff) { ApplicationManager.getApplication().runWriteAction(() -> { PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument()); final int offset = newEditor.getCaretModel().getOffset(); PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false); if (context instanceof PsiMethod) { final PsiTypeParameter[] typeParameters = ((PsiMethod)context).getTypeParameters(); if (typeParameters.length > 0) { for (PsiTypeParameter typeParameter : typeParameters) { if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) { final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject()); PsiTypeParameterList list = method1.getTypeParameterList(); if (list == null) { PsiTypeParameterList newList = factory.createTypeParameterList(); list = (PsiTypeParameterList)method1.addAfter(newList, method1.getModifierList()); } list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes())); } } } } if (method1 != null) { try { final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod; if (hasNoReturnType) { ((GrMethod)method1).setReturnType(PsiType.VOID); } if (method1.getBody() != null) { FileTemplateManager templateManager = FileTemplateManager.getInstance(project); FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY); PsiClass containingClass = method1.getContainingClass(); LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up"); CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate); } if (hasNoReturnType) { ((GrMethod)method1).setReturnType(null); } if (method1 instanceof GrMethod && GroovyModifiersUtil.isDefUnnecessary((GrMethod)method1)) { ((GrMethod)method1).getModifierList().setModifierProperty(GrModifier.DEF, false); } } catch (IncorrectOperationException e) { LOG.error(e); } CreateFromUsageUtils.setupEditor(method1, newEditor); } }); } }; manager.startTemplate(newEditor, template, templateListener); } public static Editor positionCursor(@NotNull Project project, @NotNull PsiFile targetFile, @NotNull PsiElement element) { int textOffset = element.getTextOffset(); VirtualFile virtualFile = targetFile.getVirtualFile(); if (virtualFile != null) { OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile, textOffset); return FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } else { return null; } } }
apache-2.0
romankagan/DDBWorkbench
plugins/groovy/src/org/jetbrains/plugins/groovy/util/LibrariesUtil.java
8005
/* * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.util; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author ilyas */ public class LibrariesUtil { public static final String SOME_GROOVY_CLASS = "org.codehaus.groovy.control.CompilationUnit"; private LibrariesUtil() { } public static Library[] getLibrariesByCondition(final Module module, final Condition<Library> condition) { if (module == null) return new Library[0]; final ArrayList<Library> libraries = new ArrayList<Library>(); AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); try { populateOrderEntries(module, condition, libraries, false, new THashSet<Module>()); } finally { accessToken.finish(); } return libraries.toArray(new Library[libraries.size()]); } private static void populateOrderEntries(@NotNull Module module, Condition<Library> condition, ArrayList<Library> libraries, boolean exportedOnly, Set<Module> visited) { if (!visited.add(module)) { return; } for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) { if (entry instanceof LibraryOrderEntry) { LibraryOrderEntry libEntry = (LibraryOrderEntry)entry; if (exportedOnly && !libEntry.isExported()) { continue; } Library library = libEntry.getLibrary(); if (condition.value(library)) { libraries.add(library); } } else if (entry instanceof ModuleOrderEntry) { final Module dep = ((ModuleOrderEntry)entry).getModule(); if (dep != null) { populateOrderEntries(dep, condition, libraries, true, visited); } } } } public static Library[] getGlobalLibraries(Condition<Library> condition) { LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTable(); List<Library> libs = ContainerUtil.findAll(table.getLibraries(), condition); return libs.toArray(new Library[libs.size()]); } @NotNull public static String getGroovyLibraryHome(Library library) { final VirtualFile[] classRoots = library.getFiles(OrderRootType.CLASSES); final String home = getGroovyLibraryHome(classRoots); return home == null ? "" : home; } public static boolean hasGroovySdk(@Nullable Module module) { return module != null && getGroovyHomePath(module) != null; } @Nullable public static VirtualFile findJarWithClass(@NotNull Module module, final String classQName) { GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module); for (PsiClass psiClass : JavaPsiFacade.getInstance(module.getProject()).findClasses(classQName, scope)) { final VirtualFile local = JarFileSystem.getInstance().getVirtualFileForJar(psiClass.getContainingFile().getVirtualFile()); if (local != null) { return local; } } return null; } @Nullable public static String getGroovyHomePath(@NotNull Module module) { final VirtualFile local = findJarWithClass(module, SOME_GROOVY_CLASS); if (local != null) { final VirtualFile parent = local.getParent(); if (parent != null) { if (("lib".equals(parent.getName()) || "embeddable".equals(parent.getName())) && parent.getParent() != null) { return parent.getParent().getPath(); } return parent.getPath(); } } final String home = getGroovyLibraryHome(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots()); return StringUtil.isEmpty(home) ? null : home; } @Nullable private static String getGroovySdkHome(VirtualFile[] classRoots) { for (VirtualFile file : classRoots) { final String name = file.getName(); if (name.matches(GroovyConfigUtils.GROOVY_JAR_PATTERN_NOVERSION) || name.matches(GroovyConfigUtils.GROOVY_JAR_PATTERN)) { String jarPath = file.getPresentableUrl(); File realFile = new File(jarPath); if (realFile.exists()) { File parentFile = realFile.getParentFile(); if (parentFile != null) { if ("lib".equals(parentFile.getName())) { return parentFile.getParent(); } return parentFile.getPath(); } } } } return null; } @Nullable private static String getEmbeddableGroovyJar(VirtualFile[] classRoots) { for (VirtualFile file : classRoots) { final String name = file.getName(); if (GroovyConfigUtils.matchesGroovyAll(name)) { String jarPath = file.getPresentableUrl(); File realFile = new File(jarPath); if (realFile.exists()) { return realFile.getPath(); } } } return null; } @Nullable public static String getGroovyLibraryHome(VirtualFile[] classRoots) { final String sdkHome = getGroovySdkHome(classRoots); if (sdkHome != null) { return sdkHome; } final String embeddable = getEmbeddableGroovyJar(classRoots); if (embeddable != null) { final File emb = new File(embeddable); if (emb.exists()) { final File parent = emb.getParentFile(); if ("embeddable".equals(parent.getName()) || "lib".equals(parent.getName())) { return parent.getParent(); } return parent.getPath(); } } return null; } @NotNull public static VirtualFile getLocalFile(@NotNull VirtualFile libFile) { final VirtualFileSystem system = libFile.getFileSystem(); if (system instanceof JarFileSystem) { final VirtualFile local = JarFileSystem.getInstance().getVirtualFileForJar(libFile); if (local != null) { return local; } } return libFile; } public static void placeEntryToCorrectPlace(ModifiableRootModel model, LibraryOrderEntry addedEntry) { final OrderEntry[] order = model.getOrderEntries(); //place library after module sources assert order[order.length - 1] == addedEntry; int insertionPoint = -1; for (int i = 0; i < order.length - 1; i++) { if (order[i] instanceof ModuleSourceOrderEntry) { insertionPoint = i + 1; break; } } if (insertionPoint >= 0) { for (int i = order.length - 1; i > insertionPoint; i--) { order[i] = order[i - 1]; } order[insertionPoint] = addedEntry; model.rearrangeOrderEntries(order); } } }
apache-2.0
facebook/presto
presto-spark-base/src/main/java/com/facebook/presto/spark/PrestoSparkServiceWaitTimeMetrics.java
716
/* * 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.spark; import io.airlift.units.Duration; public interface PrestoSparkServiceWaitTimeMetrics { Duration getWaitTime(); }
apache-2.0
jmspring/azure-sdk-for-java
core/src/main/java/com/microsoft/windowsazure/core/OperationStatus.java
991
/** * * Copyright (c) Microsoft and contributors. 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.microsoft.windowsazure.core; /** * The status of the asynchronous request. */ public enum OperationStatus { /** * The asynchronous request is in progress. */ INPROGRESS, /** * The asynchronous request succeeded. */ SUCCEEDED, /** * The asynchronous request failed. */ FAILED, }
apache-2.0
manstis/drools
drools-impact-analysis/drools-impact-analysis-parser/src/main/java/org/drools/impact/analysis/parser/internal/ImpactModelBuilderImpl.java
9668
/* * Copyright (c) 2020. Red Hat, Inc. and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.impact.analysis.parser.internal; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl; import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.compiler.builder.impl.TypeDeclarationFactory; import org.drools.compiler.compiler.DialectCompiletimeRegistry; import org.drools.compiler.compiler.PackageRegistry; import org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr; import org.drools.compiler.lang.descr.CompositePackageDescr; import org.drools.compiler.lang.descr.EnumDeclarationDescr; import org.drools.compiler.lang.descr.GlobalDescr; import org.drools.compiler.lang.descr.ImportDescr; import org.drools.compiler.lang.descr.PackageDescr; import org.drools.compiler.lang.descr.TypeDeclarationDescr; import org.drools.core.definitions.InternalKnowledgePackage; import org.drools.core.rule.TypeDeclaration; import org.drools.core.util.StringUtils; import org.drools.impact.analysis.model.AnalysisModel; import org.drools.impact.analysis.parser.impl.PackageParser; import org.drools.modelcompiler.builder.PackageModel; import org.drools.modelcompiler.builder.generator.DRLIdGenerator; import org.kie.api.builder.ReleaseId; import static java.util.Collections.emptyList; import static org.drools.compiler.builder.impl.ClassDefinitionFactory.createClassDefinition; import static org.drools.core.util.Drools.hasMvel; import static org.drools.modelcompiler.builder.generator.ModelGenerator.initPackageModel; public class ImpactModelBuilderImpl extends KnowledgeBuilderImpl { private final ReleaseId releaseId; private final DRLIdGenerator exprIdGenerator = new DRLIdGenerator(); private final Map<String, PackageModel> packageModels = new HashMap<>(); private Collection<CompositePackageDescr> compositePackages; private Map<String, CompositePackageDescr> compositePackagesMap; private final AnalysisModel analysisModel = new AnalysisModel(); public ImpactModelBuilderImpl( KnowledgeBuilderConfigurationImpl configuration, ReleaseId releaseId) { super(configuration); this.releaseId = releaseId; } @Override protected void doFirstBuildStep( Collection<CompositePackageDescr> packages ) { this.compositePackages = packages; } @Override public void addPackage(final PackageDescr packageDescr) { if (compositePackagesMap == null) { compositePackagesMap = new HashMap<>(); if(compositePackages != null) { for (CompositePackageDescr pkg : compositePackages) { compositePackagesMap.put(pkg.getNamespace(), pkg); } } else { compositePackagesMap.put(packageDescr.getNamespace(), new CompositePackageDescr(packageDescr.getResource(), packageDescr)); } compositePackages = null; } CompositePackageDescr pkgDescr = compositePackagesMap.get(packageDescr.getNamespace()); if (pkgDescr == null) { compositePackagesMap.put(packageDescr.getNamespace(), new CompositePackageDescr( packageDescr.getResource(), packageDescr) ); } else { pkgDescr.addPackageDescr( packageDescr.getResource(), packageDescr ); } PackageRegistry pkgRegistry = getOrCreatePackageRegistry(packageDescr); InternalKnowledgePackage pkg = pkgRegistry.getPackage(); for (final ImportDescr importDescr : packageDescr.getImports()) { pkgRegistry.addImport(importDescr); } for (GlobalDescr globalDescr : packageDescr.getGlobals()) { try { Class<?> globalType = pkg.getTypeResolver().resolveType( globalDescr.getType() ); addGlobal( globalDescr.getIdentifier(), globalType ); pkg.addGlobal( globalDescr.getIdentifier(), globalType ); } catch (ClassNotFoundException e) { throw new RuntimeException( e ); } } } @Override protected void doSecondBuildStep(Collection<CompositePackageDescr> compositePackages) { Collection<CompositePackageDescr> packages = findPackages(compositePackages); initPackageRegistries(packages); registerTypeDeclarations( packages ); buildOtherDeclarations(packages); buildRules(packages); } private Collection<CompositePackageDescr> findPackages(Collection<CompositePackageDescr> compositePackages) { Collection<CompositePackageDescr> packages; if (compositePackages != null && !compositePackages.isEmpty()) { packages = compositePackages; } else if (compositePackagesMap != null) { packages = compositePackagesMap.values(); } else { packages = emptyList(); } return packages; } @Override protected void initPackageRegistries(Collection<CompositePackageDescr> packages) { for ( CompositePackageDescr packageDescr : packages ) { if ( StringUtils.isEmpty(packageDescr.getName()) ) { packageDescr.setName( getBuilderConfiguration().getDefaultPackageName() ); } PackageRegistry pkgRegistry = getPackageRegistry( packageDescr.getNamespace() ); if (pkgRegistry == null) { getOrCreatePackageRegistry( packageDescr ); } else { for (ImportDescr importDescr : packageDescr.getImports()) { pkgRegistry.registerImport(importDescr.getTarget()); } } } } private void registerTypeDeclarations( Collection<CompositePackageDescr> packages ) { for (CompositePackageDescr packageDescr : packages) { InternalKnowledgePackage pkg = getOrCreatePackageRegistry(packageDescr).getPackage(); for (TypeDeclarationDescr typeDescr : packageDescr.getTypeDeclarations()) { processTypeDeclarationDescr(pkg, typeDescr); } for (EnumDeclarationDescr enumDeclarationDescr : packageDescr.getEnumDeclarations()) { processTypeDeclarationDescr(pkg, enumDeclarationDescr); } } } private void processTypeDeclarationDescr(InternalKnowledgePackage pkg, AbstractClassTypeDeclarationDescr typeDescr) { normalizeAnnotations(typeDescr, pkg.getTypeResolver(), false); try { Class<?> typeClass = pkg.getTypeResolver().resolveType( typeDescr.getTypeName() ); String typePkg = typeClass.getPackage().getName(); String typeName = typeClass.getName().substring( typePkg.length() + 1 ); TypeDeclaration type = new TypeDeclaration(typeName ); type.setTypeClass( typeClass ); type.setResource( typeDescr.getResource() ); if (hasMvel()) { type.setTypeClassDef( createClassDefinition( typeClass, typeDescr.getResource() ) ); } TypeDeclarationFactory.processAnnotations(typeDescr, type); getOrCreatePackageRegistry(new PackageDescr(typePkg)).getPackage().addTypeDeclaration(type ); } catch (ClassNotFoundException e) { TypeDeclaration type = new TypeDeclaration( typeDescr.getTypeName() ); type.setResource( typeDescr.getResource() ); TypeDeclarationFactory.processAnnotations(typeDescr, type); pkg.addTypeDeclaration( type ); } } protected void buildRules(Collection<CompositePackageDescr> packages) { if (hasErrors()) { // if Error while generating pojo do not try compile rule as they very likely depends hence fail too. return; } for (CompositePackageDescr packageDescr : packages) { setAssetFilter(packageDescr.getFilter()); PackageRegistry pkgRegistry = getPackageRegistry(packageDescr.getNamespace()); PackageModel packageModel = getPackageModel(packageDescr, pkgRegistry, packageDescr.getName()); initPackageModel( this, pkgRegistry.getPackage(), pkgRegistry.getPackage().getTypeResolver(), packageDescr, packageModel ); analysisModel.addPackage( new PackageParser(this, packageModel, packageDescr, pkgRegistry).parse() ); } } private PackageModel getPackageModel( PackageDescr packageDescr, PackageRegistry pkgRegistry, String pkgName) { return packageModels.computeIfAbsent(pkgName, s -> { final DialectCompiletimeRegistry dialectCompiletimeRegistry = pkgRegistry.getDialectCompiletimeRegistry(); return packageDescr.getPreferredPkgUUID() .map(pkgUUI -> new PackageModel(pkgName, this.getBuilderConfiguration(), dialectCompiletimeRegistry, exprIdGenerator, pkgUUI)) .orElse(new PackageModel(releaseId, pkgName, this.getBuilderConfiguration(), dialectCompiletimeRegistry, exprIdGenerator)); }); } public AnalysisModel getAnalysisModel() { return analysisModel; } }
apache-2.0
tadayosi/switchyard
core/security/base/src/main/java/org/switchyard/security/principal/GroupPrincipal.java
3923
/* * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. * * 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.switchyard.security.principal; import java.io.Serializable; import java.security.Principal; import java.security.acl.Group; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import org.switchyard.security.BaseSecurityMessages; /** * GroupPrincipal. * * @author David Ward &lt;<a href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; &copy; 2012 Red Hat Inc. */ public class GroupPrincipal implements Group, Serializable { private static final long serialVersionUID = -909127780618924905L; private static final String FORMAT = GroupPrincipal.class.getSimpleName() + "@%s[name=%s, members=%s]"; /** * The "CallerPrincipal" group name. */ public static final String CALLER_PRINCIPAL = "CallerPrincipal"; /** * The "Roles" group name. */ public static final String ROLES = "Roles"; private final String _name; private final Set<Principal> _members = new HashSet<Principal>(); /** * Constructs a GroupPrincipal with the specified name. * @param name the specified name */ public GroupPrincipal(String name) { if (name == null) { throw BaseSecurityMessages.MESSAGES.groupNameCannotBeNull(); } _name = name; } /** * {@inheritDoc} */ @Override public String getName() { return _name; } /** * {@inheritDoc} */ @Override public boolean addMember(Principal user) { return _members.add(user); } /** * {@inheritDoc} */ @Override public boolean isMember(Principal member) { return _members.contains(member); } /** * {@inheritDoc} */ @Override public Enumeration<? extends Principal> members() { return Collections.enumeration(_members); } /** * {@inheritDoc} */ @Override public boolean removeMember(Principal user) { return _members.remove(user); } /** * {@inheritDoc} */ @Override public String toString() { return String.format(FORMAT, System.identityHashCode(this), _name, _members); } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_members == null) ? 0 : _members.hashCode()); result = prime * result + ((_name == null) ? 0 : _name.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } GroupPrincipal other = (GroupPrincipal)obj; if (_members == null) { if (other._members != null) { return false; } } else if (!_members.equals(other._members)) { return false; } if (_name == null) { if (other._name != null) { return false; } } else if (!_name.equals(other._name)) { return false; } return true; } }
apache-2.0
mnovak1/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/discovery/DiscoveryBaseTest.java
9592
/* * 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.tests.integration.discovery; import java.net.InetAddress; 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.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory; import org.apache.activemq.artemis.core.cluster.DiscoveryEntry; import org.apache.activemq.artemis.core.cluster.DiscoveryGroup; import org.apache.activemq.artemis.core.cluster.DiscoveryListener; import org.apache.activemq.artemis.core.server.ActivateCallback; import org.apache.activemq.artemis.core.server.NodeManager; import org.apache.activemq.artemis.core.server.cluster.BroadcastGroup; import org.apache.activemq.artemis.core.server.cluster.impl.BroadcastGroupImpl; import org.apache.activemq.artemis.core.server.management.NotificationService; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.UUIDGenerator; import org.junit.Assert; public class DiscoveryBaseTest extends ActiveMQTestBase { protected static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; protected final String address1 = getUDPDiscoveryAddress(); protected final String address2 = getUDPDiscoveryAddress(1); protected final String address3 = getUDPDiscoveryAddress(2); /** * @param discoveryGroup * @throws Exception */ protected static void verifyBroadcast(BroadcastGroup broadcastGroup, DiscoveryGroup discoveryGroup) throws Exception { broadcastGroup.broadcastConnectors(); Assert.assertTrue("broadcast not received", discoveryGroup.waitForBroadcast(2000)); } /** * @param discoveryGroup * @throws Exception */ protected static void verifyNonBroadcast(BroadcastGroup broadcastGroup, DiscoveryGroup discoveryGroup) throws Exception { broadcastGroup.broadcastConnectors(); Assert.assertFalse("NO broadcast received", discoveryGroup.waitForBroadcast(2000)); } protected TransportConfiguration generateTC() { return generateTC(""); } protected TransportConfiguration generateTC(String debug) { String className = "org.foo.bar." + debug + "|" + UUIDGenerator.getInstance().generateStringUUID() + ""; String name = UUIDGenerator.getInstance().generateStringUUID(); Map<String, Object> params = new HashMap<>(); params.put(UUIDGenerator.getInstance().generateStringUUID(), 123); params.put(UUIDGenerator.getInstance().generateStringUUID(), UUIDGenerator.getInstance().generateStringUUID()); params.put(UUIDGenerator.getInstance().generateStringUUID(), true); TransportConfiguration tc = new TransportConfiguration(className, params, name); return tc; } protected static class MyListener implements DiscoveryListener { volatile boolean called; @Override public void connectorsChanged(List<DiscoveryEntry> newConnectors) { called = true; } } protected static void assertEqualsDiscoveryEntries(List<TransportConfiguration> expected, List<DiscoveryEntry> actual) { assertNotNull(actual); List<TransportConfiguration> sortedExpected = new ArrayList<>(expected); Collections.sort(sortedExpected, new Comparator<TransportConfiguration>() { @Override public int compare(TransportConfiguration o1, TransportConfiguration o2) { return o2.toString().compareTo(o1.toString()); } }); List<DiscoveryEntry> sortedActual = new ArrayList<>(actual); Collections.sort(sortedActual, new Comparator<DiscoveryEntry>() { @Override public int compare(DiscoveryEntry o1, DiscoveryEntry o2) { return o2.getConnector().toString().compareTo(o1.getConnector().toString()); } }); if (sortedExpected.size() != sortedActual.size()) { dump(sortedExpected, sortedActual); } assertEquals(sortedExpected.size(), sortedActual.size()); for (int i = 0; i < sortedExpected.size(); i++) { if (!sortedExpected.get(i).equals(sortedActual.get(i).getConnector())) { dump(sortedExpected, sortedActual); } assertEquals(sortedExpected.get(i), sortedActual.get(i).getConnector()); } } protected static void dump(List<TransportConfiguration> sortedExpected, List<DiscoveryEntry> sortedActual) { System.out.println("wrong broadcasts received"); System.out.println("expected"); System.out.println("----------------------------"); for (TransportConfiguration transportConfiguration : sortedExpected) { System.out.println("transportConfiguration = " + transportConfiguration); } System.out.println("----------------------------"); System.out.println("actual"); System.out.println("----------------------------"); for (DiscoveryEntry discoveryEntry : sortedActual) { System.out.println("transportConfiguration = " + discoveryEntry.getConnector()); } System.out.println("----------------------------"); } /** * This method is here just to facilitate creating the Broadcaster for this test */ protected BroadcastGroupImpl newBroadcast(final String nodeID, final String name, final InetAddress localAddress, int localPort, final InetAddress groupAddress, final int groupPort) throws Exception { return new BroadcastGroupImpl(new FakeNodeManager(nodeID), name, 0, null, new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress.getHostAddress()).setGroupPort(groupPort).setLocalBindAddress(localAddress != null ? localAddress.getHostAddress() : "localhost").setLocalBindPort(localPort)); } protected DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress, final InetAddress groupAddress, final int groupPort, final long timeout) throws Exception { return newDiscoveryGroup(nodeID, name, localBindAddress, groupAddress, groupPort, timeout, null); } protected DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress, final InetAddress groupAddress, final int groupPort, final long timeout, NotificationService notif) throws Exception { return new DiscoveryGroup(nodeID, name, timeout, new UDPBroadcastEndpointFactory().setGroupAddress(groupAddress.getHostAddress()).setGroupPort(groupPort).setLocalBindAddress(localBindAddress != null ? localBindAddress.getHostAddress() : "localhost"), notif); } protected final class FakeNodeManager extends NodeManager { public FakeNodeManager(String nodeID) { super(false, null); this.setNodeID(nodeID); } @Override public void awaitLiveNode() throws Exception { } @Override public void awaitLiveStatus() throws Exception { } @Override public void startBackup() throws Exception { } @Override public ActivateCallback startLiveNode() throws Exception { return new ActivateCallback() { }; } @Override public void pauseLiveServer() throws Exception { } @Override public void crashLiveServer() throws Exception { } @Override public void releaseBackup() throws Exception { } @Override public SimpleString readNodeId() { return null; } @Override public boolean isAwaitingFailback() throws Exception { return false; } @Override public boolean isBackupLive() throws Exception { return false; } @Override public void interrupt() { } } }
apache-2.0
jamiepg1/jetty.project
jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java
8933
//======================================================================== //Copyright (c) Webtide LLC //------------------------------------------------------------------------ //All rights reserved. This program and the accompanying materials //are made available under the terms of the Eclipse Public License v1.0 //and Apache License v2.0 which accompanies this distribution. // //The Eclipse Public License is available at //http://www.eclipse.org/legal/epl-v10.html // //The Apache License v2.0 is available at //http://www.apache.org/licenses/LICENSE-2.0.txt // //You may elect to redistribute this code under either of these licenses. //======================================================================== package org.eclipse.jetty.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Test; /** * HttpServer Tester. */ public abstract class ConnectorCloseTestBase extends HttpServerTestFixture { private static String __content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis felis nunc. "+ "Quisque suscipit mauris et ante auctor ornare rhoncus lacus aliquet. Pellentesque "+ "habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. "+ "Vestibulum sit amet felis augue, vel convallis dolor. Cras accumsan vehicula diam "+ "at faucibus. Etiam in urna turpis, sed congue mi. Morbi et lorem eros. Donec vulputate "+ "velit in risus suscipit lobortis. Aliquam id urna orci, nec sollicitudin ipsum. "+ "Cras a orci turpis. Donec suscipit vulputate cursus. Mauris nunc tellus, fermentum "+ "eu auctor ut, mollis at diam. Quisque porttitor ultrices metus, vitae tincidunt massa "+ "sollicitudin a. Vivamus porttitor libero eget purus hendrerit cursus. Integer aliquam "+ "consequat mauris quis luctus. Cras enim nibh, dignissim eu faucibus ac, mollis nec neque. "+ "Aliquam purus mauris, consectetur nec convallis lacinia, porta sed ante. Suspendisse "+ "et cursus magna. Donec orci enim, molestie a lobortis eu, imperdiet vitae neque."; private static int __length = __content.length(); /* ------------------------------------------------------------ */ @Test public void testCloseBetweenRequests() throws Exception { int maxLength = 32; int requestCount = iterations(maxLength); final CountDownLatch latch = new CountDownLatch(requestCount); configureServer(new HelloWorldHandler()); Socket client = newSocket(HOST,_connector.getLocalPort()); try { OutputStream os = client.getOutputStream(); ResponseReader reader = new ResponseReader(client) { private int _index = 0; /* ------------------------------------------------------------ */ @Override protected int doRead() throws IOException, InterruptedException { int count = super.doRead(); if (count > 0) { int idx; while ((idx=_response.indexOf("HTTP/1.1 200 OK", _index)) >= 0) { latch.countDown(); _index = idx + 15; } } return count; } }; Thread runner = new Thread(reader); runner.start(); for (int pipeline = 1; pipeline < maxLength; pipeline++) { if (pipeline == maxLength / 2) _connector.close(); String request = ""; for (int i = 0; i < pipeline; i++) { request += "GET /data?writes=1&block=16&id="+i+" HTTP/1.1\r\n"+ "host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+ "user-agent: testharness/1.0 (blah foo/bar)\r\n"+ "accept-encoding: nothing\r\n"+ "cookie: aaa=1234567890\r\n"+ "\r\n"; } os.write(request.getBytes()); os.flush(); Thread.sleep(25); } latch.await(30, TimeUnit.SECONDS); reader.setDone(); runner.join(); } finally { client.close(); assertEquals(requestCount, requestCount - latch.getCount()); } } /* ------------------------------------------------------------ */ private int iterations(int cnt) { return cnt > 0 ? iterations(--cnt) + cnt : 0; } /* ------------------------------------------------------------ */ @Test public void testCloseBetweenChunks() throws Exception { configureServer(new EchoHandler()); Socket client = newSocket(HOST,_connector.getLocalPort()); try { OutputStream os = client.getOutputStream(); ResponseReader reader = new ResponseReader(client); Thread runner = new Thread(reader); runner.start(); byte[] bytes = __content.getBytes("utf-8"); os.write(( "POST /echo?charset=utf-8 HTTP/1.1\r\n"+ "host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+ "content-type: text/plain; charset=utf-8\r\n"+ "content-length: "+bytes.length+"\r\n"+ "\r\n" ).getBytes("iso-8859-1")); int len = bytes.length; int offset = 0; int stop = len / 2; while (offset < stop) { os.write(bytes, offset, 64); offset += 64; Thread.sleep(25); } _connector.close(); while (offset < len) { os.write(bytes, offset, len-offset <=64 ? len-offset : 64); offset += 64; Thread.sleep(25); } os.flush(); reader.setDone(); runner.join(); String in = reader.getResponse().toString(); assertTrue(in.indexOf(__content.substring(__length-64))>0); } finally { client.close(); } } /* ------------------------------------------------------------ */ public class ResponseReader implements Runnable { private boolean _done = false; protected char[] _buffer; protected StringBuffer _response; protected BufferedReader _reader; /* ------------------------------------------------------------ */ public ResponseReader(Socket client) throws IOException { _buffer = new char[256]; _response = new StringBuffer(); _reader = new BufferedReader(new InputStreamReader(client.getInputStream())); } /* ------------------------------------------------------------ */ public void setDone() { _done = true; } public StringBuffer getResponse() { return _response; } /* ------------------------------------------------------------ */ /** * @see java.lang.Runnable#run() */ public void run() { try { int count = 0; while (!_done || count > 0) { count = doRead(); } } catch (IOException ex) { } catch (InterruptedException ex) { } finally { try { _reader.close(); } catch (IOException e) { } } } /* ------------------------------------------------------------ */ protected int doRead() throws IOException, InterruptedException { if (!_reader.ready()) { Thread.sleep(25); } int count = 0; if (_reader.ready()) { count = _reader.read(_buffer); if (count > 0) { _response.append(_buffer, 0, count); } } return count; } } }
apache-2.0
tmess567/syncope
common/rest-api/src/main/java/org/apache/syncope/common/rest/api/RESTHeaders.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.syncope.common.rest.api; /** * Custom HTTP headers in use with REST services. */ public final class RESTHeaders { public static final String DOMAIN = "X-Syncope-Domain"; public static final String OWNED_ENTITLEMENTS = "X-Syncope-Entitlements"; public static final String RESOURCE_KEY = "X-Syncope-Key"; /** * Asks for asynchronous propagation towards external resources with null priority. */ public static final String NULL_PRIORITY_ASYNC = "X-Syncope-Null-Priority-Async"; /** * Declares the type of exception being raised. * * @see org.apache.syncope.common.lib.types.ClientExceptionType */ public static final String ERROR_CODE = "X-Application-Error-Code"; /** * Declares additional information for the exception being raised. */ public static final String ERROR_INFO = "X-Application-Error-Info"; /** * Mediatype for PNG images, not defined in <tt>javax.ws.rs.core.MediaType</tt>. * * @see javax.ws.rs.core.MediaType */ public static final String MEDIATYPE_IMAGE_PNG = "image/png"; /** * Allows the client to specify a preference for the result to be returned from the server. * <a href="http://msdn.microsoft.com/en-us/library/hh537533.aspx">More information</a>. * * @see Preference */ public static final String PREFER = "Prefer"; /** * Allowd the server to inform the client about the fact that a specified preference was applied. * <a href="http://msdn.microsoft.com/en-us/library/hh554623.aspx">More information</a>. * * @see Preference */ public static final String PREFERENCE_APPLIED = "Preference-Applied"; private RESTHeaders() { // Empty constructor for static utility class. } }
apache-2.0
wmixvideo/nfe
src/test/java/com/fincatto/documentofiscal/nfe310/classes/nota/NFNotaInfoItemImpostoCOFINSTest.java
4451
package com.fincatto.documentofiscal.nfe310.classes.nota; import com.fincatto.documentofiscal.nfe310.FabricaDeObjetosFake; import org.junit.Assert; import org.junit.Test; public class NFNotaInfoItemImpostoCOFINSTest { @Test public void devePermitirApenasUmQuantidade() { final NFNotaInfoItemImpostoCOFINS cofins = new NFNotaInfoItemImpostoCOFINS(); cofins.setQuantidade(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSQuantidade()); try { cofins.setAliquota(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSAliquota()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setNaoTributavel(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSNaoTributavel()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setOutrasOperacoes(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSOutrasOperacoes()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } } @Test public void devePermitirApenasUmAliquota() { final NFNotaInfoItemImpostoCOFINS cofins = new NFNotaInfoItemImpostoCOFINS(); cofins.setAliquota(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSAliquota()); try { cofins.setQuantidade(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSQuantidade()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setNaoTributavel(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSNaoTributavel()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setOutrasOperacoes(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSOutrasOperacoes()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } } @Test public void devePermitirApenasUmNaoTributavel() { final NFNotaInfoItemImpostoCOFINS cofins = new NFNotaInfoItemImpostoCOFINS(); cofins.setNaoTributavel(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSNaoTributavel()); try { cofins.setQuantidade(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSQuantidade()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setAliquota(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSAliquota()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setOutrasOperacoes(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSOutrasOperacoes()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } } @Test public void devePermitirApenasUmOutrasOperacoes() { final NFNotaInfoItemImpostoCOFINS cofins = new NFNotaInfoItemImpostoCOFINS(); cofins.setNaoTributavel(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSNaoTributavel()); try { cofins.setQuantidade(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSQuantidade()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setAliquota(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSAliquota()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } try { cofins.setOutrasOperacoes(FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINSOutrasOperacoes()); Assert.fail("Validacao nao funcionou"); } catch (final IllegalStateException ignored) { } } @Test public void deveGerarXMLDeAcordoComOPadraoEstabelecido() { final String xmlEsperado = "<NFNotaInfoItemImpostoCOFINS><COFINSAliq><CST>01</CST><vBC>999999999999.99</vBC><pCOFINS>99.99</pCOFINS><vCOFINS>999999999999.99</vCOFINS></COFINSAliq></NFNotaInfoItemImpostoCOFINS>"; Assert.assertEquals(xmlEsperado, FabricaDeObjetosFake.getNFNotaInfoItemImpostoCOFINS().toString()); } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/test/java/com/hazelcast/cardinality/impl/hyperloglog/impl/DenseHyperLogLogConstantsTest.java
3500
/* * Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.cardinality.impl.hyperloglog.impl; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * Checks the consistency of {@link DenseHyperLogLogConstants} with hashcodes. */ @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class DenseHyperLogLogConstantsTest extends HazelcastTestSupport { private static final int THRESHOLD_HASHCODE = -1946099911; private static final int[] RAW_ESTIMATE_DATA_HASHCODES = { -1251035322, -1094734953, -61611651, -40264626, 479598381, -116264945, 1050131386, -1235040548, -1202239017, 1288152491, -769393172, -1652552964, -497616505, -1689057893, 923172265, }; private static final int[] BIAS_DATA_HASHCODES = { -1077449490, 1779769334, -1948875718, 1532988461, -990299124, -591836144, 48144655, -470742222, -1450150050, 1929284635, -697321875, -1556078395, -1405633222, -88240126, 1330624843, }; @Test public void testConstructor() { assertUtilityConstructor(DenseHyperLogLogConstants.class); } @Test public void testHashCodes() { assertEquals("DenseHyperLogLogConstants.THRESHOLD", THRESHOLD_HASHCODE, Arrays.hashCode(DenseHyperLogLogConstants.THRESHOLD)); assertArrayHashcodes("RAW_ESTIMATE_DATA", DenseHyperLogLogConstants.RAW_ESTIMATE_DATA, RAW_ESTIMATE_DATA_HASHCODES); assertArrayHashcodes("BIAS_DATA", DenseHyperLogLogConstants.BIAS_DATA, BIAS_DATA_HASHCODES); } /** * Asserts {@code double[][]} arrays by an array of hash codes per sub-array. * <p> * The method {@link Arrays#hashCode(Object[])} is not constant for {@code double[][]} arrays. * So we compare each sub-array on its own with {@link Arrays#hashCode(double[])}. */ private static void assertArrayHashcodes(String label, double[][] array, int[] hashcodes) { assertEquals(label + " and hashcode array lengths differ", hashcodes.length, array.length); for (int i = 0; i < array.length; i++) { assertEquals("DenseHyperLogLogConstants." + label + " at index " + i, hashcodes[i], Arrays.hashCode(array[i])); } } }
apache-2.0
madhav123/gkmaster
appdomain/src/main/java/org/mifos/customers/business/CustomerMovementEntity.java
3000
/* * Copyright (c) 2005-2011 Grameen Foundation USA * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.customers.business; import java.util.Date; import org.mifos.application.util.helpers.Status; import org.mifos.customers.office.business.OfficeBO; import org.mifos.framework.business.AbstractEntity; import org.mifos.framework.util.DateTimeService; public class CustomerMovementEntity extends AbstractEntity { private final Integer customerMovementId; private Short status; private final Date startDate; private Date endDate; private final CustomerBO customer; private final OfficeBO office; private Date updatedDate; private Short updatedBy; public CustomerMovementEntity(CustomerBO customer, Date startDate) { this.customer = customer; this.office = customer.getOffice(); this.startDate = startDate; this.status = Status.ACTIVE.getValue(); this.customerMovementId = null; } /* * Adding a default constructor is hibernate's requirement and should not be * used to create a valid Object. */ protected CustomerMovementEntity() { this.customerMovementId = null; this.customer = null; this.office = null; this.startDate = null; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } void setEndDate(Date endDate) { this.endDate = endDate; } public OfficeBO getOffice() { return office; } void updateStatus(Status status) { this.status = status.getValue(); } public boolean isActive() { return status.equals(Status.ACTIVE.getValue()); } void makeInactive(Short updatedBy) { updateStatus(Status.INACTIVE); setUpdatedBy(updatedBy); setUpdatedDate(new DateTimeService().getCurrentJavaDateTime()); setEndDate(new DateTimeService().getCurrentJavaDateTime()); } public Short getUpdatedBy() { return updatedBy; } public void setUpdatedBy(Short updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDate() { return updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } }
apache-2.0
stewartpark/presto
presto-orc/src/main/java/com/facebook/presto/orc/OrcWriteValidation.java
43549
/* * 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.orc; import com.facebook.presto.orc.metadata.CompressionKind; import com.facebook.presto.orc.metadata.PostScript.HiveWriterVersion; import com.facebook.presto.orc.metadata.RowGroupIndex; import com.facebook.presto.orc.metadata.StripeInformation; import com.facebook.presto.orc.metadata.statistics.BinaryStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.BooleanStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.ColumnStatistics; import com.facebook.presto.orc.metadata.statistics.DateStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.DoubleStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.IntegerStatistics; import com.facebook.presto.orc.metadata.statistics.IntegerStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.LongDecimalStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.ShortDecimalStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.StatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.StatisticsHasher; import com.facebook.presto.orc.metadata.statistics.StringStatistics; import com.facebook.presto.orc.metadata.statistics.StringStatisticsBuilder; import com.facebook.presto.orc.metadata.statistics.StripeStatistics; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.ColumnarMap; import com.facebook.presto.spi.block.ColumnarRow; import com.facebook.presto.spi.type.AbstractLongType; import com.facebook.presto.spi.type.CharType; import com.facebook.presto.spi.type.DecimalType; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.VarcharType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Iterables; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.airlift.slice.XxHash64; import org.openjdk.jol.info.ClassLayout; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.SortedMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode.BOTH; import static com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode.DETAILED; import static com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode.HASHED; import static com.facebook.presto.orc.metadata.DwrfMetadataWriter.STATIC_METADATA; import static com.facebook.presto.orc.metadata.OrcMetadataReader.maxStringTruncateToValidRange; import static com.facebook.presto.orc.metadata.OrcMetadataReader.minStringTruncateToValidRange; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.block.ColumnarArray.toColumnarArray; import static com.facebook.presto.spi.block.ColumnarMap.toColumnarMap; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.StandardTypes.ARRAY; import static com.facebook.presto.spi.type.StandardTypes.MAP; import static com.facebook.presto.spi.type.StandardTypes.ROW; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; public class OrcWriteValidation { public enum OrcWriteValidationMode { HASHED, DETAILED, BOTH } private final List<Integer> version; private final CompressionKind compression; private final int rowGroupMaxRowCount; private final List<String> columnNames; private final Map<String, Slice> metadata; private final WriteChecksum checksum; private final Map<Long, List<RowGroupStatistics>> rowGroupStatistics; private final Map<Long, StripeStatistics> stripeStatistics; private final List<ColumnStatistics> fileStatistics; private final int stringStatisticsLimitInBytes; private OrcWriteValidation( List<Integer> version, CompressionKind compression, int rowGroupMaxRowCount, List<String> columnNames, Map<String, Slice> metadata, WriteChecksum checksum, Map<Long, List<RowGroupStatistics>> rowGroupStatistics, Map<Long, StripeStatistics> stripeStatistics, List<ColumnStatistics> fileStatistics, int stringStatisticsLimitInBytes) { this.version = version; this.compression = compression; this.rowGroupMaxRowCount = rowGroupMaxRowCount; this.columnNames = columnNames; this.metadata = metadata; this.checksum = checksum; this.rowGroupStatistics = rowGroupStatistics; this.stripeStatistics = stripeStatistics; this.fileStatistics = fileStatistics; this.stringStatisticsLimitInBytes = stringStatisticsLimitInBytes; } public List<Integer> getVersion() { return version; } public CompressionKind getCompression() { return compression; } public int getRowGroupMaxRowCount() { return rowGroupMaxRowCount; } public List<String> getColumnNames() { return columnNames; } public Map<String, Slice> getMetadata() { return metadata; } public void validateMetadata(OrcDataSourceId orcDataSourceId, Map<String, Slice> actualMetadata) throws OrcCorruptionException { // Filter out metadata value statically added by the DWRF writer Map<String, Slice> filteredMetadata = actualMetadata.entrySet().stream() .filter(entry -> !STATIC_METADATA.containsKey(entry.getKey())) .collect(toImmutableMap(Entry::getKey, Entry::getValue)); if (!metadata.equals(filteredMetadata)) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected metadata"); } } public WriteChecksum getChecksum() { return checksum; } public void validateFileStatistics(OrcDataSourceId orcDataSourceId, List<ColumnStatistics> actualFileStatistics) throws OrcCorruptionException { if (actualFileStatistics.isEmpty()) { // DWRF file statistics are disabled return; } validateColumnStatisticsEquivalent(orcDataSourceId, "file", actualFileStatistics, fileStatistics); } public void validateStripeStatistics(OrcDataSourceId orcDataSourceId, List<StripeInformation> actualStripes, List<StripeStatistics> actualStripeStatistics) throws OrcCorruptionException { requireNonNull(actualStripes, "actualStripes is null"); requireNonNull(actualStripeStatistics, "actualStripeStatistics is null"); if (actualStripeStatistics.isEmpty()) { // DWRF does not have stripe statistics return; } if (actualStripeStatistics.size() != stripeStatistics.size()) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected number of columns in stripe statistics"); } for (int stripeIndex = 0; stripeIndex < actualStripes.size(); stripeIndex++) { long stripeOffset = actualStripes.get(stripeIndex).getOffset(); StripeStatistics actual = actualStripeStatistics.get(stripeIndex); validateStripeStatistics(orcDataSourceId, stripeOffset, actual.getColumnStatistics()); } } public void validateStripeStatistics(OrcDataSourceId orcDataSourceId, long stripeOffset, List<ColumnStatistics> actual) throws OrcCorruptionException { StripeStatistics expected = stripeStatistics.get(stripeOffset); if (expected == null) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected stripe at offset %s", stripeOffset); } validateColumnStatisticsEquivalent(orcDataSourceId, "Stripe at " + stripeOffset, actual, expected.getColumnStatistics()); } public void validateRowGroupStatistics(OrcDataSourceId orcDataSourceId, long stripeOffset, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) throws OrcCorruptionException { requireNonNull(actualRowGroupStatistics, "actualRowGroupStatistics is null"); List<RowGroupStatistics> expectedRowGroupStatistics = rowGroupStatistics.get(stripeOffset); if (expectedRowGroupStatistics == null) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected stripe at offset %s", stripeOffset); } int rowGroupCount = expectedRowGroupStatistics.size(); for (Entry<StreamId, List<RowGroupIndex>> entry : actualRowGroupStatistics.entrySet()) { // TODO: Remove once the Presto writer supports flat map if (entry.getKey().getSequence() > 0) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected sequence ID for column %s at offset %s", entry.getKey().getColumn(), stripeOffset); } if (entry.getValue().size() != rowGroupCount) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected row group count stripe in at offset %s", stripeOffset); } } for (int rowGroupIndex = 0; rowGroupIndex < expectedRowGroupStatistics.size(); rowGroupIndex++) { RowGroupStatistics expectedRowGroup = expectedRowGroupStatistics.get(rowGroupIndex); if (expectedRowGroup.getValidationMode() != HASHED) { Map<Integer, ColumnStatistics> expectedStatistics = expectedRowGroup.getColumnStatistics(); Set<Integer> actualColumns = actualRowGroupStatistics.keySet().stream() .map(StreamId::getColumn) .collect(Collectors.toSet()); if (!expectedStatistics.keySet().equals(actualColumns)) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected column in row group %s in stripe at offset %s", rowGroupIndex, stripeOffset); } for (Entry<StreamId, List<RowGroupIndex>> entry : actualRowGroupStatistics.entrySet()) { ColumnStatistics actual = entry.getValue().get(rowGroupIndex).getColumnStatistics(); ColumnStatistics expected = expectedStatistics.get(entry.getKey().getColumn()); validateColumnStatisticsEquivalent(orcDataSourceId, "Row group " + rowGroupIndex + " in stripe at offset " + stripeOffset, actual, expected); } } if (expectedRowGroup.getValidationMode() != DETAILED) { RowGroupStatistics actualRowGroup = buildActualRowGroupStatistics(rowGroupIndex, actualRowGroupStatistics); if (expectedRowGroup.getHash() != actualRowGroup.getHash()) { throw new OrcCorruptionException(orcDataSourceId, "Checksum mismatch for row group %s in stripe at offset %s", rowGroupIndex, stripeOffset); } } } } private static RowGroupStatistics buildActualRowGroupStatistics(int rowGroupIndex, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) { return new RowGroupStatistics( BOTH, actualRowGroupStatistics.entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().getColumn(), entry -> entry.getValue().get(rowGroupIndex).getColumnStatistics()))); } public void validateRowGroupStatistics( OrcDataSourceId orcDataSourceId, long stripeOffset, int rowGroupIndex, List<ColumnStatistics> actual) throws OrcCorruptionException { List<RowGroupStatistics> rowGroups = rowGroupStatistics.get(stripeOffset); if (rowGroups == null) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected stripe at offset %s", stripeOffset); } if (rowGroups.size() <= rowGroupIndex) { throw new OrcCorruptionException(orcDataSourceId, "Unexpected row group %s in stripe at offset %s", rowGroupIndex, stripeOffset); } RowGroupStatistics expectedRowGroup = rowGroups.get(rowGroupIndex); RowGroupStatistics actualRowGroup = new RowGroupStatistics(BOTH, IntStream.range(1, actual.size()).boxed().collect(toImmutableMap(identity(), actual::get))); if (expectedRowGroup.getValidationMode() != HASHED) { Map<Integer, ColumnStatistics> expectedByColumnIndex = expectedRowGroup.getColumnStatistics(); // new writer does not write row group stats for column zero (table row column) List<ColumnStatistics> expected = IntStream.range(1, actual.size()) .mapToObj(expectedByColumnIndex::get) .collect(toImmutableList()); actual = actual.subList(1, actual.size()); validateColumnStatisticsEquivalent(orcDataSourceId, "Row group " + rowGroupIndex + " in stripe at offset " + stripeOffset, actual, expected); } if (expectedRowGroup.getValidationMode() != DETAILED) { if (expectedRowGroup.getHash() != actualRowGroup.getHash()) { throw new OrcCorruptionException(orcDataSourceId, "Checksum mismatch for row group %s in stripe at offset %s", rowGroupIndex, stripeOffset); } } } public StatisticsValidation createWriteStatisticsBuilder(Map<Integer, Type> readColumns) { requireNonNull(readColumns, "readColumns is null"); checkArgument(!readColumns.isEmpty(), "readColumns is empty"); int columnCount = readColumns.keySet().stream() .mapToInt(Integer::intValue) .max().getAsInt() + 1; checkArgument(readColumns.size() == columnCount, "statistics validation requires all columns to be read"); ImmutableList.Builder<Type> types = ImmutableList.builder(); for (int column = 0; column < columnCount; column++) { Type type = readColumns.get(column); checkArgument(type != null, "statistics validation requires all columns to be read"); types.add(type); } return new StatisticsValidation(types.build()); } private static void validateColumnStatisticsEquivalent( OrcDataSourceId orcDataSourceId, String name, List<ColumnStatistics> actualColumnStatistics, List<ColumnStatistics> expectedColumnStatistics) throws OrcCorruptionException { requireNonNull(name, "name is null"); requireNonNull(actualColumnStatistics, "actualColumnStatistics is null"); requireNonNull(expectedColumnStatistics, "expectedColumnStatistics is null"); if (actualColumnStatistics.size() != expectedColumnStatistics.size()) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected number of columns in %s statistics", name); } for (int i = 0; i < actualColumnStatistics.size(); i++) { ColumnStatistics actual = actualColumnStatistics.get(i); ColumnStatistics expected = expectedColumnStatistics.get(i); validateColumnStatisticsEquivalent(orcDataSourceId, name + " column " + i, actual, expected); } } private static void validateColumnStatisticsEquivalent( OrcDataSourceId orcDataSourceId, String name, ColumnStatistics actualColumnStatistics, ColumnStatistics expectedColumnStatistics) throws OrcCorruptionException { requireNonNull(name, "name is null"); requireNonNull(actualColumnStatistics, "actualColumnStatistics is null"); requireNonNull(expectedColumnStatistics, "expectedColumnStatistics is null"); if (actualColumnStatistics.getNumberOfValues() != expectedColumnStatistics.getNumberOfValues()) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected number of values in %s statistics", name); } if (!Objects.equals(actualColumnStatistics.getBooleanStatistics(), expectedColumnStatistics.getBooleanStatistics())) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected boolean counts in %s statistics", name); } if (!Objects.equals(actualColumnStatistics.getIntegerStatistics(), expectedColumnStatistics.getIntegerStatistics())) { IntegerStatistics actualIntegerStatistics = actualColumnStatistics.getIntegerStatistics(); IntegerStatistics expectedIntegerStatistics = expectedColumnStatistics.getIntegerStatistics(); // The sum of the integer stats depends on the order of how we merge them. // It is possible the sum can overflow with one order but not in another. // Ignore the validation of sum if one of the two sums is null. if (actualIntegerStatistics == null || expectedIntegerStatistics == null || !Objects.equals(actualIntegerStatistics.getMin(), expectedIntegerStatistics.getMin()) || !Objects.equals(actualIntegerStatistics.getMax(), expectedIntegerStatistics.getMax()) || (actualIntegerStatistics.getSum() != null && expectedIntegerStatistics.getSum() != null && !Objects.equals(actualIntegerStatistics.getSum(), expectedIntegerStatistics.getSum()))) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected integer range in %s statistics", name); } } if (!Objects.equals(actualColumnStatistics.getDoubleStatistics(), expectedColumnStatistics.getDoubleStatistics())) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected double range in %s statistics", name); } StringStatistics expectedStringStatistics = expectedColumnStatistics.getStringStatistics(); if (expectedStringStatistics != null) { expectedStringStatistics = new StringStatistics( minStringTruncateToValidRange(expectedStringStatistics.getMin(), HiveWriterVersion.ORC_HIVE_8732), maxStringTruncateToValidRange(expectedStringStatistics.getMax(), HiveWriterVersion.ORC_HIVE_8732), expectedStringStatistics.getSum()); } StringStatistics actualStringStatistics = actualColumnStatistics.getStringStatistics(); if (!Objects.equals(actualColumnStatistics.getStringStatistics(), expectedStringStatistics) && expectedStringStatistics != null) { // expectedStringStatistics (or the min/max of it) could be null while the actual one might not because // expectedStringStatistics is calculated by merging all row group stats in the stripe but the actual one is by scanning each row in the stripe on disk. // Merging row group stats can produce nulls given we have string stats limit. if (actualStringStatistics == null || actualStringStatistics.getSum() != expectedStringStatistics.getSum() || (expectedStringStatistics.getMax() != null && !Objects.equals(actualStringStatistics.getMax(), expectedStringStatistics.getMax())) || (expectedStringStatistics.getMin() != null && !Objects.equals(actualStringStatistics.getMin(), expectedStringStatistics.getMin()))) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected string range in %s statistics", name); } } if (!Objects.equals(actualColumnStatistics.getDateStatistics(), expectedColumnStatistics.getDateStatistics())) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected date range in %s statistics", name); } if (!Objects.equals(actualColumnStatistics.getDecimalStatistics(), expectedColumnStatistics.getDecimalStatistics())) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected decimal range in %s statistics", name); } if (!Objects.equals(actualColumnStatistics.getBloomFilter(), expectedColumnStatistics.getBloomFilter())) { throw new OrcCorruptionException(orcDataSourceId, "Write validation failed: unexpected bloom filter in %s statistics", name); } } public static class WriteChecksum { private final long totalRowCount; private final long stripeHash; private final List<Long> columnHashes; public WriteChecksum(long totalRowCount, long stripeHash, List<Long> columnHashes) { this.totalRowCount = totalRowCount; this.stripeHash = stripeHash; this.columnHashes = columnHashes; } public long getTotalRowCount() { return totalRowCount; } public long getStripeHash() { return stripeHash; } public List<Long> getColumnHashes() { return columnHashes; } } public static class WriteChecksumBuilder { private static final long NULL_HASH_CODE = 0x6e3efbd56c16a0cbL; private final List<Type> types; private long totalRowCount; private final List<XxHash64> columnHashes; private final XxHash64 stripeHash = new XxHash64(); private final byte[] longBuffer = new byte[Long.BYTES]; private final Slice longSlice = Slices.wrappedBuffer(longBuffer); private WriteChecksumBuilder(List<Type> types) { this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); ImmutableList.Builder<XxHash64> columnHashes = ImmutableList.builder(); for (Type ignored : types) { columnHashes.add(new XxHash64()); } this.columnHashes = columnHashes.build(); } public static WriteChecksumBuilder createWriteChecksumBuilder(Map<Integer, Type> readColumns) { requireNonNull(readColumns, "readColumns is null"); checkArgument(!readColumns.isEmpty(), "readColumns is empty"); int columnCount = readColumns.keySet().stream() .mapToInt(Integer::intValue) .max().getAsInt() + 1; checkArgument(readColumns.size() == columnCount, "checksum requires all columns to be read"); ImmutableList.Builder<Type> types = ImmutableList.builder(); for (int column = 0; column < columnCount; column++) { Type type = readColumns.get(column); checkArgument(type != null, "checksum requires all columns to be read"); types.add(type); } return new WriteChecksumBuilder(types.build()); } public void addStripe(int rowCount) { longSlice.setInt(0, rowCount); stripeHash.update(longBuffer, 0, Integer.BYTES); } public void addPage(Page page) { requireNonNull(page, "page is null"); checkArgument(page.getChannelCount() == columnHashes.size(), "invalid page"); for (int channel = 0; channel < columnHashes.size(); channel++) { Type type = types.get(channel); Block block = page.getBlock(channel); XxHash64 xxHash64 = columnHashes.get(channel); for (int position = 0; position < block.getPositionCount(); position++) { long hash = hashPositionSkipNullMapKeys(type, block, position); longSlice.setLong(0, hash); xxHash64.update(longBuffer); } } totalRowCount += page.getPositionCount(); } private static long hashPositionSkipNullMapKeys(Type type, Block block, int position) { if (block.isNull(position)) { return NULL_HASH_CODE; } if (type.getTypeSignature().getBase().equals(MAP)) { Type keyType = type.getTypeParameters().get(0); Type valueType = type.getTypeParameters().get(1); Block mapBlock = (Block) type.getObject(block, position); long hash = 0; for (int i = 0; i < mapBlock.getPositionCount(); i += 2) { if (!mapBlock.isNull(i)) { hash += hashPositionSkipNullMapKeys(keyType, mapBlock, i); hash += hashPositionSkipNullMapKeys(valueType, mapBlock, i + 1); } } return hash; } if (type.getTypeSignature().getBase().equals(ARRAY)) { Type elementType = type.getTypeParameters().get(0); Block array = (Block) type.getObject(block, position); long hash = 0; for (int i = 0; i < array.getPositionCount(); i++) { hash = 31 * hash + hashPositionSkipNullMapKeys(elementType, array, i); } return hash; } if (type.getTypeSignature().getBase().equals(ROW)) { Block row = (Block) type.getObject(block, position); long hash = 0; for (int i = 0; i < row.getPositionCount(); i++) { Type elementType = type.getTypeParameters().get(i); hash = 31 * hash + hashPositionSkipNullMapKeys(elementType, row, i); } return hash; } if (type.getTypeSignature().getBase().equals(StandardTypes.TIMESTAMP)) { // A flaw in ORC encoding makes it impossible to represent timestamp // between 1969-12-31 23:59:59.000, exclusive, and 1970-01-01 00:00:00.000, exclusive. // Therefore, such data won't round trip. The data read back is expected to be 1 second later than the original value. long mills = TIMESTAMP.getLong(block, position); if (mills > -1000 && mills < 0) { return AbstractLongType.hash(mills + 1000); } } return type.hash(block, position); } public WriteChecksum build() { return new WriteChecksum( totalRowCount, stripeHash.hash(), columnHashes.stream() .map(XxHash64::hash) .collect(toImmutableList())); } } public class StatisticsValidation { private final List<Type> types; private List<ColumnStatisticsValidation> columnStatisticsValidations; private long rowCount; private StatisticsValidation(List<Type> types) { this.types = requireNonNull(types, "types is null"); columnStatisticsValidations = types.stream() .map(ColumnStatisticsValidation::new) .collect(toImmutableList()); } public void reset() { rowCount = 0; columnStatisticsValidations = types.stream() .map(ColumnStatisticsValidation::new) .collect(toImmutableList()); } public void addPage(Page page) { rowCount += page.getPositionCount(); for (int channel = 0; channel < columnStatisticsValidations.size(); channel++) { columnStatisticsValidations.get(channel).addBlock(page.getBlock(channel)); } } public List<ColumnStatistics> build() { ImmutableList.Builder<ColumnStatistics> statisticsBuilders = ImmutableList.builder(); // if there are no rows, there will be no stats if (rowCount > 0) { statisticsBuilders.add(new ColumnStatistics(rowCount, 0, null, null, null, null, null, null, null, null)); columnStatisticsValidations.forEach(validation -> validation.build(statisticsBuilders)); } return statisticsBuilders.build(); } } private class ColumnStatisticsValidation { private final Type type; private final StatisticsBuilder statisticsBuilder; private final Function<Block, List<Block>> fieldExtractor; private final List<ColumnStatisticsValidation> fieldBuilders; private ColumnStatisticsValidation(Type type) { this.type = requireNonNull(type, "type is null"); if (BOOLEAN.equals(type)) { statisticsBuilder = new BooleanStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (TINYINT.equals(type)) { statisticsBuilder = new CountStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (SMALLINT.equals(type)) { statisticsBuilder = new IntegerStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (INTEGER.equals(type)) { statisticsBuilder = new IntegerStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (BIGINT.equals(type)) { statisticsBuilder = new IntegerStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (DOUBLE.equals(type)) { statisticsBuilder = new DoubleStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (REAL.equals(type)) { statisticsBuilder = new DoubleStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (type instanceof VarcharType) { statisticsBuilder = new StringStatisticsBuilder(stringStatisticsLimitInBytes); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (type instanceof CharType) { statisticsBuilder = new StringStatisticsBuilder(stringStatisticsLimitInBytes); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (VARBINARY.equals(type)) { statisticsBuilder = new BinaryStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (DATE.equals(type)) { statisticsBuilder = new DateStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (TIMESTAMP.equals(type)) { statisticsBuilder = new CountStatisticsBuilder(); fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; if (decimalType.isShort()) { statisticsBuilder = new ShortDecimalStatisticsBuilder((decimalType).getScale()); } else { statisticsBuilder = new LongDecimalStatisticsBuilder(); } fieldExtractor = ignored -> ImmutableList.of(); fieldBuilders = ImmutableList.of(); } else if (type.getTypeSignature().getBase().equals(ARRAY)) { statisticsBuilder = new CountStatisticsBuilder(); fieldExtractor = block -> ImmutableList.of(toColumnarArray(block).getElementsBlock()); fieldBuilders = ImmutableList.of(new ColumnStatisticsValidation(Iterables.getOnlyElement(type.getTypeParameters()))); } else if (type.getTypeSignature().getBase().equals(MAP)) { statisticsBuilder = new CountStatisticsBuilder(); fieldExtractor = block -> { ColumnarMap columnarMap = toColumnarMap(block); return ImmutableList.of(columnarMap.getKeysBlock(), columnarMap.getValuesBlock()); }; fieldBuilders = type.getTypeParameters().stream() .map(ColumnStatisticsValidation::new) .collect(toImmutableList()); } else if (type.getTypeSignature().getBase().equals(ROW)) { statisticsBuilder = new CountStatisticsBuilder(); fieldExtractor = block -> { ColumnarRow columnarRow = ColumnarRow.toColumnarRow(block); ImmutableList.Builder<Block> fields = ImmutableList.builder(); for (int index = 0; index < columnarRow.getFieldCount(); index++) { fields.add(columnarRow.getField(index)); } return fields.build(); }; fieldBuilders = type.getTypeParameters().stream() .map(ColumnStatisticsValidation::new) .collect(toImmutableList()); } else { throw new PrestoException(NOT_SUPPORTED, format("Unsupported Hive type: %s", type)); } } private void addBlock(Block block) { statisticsBuilder.addBlock(type, block); List<Block> fields = fieldExtractor.apply(block); for (int i = 0; i < fieldBuilders.size(); i++) { fieldBuilders.get(i).addBlock(fields.get(i)); } } private void build(ImmutableList.Builder<ColumnStatistics> output) { output.add(statisticsBuilder.buildColumnStatistics()); fieldBuilders.forEach(fieldBuilders -> fieldBuilders.build(output)); } } private static class CountStatisticsBuilder implements StatisticsBuilder { private long rowCount; @Override public void addBlock(Type type, Block block) { for (int position = 0; position < block.getPositionCount(); position++) { if (!block.isNull(position)) { rowCount++; } } } @Override public ColumnStatistics buildColumnStatistics() { return new ColumnStatistics(rowCount, 0, null, null, null, null, null, null, null, null); } } private static class RowGroupStatistics { private static final int INSTANCE_SIZE = ClassLayout.parseClass(RowGroupStatistics.class).instanceSize(); private final OrcWriteValidationMode validationMode; private final SortedMap<Integer, ColumnStatistics> columnStatistics; private final long hash; public RowGroupStatistics(OrcWriteValidationMode validationMode, Map<Integer, ColumnStatistics> columnStatistics) { this.validationMode = validationMode; requireNonNull(columnStatistics, "columnStatistics is null"); if (validationMode == HASHED) { this.columnStatistics = ImmutableSortedMap.of(); hash = hashColumnStatistics(ImmutableSortedMap.copyOf(columnStatistics)); } else if (validationMode == DETAILED) { this.columnStatistics = ImmutableSortedMap.copyOf(columnStatistics); hash = 0; } else if (validationMode == BOTH) { this.columnStatistics = ImmutableSortedMap.copyOf(columnStatistics); hash = hashColumnStatistics(this.columnStatistics); } else { throw new IllegalArgumentException("Unsupported validation mode"); } } private static long hashColumnStatistics(SortedMap<Integer, ColumnStatistics> columnStatistics) { StatisticsHasher statisticsHasher = new StatisticsHasher(); statisticsHasher.putInt(columnStatistics.size()); for (Entry<Integer, ColumnStatistics> entry : columnStatistics.entrySet()) { statisticsHasher.putInt(entry.getKey()) .putOptionalHashable(entry.getValue()); } return statisticsHasher.hash(); } public OrcWriteValidationMode getValidationMode() { return validationMode; } public Map<Integer, ColumnStatistics> getColumnStatistics() { verify(validationMode != HASHED, "columnStatistics are not available in HASHED mode"); return columnStatistics; } public long getHash() { return hash; } } public static class OrcWriteValidationBuilder { private static final int INSTANCE_SIZE = ClassLayout.parseClass(OrcWriteValidationBuilder.class).instanceSize(); private final OrcWriteValidationMode validationMode; private List<Integer> version; private CompressionKind compression; private int rowGroupMaxRowCount; private int stringStatisticsLimitInBytes; private List<String> columnNames; private final Map<String, Slice> metadata = new HashMap<>(); private final WriteChecksumBuilder checksum; private List<RowGroupStatistics> currentRowGroupStatistics = new ArrayList<>(); private final Map<Long, List<RowGroupStatistics>> rowGroupStatisticsByStripe = new HashMap<>(); private final Map<Long, StripeStatistics> stripeStatistics = new HashMap<>(); private List<ColumnStatistics> fileStatistics; private long retainedSize = INSTANCE_SIZE; public OrcWriteValidationBuilder(OrcWriteValidationMode validationMode, List<Type> types) { this.validationMode = validationMode; this.checksum = new WriteChecksumBuilder(types); } public long getRetainedSize() { return retainedSize; } public OrcWriteValidationBuilder setVersion(List<Integer> version) { this.version = ImmutableList.copyOf(version); return this; } public void setCompression(CompressionKind compression) { this.compression = compression; } public void setRowGroupMaxRowCount(int rowGroupMaxRowCount) { this.rowGroupMaxRowCount = rowGroupMaxRowCount; } public OrcWriteValidationBuilder setStringStatisticsLimitInBytes(int stringStatisticsLimitInBytes) { this.stringStatisticsLimitInBytes = stringStatisticsLimitInBytes; return this; } public OrcWriteValidationBuilder setColumnNames(List<String> columnNames) { this.columnNames = ImmutableList.copyOf(requireNonNull(columnNames, "columnNames is null")); return this; } public OrcWriteValidationBuilder addMetadataProperty(String key, Slice value) { metadata.put(key, value); return this; } public OrcWriteValidationBuilder addStripe(int rowCount) { checksum.addStripe(rowCount); return this; } public OrcWriteValidationBuilder addPage(Page page) { checksum.addPage(page); return this; } public void addRowGroupStatistics(Map<Integer, ColumnStatistics> columnStatistics) { RowGroupStatistics rowGroupStatistics = new RowGroupStatistics(validationMode, columnStatistics); currentRowGroupStatistics.add(rowGroupStatistics); retainedSize += RowGroupStatistics.INSTANCE_SIZE; if (validationMode != HASHED) { for (ColumnStatistics statistics : rowGroupStatistics.getColumnStatistics().values()) { retainedSize += Integer.BYTES + statistics.getRetainedSizeInBytes(); } } } public void addStripeStatistics(long stripStartOffset, StripeStatistics columnStatistics) { stripeStatistics.put(stripStartOffset, columnStatistics); rowGroupStatisticsByStripe.put(stripStartOffset, currentRowGroupStatistics); currentRowGroupStatistics = new ArrayList<>(); } public void setFileStatistics(List<ColumnStatistics> fileStatistics) { this.fileStatistics = fileStatistics; } public OrcWriteValidation build() { return new OrcWriteValidation( version, compression, rowGroupMaxRowCount, columnNames, metadata, checksum.build(), rowGroupStatisticsByStripe, stripeStatistics, fileStatistics, stringStatisticsLimitInBytes); } } }
apache-2.0
alien11689/incubator-groovy
subprojects/groovy-json/src/main/java/groovy/json/internal/NumberValue.java
6453
/* * 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 groovy.json.internal; import groovy.json.JsonException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Date; import static groovy.json.internal.CharScanner.*; import static groovy.json.internal.Exceptions.die; import static groovy.json.internal.Exceptions.sputs; /** * @author Rick Hightower */ public class NumberValue extends java.lang.Number implements Value { private char[] buffer; private boolean chopped; private int startIndex; private int endIndex; private final Type type; private Object value; public NumberValue(Type type) { this.type = type; } public NumberValue() { this.type = null; } public NumberValue(boolean chop, Type type, int startIndex, int endIndex, char[] buffer) { this.type = type; try { if (chop) { this.buffer = ArrayUtils.copyRange(buffer, startIndex, endIndex); this.startIndex = 0; this.endIndex = this.buffer.length; chopped = true; } else { this.startIndex = startIndex; this.endIndex = endIndex; this.buffer = buffer; } } catch (Exception ex) { Exceptions.handle(sputs("exception", ex, "start", startIndex, "end", endIndex), ex); } } public String toString() { if (startIndex == 0 && endIndex == buffer.length) { return FastStringUtils.noCopyStringFromChars(buffer); } else { return new String(buffer, startIndex, (endIndex - startIndex)); } } public final Object toValue() { return value != null ? value : (value = doToValue()); } public <T extends Enum> T toEnum(Class<T> cls) { return toEnum(cls, intValue()); } public static <T extends Enum> T toEnum(Class<T> cls, int value) { T[] enumConstants = cls.getEnumConstants(); for (T e : enumConstants) { if (e.ordinal() == value) { return e; } } die("Can't convert ordinal value " + value + " into enum of type " + cls); return null; } public boolean isContainer() { return false; } private Object doToValue() { switch (type) { case DOUBLE: return bigDecimalValue(); case INTEGER: int sign = 1; if (buffer[startIndex] == '-') { startIndex++; sign = -1; } if (isInteger(buffer, startIndex, endIndex - startIndex)) { return intValue() * sign; } else { return longValue() * sign; } } die(); return null; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Value)) return false; NumberValue value1 = (NumberValue) o; if (endIndex != value1.endIndex) return false; if (startIndex != value1.startIndex) return false; if (!Arrays.equals(buffer, value1.buffer)) return false; if (type != value1.type) return false; return value != null ? value.equals(value1.value) : value1.value == null; } public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + (buffer != null ? Arrays.hashCode(buffer) : 0); result = 31 * result + startIndex; result = 31 * result + endIndex; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } public BigDecimal bigDecimalValue() { try { return new BigDecimal(buffer, startIndex, endIndex - startIndex); } catch (NumberFormatException e) { throw new JsonException("unable to parse " + new String(buffer, startIndex, endIndex - startIndex), e); } } public BigInteger bigIntegerValue() { return new BigInteger(toString()); } public String stringValue() { return toString(); } public String stringValueEncoded() { return toString(); } public Date dateValue() { return new Date(Dates.utc(longValue())); } public int intValue() { int sign = 1; if (buffer[startIndex] == '-') { startIndex++; sign = -1; } return parseIntFromTo(buffer, startIndex, endIndex) * sign; } public long longValue() { if (isInteger(buffer, startIndex, endIndex - startIndex)) { return parseIntFromTo(buffer, startIndex, endIndex); } else { return parseLongFromTo(buffer, startIndex, endIndex); } } public byte byteValue() { return (byte) intValue(); } public short shortValue() { return (short) intValue(); } public double doubleValue() { return CharScanner.parseDouble(this.buffer, startIndex, endIndex); } public boolean booleanValue() { return Boolean.parseBoolean(toString()); } public float floatValue() { return CharScanner.parseFloat(this.buffer, startIndex, endIndex); } public final void chop() { if (!chopped) { this.chopped = true; this.buffer = ArrayUtils.copyRange(buffer, startIndex, endIndex); this.startIndex = 0; this.endIndex = this.buffer.length; } } public char charValue() { return buffer[startIndex]; } }
apache-2.0
diegoam/fab
fab/src/main/java/com/software/shell/fab/ActionButton.java
55568
/* * Copyright 2015 Shell Software 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. * * File created: 2015-01-17 10:39:13 */ package com.software.shell.fab; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.*; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import com.software.shell.uitools.convert.DensityConverter; import com.software.shell.uitools.resutils.color.ColorModifier; import com.software.shell.uitools.resutils.id.IdGenerator; import com.software.shell.viewmover.configuration.MovingParams; import com.software.shell.viewmover.movers.ViewMover; import com.software.shell.viewmover.movers.ViewMoverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents a <b>Action Button</b>, which is used in * <a href="http://www.google.com.ua/design/spec/components/buttons.html">Material Design</a> * * @author Vladislav * @version 1.1.0 * @since 1.0.0 */ public class ActionButton extends View { /** * Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(ActionButton.class); /** * <b>Action Button</b> type */ private Type type = Type.DEFAULT; /** * <b>Action Button</b> size in actual pixels */ private float size = dpToPx(type.getSize()); /** * <b>Action Button</b> state */ private State state = State.NORMAL; /** * <b>Action Button</b> color for the {@link State#NORMAL} state */ private int buttonColor = Color.parseColor("#FF9B9B9B"); /** * <b>Action Button</b> color for the {@link State#PRESSED} state */ private int buttonColorPressed = Color.parseColor("#FF696969"); /** * Determines whether <b>Action Button</b> Ripple Effect enabled or not */ private boolean rippleEffectEnabled; /** * <b>Action Button</b> Ripple Effect color */ private int buttonColorRipple = darkenButtonColorPressed(); /** * Shadow radius expressed in actual pixels */ private float shadowRadius = dpToPx(8.0f); /** * Shadow X-axis offset expressed in actual pixels */ private float shadowXOffset = dpToPx(0.0f); /** * Shadow Y-axis offset expressed in actual pixels */ private float shadowYOffset = dpToPx(8.0f); /** * Shadow color */ private int shadowColor = Color.parseColor("#42000000"); /** * Determines whether Shadow Responsive Effect enabled * <p> * Responsive Shadow means that shadow is enlarged up to the certain limits * while in the {@link com.software.shell.fab.ActionButton.State#PRESSED} state */ private boolean shadowResponsiveEffectEnabled = true; /** * Stroke width */ private float strokeWidth = 0.0f; /** * Stroke color */ private int strokeColor = Color.BLACK; /** * <b>Action Button</b> image drawable centered inside the view */ private Drawable image; /** * Size of the <b>Action Button</b> image inside the view */ private float imageSize = dpToPx(24.0f); /** * Animation, which is used while showing <b>Action Button</b> */ private Animation showAnimation; /** * Animation, which is used while hiding or dismissing <b>Action Button</b> */ private Animation hideAnimation; /** * <b>Action Button</b> touch point * <p> * {@link TouchPoint} contains information about X- and * Y-axis touch points within the <b>Action Button</b> */ private TouchPoint touchPoint = new TouchPoint(0.0f, 0.0f); /** * {@link android.graphics.Paint}, which is used for drawing the elements of * <b>Action Button</b> */ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); /** * A view invalidator, which is used to invalidate the <b>Action Button</b> */ private final ViewInvalidator invalidator = new ViewInvalidator(this); /** * A drawer, which is used for drawing the <b>Action Button</b> Ripple Effect */ protected final EffectDrawer rippleEffectDrawer = new RippleEffectDrawer(this); /** * A drawer, which is used for drawing the <b>Action Button</b> Shadow Responsive Effect */ protected final EffectDrawer shadowResponsiveDrawer = new ShadowResponsiveDrawer(this); /** * A view mover, which is used to move the <b>Action Button</b> */ protected final ViewMover mover = ViewMoverFactory.createInstance(this); /** * Creates an instance of the <b>Action Button</b> * <p> * Used when instantiating <b>Action Button</b> programmatically * * @param context context the view is running in */ public ActionButton(Context context) { super(context); initActionButton(); } /** * Creates an instance of the <b>Action Button</b> * <p> * Used when inflating the declared <b>Action Button</b> * within XML resource * * @param context context the view is running in * @param attrs attributes of the XML tag that is inflating the view */ public ActionButton(Context context, AttributeSet attrs) { super(context, attrs); initActionButton(); initActionButtonAttrs(context, attrs, 0, 0); } /** * Creates an instance of the <b>Action Button</b> * <p> * Used when inflating the declared <b>Action Button</b> * within XML resource * * @param context context the view is running in * @param attrs attributes of the XML tag that is inflating the view * @param defStyleAttr attribute in the current theme that contains a * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults */ public ActionButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initActionButton(); initActionButtonAttrs(context, attrs, defStyleAttr, 0); } /** * Creates an instance of the <b>Action Button</b> * <p> * Used when inflating the declared <b>Action Button</b> * within XML resource * <p> * Might be called if target API is LOLLIPOP (21) and higher * * @param context context the view is running in * @param attrs attributes of the XML tag that is inflating the view * @param defStyleAttr attribute in the current theme that contains a * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults * @param defStyleRes resource identifier of a style resource that * supplies default values for the view, used only if * defStyleAttr is 0 or can not be found in the theme. Can be 0 * to not look for defaults */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ActionButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initActionButton(); initActionButtonAttrs(context, attrs, defStyleAttr, defStyleRes); } /** * Initializes the <b>Action Button</b>, which is created programmatically */ private void initActionButton() { initLayerType(); LOGGER.trace("Initialized the Action Button"); } /** * Initializes the <b>Action Button</b> attributes, declared within XML resource * <p> * Makes calls to different initialization methods for parameters initialization. * For those parameters, which are not declared in the XML resource, * the default value will be used * * @param context context the view is running in * @param attrs attributes of the XML tag that is inflating the view * @param defStyleAttr attribute in the current theme that contains a * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults * @param defStyleRes resource identifier of a style resource that * supplies default values for the view, used only if * defStyleAttr is 0 or can not be found in the theme. Can be 0 * to not look for defaults */ private void initActionButtonAttrs(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ActionButton, defStyleAttr, defStyleRes); try { initType(attributes); initSize(attributes); initButtonColor(attributes); initButtonColorPressed(attributes); initRippleEffectEnabled(attributes); initButtonColorRipple(attributes); initShadowRadius(attributes); initShadowXOffset(attributes); initShadowYOffset(attributes); initShadowColor(attributes); initShadowResponsiveEffectEnabled(attributes); initStrokeWidth(attributes); initStrokeColor(attributes); initImage(attributes); initImageSize(attributes); initShowAnimation(attributes); initHideAnimation(attributes); } catch (Exception e) { LOGGER.trace("Failed to read attribute", e); } finally { attributes.recycle(); } LOGGER.trace("Successfully initialized the Action Button attributes"); } /** * Initializes the layer type needed for shadows drawing * <p> * Might be called if target API is {@code HONEYCOMB (11)} and higher */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void initLayerType() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setLayerType(LAYER_TYPE_SOFTWARE, getPaint()); LOGGER.trace("Initialized the layer type"); } } /** * Initializes the {@link Type} of <b>Action Button</b> * <p> * Must be called before {@link #initSize(TypedArray)} for the proper * <b>Action Button</b> {@link #size} initialization * * @param attrs attributes of the XML tag that is inflating the view */ private void initType(TypedArray attrs) { int index = R.styleable.ActionButton_type; if (attrs.hasValue(index)) { int id = attrs.getInteger(index, type.getId()); type = Type.forId(id); LOGGER.trace("Initialized Action Button type: {}", getType()); } } /** * Initializes the {@link #size} of <b>Action Button</b> * <p> * Must be called after {@link #initType(TypedArray)} for the proper * <b>Action Button</b> {@link #size} initialization * * @param attrs attributes of the XML tag that is inflating the view */ private void initSize(TypedArray attrs) { int index = R.styleable.ActionButton_size; if (attrs.hasValue(index)) { this.size = attrs.getDimension(index, size); } else { this.size = dpToPx(type.getSize()); } LOGGER.trace("Initialized Action Button size: {}", getSize()); } /** * Initializes the <b>Action Button</b> color for the {@link State#NORMAL} * {@link #state} * * @param attrs attributes of the XML tag that is inflating the view */ private void initButtonColor(TypedArray attrs) { int index = R.styleable.ActionButton_button_color; if (attrs.hasValue(index)) { buttonColor = attrs.getColor(index, buttonColor); LOGGER.trace("Initialized Action Button color: {}", getButtonColor()); } } /** * Initializes the <b>Action Button</b> color for the {@link State#PRESSED} * {@link #state} * <p> * Initialized the <b>Action Button</b> default Ripple Effect color * <p> * Must be called before {@link #initButtonColorRipple(TypedArray)} for proper * {@link #buttonColorRipple} initialization * * @param attrs attributes of the XML tag that is inflating the view */ private void initButtonColorPressed(TypedArray attrs) { int index = R.styleable.ActionButton_button_colorPressed; if (attrs.hasValue(index)) { buttonColorPressed = attrs.getColor(index, buttonColorPressed); buttonColorRipple = darkenButtonColorPressed(); LOGGER.trace("Initialized Action Button color pressed: {}", getButtonColorPressed()); } } /** * Initializes the <b>Action Button</b> Ripple Effect state * * @param attrs attributes of the XML tag that is inflating the view */ private void initRippleEffectEnabled(TypedArray attrs) { int index = R.styleable.ActionButton_rippleEffect_enabled; if (attrs.hasValue(index)) { rippleEffectEnabled = attrs.getBoolean(index, rippleEffectEnabled); LOGGER.trace("Initialized Action Button Ripple Effect enabled: {}", isRippleEffectEnabled()); } } /** * Initializes the <b>Action Button</b> Ripple Effect color * <p> * Must be called after {@link #initButtonColorPressed(TypedArray)} for proper * {@link #buttonColorRipple} initialization * * @param attrs attributes of the XML tag that is inflating the view */ private void initButtonColorRipple(TypedArray attrs) { int index = R.styleable.ActionButton_button_colorRipple; if (attrs.hasValue(index)) { buttonColorRipple = attrs.getColor(index, buttonColorRipple); LOGGER.trace("Initialized Action Button Ripple Effect color: {}", getButtonColorRipple()); } } /** * Initializes the shadow radius * * @param attrs attributes of the XML tag that is inflating the view */ private void initShadowRadius(TypedArray attrs) { int index = R.styleable.ActionButton_shadow_radius; if (attrs.hasValue(index)) { shadowRadius = attrs.getDimension(index, shadowRadius); LOGGER.trace("Initialized Action Button shadow radius: {}", getShadowRadius()); } } /** * Initializes the shadow X-axis offset * * @param attrs attributes of the XML tag that is inflating the view */ private void initShadowXOffset(TypedArray attrs) { int index = R.styleable.ActionButton_shadow_xOffset; if (attrs.hasValue(index)) { shadowXOffset = attrs.getDimension(index, shadowXOffset); LOGGER.trace("Initialized Action Button X-axis offset: {}", getShadowXOffset()); } } /** * Initializes the shadow Y-axis offset * * @param attrs attributes of the XML tag that is inflating the view */ private void initShadowYOffset(TypedArray attrs) { int index = R.styleable.ActionButton_shadow_yOffset; if (attrs.hasValue(index)) { shadowYOffset = attrs.getDimension(index, shadowYOffset); LOGGER.trace("Initialized Action Button shadow Y-axis offset: {}", getShadowYOffset()); } } /** * Initializes the shadow color * * @param attrs attributes of the XML tag that is inflating the view */ private void initShadowColor(TypedArray attrs) { int index = R.styleable.ActionButton_shadow_color; if (attrs.hasValue(index)) { shadowColor = attrs.getColor(index, shadowColor); LOGGER.trace("Initialized Action Button shadow color: {}", getShadowColor()); } } /** * Initializes the Shadow Responsive Effect * * @param attrs attributes of the XML tag that is inflating the view */ private void initShadowResponsiveEffectEnabled(TypedArray attrs) { int index = R.styleable.ActionButton_shadowResponsiveEffect_enabled; if (attrs.hasValue(index)) { shadowResponsiveEffectEnabled = attrs.getBoolean(index, shadowResponsiveEffectEnabled); LOGGER.trace("Initialized Action Button Shadow Responsive Effect enabled: {}", isShadowResponsiveEffectEnabled()); } } /** * Initializes the stroke width * * @param attrs attributes of the XML tag that is inflating the view */ private void initStrokeWidth(TypedArray attrs) { int index = R.styleable.ActionButton_stroke_width; if (attrs.hasValue(index)) { strokeWidth = attrs.getDimension(index, strokeWidth); LOGGER.trace("Initialized Action Button stroke width: {}", getStrokeWidth()); } } /** * Initializes the stroke color * * @param attrs attributes of the XML tag that is inflating the view */ private void initStrokeColor(TypedArray attrs) { int index = R.styleable.ActionButton_stroke_color; if (attrs.hasValue(index)) { strokeColor = attrs.getColor(index, strokeColor); LOGGER.trace("Initialized Action Button stroke color: {}", getStrokeColor()); } } /** * Initializes the animation, which is used while showing * <b>Action Button</b> * * @param attrs attributes of the XML tag that is inflating the view */ private void initShowAnimation(TypedArray attrs) { int index = R.styleable.ActionButton_show_animation; if (attrs.hasValue(index)) { int animResId = attrs.getResourceId(index, Animations.NONE.animResId); showAnimation = Animations.load(getContext(), animResId); LOGGER.trace("Initialized Action Button show animation"); } } /** * Initializes the animation, which is used while hiding or dismissing * <b>Action Button</b> * * @param attrs attributes of the XML tag that is inflating the view */ private void initHideAnimation(TypedArray attrs) { int index = R.styleable.ActionButton_hide_animation; if (attrs.hasValue(index)) { int animResId = attrs.getResourceId(index, Animations.NONE.animResId); hideAnimation = Animations.load(getContext(), animResId); LOGGER.trace("Initialized Action Button hide animation"); } } /** * Initializes the image inside <b>Action Button</b> * * @param attrs attributes of the XML tag that is inflating the view */ private void initImage(TypedArray attrs) { int index = R.styleable.ActionButton_image; if (attrs.hasValue(index)) { image = attrs.getDrawable(index); LOGGER.trace("Initialized Action Button image"); } } /** * Initializes the image size inside <b>Action Button</b> * <p> * Changing the default size of the image breaks the rules of * <a href="http://www.google.com/design/spec/components/buttons.html">Material Design</a> * * @param attrs attributes of the XML tag that is inflating the view */ private void initImageSize(TypedArray attrs) { int index = R.styleable.ActionButton_image_size; if (attrs.hasValue(index)) { imageSize = attrs.getDimension(index, imageSize); LOGGER.trace("Initialized Action Button image size: {}", getImageSize()); } } /** * Plays the {@link #showAnimation} if set */ public void playShowAnimation() { startAnimation(getShowAnimation()); } /** * Plays the {@link #hideAnimation} if set */ public void playHideAnimation() { startAnimation(getHideAnimation()); } /** * Makes the <b>Action Button</b> to appear if it is hidden and * sets its visibility to {@link #VISIBLE} * <p> * {@link #showAnimation} is played if set */ public void show() { if (isHidden()) { playShowAnimation(); setVisibility(VISIBLE); LOGGER.trace("Shown the Action Button"); } } /** * Makes the <b>Action Button</b> to disappear if it is showing and * sets its visibility to {@link #INVISIBLE} * <p> * {@link #hideAnimation} is played if set */ public void hide() { if (!isHidden() && !isDismissed()) { playHideAnimation(); setVisibility(INVISIBLE); LOGGER.trace("Hidden the Action Button"); } } /** * Completely dismisses the <b>Action Button</b>, * sets its visibility to {@link #GONE} and removes it from the parent view * <p> * After calling this method any calls to {@link #show()} won't result in showing * the <b>Action Button</b> so far as it is removed from the parent View * <p> * {@link #hideAnimation} is played if set */ public void dismiss() { if (!isDismissed()) { if (!isHidden()) { playHideAnimation(); } setVisibility(GONE); ViewGroup parent = (ViewGroup) getParent(); parent.removeView(this); LOGGER.trace("Dismissed the Action Button"); } } /** * Checks whether <b>Action Button</b> is hidden * * @return true if <b>Action Button</b> is hidden, otherwise false */ public boolean isHidden() { return getVisibility() == INVISIBLE; } /** * Checks whether <b>Action Button</b> is dismissed * * @return true if <b>Action Button</b> is dismissed, otherwise false */ public boolean isDismissed() { return getParent() == null; } /** * Moves the <b>Action Button</b> to a specified position defined in moving * parameters * * @param params moving parameters, which contain the desired position to move */ public void move(MovingParams params) { LOGGER.trace("About to move the Action Button: X-axis delta = {}, Y-axis delta = {}", params.getXAxisDelta(), params.getYAxisDelta()); mover.move(params); } /** * Moves the <b>Action Button</b> right to a specified distance * * @param distance distance specified in density-independent pixels to move * the <b>Action Button</b> right */ public void moveRight(float distance) { final MovingParams params = new MovingParams(getContext(), distance, 0); move(params); } /** * Moves the <b>Action Button</b> down to a specified distance * * @param distance distance specified in density-independent pixels * to move the <b>Action Button</b> down */ public void moveDown(float distance) { final MovingParams params = new MovingParams(getContext(), 0, distance); move(params); } /** * Moves the <b>Action Button</b> left to a specified distance * * @param distance distance specified in density-independent pixels * to move the <b>Action Button</b> left */ public void moveLeft(float distance) { final MovingParams params = new MovingParams(getContext(), -distance, 0); move(params); } /** * Moves the <b>Action Button</b> up to a specified distance * * @param distance distance specified in density-independent pixels * to move the <b>Action Button</b> up */ public void moveUp(float distance) { final MovingParams params = new MovingParams(getContext(), 0, -distance); move(params); } /** * Returns the type of the <b>Action Button</b> * * @return type of the <b>Action Button</b> */ public Type getType() { return type; } /** * Sets the <b>Action Button</b> {@link com.software.shell.fab.ActionButton.Type} * and calls {@link #setSize(float)} to set the size depending on {@link #type} set * * @param type type of the <b>Action Button</b> */ public void setType(Type type) { this.type = type; LOGGER.trace("Changed the Action Button type to: {}", getType()); setSize(getType().getSize()); } /** * Returns the size of the <b>Action Button</b> in actual pixels (px). * Size of the <b>Action Button</b> is the diameter of the main circle * * @deprecated since version <b>1.1.0</b>. Please use {@link #getSize()} instead * * @return size of the <b>Action Button</b> in actual pixels (px) */ @Deprecated public int getButtonSize() { return (int) getSize(); } /** * Returns the size of the <b>Action Button</b> in actual pixels (px). * Size of the <b>Action Button</b> is the diameter of the main circle * * @return size of the <b>Action Button</b> in actual pixels (px) */ public float getSize() { return size; } /** * Sets the <b>Action Button</b> size and invalidates the layout of the view * <p> * Changing the default size of the button breaks the rules of * <a href="http://www.google.com/design/spec/components/buttons.html">Material Design</a>* * <p> * Setting the button size explicitly means, that button types with its default sizes are * completely ignored. Do not use this method, unless you know what you are doing * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px) * * @param size size of the button specified in density-independent * (dp) pixels */ public void setSize(float size) { this.size = dpToPx(size); requestLayout(); LOGGER.trace("Set the Action Button size to: {}", getSize()); } /** * Returns the current state of the <b>Action Button</b> * * @return current state of the <b>Action Button</b> */ public State getState() { return state; } /** * Sets the current state of the <b>Action Button</b> and * invalidates the view * * @param state new state of the <b>Action Button</b> */ public void setState(State state) { this.state = state; invalidate(); LOGGER.trace("Changed the Action Button state to: {}", getState()); } /** * Returns the <b>Action Button</b> color when in * {@link State#NORMAL} state * * @return <b>Action Button</b> color when in * {@link State#NORMAL} state */ public int getButtonColor() { return buttonColor; } /** * Sets the <b>Action Button</b> color when in * {@link State#NORMAL} state and invalidates the view * * @param buttonColor <b>Action Button</b> color * when in {@link State#NORMAL} state */ public void setButtonColor(int buttonColor) { this.buttonColor = buttonColor; invalidate(); LOGGER.trace("Changed the Action Button color to: {}", getButtonColor()); } /** * Returns the <b>Action Button</b> color when in * {@link State#PRESSED} state * * @return <b>Action Button</b> color when in * {@link State#PRESSED} state */ public int getButtonColorPressed() { return buttonColorPressed; } /** * Sets the <b>Action Button</b> color when in * {@link State#PRESSED} state and invalidates the view * * @param buttonColorPressed <b>Action Button</b> color * when in {@link State#PRESSED} state */ public void setButtonColorPressed(int buttonColorPressed) { this.buttonColorPressed = buttonColorPressed; setButtonColorRipple(darkenButtonColorPressed()); LOGGER.trace("Changed the Action Button color pressed to: {}", getButtonColorPressed()); } /** * Darkens the {@link #buttonColorPressed} using the darkening factor * * @return darker color variant of {@link #buttonColorPressed} */ private int darkenButtonColorPressed() { float darkenFactor = 0.8f; return ColorModifier.modifyExposure(getButtonColorPressed(), darkenFactor); } /** * Checks whether <b>Action Button</b> Ripple Effect enabled * * @return true, if Ripple Effect enabled, otherwise false */ public boolean isRippleEffectEnabled() { return rippleEffectEnabled; } /** * Toggles the Ripple Effect state * * @param enabled true if Ripple Effect needs to be enabled, otherwise false */ public void setRippleEffectEnabled(boolean enabled) { this.rippleEffectEnabled = enabled; LOGGER.trace("{} the Action Button Ripple Effect", isRippleEffectEnabled() ? "Enabled" : "Disabled"); } /** * Returns the <b>Action Button</b> Ripple Effect color * * @return <b>Action Button</b> Ripple Effect color */ public int getButtonColorRipple() { return buttonColorRipple; } /** * Sets the <b>Action Button</b> ripple effect color * * @param buttonColorRipple <b>Action Button</b> ripple effect color */ public void setButtonColorRipple(int buttonColorRipple) { this.buttonColorRipple = buttonColorRipple; LOGGER.trace("Action Button Ripple Effect color changed to: {}", getButtonColorRipple()); } /** * Checks whether <b>Action Button</b> has shadow by determining shadow radius * <p> * Shadow is disabled if elevation is set * * @return true if <b>Action Button</b> has radius, otherwise false */ public boolean hasShadow() { return !hasElevation() && getShadowRadius() > 0.0f; } /** * Returns the <b>Action Button</b> shadow radius in actual * pixels (px) * * @return <b>Action Button</b> shadow radius in actual pixels (px) */ public float getShadowRadius() { return shadowRadius; } /** * Sets the <b>Action Button</b> shadow radius and * invalidates the layout of the view * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px). If shadow radius is set to 0, * shadow is removed * <p> * Additionally sets the {@link #shadowResponsiveDrawer} current radius * in case if Shadow Responsive Effect enabled * * @param shadowRadius shadow radius specified in density-independent * (dp) pixels */ public void setShadowRadius(float shadowRadius) { this.shadowRadius = dpToPx(shadowRadius); if (isShadowResponsiveEffectEnabled()) { ((ShadowResponsiveDrawer) shadowResponsiveDrawer).setCurrentShadowRadius(getShadowRadius()); } requestLayout(); LOGGER.trace("Action Button shadow radius changed to: {}", getShadowRadius()); } /** * Removes the <b>Action Button</b> shadow by setting its radius to 0 */ public void removeShadow() { if (hasShadow()) { setShadowRadius(0.0f); } } /** * Returns the <b>Action Button</b> shadow X-axis offset * in actual pixels (px) * <p> * If X-axis offset is greater than 0 shadow is shifted right. * If X-axis offset is lesser than 0 shadow is shifted left. * 0 X-axis offset means that shadow is not X-axis shifted at all * * @return <b>Action Button</b> shadow X-axis offset * in actual pixels (px) */ public float getShadowXOffset() { return shadowXOffset; } /** * Sets the <b>Action Button</b> shadow X-axis offset and * invalidates the layout of the view * <p> * If X-axis offset is greater than 0 shadow is shifted right. * If X-axis offset is lesser than 0 shadow is shifted left. * 0 X-axis offset means that shadow is not shifted at all * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px) * * @param shadowXOffset shadow X-axis offset specified in density-independent * (dp) pixels */ public void setShadowXOffset(float shadowXOffset) { this.shadowXOffset = dpToPx(shadowXOffset); requestLayout(); LOGGER.trace("Changed the Action Button shadow X offset to: {}", getShadowXOffset()); } /** * Returns the <b>Action Button</b> shadow Y-axis offset * in actual pixels (px) * <p> * If Y-axis offset is greater than 0 shadow is shifted down. * If Y-axis offset is lesser than 0 shadow is shifted up. * 0 Y-axis offset means that shadow is not Y-axis shifted at all * * @return <b>Action Button</b> shadow Y-axis offset * in actual pixels (px) */ public float getShadowYOffset() { return shadowYOffset; } /** * Sets the <b>Action Button</b> shadow Y-axis offset and * invalidates the layout of the view * <p> * If Y-axis offset is greater than 0 shadow is shifted down. * If Y-axis offset is lesser than 0 shadow is shifted up. * 0 Y-axis offset means that shadow is not Y-axis shifted at all * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px) * * @param shadowYOffset shadow Y-axis offset specified in density-independent * (dp) pixels */ public void setShadowYOffset(float shadowYOffset) { this.shadowYOffset = dpToPx(shadowYOffset); requestLayout(); LOGGER.trace("Changed the Action Button shadow Y offset to: {}", getShadowYOffset()); } /** * Returns <b>Action Button</b> shadow color * * @return <b>Action Button</b> shadow color */ public int getShadowColor() { return shadowColor; } /** * Sets the <b>Action Button</b> shadow color and * invalidates the view * * @param shadowColor <b>Action Button</b> color */ public void setShadowColor(int shadowColor) { this.shadowColor = shadowColor; invalidate(); LOGGER.trace("Changed the Action Button shadow color to: {}", getShadowColor()); } /** * Checks whether Shadow Responsive Effect enabled * <p> * Shadow Responsive Effect means that shadow is enlarged up to the certain limits * while in the {@link com.software.shell.fab.ActionButton.State#PRESSED} state * * @return true if <b>Action Button</b> Shadow Responsive Effect enabled, otherwise false */ public boolean isShadowResponsiveEffectEnabled() { return shadowResponsiveEffectEnabled; } /** * Toggles the Shadow Responsive Effect * <p> * Shadow Responsive Effect means that shadow is enlarged up to the certain limits * while in the {@link com.software.shell.fab.ActionButton.State#PRESSED} state * * @param shadowResponsiveEffectEnabled true if Shadow Responsive Effect must be * enabled, otherwise false */ public void setShadowResponsiveEffectEnabled(boolean shadowResponsiveEffectEnabled) { this.shadowResponsiveEffectEnabled = shadowResponsiveEffectEnabled; requestLayout(); LOGGER.trace("{} the Shadow Responsive Effect", isShadowResponsiveEffectEnabled() ? "Enabled" : "Disabled"); } /** * Returns the <b>Action Button</b> stroke width in actual * pixels (px) * * @return <b>Action Button</b> stroke width in actual * pixels (px) */ public float getStrokeWidth() { return strokeWidth; } /** * Checks whether <b>Action Button</b> has stroke by checking * stroke width * * @return true if <b>Action Button</b> has stroke, otherwise false */ public boolean hasStroke() { return getStrokeWidth() > 0.0f; } /** * Sets the <b>Action Button</b> stroke width and * invalidates the layout of the view * <p> * Stroke width value must be greater than 0. If stroke width is * set to 0 stroke is removed * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px) * * @param strokeWidth stroke width specified in density-independent * (dp) pixels */ public void setStrokeWidth(float strokeWidth) { this.strokeWidth = dpToPx(strokeWidth); requestLayout(); LOGGER.trace("Changed the stroke width to: {}", getStrokeWidth()); } /** * Removes the <b>Action Button</b> stroke by setting its width to 0 */ public void removeStroke() { if (hasStroke()) { setStrokeWidth(0.0f); } } /** * Returns the <b>Action Button</b> stroke color * * @return <b>Action Button</b> stroke color */ public int getStrokeColor() { return strokeColor; } /** * Sets the <b>Action Button</b> stroke color and * invalidates the view * * @param strokeColor <b>Action Button</b> stroke color */ public void setStrokeColor(int strokeColor) { this.strokeColor = strokeColor; invalidate(); LOGGER.trace("Changed the stroke color to: {}", getStrokeColor()); } /** * Returns the <b>Action Button</b> image drawable centered * inside the view * * @return <b>Action Button</b> image drawable centered * inside the view */ public Drawable getImage() { return image; } /** * Checks whether <b>Action Button</b> has an image centered * inside the view * * @return true if <b>Action Button</b> has an image centered * inside the view, otherwise false */ public boolean hasImage() { return getImage() != null; } /** * Places the image drawable centered inside the view and * invalidates the view * <p> * Size of the image while drawing is fit to {@link #imageSize} * * @param image image drawable, which will be placed centered * inside the view */ public void setImageDrawable(Drawable image) { this.image = image; invalidate(); LOGGER.trace("Set the Action Button image drawable"); } /** * Resolves the drawable resource id and places the resolved image drawable * centered inside the view * * @param resId drawable resource id, which is to be resolved to * image drawable and used as parameter when calling * {@link #setImageDrawable(android.graphics.drawable.Drawable)} */ public void setImageResource(int resId) { setImageDrawable(getResources().getDrawable(resId)); } /** * Creates the {@link android.graphics.drawable.BitmapDrawable} from the given * {@link android.graphics.Bitmap} and places it centered inside the view * * @param bitmap bitmap, from which {@link android.graphics.drawable.BitmapDrawable} * is created and used as parameter when calling * {@link #setImageDrawable(android.graphics.drawable.Drawable)} */ public void setImageBitmap(Bitmap bitmap) { setImageDrawable(new BitmapDrawable(getResources(), bitmap)); } /** * Removes the <b>Action Button</b> image by setting its value to null */ public void removeImage() { if (hasImage()) { setImageDrawable(null); } } /** * Returns the <b>Action Button</b> image size in actual pixels (px). * If <b>Action Button</b> image is not set returns 0 * * @return <b>Action Button</b> image size in actual pixels (px), * 0 if image is not set */ public float getImageSize() { return getImage() != null ? imageSize : 0.0f; } /** * Sets the size of the <b>Action Button</b> image * <p> * Changing the default size of the image breaks the rules of * <a href="http://www.google.com/design/spec/components/buttons.html">Material Design</a> * <p> * Must be specified in density-independent (dp) pixels, which are * then converted into actual pixels (px) * * @param size size of the <b>Action Button</b> image * specified in density-independent (dp) pixels */ public void setImageSize(float size) { this.imageSize = dpToPx(size); LOGGER.trace("Changed the Action Button image size to: {}", getImageSize()); } /** * Returns an animation, which is used while showing <b>Action Button</b> * * @return animation, which is used while showing <b>Action Button</b> */ public Animation getShowAnimation() { return showAnimation; } /** * Sets the animation, which is used while showing <b>Action Button</b> * * @param animation animation, which is to be used while showing * <b>Action Button</b> */ public void setShowAnimation(Animation animation) { this.showAnimation = animation; LOGGER.trace("Set the Action Button show animation"); } /** * Sets one of the {@link Animations} as animation, which is used while showing * <b>Action Button</b> * * @param animation one of the {@link Animations}, which is to be used while * showing <b>Action Button</b> */ public void setShowAnimation(Animations animation) { setShowAnimation(Animations.load(getContext(), animation.animResId)); } /** * Removes the animation, which is used while showing <b>Action Button</b> */ public void removeShowAnimation() { setShowAnimation(Animations.NONE); LOGGER.trace("Removed the Action Button show animation"); } /** * Returns an animation, which is used while hiding <b>Action Button</b> * * @return animation, which is used while hiding <b>Action Button</b> */ public Animation getHideAnimation() { return hideAnimation; } /** * Sets the animation, which is used while hiding <b>Action Button</b> * * @param animation animation, which is to be used while hiding * <b>Action Button</b> */ public void setHideAnimation(Animation animation) { this.hideAnimation = animation; LOGGER.trace("Set the Action Button hide animation"); } /** * Sets one of the {@link Animations} as animation, which is used while hiding * <b>Action Button</b> * * @param animation one of the {@link Animations}, which is to be used while * hiding <b>Action Button</b> */ public void setHideAnimation(Animations animation) { setHideAnimation(Animations.load(getContext(), animation.animResId)); } /** * Removes the animation, which is used while hiding <b>Action Button</b> */ public void removeHideAnimation() { setHideAnimation(Animations.NONE); LOGGER.trace("Removed the Action Button hide animation"); } /** * Returns the <b>Action Button</b> touch point * <p> * {@link TouchPoint} contains information about X- and * Y-axis touch points within the <b>Action Button</b> * * @return <b>Action Button</b> touch point */ public TouchPoint getTouchPoint() { return touchPoint; } /** * Sets the <b>Action Button</b> touch point * * @param point <b>Action Button</b> touch point */ protected void setTouchPoint(TouchPoint point) { this.touchPoint = point; } /** * Adds additional actions on motion events: * 1. Changes the <b>Action Button</b> {@link #state} to {@link State#PRESSED} * on {@link android.view.MotionEvent#ACTION_DOWN} * 2. Changes the <b>Action Button</b> {@link #state} to {@link State#NORMAL} * on {@link android.view.MotionEvent#ACTION_UP} * 3. Changes the <b>Action Button</b> {@link #state} to {@link State#NORMAL} * on {@link android.view.MotionEvent#ACTION_MOVE} in case when touch point * leaves the main circle * * @param event motion event * @return true if event was handled, otherwise false */ @SuppressWarnings("all") @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); TouchPoint point = new TouchPoint(event.getX(), event.getY()); boolean touchPointInsideCircle = point.isInsideCircle(calculateCenterX(), calculateCenterY(), calculateCircleRadius()); int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (touchPointInsideCircle) { setState(State.PRESSED); setTouchPoint(point); LOGGER.trace("Detected the ACTION_DOWN motion event"); return true; } break; case MotionEvent.ACTION_UP: if (touchPointInsideCircle) { setState(State.NORMAL); getTouchPoint().reset(); LOGGER.trace("Detected the ACTION_UP motion event"); return true; } break; case MotionEvent.ACTION_MOVE: if (!touchPointInsideCircle && getState() == State.PRESSED) { setState(State.NORMAL); getTouchPoint().reset(); LOGGER.trace("Detected the ACTION_MOVE motion event"); return true; } break; default: LOGGER.warn("Detected unrecognized motion event"); break; } return false; } /** * Adds additional checking whether animation is null before starting to play it * * @param animation animation to play */ @SuppressWarnings("all") @Override public void startAnimation(Animation animation) { if (animation != null && (getAnimation() == null || getAnimation().hasEnded())) { super.startAnimation(animation); } } /** * Returns the paint, which is used for drawing the <b>Action Button</b> elements * * return paint, which is used for drawing the <b>Action Button</b> elements */ protected Paint getPaint() { return paint; } /** * Resets the paint to its default values and sets initial flags to it * <p> * Use this method before drawing the new element of the view */ protected final void resetPaint() { getPaint().reset(); getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); LOGGER.trace("Reset the Action Button paint"); } /** * Returns the view invalidator, which is used to invalidate the * <b>Action Button</b> * * @return view invalidator, which is used to invalidate the <b>Action Button</b> */ protected ViewInvalidator getInvalidator() { return invalidator; } /** * Draws the elements of the <b>Action Button</b> * * @param canvas canvas, on which the drawing is to be performed */ @SuppressWarnings("all") @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); LOGGER.trace("Called Action Button onDraw"); drawCircle(canvas); if (isRippleEffectEnabled()) { drawRipple(canvas); } if (hasElevation()) { drawElevation(); } if (hasStroke()) { drawStroke(canvas); } if (hasImage()) { drawImage(canvas); } getInvalidator().invalidate(); } /** * Draws the main circle of the <b>Action Button</b> and calls * {@link #drawShadow()} to draw the shadow if present * * @param canvas canvas, on which circle is to be drawn */ protected void drawCircle(Canvas canvas) { resetPaint(); if (hasShadow()) { if (isShadowResponsiveEffectEnabled()) { shadowResponsiveDrawer.draw(canvas); } else { drawShadow(); } } getPaint().setStyle(Paint.Style.FILL); boolean rippleInProgress = isRippleEffectEnabled() && ((RippleEffectDrawer) rippleEffectDrawer).isDrawingInProgress(); getPaint().setColor(getState() == State.PRESSED || rippleInProgress ? getButtonColorPressed() : getButtonColor()); canvas.drawCircle(calculateCenterX(), calculateCenterY(), calculateCircleRadius(), getPaint()); LOGGER.trace("Drawn the Action Button circle"); } /** * Calculates the X-axis center coordinate of the entire view * * @return X-axis center coordinate of the entire view */ protected float calculateCenterX() { float centerX = getMeasuredWidth() / 2; LOGGER.trace("Calculated Action Button center X: {}", centerX); return centerX; } /** * Calculates the Y-axis center coordinate of the entire view * * @return Y-axis center coordinate of the entire view */ protected float calculateCenterY() { float centerY = getMeasuredHeight() / 2; LOGGER.trace("Calculated Action Button center Y: {}", centerY); return centerY; } /** * Calculates the radius of the main circle * * @return radius of the main circle */ protected final float calculateCircleRadius() { float circleRadius = getSize() / 2; LOGGER.trace("Calculated Action Button circle radius: {}", circleRadius); return circleRadius; } /** * Draws the shadow if view elevation is not enabled */ protected void drawShadow() { getPaint().setShadowLayer(getShadowRadius(), getShadowXOffset(), getShadowYOffset(), getShadowColor()); LOGGER.trace("Drawn the Action Button shadow"); } /** * Draws the Ripple Effect * * @param canvas canvas, on which ripple effect is to be drawn */ protected void drawRipple(Canvas canvas) { rippleEffectDrawer.draw(canvas); LOGGER.trace("Drawn the Action Button Ripple Effect"); } /** * Draws the elevation around the main circle * <p> * Stroke corrective is used due to ambiguity in drawing stroke in * combination with elevation enabled (for API 21 and higher only. * In such case there is no possibility to determine the accurate * <b>Action Button</b> size, so width and height must be corrected * <p> * This logic may be changed in future if the better solution is found */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) protected void drawElevation() { float halfSize = getSize() / 2; final int left = (int) (calculateCenterX() - halfSize); final int top = (int) (calculateCenterY() - halfSize); final int right = (int) (calculateCenterX() + halfSize); final int bottom = (int) (calculateCenterY() + halfSize); ViewOutlineProvider provider = new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setOval(left, top, right, bottom); } }; setOutlineProvider(provider); LOGGER.trace("Drawn the Action Button elevation"); } /** * Checks whether view elevation is enabled * * @return true if view elevation enabled, otherwise false */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean hasElevation() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && getElevation() > 0.0f; } /** * Draws stroke around the main circle * * @param canvas canvas, on which circle is to be drawn */ protected void drawStroke(Canvas canvas) { resetPaint(); getPaint().setStyle(Paint.Style.STROKE); getPaint().setStrokeWidth(getStrokeWidth()); getPaint().setColor(getStrokeColor()); canvas.drawCircle(calculateCenterX(), calculateCenterY(), calculateCircleRadius(), getPaint()); LOGGER.trace("Drawn the Action Button stroke"); } /** * Draws the image centered inside the view * * @param canvas canvas, on which circle is to be drawn */ protected void drawImage(Canvas canvas) { int startPointX = (int) (calculateCenterX() - getImageSize() / 2); int startPointY = (int) (calculateCenterY() - getImageSize() / 2); int endPointX = (int) (startPointX + getImageSize()); int endPointY = (int) (startPointY + getImageSize()); getImage().setBounds(startPointX, startPointY, endPointX, endPointY); getImage().draw(canvas); LOGGER.trace("Drawn the Action Button image on canvas with coordinates: X start point = {}, " + "Y start point = {}, X end point = {}, Y end point = {}", startPointX, startPointY, endPointX, endPointY); } /** * Sets the measured dimension for the entire view * * @param widthMeasureSpec horizontal space requirements as imposed by the parent. * The requirements are encoded with * {@link android.view.View.MeasureSpec} * @param heightMeasureSpec vertical space requirements as imposed by the parent. * The requirements are encoded with * {@link android.view.View.MeasureSpec} */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOGGER.trace("Called Action Button onMeasure"); setMeasuredDimension(calculateMeasuredWidth(), calculateMeasuredHeight()); LOGGER.trace("Measured the Action Button size: height = {}, width = {}", getHeight(), getWidth()); } /** * Calculates the measured width in actual pixels for the entire view * * @return measured width in actual pixels for the entire view */ private int calculateMeasuredWidth() { int measuredWidth = (int) (getSize() + calculateShadowWidth() + calculateStrokeWeight()); LOGGER.trace("Calculated Action Button measured width: {}", measuredWidth); return measuredWidth; } /** * Calculates the measured height in actual pixels for the entire view * * @return measured width in actual pixels for the entire view */ private int calculateMeasuredHeight() { int measuredHeight = (int) (getSize() + calculateShadowHeight() + calculateStrokeWeight()); LOGGER.trace("Calculated Action Button measured height: {}", measuredHeight); return measuredHeight; } /** * Calculates shadow width in actual pixels * * @return shadow width in actual pixels */ private int calculateShadowWidth() { float mShadowRadius = isShadowResponsiveEffectEnabled() ? ((ShadowResponsiveDrawer) shadowResponsiveDrawer).getMaxShadowRadius() : getShadowRadius(); int shadowWidth = hasShadow() ? (int) ((mShadowRadius + Math.abs(getShadowXOffset())) * 2) : 0; LOGGER.trace("Calculated Action Button shadow width: {}", shadowWidth); return shadowWidth; } /** * Calculates shadow height in actual pixels * * @return shadow height in actual pixels */ private int calculateShadowHeight() { float mShadowRadius = isShadowResponsiveEffectEnabled() ? ((ShadowResponsiveDrawer) shadowResponsiveDrawer).getMaxShadowRadius() : getShadowRadius(); int shadowHeight = hasShadow() ? (int) ((mShadowRadius + Math.abs(getShadowYOffset())) * 2) : 0; LOGGER.trace("Calculated Action Button shadow height: {}", shadowHeight); return shadowHeight; } /** * Calculates the stroke weight in actual pixels * * * @return stroke weight in actual pixels */ private int calculateStrokeWeight() { int strokeWeight = (int) (getStrokeWidth() * 2.0f); LOGGER.trace("Calculated Action Button stroke width: {}", strokeWidth); return strokeWeight; } /** * Converts the density-independent value into density-dependent one * * @param dp density-independent value * @return density-dependent value */ protected float dpToPx(float dp) { return DensityConverter.dpToPx(getContext(), dp); } /** * Determines the <b>Action Button</b> types */ public enum Type { /** * <b>Action Button</b> default (56dp) type */ DEFAULT { @Override int getId() { return 0; } @Override float getSize() { return 56.0f; } }, /** * <b>Action Button</b> mini (40dp) type */ MINI { @Override int getId() { return 1; } @Override float getSize() { return 40.0f; } }, /** * <b>Action Button</b> big (72dp) type */ BIG { @Override int getId() { return 2; } @Override float getSize() { return 72.0f; } }; /** * Returns an {@code id} for specific <b>Action Button</b> * type, which is defined in attributes * * @return {@code id} for particular <b>Action Button</b> type, * which is defined in attributes */ abstract int getId(); /** * Returns the size of the specific type of the <b>Action Button</b> * in density-independent pixels, which then must be converted into * real pixels * * @return size of the particular type of the <b>Action Button</b> */ abstract float getSize(); /** * Returns the <b>Action Button</b> type for a specific {@code id} * * @param id an {@code id}, for which <b>Action Button</b> type required * @return <b>Action Button</b> type */ static Type forId(int id) { for (Type type : values()) { if (type.getId() == id) { return type; } } return DEFAULT; } } /** * Determines the <b>Action Button</b> states */ public enum State { /** * <b>Action Button</b> normal state */ NORMAL, /** * <b>Action Button</b> pressed state */ PRESSED } /** * Determines the <b>Action Button</b> animations */ public enum Animations { /** * None. Animation absent */ NONE (IdGenerator.next()), /** * Fade in animation */ FADE_IN (R.anim.fab_fade_in), /** * Fade out animation */ FADE_OUT (R.anim.fab_fade_out), /** * Scale up animation */ SCALE_UP (R.anim.fab_scale_up), /** * Scale down animation */ SCALE_DOWN (R.anim.fab_scale_down), /** * Roll from down animation */ ROLL_FROM_DOWN (R.anim.fab_roll_from_down), /** * Roll to down animation */ ROLL_TO_DOWN (R.anim.fab_roll_to_down), /** * Roll from right animation */ ROLL_FROM_RIGHT (R.anim.fab_roll_from_right), /** * Roll to right animation */ ROLL_TO_RIGHT (R.anim.fab_roll_to_right), /** * Jump from down animation */ JUMP_FROM_DOWN (R.anim.fab_jump_from_down), /** * Jump to down animation */ JUMP_TO_DOWN (R.anim.fab_jump_to_down), /** * Jump from right animation */ JUMP_FROM_RIGHT (R.anim.fab_jump_from_right), /** * Jump to right animation */ JUMP_TO_RIGHT (R.anim.fab_jump_to_right); /** * Correspondent animation resource id */ final int animResId; Animations(int animResId) { this.animResId = animResId; } /** * Loads an animation from animation resource id * * @param context context the view is running in * @param animResId resource id of the animation, which is to be loaded * @return loaded animation */ protected static Animation load(Context context, int animResId) { return animResId == NONE.animResId ? null : AnimationUtils.loadAnimation(context, animResId); } } }
apache-2.0
sflyphotobooks/crp-batik
sources/org/apache/batik/svggen/font/table/Table.java
7207
/* 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.batik.svggen.font.table; /** * @version $Id: Table.java 478176 2006-11-22 14:50:50Z dvholten $ * @author <a href="mailto:david@steadystate.co.uk">David Schweinsberg</a> */ public interface Table { // Table constants int BASE = 0x42415345; // Baseline data [OpenType] int CFF = 0x43464620; // PostScript font program (compact font format) [PostScript] int DSIG = 0x44534947; // Digital signature int EBDT = 0x45424454; // Embedded bitmap data int EBLC = 0x45424c43; // Embedded bitmap location data int EBSC = 0x45425343; // Embedded bitmap scaling data int GDEF = 0x47444546; // Glyph definition data [OpenType] int GPOS = 0x47504f53; // Glyph positioning data [OpenType] int GSUB = 0x47535542; // Glyph substitution data [OpenType] int JSTF = 0x4a535446; // Justification data [OpenType] int LTSH = 0x4c545348; // Linear threshold table int MMFX = 0x4d4d4658; // Multiple master font metrics [PostScript] int MMSD = 0x4d4d5344; // Multiple master supplementary data [PostScript] int OS_2 = 0x4f532f32; // OS/2 and Windows specific metrics [r] int PCLT = 0x50434c54; // PCL5 int VDMX = 0x56444d58; // Vertical Device Metrics table int cmap = 0x636d6170; // character to glyph mapping [r] int cvt = 0x63767420; // Control Value Table int fpgm = 0x6670676d; // font program int fvar = 0x66766172; // Apple's font variations table [PostScript] int gasp = 0x67617370; // grid-fitting and scan conversion procedure (grayscale) int glyf = 0x676c7966; // glyph data [r] int hdmx = 0x68646d78; // horizontal device metrics int head = 0x68656164; // font header [r] int hhea = 0x68686561; // horizontal header [r] int hmtx = 0x686d7478; // horizontal metrics [r] int kern = 0x6b65726e; // kerning int loca = 0x6c6f6361; // index to location [r] int maxp = 0x6d617870; // maximum profile [r] int name = 0x6e616d65; // naming table [r] int prep = 0x70726570; // CVT Program int post = 0x706f7374; // PostScript information [r] int vhea = 0x76686561; // Vertical Metrics header int vmtx = 0x766d7478; // Vertical Metrics // Platform IDs short platformAppleUnicode = 0; short platformMacintosh = 1; short platformISO = 2; short platformMicrosoft = 3; // Microsoft Encoding IDs short encodingUndefined = 0; short encodingUGL = 1; // Macintosh Encoding IDs short encodingRoman = 0; short encodingJapanese = 1; short encodingChinese = 2; short encodingKorean = 3; short encodingArabic = 4; short encodingHebrew = 5; short encodingGreek = 6; short encodingRussian = 7; short encodingRSymbol = 8; short encodingDevanagari = 9; short encodingGurmukhi = 10; short encodingGujarati = 11; short encodingOriya = 12; short encodingBengali = 13; short encodingTamil = 14; short encodingTelugu = 15; short encodingKannada = 16; short encodingMalayalam = 17; short encodingSinhalese = 18; short encodingBurmese = 19; short encodingKhmer = 20; short encodingThai = 21; short encodingLaotian = 22; short encodingGeorgian = 23; short encodingArmenian = 24; short encodingMaldivian = 25; short encodingTibetan = 26; short encodingMongolian = 27; short encodingGeez = 28; short encodingSlavic = 29; short encodingVietnamese = 30; short encodingSindhi = 31; short encodingUninterp = 32; // ISO Encoding IDs short encodingASCII = 0; short encodingISO10646 = 1; short encodingISO8859_1 = 2; // Microsoft Language IDs short languageSQI = 0x041c; short languageEUQ = 0x042d; short languageBEL = 0x0423; short languageBGR = 0x0402; short languageCAT = 0x0403; short languageSHL = 0x041a; short languageCSY = 0x0405; short languageDAN = 0x0406; short languageNLD = 0x0413; short languageNLB = 0x0813; short languageENU = 0x0409; short languageENG = 0x0809; short languageENA = 0x0c09; short languageENC = 0x1009; short languageENZ = 0x1409; short languageENI = 0x1809; short languageETI = 0x0425; short languageFIN = 0x040b; short languageFRA = 0x040c; short languageFRB = 0x080c; short languageFRC = 0x0c0c; short languageFRS = 0x100c; short languageFRL = 0x140c; short languageDEU = 0x0407; short languageDES = 0x0807; short languageDEA = 0x0c07; short languageDEL = 0x1007; short languageDEC = 0x1407; short languageELL = 0x0408; short languageHUN = 0x040e; short languageISL = 0x040f; short languageITA = 0x0410; short languageITS = 0x0810; short languageLVI = 0x0426; short languageLTH = 0x0427; short languageNOR = 0x0414; short languageNON = 0x0814; short languagePLK = 0x0415; short languagePTB = 0x0416; short languagePTG = 0x0816; short languageROM = 0x0418; short languageRUS = 0x0419; short languageSKY = 0x041b; short languageSLV = 0x0424; short languageESP = 0x040a; short languageESM = 0x080a; short languageESN = 0x0c0a; short languageSVE = 0x041d; short languageTRK = 0x041f; short languageUKR = 0x0422; // Macintosh Language IDs short languageEnglish = 0; short languageFrench = 1; short languageGerman = 2; short languageItalian = 3; short languageDutch = 4; short languageSwedish = 5; short languageSpanish = 6; short languageDanish = 7; short languagePortuguese = 8; short languageNorwegian = 9; short languageHebrew = 10; short languageJapanese = 11; short languageArabic = 12; short languageFinnish = 13; short languageGreek = 14; short languageIcelandic = 15; short languageMaltese = 16; short languageTurkish = 17; short languageYugoslavian = 18; short languageChinese = 19; short languageUrdu = 20; short languageHindi = 21; short languageThai = 22; // Name IDs short nameCopyrightNotice = 0; short nameFontFamilyName = 1; short nameFontSubfamilyName = 2; short nameUniqueFontIdentifier = 3; short nameFullFontName = 4; short nameVersionString = 5; short namePostscriptName = 6; short nameTrademark = 7; /** * Get the table type, as a table directory value. * @return The table type */ int getType(); }
apache-2.0
andreagenso/java2scala
test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java
28356
/* * Copyright (c) 2000, 2007, 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 javax.imageio.stream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteOrder; import java.util.Stack; import javax.imageio.IIOException; /** * An abstract class implementing the <code>ImageInputStream</code> interface. * This class is designed to reduce the number of methods that must * be implemented by subclasses. * * <p> In particular, this class handles most or all of the details of * byte order interpretation, buffering, mark/reset, discarding, * closing, and disposing. */ public abstract class ImageInputStreamImpl implements ImageInputStream { private Stack markByteStack = new Stack(); private Stack markBitStack = new Stack(); private boolean isClosed = false; // Length of the buffer used for readFully(type[], int, int) private static final int BYTE_BUF_LENGTH = 8192; /** * Byte buffer used for readFully(type[], int, int). Note that this * array is also used for bulk reads in readShort(), readInt(), etc, so * it should be large enough to hold a primitive value (i.e. >= 8 bytes). * Also note that this array is package protected, so that it can be * used by ImageOutputStreamImpl in a similar manner. */ byte[] byteBuf = new byte[BYTE_BUF_LENGTH]; /** * The byte order of the stream as an instance of the enumeration * class <code>java.nio.ByteOrder</code>, where * <code>ByteOrder.BIG_ENDIAN</code> indicates network byte order * and <code>ByteOrder.LITTLE_ENDIAN</code> indicates the reverse * order. By default, the value is * <code>ByteOrder.BIG_ENDIAN</code>. */ protected ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; /** * The current read position within the stream. Subclasses are * responsible for keeping this value current from any method they * override that alters the read position. */ protected long streamPos; /** * The current bit offset within the stream. Subclasses are * responsible for keeping this value current from any method they * override that alters the bit offset. */ protected int bitOffset; /** * The position prior to which data may be discarded. Seeking * to a smaller position is not allowed. <code>flushedPos</code> * will always be >= 0. */ protected long flushedPos = 0; /** * Constructs an <code>ImageInputStreamImpl</code>. */ public ImageInputStreamImpl() { } /** * Throws an <code>IOException</code> if the stream has been closed. * Subclasses may call this method from any of their methods that * require the stream not to be closed. * * @exception IOException if the stream is closed. */ protected final void checkClosed() throws IOException { if (isClosed) { throw new IOException("closed"); } } public void setByteOrder(ByteOrder byteOrder) { this.byteOrder = byteOrder; } public ByteOrder getByteOrder() { return byteOrder; } /** * Reads a single byte from the stream and returns it as an * <code>int</code> between 0 and 255. If EOF is reached, * <code>-1</code> is returned. * * <p> Subclasses must provide an implementation for this method. * The subclass implementation should update the stream position * before exiting. * * <p> The bit offset within the stream must be reset to zero before * the read occurs. * * @return the value of the next byte in the stream, or <code>-1</code> * if EOF is reached. * * @exception IOException if the stream has been closed. */ public abstract int read() throws IOException; /** * A convenience method that calls <code>read(b, 0, b.length)</code>. * * <p> The bit offset within the stream is reset to zero before * the read occurs. * * @return the number of bytes actually read, or <code>-1</code> * to indicate EOF. * * @exception NullPointerException if <code>b</code> is * <code>null</code>. * @exception IOException if an I/O error occurs. */ public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Reads up to <code>len</code> bytes from the stream, and stores * them into <code>b</code> starting at index <code>off</code>. * If no bytes can be read because the end of the stream has been * reached, <code>-1</code> is returned. * * <p> The bit offset within the stream must be reset to zero before * the read occurs. * * <p> Subclasses must provide an implementation for this method. * The subclass implementation should update the stream position * before exiting. * * @param b an array of bytes to be written to. * @param off the starting position within <code>b</code> to write to. * @param len the maximum number of bytes to read. * * @return the number of bytes actually read, or <code>-1</code> * to indicate EOF. * * @exception IndexOutOfBoundsException if <code>off</code> is * negative, <code>len</code> is negative, or <code>off + * len</code> is greater than <code>b.length</code>. * @exception NullPointerException if <code>b</code> is * <code>null</code>. * @exception IOException if an I/O error occurs. */ public abstract int read(byte[] b, int off, int len) throws IOException; public void readBytes(IIOByteBuffer buf, int len) throws IOException { if (len < 0) { throw new IndexOutOfBoundsException("len < 0!"); } if (buf == null) { throw new NullPointerException("buf == null!"); } byte[] data = new byte[len]; len = read(data, 0, len); buf.setData(data); buf.setOffset(0); buf.setLength(len); } public boolean readBoolean() throws IOException { int ch = this.read(); if (ch < 0) { throw new EOFException(); } return (ch != 0); } public byte readByte() throws IOException { int ch = this.read(); if (ch < 0) { throw new EOFException(); } return (byte)ch; } public int readUnsignedByte() throws IOException { int ch = this.read(); if (ch < 0) { throw new EOFException(); } return ch; } public short readShort() throws IOException { if (read(byteBuf, 0, 2) < 0) { throw new EOFException(); } if (byteOrder == ByteOrder.BIG_ENDIAN) { return (short) (((byteBuf[0] & 0xff) << 8) | ((byteBuf[1] & 0xff) << 0)); } else { return (short) (((byteBuf[1] & 0xff) << 8) | ((byteBuf[0] & 0xff) << 0)); } } public int readUnsignedShort() throws IOException { return ((int)readShort()) & 0xffff; } public char readChar() throws IOException { return (char)readShort(); } public int readInt() throws IOException { if (read(byteBuf, 0, 4) < 0) { throw new EOFException(); } if (byteOrder == ByteOrder.BIG_ENDIAN) { return (((byteBuf[0] & 0xff) << 24) | ((byteBuf[1] & 0xff) << 16) | ((byteBuf[2] & 0xff) << 8) | ((byteBuf[3] & 0xff) << 0)); } else { return (((byteBuf[3] & 0xff) << 24) | ((byteBuf[2] & 0xff) << 16) | ((byteBuf[1] & 0xff) << 8) | ((byteBuf[0] & 0xff) << 0)); } } public long readUnsignedInt() throws IOException { return ((long)readInt()) & 0xffffffffL; } public long readLong() throws IOException { // REMIND: Once 6277756 is fixed, we should do a bulk read of all 8 // bytes here as we do in readShort() and readInt() for even better // performance (see 6347575 for details). int i1 = readInt(); int i2 = readInt(); if (byteOrder == ByteOrder.BIG_ENDIAN) { return ((long)i1 << 32) + (i2 & 0xFFFFFFFFL); } else { return ((long)i2 << 32) + (i1 & 0xFFFFFFFFL); } } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public String readLine() throws IOException { StringBuffer input = new StringBuffer(); int c = -1; boolean eol = false; while (!eol) { switch (c = read()) { case -1: case '\n': eol = true; break; case '\r': eol = true; long cur = getStreamPosition(); if ((read()) != '\n') { seek(cur); } break; default: input.append((char)c); break; } } if ((c == -1) && (input.length() == 0)) { return null; } return input.toString(); } public String readUTF() throws IOException { this.bitOffset = 0; // Fix 4494369: method ImageInputStreamImpl.readUTF() // does not work as specified (it should always assume // network byte order). ByteOrder oldByteOrder = getByteOrder(); setByteOrder(ByteOrder.BIG_ENDIAN); String ret; try { ret = DataInputStream.readUTF(this); } catch (IOException e) { // Restore the old byte order even if an exception occurs setByteOrder(oldByteOrder); throw e; } setByteOrder(oldByteOrder); return ret; } public void readFully(byte[] b, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > b.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > b.length!"); } while (len > 0) { int nbytes = read(b, off, len); if (nbytes == -1) { throw new EOFException(); } off += nbytes; len -= nbytes; } } public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } public void readFully(short[] s, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > s.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > s.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/2); readFully(byteBuf, 0, nelts*2); toShorts(byteBuf, s, off, nelts); off += nelts; len -= nelts; } } public void readFully(char[] c, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > c.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > c.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/2); readFully(byteBuf, 0, nelts*2); toChars(byteBuf, c, off, nelts); off += nelts; len -= nelts; } } public void readFully(int[] i, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > i.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > i.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/4); readFully(byteBuf, 0, nelts*4); toInts(byteBuf, i, off, nelts); off += nelts; len -= nelts; } } public void readFully(long[] l, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > l.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > l.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/8); readFully(byteBuf, 0, nelts*8); toLongs(byteBuf, l, off, nelts); off += nelts; len -= nelts; } } public void readFully(float[] f, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > f.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > f.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/4); readFully(byteBuf, 0, nelts*4); toFloats(byteBuf, f, off, nelts); off += nelts; len -= nelts; } } public void readFully(double[] d, int off, int len) throws IOException { // Fix 4430357 - if off + len < 0, overflow occurred if (off < 0 || len < 0 || off + len > d.length || off + len < 0) { throw new IndexOutOfBoundsException ("off < 0 || len < 0 || off + len > d.length!"); } while (len > 0) { int nelts = Math.min(len, byteBuf.length/8); readFully(byteBuf, 0, nelts*8); toDoubles(byteBuf, d, off, nelts); off += nelts; len -= nelts; } } private void toShorts(byte[] b, short[] s, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; s[off + j] = (short)((b0 << 8) | b1); boff += 2; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 1]; int b1 = b[boff] & 0xff; s[off + j] = (short)((b0 << 8) | b1); boff += 2; } } } private void toChars(byte[] b, char[] c, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; c[off + j] = (char)((b0 << 8) | b1); boff += 2; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 1]; int b1 = b[boff] & 0xff; c[off + j] = (char)((b0 << 8) | b1); boff += 2; } } } private void toInts(byte[] b, int[] i, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; int b2 = b[boff + 2] & 0xff; int b3 = b[boff + 3] & 0xff; i[off + j] = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; boff += 4; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 3]; int b1 = b[boff + 2] & 0xff; int b2 = b[boff + 1] & 0xff; int b3 = b[boff] & 0xff; i[off + j] = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; boff += 4; } } } private void toLongs(byte[] b, long[] l, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; int b2 = b[boff + 2] & 0xff; int b3 = b[boff + 3] & 0xff; int b4 = b[boff + 4]; int b5 = b[boff + 5] & 0xff; int b6 = b[boff + 6] & 0xff; int b7 = b[boff + 7] & 0xff; int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7; l[off + j] = ((long)i0 << 32) | (i1 & 0xffffffffL); boff += 8; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 7]; int b1 = b[boff + 6] & 0xff; int b2 = b[boff + 5] & 0xff; int b3 = b[boff + 4] & 0xff; int b4 = b[boff + 3]; int b5 = b[boff + 2] & 0xff; int b6 = b[boff + 1] & 0xff; int b7 = b[boff] & 0xff; int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7; l[off + j] = ((long)i0 << 32) | (i1 & 0xffffffffL); boff += 8; } } } private void toFloats(byte[] b, float[] f, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; int b2 = b[boff + 2] & 0xff; int b3 = b[boff + 3] & 0xff; int i = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; f[off + j] = Float.intBitsToFloat(i); boff += 4; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 3]; int b1 = b[boff + 2] & 0xff; int b2 = b[boff + 1] & 0xff; int b3 = b[boff + 0] & 0xff; int i = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; f[off + j] = Float.intBitsToFloat(i); boff += 4; } } } private void toDoubles(byte[] b, double[] d, int off, int len) { int boff = 0; if (byteOrder == ByteOrder.BIG_ENDIAN) { for (int j = 0; j < len; j++) { int b0 = b[boff]; int b1 = b[boff + 1] & 0xff; int b2 = b[boff + 2] & 0xff; int b3 = b[boff + 3] & 0xff; int b4 = b[boff + 4]; int b5 = b[boff + 5] & 0xff; int b6 = b[boff + 6] & 0xff; int b7 = b[boff + 7] & 0xff; int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7; long l = ((long)i0 << 32) | (i1 & 0xffffffffL); d[off + j] = Double.longBitsToDouble(l); boff += 8; } } else { for (int j = 0; j < len; j++) { int b0 = b[boff + 7]; int b1 = b[boff + 6] & 0xff; int b2 = b[boff + 5] & 0xff; int b3 = b[boff + 4] & 0xff; int b4 = b[boff + 3]; int b5 = b[boff + 2] & 0xff; int b6 = b[boff + 1] & 0xff; int b7 = b[boff] & 0xff; int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7; long l = ((long)i0 << 32) | (i1 & 0xffffffffL); d[off + j] = Double.longBitsToDouble(l); boff += 8; } } } public long getStreamPosition() throws IOException { checkClosed(); return streamPos; } public int getBitOffset() throws IOException { checkClosed(); return bitOffset; } public void setBitOffset(int bitOffset) throws IOException { checkClosed(); if (bitOffset < 0 || bitOffset > 7) { throw new IllegalArgumentException("bitOffset must be betwwen 0 and 7!"); } this.bitOffset = bitOffset; } public int readBit() throws IOException { checkClosed(); // Compute final bit offset before we call read() and seek() int newBitOffset = (this.bitOffset + 1) & 0x7; int val = read(); if (val == -1) { throw new EOFException(); } if (newBitOffset != 0) { // Move byte position back if in the middle of a byte seek(getStreamPosition() - 1); // Shift the bit to be read to the rightmost position val >>= 8 - newBitOffset; } this.bitOffset = newBitOffset; return val & 0x1; } public long readBits(int numBits) throws IOException { checkClosed(); if (numBits < 0 || numBits > 64) { throw new IllegalArgumentException(); } if (numBits == 0) { return 0L; } // Have to read additional bits on the left equal to the bit offset int bitsToRead = numBits + bitOffset; // Compute final bit offset before we call read() and seek() int newBitOffset = (this.bitOffset + numBits) & 0x7; // Read a byte at a time, accumulate long accum = 0L; while (bitsToRead > 0) { int val = read(); if (val == -1) { throw new EOFException(); } accum <<= 8; accum |= val; bitsToRead -= 8; } // Move byte position back if in the middle of a byte if (newBitOffset != 0) { seek(getStreamPosition() - 1); } this.bitOffset = newBitOffset; // Shift away unwanted bits on the right. accum >>>= (-bitsToRead); // Negative of bitsToRead == extra bits read // Mask out unwanted bits on the left accum &= (-1L >>> (64 - numBits)); return accum; } /** * Returns <code>-1L</code> to indicate that the stream has unknown * length. Subclasses must override this method to provide actual * length information. * * @return -1L to indicate unknown length. */ public long length() { return -1L; } /** * Advances the current stream position by calling * <code>seek(getStreamPosition() + n)</code>. * * <p> The bit offset is reset to zero. * * @param n the number of bytes to seek forward. * * @return an <code>int</code> representing the number of bytes * skipped. * * @exception IOException if <code>getStreamPosition</code> * throws an <code>IOException</code> when computing either * the starting or ending position. */ public int skipBytes(int n) throws IOException { long pos = getStreamPosition(); seek(pos + n); return (int)(getStreamPosition() - pos); } /** * Advances the current stream position by calling * <code>seek(getStreamPosition() + n)</code>. * * <p> The bit offset is reset to zero. * * @param n the number of bytes to seek forward. * * @return a <code>long</code> representing the number of bytes * skipped. * * @exception IOException if <code>getStreamPosition</code> * throws an <code>IOException</code> when computing either * the starting or ending position. */ public long skipBytes(long n) throws IOException { long pos = getStreamPosition(); seek(pos + n); return getStreamPosition() - pos; } public void seek(long pos) throws IOException { checkClosed(); // This test also covers pos < 0 if (pos < flushedPos) { throw new IndexOutOfBoundsException("pos < flushedPos!"); } this.streamPos = pos; this.bitOffset = 0; } /** * Pushes the current stream position onto a stack of marked * positions. */ public void mark() { try { markByteStack.push(new Long(getStreamPosition())); markBitStack.push(new Integer(getBitOffset())); } catch (IOException e) { } } /** * Resets the current stream byte and bit positions from the stack * of marked positions. * * <p> An <code>IOException</code> will be thrown if the previous * marked position lies in the discarded portion of the stream. * * @exception IOException if an I/O error occurs. */ public void reset() throws IOException { if (markByteStack.empty()) { return; } long pos = ((Long)markByteStack.pop()).longValue(); if (pos < flushedPos) { throw new IIOException ("Previous marked position has been discarded!"); } seek(pos); int offset = ((Integer)markBitStack.pop()).intValue(); setBitOffset(offset); } public void flushBefore(long pos) throws IOException { checkClosed(); if (pos < flushedPos) { throw new IndexOutOfBoundsException("pos < flushedPos!"); } if (pos > getStreamPosition()) { throw new IndexOutOfBoundsException("pos > getStreamPosition()!"); } // Invariant: flushedPos >= 0 flushedPos = pos; } public void flush() throws IOException { flushBefore(getStreamPosition()); } public long getFlushedPosition() { return flushedPos; } /** * Default implementation returns false. Subclasses should * override this if they cache data. */ public boolean isCached() { return false; } /** * Default implementation returns false. Subclasses should * override this if they cache data in main memory. */ public boolean isCachedMemory() { return false; } /** * Default implementation returns false. Subclasses should * override this if they cache data in a temporary file. */ public boolean isCachedFile() { return false; } public void close() throws IOException { checkClosed(); isClosed = true; } /** * Finalizes this object prior to garbage collection. The * <code>close</code> method is called to close any open input * source. This method should not be called from application * code. * * @exception Throwable if an error occurs during superclass * finalization. */ protected void finalize() throws Throwable { if (!isClosed) { try { close(); } catch (IOException e) { } } super.finalize(); } }
apache-2.0
mbiarnes/uberfire
uberfire-extensions/uberfire-wires/uberfire-wires-webapp/src/main/java/org/uberfire/ext/wires/client/preferences/resources/i18n/PreferencesConstants.java
3094
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.wires.client.preferences.resources.i18n; import org.jboss.errai.ui.shared.api.annotations.TranslationKey; public class PreferencesConstants { @TranslationKey(defaultValue = "") public static final String MySharedPreference_Label = "MySharedPreference.Label"; @TranslationKey(defaultValue = "") public static final String MySharedPreference_Text = "MySharedPreference.Text"; @TranslationKey(defaultValue = "") public static final String MySharedPreference_MyInnerPreference2 = "MySharedPreference.MyInnerPreference2"; @TranslationKey(defaultValue = "") public static final String MySharedPreference2_Label = "MySharedPreference2.Label"; @TranslationKey(defaultValue = "") public static final String MySharedPreference2_Text = "MySharedPreference2.Text"; @TranslationKey(defaultValue = "") public static final String MyInnerPreference_Label = "MyInnerPreference.Label"; @TranslationKey(defaultValue = "") public static final String MyInnerPreference_Text = "MyInnerPreference.Text"; @TranslationKey(defaultValue = "") public static final String MyInnerPreference2_Label = "MyInnerPreference2.Label"; @TranslationKey(defaultValue = "") public static final String MyInnerPreference2_Text = "MyInnerPreference2.Text"; @TranslationKey(defaultValue = "") public static final String MyInnerPreference2_MySharedPreference2 = "MyInnerPreference2.MySharedPreference2"; @TranslationKey(defaultValue = "") public static final String MyPreference_Label = "MyPreference.Label"; @TranslationKey(defaultValue = "") public static final String MyPreference_Text = "MyPreference.Text"; @TranslationKey(defaultValue = "") public static final String MyPreference_SendReports = "MyPreference.SendReports"; @TranslationKey(defaultValue = "") public static final String MyPreference_BackgroundColor = "MyPreference.BackgroundColor"; @TranslationKey(defaultValue = "") public static final String MyPreference_Age = "MyPreference.Age"; @TranslationKey(defaultValue = "") public static final String MyPreference_Password = "MyPreference.Password"; @TranslationKey(defaultValue = "") public static final String MyPreference_MyInnerPreference = "MyPreference.MyInnerPreference"; @TranslationKey(defaultValue = "") public static final String MyPreference_MySharedPreference = "MyPreference.MySharedPreference"; }
apache-2.0
GlenRSmith/elasticsearch
x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/Deprecation.java
5599
/* * 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; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.deprecation; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.logging.RateLimitingFilter; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.IndexScopedSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsFilter; import org.elasticsearch.env.Environment; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.script.ScriptService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xcontent.NamedXContentRegistry; import org.elasticsearch.xpack.deprecation.logging.DeprecationCacheResetAction; import org.elasticsearch.xpack.deprecation.logging.DeprecationIndexingComponent; import org.elasticsearch.xpack.deprecation.logging.DeprecationIndexingTemplateRegistry; import org.elasticsearch.xpack.deprecation.logging.RestDeprecationCacheResetAction; import org.elasticsearch.xpack.deprecation.logging.TransportDeprecationCacheResetAction; import java.util.Collection; import java.util.List; import java.util.function.Supplier; import static org.elasticsearch.xpack.deprecation.DeprecationChecks.SKIP_DEPRECATIONS_SETTING; /** * The plugin class for the Deprecation API */ public class Deprecation extends Plugin implements ActionPlugin { public static final Setting<Boolean> WRITE_DEPRECATION_LOGS_TO_INDEX = Setting.boolSetting( "cluster.deprecation_indexing.enabled", true, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final Setting<Boolean> USE_X_OPAQUE_ID_IN_FILTERING = Setting.boolSetting( "cluster.deprecation_indexing.x_opaque_id_used.enabled", true, Setting.Property.NodeScope, Setting.Property.Dynamic ); @Override public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() { return List.of( new ActionHandler<>(DeprecationInfoAction.INSTANCE, TransportDeprecationInfoAction.class), new ActionHandler<>(NodesDeprecationCheckAction.INSTANCE, TransportNodeDeprecationCheckAction.class), new ActionHandler<>(DeprecationCacheResetAction.INSTANCE, TransportDeprecationCacheResetAction.class) ); } @Override public List<RestHandler> getRestHandlers( Settings settings, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster ) { return List.of(new RestDeprecationInfoAction(), new RestDeprecationCacheResetAction()); } @Override public Collection<Object> createComponents( Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry, Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<RepositoriesService> repositoriesServiceSupplier ) { final DeprecationIndexingTemplateRegistry templateRegistry = new DeprecationIndexingTemplateRegistry( environment.settings(), clusterService, threadPool, client, xContentRegistry ); templateRegistry.initialize(); final RateLimitingFilter rateLimitingFilterForIndexing = new RateLimitingFilter(); // enable on start. rateLimitingFilterForIndexing.setUseXOpaqueId(USE_X_OPAQUE_ID_IN_FILTERING.get(environment.settings())); clusterService.getClusterSettings() .addSettingsUpdateConsumer(USE_X_OPAQUE_ID_IN_FILTERING, rateLimitingFilterForIndexing::setUseXOpaqueId); final DeprecationIndexingComponent component = DeprecationIndexingComponent.createDeprecationIndexingComponent( client, environment.settings(), rateLimitingFilterForIndexing, WRITE_DEPRECATION_LOGS_TO_INDEX.get(environment.settings()), // pass the default on startup clusterService ); return List.of(component, rateLimitingFilterForIndexing); } @Override public List<Setting<?>> getSettings() { return List.of(USE_X_OPAQUE_ID_IN_FILTERING, WRITE_DEPRECATION_LOGS_TO_INDEX, SKIP_DEPRECATIONS_SETTING); } }
apache-2.0