repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
hongyan99/chart-faces | chartfaces/src/main/java/org/javaq/chartfaces/render/tool/impl/HeaderTool.java | 3001 | package org.javaq.chartfaces.render.tool.impl;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIComponent;
import org.javaq.chartfaces.api.IChartPart;
import org.javaq.chartfaces.component.impl.UIChartBase;
import org.javaq.chartfaces.constants.EnumPart;
import org.javaq.chartfaces.constants.SVGConstants;
import org.javaq.chartfaces.document.IDataElement;
import org.javaq.chartfaces.document.IElement;
import org.javaq.chartfaces.document.impl.Element;
import org.javaq.chartfaces.render.tool.IChartToolFactory;
public class HeaderTool extends AbstractChartTool {
HeaderTool(final IChartToolFactory factory, final IChartPart part,
final Map<Object, Object> state) {
super(factory, part, state);
}
private void addAttributes(final IElement element) {
ChartToolUtil.createLayoutBox(getBoxModel(), element);
}
private String getTextanchor() {
UIComponent comp = (UIComponent) getChartPart();
return (String) comp.getAttributes().get("textanchor");
}
@Override
protected List<IDataElement> createDataElementList() {
// we don't need to have any ajax support for headers
return null;
}
@Override
protected final IElement createLayoutElement() {
UIChartBase part = (UIChartBase) getChartPart();
final Object headerObj = part.getValue();
final IElement headerOuter = Element.newInstance(SVGConstants.SVG_G_NS);
addAttributes(headerOuter);
final IElement header = Element.newInstance(SVGConstants.SVG_G_NS);
header.addProperty(SVGConstants.SVG_STYLE, getChartPart().getStyle());
header.addProperty(SVGConstants.SVG_TEXT_ANCHOR, getTextanchor());
if (headerObj == null) {
if (part.getChildCount() > 0) {
String content = part.getChildren().get(0).toString();
String innerText = ChartToolUtil.eveluateContent(content);
header.setInnerText(innerText);
}
} else {
final IElement headerTextElement = createTextElement(headerObj);
header.addChildren(headerTextElement);
}
headerOuter.addChildren(header);
return headerOuter;
}
protected IElement createTextElement(final Object headerObj) {
final IElement headerTextElement = Element.newInstance(SVGConstants.SVG_TEXT_NS);
headerTextElement.addProperty(SVGConstants.SVG_X, getViewBox()
.getWidth() / 2);
headerTextElement.addProperty(SVGConstants.SVG_Y, getViewBox()
.getHeight() / 2);
headerTextElement.setInnerText(headerObj.toString());
return headerTextElement;
}
@Override
protected ChartDocumentType getDocumentType() {
return ChartDocumentType.header;
}
@Override
protected boolean hasContainerElementForData() {
return false;
}
@Override
protected boolean isValid(final IChartPart part) {
return part.getPartType() == EnumPart.header;
}
@Override
protected void prepareData() {
// do nothing
}
@Override
protected void synchToolState(final Map<Object, Object> state) {
// do nothing
}
}
| apache-2.0 |
opensim-org/opensim-gui | Gui/opensim/modeling/src/org/opensim/modeling/SWIGTYPE_p_SimTK__VectorView_T_SimTK__UnitVecT_double_1_t_t.java | 922 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.opensim.modeling;
public class SWIGTYPE_p_SimTK__VectorView_T_SimTK__UnitVecT_double_1_t_t {
private transient long swigCPtr;
protected SWIGTYPE_p_SimTK__VectorView_T_SimTK__UnitVecT_double_1_t_t(long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_SimTK__VectorView_T_SimTK__UnitVecT_double_1_t_t() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_SimTK__VectorView_T_SimTK__UnitVecT_double_1_t_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| apache-2.0 |
spring-cloud/spring-cloud-connectors | spring-cloud-core/src/main/java/org/springframework/cloud/service/common/RedisServiceInfo.java | 656 | package org.springframework.cloud.service.common;
import org.springframework.cloud.service.UriBasedServiceInfo;
import org.springframework.cloud.service.ServiceInfo.ServiceLabel;
/**
*
* @author Ramnivas Laddad
* @author Scott Frederick
*
*/
@ServiceLabel("redis")
public class RedisServiceInfo extends UriBasedServiceInfo {
public static final String REDIS_SCHEME = "redis";
public static final String REDISS_SCHEME = "rediss";
public RedisServiceInfo(String id, String host, int port, String password) {
super(id, REDIS_SCHEME, host, port, null, password, null);
}
public RedisServiceInfo(String id, String uri) {
super(id, uri);
}
}
| apache-2.0 |
hgschmie/presto | presto-main/src/test/java/io/prestosql/execution/TestSetSessionTask.java | 7701 | /*
* 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.execution;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Catalog;
import io.prestosql.metadata.CatalogManager;
import io.prestosql.metadata.Metadata;
import io.prestosql.security.AccessControl;
import io.prestosql.security.AllowAllAccessControl;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.resourcegroups.ResourceGroupId;
import io.prestosql.spi.session.PropertyMetadata;
import io.prestosql.sql.analyzer.FeaturesConfig;
import io.prestosql.sql.planner.FunctionCallBuilder;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.FunctionCall;
import io.prestosql.sql.tree.LongLiteral;
import io.prestosql.sql.tree.Parameter;
import io.prestosql.sql.tree.QualifiedName;
import io.prestosql.sql.tree.SetSession;
import io.prestosql.sql.tree.StringLiteral;
import io.prestosql.transaction.TransactionManager;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.prestosql.SessionTestUtils.TEST_SESSION;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.spi.StandardErrorCode.INVALID_SESSION_PROPERTY;
import static io.prestosql.spi.session.PropertyMetadata.stringProperty;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.testing.TestingSession.createBogusTestingCatalog;
import static io.prestosql.transaction.InMemoryTransactionManager.createTestTransactionManager;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
public class TestSetSessionTask
{
private static final String CATALOG_NAME = "foo";
private static final String MUST_BE_POSITIVE = "property must be positive";
private final TransactionManager transactionManager;
private final AccessControl accessControl;
private final Metadata metadata;
public TestSetSessionTask()
{
CatalogManager catalogManager = new CatalogManager();
transactionManager = createTestTransactionManager(catalogManager);
accessControl = new AllowAllAccessControl();
metadata = createTestMetadataManager(transactionManager, new FeaturesConfig());
metadata.getSessionPropertyManager().addSystemSessionProperty(stringProperty(
CATALOG_NAME,
"test property",
null,
false));
Catalog bogusTestingCatalog = createBogusTestingCatalog(CATALOG_NAME);
List<PropertyMetadata<?>> sessionProperties = ImmutableList.of(
stringProperty(
"bar",
"test property",
null,
false),
new PropertyMetadata<>(
"positive_property",
"property that should be positive",
INTEGER,
Integer.class,
null,
false,
TestSetSessionTask::validatePositive,
value -> value));
metadata.getSessionPropertyManager().addConnectorSessionProperties(bogusTestingCatalog.getConnectorCatalogName(), sessionProperties);
catalogManager.registerCatalog(bogusTestingCatalog);
}
private static int validatePositive(Object value)
{
int intValue = ((Number) value).intValue();
if (intValue < 0) {
throw new PrestoException(INVALID_SESSION_PROPERTY, MUST_BE_POSITIVE);
}
return intValue;
}
private final ExecutorService executor = newCachedThreadPool(daemonThreadsNamed("stage-executor-%s"));
@AfterClass(alwaysRun = true)
public void tearDown()
{
executor.shutdownNow();
}
@Test
public void testSetSession()
{
testSetSession(new StringLiteral("baz"), "baz");
testSetSession(
new FunctionCallBuilder(metadata)
.setName(QualifiedName.of("concat"))
.addArgument(VARCHAR, new StringLiteral("ban"))
.addArgument(VARCHAR, new StringLiteral("ana"))
.build(),
"banana");
}
@Test
public void testSetSessionWithValidation()
{
testSetSessionWithValidation(new LongLiteral("0"), "0");
testSetSessionWithValidation(new LongLiteral("2"), "2");
try {
testSetSessionWithValidation(new LongLiteral("-1"), "-1");
fail();
}
catch (PrestoException e) {
assertEquals(e.getMessage(), MUST_BE_POSITIVE);
}
}
@Test
public void testSetSessionWithParameters()
{
FunctionCall functionCall = new FunctionCallBuilder(metadata)
.setName(QualifiedName.of("concat"))
.addArgument(VARCHAR, new StringLiteral("ban"))
.addArgument(VARCHAR, new Parameter(0))
.build();
testSetSessionWithParameters("bar", functionCall, "banana", ImmutableList.of(new StringLiteral("ana")));
}
private void testSetSession(Expression expression, String expectedValue)
{
testSetSessionWithParameters("bar", expression, expectedValue, emptyList());
}
private void testSetSessionWithValidation(Expression expression, String expectedValue)
{
testSetSessionWithParameters("positive_property", expression, expectedValue, emptyList());
}
private void testSetSessionWithParameters(String property, Expression expression, String expectedValue, List<Expression> parameters)
{
QualifiedName qualifiedPropName = QualifiedName.of(CATALOG_NAME, property);
QueryStateMachine stateMachine = QueryStateMachine.begin(
format("set %s = 'old_value'", qualifiedPropName),
Optional.empty(),
TEST_SESSION,
URI.create("fake://uri"),
new ResourceGroupId("test"),
false,
transactionManager,
accessControl,
executor,
metadata,
WarningCollector.NOOP);
getFutureValue(new SetSessionTask().execute(new SetSession(qualifiedPropName, expression), transactionManager, metadata, accessControl, stateMachine, parameters));
Map<String, String> sessionProperties = stateMachine.getSetSessionProperties();
assertEquals(sessionProperties, ImmutableMap.of(qualifiedPropName.toString(), expectedValue));
}
}
| apache-2.0 |
frincon/openeos | modules/org.openeos.services.ui.vaadin/src/main/java/org/openeos/services/ui/vaadin/internal/abstractform/AbstractFormVaadinTabImpl.java | 4961 | /**
* Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openeos.services.ui.vaadin.internal.abstractform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.abstractform.binding.BindingToolkit;
import org.abstractform.binding.vaadin.VaadinBindingFormInstance;
import org.abstractform.binding.vaadin.VaadinBindingFormToolkit;
import org.openeos.services.dictionary.IDictionaryService;
import org.openeos.services.ui.UIApplication;
import org.openeos.services.ui.UIBean;
import org.openeos.services.ui.form.BindingFormCapability;
import org.openeos.services.ui.form.FormRegistryService;
import org.openeos.services.ui.form.abstractform.AbstractFormBindingForm;
import org.openeos.services.ui.model.ITabDefinition;
import org.openeos.services.ui.vaadin.IVaadinContainerFactory;
import org.openeos.services.ui.vaadin.internal.AbstractVaadinTabImpl;
import org.openeos.vaadin.main.IUnoVaadinApplication;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window.Notification;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AbstractFormVaadinTabImpl extends AbstractVaadinTabImpl {
private VaadinBindingFormToolkit vaadinToolKit;
private BindingToolkit bindingToolkit;
private FormRegistryService formRegistryService;
private IDictionaryService dictionaryService;
private VaadinBindingFormInstance editForm;
private VaadinBindingFormInstance newForm;
private boolean modified = false;
public AbstractFormVaadinTabImpl(ITabDefinition tabDefinition, IVaadinContainerFactory containerFactory,
UIApplication<IUnoVaadinApplication> application, IDictionaryService dictionaryService,
VaadinBindingFormToolkit vaadinToolKit, BindingToolkit bindingToolkit, FormRegistryService formRegistryService) {
super(tabDefinition, containerFactory, application);
this.vaadinToolKit = vaadinToolKit;
this.bindingToolkit = bindingToolkit;
this.dictionaryService = dictionaryService;
this.formRegistryService = formRegistryService;
initDefaultForms();
}
private void initDefaultForms() {
editForm = getDefaultForm(BindingFormCapability.EDIT);
newForm = getDefaultForm(BindingFormCapability.NEW);
PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
modified = true;
}
};
editForm.addFieldChangeListener(listener);
newForm.addFieldChangeListener(listener);
}
private VaadinBindingFormInstance getDefaultForm(BindingFormCapability capability) {
AbstractFormBindingForm bindingEditForm = formRegistryService.getDefaultForm(
dictionaryService.getClassDefinition(getTabDefinition().getClassName()).getClassDefined(),
AbstractFormBindingForm.class, capability);
Map<String, Object> extraObjects = new HashMap<String, Object>();
extraObjects.put(UIVaadinFormToolkit.EXTRA_OBJECT_APPLICATION, getApplication());
return vaadinToolKit.buildForm(bindingEditForm.getAbstractBForm(), bindingToolkit, extraObjects);
}
@Override
protected void showEdit() {
if (getActiveObject() == null) {
List<UIBean> selectedObjects = getSelectedObjectsInList();
if (selectedObjects.size() > 0) {
this.setActiveObject(selectedObjects.get(0));
} else {
//TODO i18n
getMainContainer().getWindow().showNotification("Select an intem", "Please select an item to edit",
Notification.TYPE_HUMANIZED_MESSAGE);
showView(View.LIST);
return;
}
}
Panel panel = new Panel();
panel.setSizeFull();
panel.setStyleName("background-default");
getMainContainer().addComponent(panel);
if (getActiveObject().isNew()) {
newForm.setValue(getActiveObject());
panel.addComponent(newForm.getImplementation());
} else {
editForm.setValue(getActiveObject());
editForm.getBindingContext().updateFields();
panel.addComponent(editForm.getImplementation());
}
modified = false;
}
@Override
public boolean isModified() {
return modified;
}
@Override
public boolean validate() {
if (getActualView() == View.EDIT) {
VaadinBindingFormInstance instance;
if (getActiveObject().isNew()) {
instance = newForm;
} else {
instance = editForm;
}
instance.updateModel();
instance.refreshValidationSummary();
return instance.getErrors().size() == 0;
}
return false;
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p490/Test9813.java | 2111 | package org.gradle.test.performance.mediummonolithicjavaproject.p490;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test9813 {
Production9813 objectUnderTest = new Production9813();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
genome-vendor/libcommons-jexl2-java | src/test/java/org/apache/commons/jexl2/ForEachTest.java | 5595 | /*
* 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.commons.jexl2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Tests for the foreach statement
* @since 1.1
*/
public class ForEachTest extends JexlTestCase {
/** create a named test */
public ForEachTest(String name) {
super(name);
}
public void testForEachWithEmptyStatement() throws Exception {
Expression e = JEXL.createExpression("for(item : list) ;");
JexlContext jc = new MapContext();
Object o = e.evaluate(jc);
assertNull("Result is not null", o);
}
public void testForEachWithEmptyList() throws Exception {
Expression e = JEXL.createExpression("for(item : list) 1+1");
JexlContext jc = new MapContext();
Object o = e.evaluate(jc);
assertNull("Result is not null", o);
}
public void testForEachWithArray() throws Exception {
Expression e = JEXL.createExpression("for(item : list) item");
JexlContext jc = new MapContext();
jc.set("list", new Object[] {"Hello", "World"});
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "World", o);
}
public void testForEachWithCollection() throws Exception {
Expression e = JEXL.createExpression("for(item : list) item");
JexlContext jc = new MapContext();
jc.set("list", Arrays.asList(new Object[] {"Hello", "World"}));
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "World", o);
}
public void testForEachWithEnumeration() throws Exception {
Expression e = JEXL.createExpression("for(item : list) item");
JexlContext jc = new MapContext();
jc.set("list", new StringTokenizer("Hello,World", ","));
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "World", o);
}
public void testForEachWithIterator() throws Exception {
Expression e = JEXL.createExpression("for(item : list) item");
JexlContext jc = new MapContext();
jc.set("list", Arrays.asList(new Object[] {"Hello", "World"}).iterator());
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "World", o);
}
public void testForEachWithMap() throws Exception {
Expression e = JEXL.createExpression("for(item : list) item");
JexlContext jc = new MapContext();
Map<?, ?> map = System.getProperties();
String lastProperty = (String) new ArrayList<Object>(map.values()).get(System.getProperties().size() - 1);
jc.set("list", map);
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", lastProperty, o);
}
public void testForEachWithBlock() throws Exception {
Expression exs0 = JEXL.createExpression("for(in : list) { x = x + in; }");
Expression exs1 = JEXL.createExpression("foreach(item in list) { x = x + item; }");
Expression []exs = { exs0, exs1 };
JexlContext jc = new MapContext();
jc.set("list", new Object[] {"2", "3"});
for(int ex = 0; ex < exs.length; ++ex) {
jc.set("x", new Integer(1));
Object o = exs[ex].evaluate(jc);
assertEquals("Result is wrong", new Integer(6), o);
assertEquals("x is wrong", new Integer(6), jc.get("x"));
}
}
public void testForEachWithListExpression() throws Exception {
Expression e = JEXL.createExpression("for(item : list.keySet()) item");
JexlContext jc = new MapContext();
Map<?, ?> map = System.getProperties();
String lastKey = (String) new ArrayList<Object>(map.keySet()).get(System.getProperties().size() - 1);
jc.set("list", map);
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", lastKey, o);
}
public void testForEachWithProperty() throws Exception {
Expression e = JEXL.createExpression("for(item : list.cheeseList) item");
JexlContext jc = new MapContext();
jc.set("list", new Foo());
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "brie", o);
}
public void testForEachWithIteratorMethod() throws Exception {
Expression e = JEXL.createExpression("for(item : list.cheezy) item");
JexlContext jc = new MapContext();
jc.set("list", new Foo());
Object o = e.evaluate(jc);
assertEquals("Result is not last evaluated expression", "brie", o);
}
} | apache-2.0 |
vespa-engine/vespa | service-monitor/src/main/java/com/yahoo/vespa/service/executor/Runlet.java | 648 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.executor;
/**
* A {@code Runlet} joins {@link AutoCloseable} with {@link Runnable} with the following semantics:
*
* <ul>
* <li>The {@link #run()} method may be called any number of times, followed by a single call to {@link #close()}.
* <li>The caller must ensure the calls are ordered by {@code happens-before}, i.e. the class can be thread-unsafe.
* </ul>
*
* @author hakonhall
*/
public interface Runlet extends AutoCloseable, Runnable {
void run();
@Override
void close();
}
| apache-2.0 |
danberindei/infinispan-cachestore-jpa | src/main/java/org/infinispan/loaders/jpa/JpaCacheLoaderException.java | 596 | package org.infinispan.loaders.jpa;
import org.infinispan.loaders.CacheLoaderException;
/**
*
* @author <a href="mailto:rtsang@redhat.com">Ray Tsang</a>
*
*/
public class JpaCacheLoaderException extends CacheLoaderException {
private static final long serialVersionUID = -5941891649874210344L;
public JpaCacheLoaderException() {
super();
}
public JpaCacheLoaderException(String message, Throwable cause) {
super(message, cause);
}
public JpaCacheLoaderException(String message) {
super(message);
}
public JpaCacheLoaderException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
joewalnes/idea-community | java/java-impl/src/com/intellij/psi/impl/java/stubs/JavaAnnotationElementType.java | 3405 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.java.stubs;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LighterAST;
import com.intellij.lang.LighterASTNode;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiNameHelper;
import com.intellij.psi.impl.compiled.ClsAnnotationImpl;
import com.intellij.psi.impl.java.stubs.impl.PsiAnnotationStubImpl;
import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex;
import com.intellij.psi.impl.source.tree.LightTreeUtil;
import com.intellij.psi.impl.source.tree.java.AnnotationElement;
import com.intellij.psi.impl.source.tree.java.PsiAnnotationImpl;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/*
* @author max
*/
public class JavaAnnotationElementType extends JavaStubElementType<PsiAnnotationStub, PsiAnnotation> {
public JavaAnnotationElementType() {
super("ANNOTATION");
}
@NotNull
@Override
public ASTNode createCompositeNode() {
return new AnnotationElement();
}
public PsiAnnotation createPsi(final PsiAnnotationStub stub) {
if (isCompiled(stub)) {
return new ClsAnnotationImpl(stub);
}
else {
return new PsiAnnotationImpl(stub);
}
}
public PsiAnnotation createPsi(final ASTNode node) {
return new PsiAnnotationImpl(node);
}
public PsiAnnotationStub createStub(final PsiAnnotation psi, final StubElement parentStub) {
return new PsiAnnotationStubImpl(parentStub, psi.getText());
}
@Override
public PsiAnnotationStub createStub(final LighterAST tree, final LighterASTNode node, final StubElement parentStub) {
final String text = LightTreeUtil.toFilteredString(tree, node, null);
return new PsiAnnotationStubImpl(parentStub, text);
}
public void serialize(final PsiAnnotationStub stub, final StubOutputStream dataStream) throws IOException {
dataStream.writeUTFFast(stub.getText());
}
public PsiAnnotationStub deserialize(final StubInputStream dataStream, final StubElement parentStub) throws IOException {
return new PsiAnnotationStubImpl(parentStub, dataStream.readUTFFast());
}
public void indexStub(final PsiAnnotationStub stub, final IndexSink sink) {
final String refText = getReferenceShortName(stub.getText());
sink.occurrence(JavaAnnotationIndex.KEY, refText);
}
private static String getReferenceShortName(String annotationText) {
final int index = annotationText.indexOf('('); //to get the text of reference itself
if (index >= 0) {
return PsiNameHelper.getShortClassName(annotationText.substring(0, index));
}
return PsiNameHelper.getShortClassName(annotationText);
}
} | apache-2.0 |
ApacheInfra/incubator-datasketches-memory | src/test/java/com/yahoo/memory/MemoryTest.java | 14448 | /*
* Copyright 2017, Yahoo! Inc. Licensed under the terms of the
* Apache License 2.0. See LICENSE file at the project root for terms.
*/
package com.yahoo.memory;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
public class MemoryTest {
@BeforeClass
public void setReadOnly() {
UtilTest.setGettysburgAddressFileToReadOnly(this);
}
@Test
public void checkDirectRoundTrip() {
int n = 1024; //longs
try (WritableHandle wh = WritableMemory.allocateDirect(n * 8)) {
WritableMemory mem = wh.get();
for (int i = 0; i < n; i++) {
mem.putLong(i * 8, i);
}
for (int i = 0; i < n; i++) {
long v = mem.getLong(i * 8);
assertEquals(v, i);
}
}
}
@Test
public void checkAutoHeapRoundTrip() {
int n = 1024; //longs
WritableMemory wmem = WritableMemory.allocate(n * 8);
for (int i = 0; i < n; i++) {
wmem.putLong(i * 8, i);
}
for (int i = 0; i < n; i++) {
long v = wmem.getLong(i * 8);
assertEquals(v, i);
}
}
@Test
public void checkArrayWrap() {
int n = 1024; //longs
byte[] arr = new byte[n * 8];
WritableMemory wmem = WritableMemory.wrap(arr);
for (int i = 0; i < n; i++) {
wmem.putLong(i * 8, i);
}
for (int i = 0; i < n; i++) {
long v = wmem.getLong(i * 8);
assertEquals(v, i);
}
Memory mem = Memory.wrap(arr, ByteOrder.nativeOrder());
for (int i = 0; i < n; i++) {
long v = mem.getLong(i * 8);
assertEquals(v, i);
}
// check 0 length array wraps
Memory memZeroLengthArrayBoolean = WritableMemory.wrap(new boolean[0]);
Memory memZeroLengthArrayByte = WritableMemory.wrap(new byte[0]);
Memory memZeroLengthArrayChar = WritableMemory.wrap(new char[0]);
Memory memZeroLengthArrayShort = WritableMemory.wrap(new short[0]);
Memory memZeroLengthArrayInt = WritableMemory.wrap(new int[0]);
Memory memZeroLengthArrayLong = WritableMemory.wrap(new long[0]);
Memory memZeroLengthArrayFloat = WritableMemory.wrap(new float[0]);
Memory memZeroLengthArrayDouble = WritableMemory.wrap(new double[0]);
assertEquals(memZeroLengthArrayBoolean.getCapacity(), 0);
assertEquals(memZeroLengthArrayByte.getCapacity(), 0);
assertEquals(memZeroLengthArrayChar.getCapacity(), 0);
assertEquals(memZeroLengthArrayShort.getCapacity(), 0);
assertEquals(memZeroLengthArrayInt.getCapacity(), 0);
assertEquals(memZeroLengthArrayLong.getCapacity(), 0);
assertEquals(memZeroLengthArrayFloat.getCapacity(), 0);
assertEquals(memZeroLengthArrayDouble.getCapacity(), 0);
// check 0 length array wraps
List<Memory> memoryToCheck = Lists.newArrayList();
memoryToCheck.add(WritableMemory.allocate(0));
memoryToCheck.add(WritableMemory.wrap(ByteBuffer.allocate(0)));
memoryToCheck.add(WritableMemory.wrap(new boolean[0]));
memoryToCheck.add(WritableMemory.wrap(new byte[0]));
memoryToCheck.add(WritableMemory.wrap(new char[0]));
memoryToCheck.add(WritableMemory.wrap(new short[0]));
memoryToCheck.add(WritableMemory.wrap(new int[0]));
memoryToCheck.add(WritableMemory.wrap(new long[0]));
memoryToCheck.add(WritableMemory.wrap(new float[0]));
memoryToCheck.add(WritableMemory.wrap(new double[0]));
memoryToCheck.add(Memory.wrap(ByteBuffer.allocate(0)));
memoryToCheck.add(Memory.wrap(new boolean[0]));
memoryToCheck.add(Memory.wrap(new byte[0]));
memoryToCheck.add(Memory.wrap(new char[0]));
memoryToCheck.add(Memory.wrap(new short[0]));
memoryToCheck.add(Memory.wrap(new int[0]));
memoryToCheck.add(Memory.wrap(new long[0]));
memoryToCheck.add(Memory.wrap(new float[0]));
memoryToCheck.add(Memory.wrap(new double[0]));
//Check the Memory lengths
for (Memory memory : memoryToCheck) {
assertEquals(memory.getCapacity(), 0);
}
}
@Test
public void checkByteBufHeap() {
int n = 1024; //longs
byte[] arr = new byte[n * 8];
ByteBuffer bb = ByteBuffer.wrap(arr);
bb.order(ByteOrder.nativeOrder());
WritableMemory wmem = WritableMemory.wrap(bb);
for (int i = 0; i < n; i++) { //write to wmem
wmem.putLong(i * 8, i);
}
for (int i = 0; i < n; i++) { //read from wmem
long v = wmem.getLong(i * 8);
assertEquals(v, i);
}
for (int i = 0; i < n; i++) { //read from BB
long v = bb.getLong(i * 8);
assertEquals(v, i);
}
Memory mem1 = Memory.wrap(arr);
for (int i = 0; i < n; i++) { //read from wrapped arr
long v = mem1.getLong(i * 8);
assertEquals(v, i);
}
//convert to RO
Memory mem = wmem;
for (int i = 0; i < n; i++) {
long v = mem.getLong(i * 8);
assertEquals(v, i);
}
}
@Test
public void checkByteBufDirect() {
int n = 1024; //longs
ByteBuffer bb = ByteBuffer.allocateDirect(n * 8);
bb.order(ByteOrder.nativeOrder());
WritableMemory wmem = WritableMemory.wrap(bb);
for (int i = 0; i < n; i++) { //write to wmem
wmem.putLong(i * 8, i);
}
for (int i = 0; i < n; i++) { //read from wmem
long v = wmem.getLong(i * 8);
assertEquals(v, i);
}
for (int i = 0; i < n; i++) { //read from BB
long v = bb.getLong(i * 8);
assertEquals(v, i);
}
Memory mem1 = Memory.wrap(bb);
for (int i = 0; i < n; i++) { //read from wrapped bb RO
long v = mem1.getLong(i * 8);
assertEquals(v, i);
}
//convert to RO
Memory mem = wmem;
for (int i = 0; i < n; i++) {
long v = mem.getLong(i * 8);
assertEquals(v, i);
}
}
@Test
public void checkByteBufWrongOrder() {
int n = 1024; //longs
ByteBuffer bb = ByteBuffer.allocate(n * 8);
bb.order(ByteOrder.BIG_ENDIAN);
Memory mem = Memory.wrap(bb);
assertFalse(mem.isNativeOrder());
assertEquals(mem.getByteOrder(), ByteOrder.BIG_ENDIAN);
}
@Test
public void checkReadOnlyHeapByteBuffer() {
ByteBuffer bb = ByteBuffer.allocate(128);
bb.order(ByteOrder.nativeOrder());
for (int i = 0; i < 128; i++) { bb.put(i, (byte)i); }
bb.position(64);
ByteBuffer slice = bb.slice().asReadOnlyBuffer();
slice.order(ByteOrder.nativeOrder());
Memory mem = Memory.wrap(slice);
for (int i = 0; i < 64; i++) {
assertEquals(mem.getByte(i), 64 + i);
}
mem.toHexString("slice", 0, slice.capacity());
//println(s);
}
@Test
public void checkPutGetArraysHeap() {
int n = 1024; //longs
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = i; }
WritableMemory wmem = WritableMemory.allocate(n * 8);
wmem.putLongArray(0, arr, 0, n);
long[] arr2 = new long[n];
wmem.getLongArray(0, arr2, 0, n);
for (int i = 0; i < n; i++) {
assertEquals(arr2[i], i);
}
}
@Test
public void checkRORegions() {
int n = 16;
int n2 = n / 2;
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = i; }
Memory mem = Memory.wrap(arr);
Memory reg = mem.region(n2 * 8, n2 * 8); //top half
for (int i = 0; i < n2; i++) {
long v = reg.getLong(i * 8);
long e = i + n2;
assertEquals(v, e);
}
}
@Test
public void checkRORegionsReverseBO() {
int n = 16;
int n2 = n / 2;
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = i; }
Memory mem = Memory.wrap(arr);
Memory reg = mem.region(n2 * 8, n2 * 8, Util.nonNativeOrder); //top half
for (int i = 0; i < n2; i++) {
long v = Long.reverseBytes(reg.getLong(i * 8));
long e = i + n2;
assertEquals(v, e);
}
}
@Test
public void checkWRegions() {
int n = 16;
int n2 = n / 2;
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = i; }
WritableMemory wmem = WritableMemory.wrap(arr);
for (int i = 0; i < n; i++) {
assertEquals(wmem.getLong(i * 8), i);
//println("" + wmem.getLong(i * 8));
}
//println("");
WritableMemory reg = wmem.writableRegion(n2 * 8, n2 * 8);
for (int i = 0; i < n2; i++) { reg.putLong(i * 8, i); }
for (int i = 0; i < n; i++) {
assertEquals(wmem.getLong(i * 8), i % 8);
//println("" + wmem.getLong(i * 8));
}
}
@Test
public void checkWRegionsReverseBO() {
int n = 16;
int n2 = n / 2;
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = i; }
WritableMemory wmem = WritableMemory.wrap(arr);
for (int i = 0; i < n; i++) {
assertEquals(wmem.getLong(i * 8), i);
//println("" + wmem.getLong(i * 8));
}
//println("");
WritableMemory reg = wmem.writableRegion(n2 * 8, n2 * 8, Util.nonNativeOrder);
for (int i = 0; i < n2; i++) { reg.putLong(i * 8, i); }
for (int i = 0; i < n; i++) {
long v = wmem.getLong(i * 8);
if (i < n2) {
assertEquals(v, i % 8);
} else {
assertEquals(Long.reverseBytes(v), i % 8);
}
//println("" + wmem.getLong(i * 8));
}
}
@Test(expectedExceptions = AssertionError.class)
public void checkParentUseAfterFree() {
int bytes = 64 * 8;
@SuppressWarnings("resource") //intentionally not using try-with-resouces here
WritableHandle wh = WritableMemory.allocateDirect(bytes);
WritableMemory wmem = wh.get();
wh.close();
//with -ea assert: Memory not valid.
//with -da sometimes segfaults, sometimes passes!
wmem.getLong(0);
}
@Test(expectedExceptions = AssertionError.class)
public void checkRegionUseAfterFree() {
int bytes = 64;
@SuppressWarnings("resource") //intentionally not using try-with-resouces here
WritableHandle wh = WritableMemory.allocateDirect(bytes);
Memory wmem = wh.get();
Memory region = wmem.region(0L, bytes);
wh.close();
//with -ea assert: Memory not valid.
//with -da sometimes segfaults, sometimes passes!
region.getByte(0);
}
@Test
public void checkUnsafeByteBufferView() {
try (WritableDirectHandle wmemDirectHandle = WritableMemory.allocateDirect(2)) {
WritableMemory wmemDirect = wmemDirectHandle.get();
wmemDirect.putByte(0, (byte) 1);
wmemDirect.putByte(1, (byte) 2);
checkUnsafeByteBufferView(wmemDirect);
}
checkUnsafeByteBufferView(Memory.wrap(new byte[] {1, 2}));
try {
@SuppressWarnings("unused")
ByteBuffer unused = Memory.wrap(new int[]{1}).unsafeByteBufferView(0, 1);
Assert.fail();
} catch (UnsupportedOperationException ingore) {
// expected
}
}
private static void checkUnsafeByteBufferView(final Memory mem) {
ByteBuffer emptyByteBuffer = mem.unsafeByteBufferView(0, 0);
Assert.assertEquals(emptyByteBuffer.capacity(), 0);
ByteBuffer bb = mem.unsafeByteBufferView(1, 1);
Assert.assertTrue(bb.isReadOnly());
Assert.assertEquals(bb.capacity(), 1);
Assert.assertEquals(bb.get(), 2);
try {
@SuppressWarnings("unused")
ByteBuffer unused = mem.unsafeByteBufferView(1, 2);
Assert.fail();
} catch (IllegalArgumentException ignore) {
// expected
}
}
@SuppressWarnings("resource")
@Test
public void checkMonitorDirectStats() {
int bytes = 1024;
WritableHandle wh1 = WritableMemory.allocateDirect(bytes);
WritableHandle wh2 = WritableMemory.allocateDirect(bytes);
assertEquals(BaseState.getCurrentDirectMemoryAllocations(), 2L);
assertEquals(BaseState.getCurrentDirectMemoryAllocated(), 2 * bytes);
wh1.close();
assertEquals(BaseState.getCurrentDirectMemoryAllocations(), 1L);
assertEquals(BaseState.getCurrentDirectMemoryAllocated(), bytes);
wh2.close();
wh2.close(); //check that it doesn't go negative.
assertEquals(BaseState.getCurrentDirectMemoryAllocations(), 0L);
assertEquals(BaseState.getCurrentDirectMemoryAllocated(), 0L);
}
@SuppressWarnings("resource")
@Test
public void checkMonitorDirectMapStats() throws Exception {
File file = new File(getClass().getClassLoader().getResource("GettysburgAddress.txt").getFile());
long bytes = file.length();
MapHandle mmh1 = Memory.map(file);
MapHandle mmh2 = Memory.map(file);
assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 2L);
assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), 2 * bytes);
mmh1.close();
assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 1L);
assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), bytes);
mmh2.close();
mmh2.close(); //check that it doesn't go negative.
assertEquals(BaseState.getCurrentDirectMemoryMapAllocations(), 0L);
assertEquals(BaseState.getCurrentDirectMemoryMapAllocated(), 0L);
}
@Test
public void checkNullMemReqSvr() {
WritableMemory wmem = WritableMemory.wrap(new byte[16]);
assertNull(wmem.getMemoryRequestServer());
try (WritableDirectHandle wdh = WritableMemory.allocateDirect(16)) {
WritableMemory wmem2 = wdh.get();
assertNotNull(wmem2.getMemoryRequestServer());
}
println(wmem.toHexString("Test", 0, 16));
}
@Test
public void checkHashCode() {
WritableMemory wmem = WritableMemory.allocate(32 + 7);
int hc = wmem.hashCode();
assertEquals(hc, -1895166923);
}
@Test
public void checkSelfEqualsToAndCompareTo() {
int len = 64;
WritableMemory wmem = WritableMemory.allocate(len);
for (int i = 0; i < len; i++) { wmem.putByte(i, (byte) i); }
assertTrue(wmem.equalTo(0, wmem, 0, len));
assertFalse(wmem.equalTo(0, wmem, len/2, len/2));
assertEquals(wmem.compareTo(0, len, wmem, 0, len), 0);
assertTrue(wmem.compareTo(0, 0, wmem, len/2, len/2) < 0);
}
@Test
public void wrapBigEndianAsLittle() {
ByteBuffer bb = ByteBuffer.allocate(64);
bb.putChar(0, (char)1); //as BE
Memory mem = Memory.wrap(bb, ByteOrder.LITTLE_ENDIAN);
assertEquals(mem.getChar(0), 256);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(final String s) {
//System.out.println(s);
}
}
| apache-2.0 |
itYangJie/leetcode | src/com/ityang/leetcode/Subject8.java | 987 | package com.ityang.leetcode;
public class Subject8 {
public static void main(String[] args) {
System.out.println(myAtoi("1"));
}
public static int myAtoi(String str) {
double result = 0;
int POrN = 1;
int count = 0;
char[] charArr = str.toCharArray();
for(char c:charArr){
count ++;
if( c >='0' && c <='9' ){
result *= 10;
result += ( c - '0');
}else if( c == '-' && count == 1){
POrN = -1;
}else if( c == '+' && count == 1){
POrN = 1;
}else if( c == ' ' && count == 1){
count --;
}else{
break;
}
}
if( result > Integer.MAX_VALUE ){
if(POrN == 1)
return Integer.MAX_VALUE;
else
return Integer.MIN_VALUE;
}else{
return (int)(result * POrN);
}
}
}
| apache-2.0 |
alexcwyu/real-time-risk | reporting-service/src/main/java/net/alexyu/model/InterestRateId.java | 1628 | package net.alexyu.model;
import net.alexyu.common.pubsub.DataId;
import net.alexyu.common.pubsub.SubscriptionKey;
/**
* Created by alex on 3/23/17.
*/
public class InterestRateId implements DataId<InterestRate>, SubscriptionKey<InterestRate> {
public final String ccyId;
public InterestRateId(String ccyId) {
this.ccyId = ccyId;
}
public InterestRateId(Instrument instrument) {
this.ccyId = instrument.getCcyId();
}
public InterestRateId(InterestRate interestRate) {
this.ccyId = interestRate.getCcyId();
}
public static InterestRateId of(String ccyId) {
return new InterestRateId(ccyId);
}
public static InterestRateId of(Instrument instrument) {
return new InterestRateId(instrument);
}
public static InterestRateId of(InterestRate interestRate) {
return new InterestRateId(interestRate);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InterestRateId that = (InterestRateId) o;
return ccyId != null ? ccyId.equals(that.ccyId) : that.ccyId == null;
}
@Override
public int hashCode() {
return ccyId != null ? ccyId.hashCode() : 0;
}
@Override
public String toString() {
return "InterestRateId{" +
"ccyId='" + ccyId + '\'' +
'}';
}
@Override
public boolean test(DataId<InterestRate> dataId) {
return equals(dataId);
}
@Override
public String id() {
return ccyId;
}
}
| apache-2.0 |
drackows/ago-crm | src/main/java/pl/inpar/agocrm/domain/Person.java | 153 | package pl.inpar.agocrm.domain;
import java.util.Set;
public class Person {
String id;
String name;
Set<String> emails;
Set<Integer> phones;
}
| apache-2.0 |
xjdr/xio | chicago-example/src/main/java/com/xjeffrose/xio/client/chicago/XioChicagoClient.java | 6556 | package com.xjeffrose.xio.client.chicago;
import com.xjeffrose.xio.client.asyncretry.AsyncRetryLoop;
import com.xjeffrose.xio.client.asyncretry.AsyncRetryLoopFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class XioChicagoClient implements AutoCloseable {
private final EventLoopGroup eventLoopGroup;
private final ChicagoCluster cluster;
private DefaultPromise<WriteResult> writeResult() {
return new DefaultPromise<WriteResult>(eventLoopGroup.next());
}
private DefaultPromise<WriteResultGroup> writeResultGroup() {
return new DefaultPromise<WriteResultGroup>(eventLoopGroup.next());
}
public static class XioCluster {}
XioChicagoClient(Bootstrap bootstrap, ChicagoCluster cluster) {
this.eventLoopGroup = bootstrap.config().group();
this.cluster = cluster;
}
public XioChicagoClient start() {
System.out.println("Starting");
return this;
}
public void stop() {
System.out.println("Stopping");
}
public Future<WriteResultGroup> write(String columnFamily, String key, String value) {
DefaultPromise<WriteResultGroup> result = writeResultGroup();
WriteResultGroup resultGroup = new WriteResultGroup(3);
for (ChicagoNode node : cluster.quorumNodesForKey(key)) {
UUID id = UUID.randomUUID();
DefaultPromise<WriteResult> thisResult = writeResult();
node.send(ChicagoMessage.write(id, columnFamily, key, value), thisResult);
thisResult.addListener(
new FutureListener<WriteResult>() {
public void operationComplete(Future<WriteResult> future) {
if (future.isSuccess()) {
WriteResult writeResult = future.getNow();
if (resultGroup.quorumAcheived(writeResult)) {
result.setSuccess(resultGroup);
}
} else {
// TODO retry?
result.setFailure(future.cause());
}
}
});
}
//result.setSuccess(new WriteResultGroup(3));
return result;
}
public static XioChicagoClient newClient(XioClusterBootstrap clusterBootstrap) {
ChicagoCluster cluster = new ChicagoCluster(clusterBootstrap);
Bootstrap bootstrap = clusterBootstrap.config().bootstrap();
return new XioChicagoClient(bootstrap, cluster).start();
}
public void close() {
stop();
}
public static void main(String[] args) {
List<InetSocketAddress> endpoints =
Arrays.asList(
new InetSocketAddress("localhost", 9001),
new InetSocketAddress("localhost", 9002),
new InetSocketAddress("localhost", 9003),
new InetSocketAddress("localhost", 9004));
NioEventLoopGroup group = new NioEventLoopGroup();
List<ChannelFuture> serverChannels = new ArrayList<ChannelFuture>();
ServerBootstrap serverBootstrap =
new ServerBootstrap()
.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(
new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(
new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("incoming channel active");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(
ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
});
}
})
.childHandler(
new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("Got data" + msg);
ctx.writeAndFlush(msg);
}
});
for (InetSocketAddress address : endpoints) {
serverChannels.add(serverBootstrap.clone().localAddress(address).bind());
}
Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class);
XioClusterBootstrap clusterBootstrap =
new XioClusterBootstrap(bootstrap)
.addNodes(endpoints)
.retryLoopFactory(
new AsyncRetryLoopFactory() {
public AsyncRetryLoop buildLoop(EventLoopGroup eventLoopGroup) {
return new AsyncRetryLoop(0, eventLoopGroup, 1, TimeUnit.MILLISECONDS);
}
});
try (XioChicagoClient client = XioChicagoClient.newClient(clusterBootstrap)) {
System.out.println("HI!!!");
Future<WriteResultGroup> result = client.write("chicago", "key", "value");
System.out.println("waiting");
result.awaitUninterruptibly();
System.out.println("done waiting");
System.out.println("result " + result);
}
group.shutdownGracefully();
}
}
| apache-2.0 |
jonasrmichel/spatiotemporal-data | src/stdata/rules/GraphChangedRule.java | 908 | package stdata.rules;
import com.tinkerpop.blueprints.TransactionalGraph;
import com.tinkerpop.blueprints.util.wrappers.event.EventGraph;
import com.tinkerpop.blueprints.util.wrappers.event.listener.GraphChangedListener;
import com.tinkerpop.frames.FramedGraph;
public abstract class GraphChangedRule<G extends TransactionalGraph, E extends EventGraph<G>, F extends FramedGraph<EventGraph<G>>>
extends Rule<G, E, F> implements GraphChangedListener {
public GraphChangedRule(G baseGraph, E eventGraph, F framedGraph) {
super(baseGraph, eventGraph, framedGraph);
addListener();
}
public GraphChangedRule(G baseGraph, E eventGraph, F framedGraph,
IRuleDelegate delegate) {
super(baseGraph, eventGraph, framedGraph, delegate);
addListener();
}
/**
* Adds this rule as a graph changed listener in the event graph.
*/
public void addListener() {
eventGraph.addListener(this);
}
}
| apache-2.0 |
mF2C/COMPSs | compss/runtime/adaptors/nio/commons/src/main/java/es/bsc/compss/nio/commands/CommandExecutorShutdownACK.java | 1667 | /*
* Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.nio.commands;
import es.bsc.comm.Connection;
import es.bsc.compss.nio.NIOAgent;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class CommandExecutorShutdownACK implements Command {
/**
* Creates a new CommandExecutorShutdownACK for externalization.
*/
public CommandExecutorShutdownACK() {
super();
}
@Override
public void handle(NIOAgent agent, Connection c) {
agent.shutdownExecutionManagerNotification(c);
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// Nothing to write
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// Nothing to read
}
@Override
public String toString() {
return "ExecutorShutdownACK";
}
@Override
public void error(NIOAgent agent, Connection c) {
agent.handleExecutorShutdownCommandACKError(c, this);
}
}
| apache-2.0 |
Dafnik/RageMode | RageMode/src/at/dafnik/ragemode/Shop/Pages/AdvancedShopPageBasic.java | 1713 | package at.dafnik.ragemode.Shop.Pages;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import at.dafnik.ragemode.Main.Main;
import at.dafnik.ragemode.Main.Main.Status;
import at.dafnik.ragemode.Shop.Shop;
import net.md_5.bungee.api.ChatColor;
public abstract class AdvancedShopPageBasic implements Listener{
public String pagename = "";
public AdvancedShopPageBasic(String pagename) {
this.pagename = pagename;
Main.getInstance().getServer().getPluginManager().registerEvents(this, Main.getInstance());
}
@EventHandler
public void onClick(InventoryClickEvent event) {
if(Main.status == Status.PRE_LOBBY || Main.status == Status.LOBBY) {
if(event.getWhoClicked() instanceof Player) {
if(ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase(pagename)) {
Player player = (Player) event.getWhoClicked();
event.setCancelled(true);
switch(event.getCurrentItem().getType()) {
case IRON_DOOR:
player.closeInventory();
Shop.createBasicShopMenu(player);
break;
case BOOK:
break;
case FEATHER:
break;
case SULPHUR:
break;
case SPECTRAL_ARROW:
break;
case BLAZE_POWDER:
break;
case FLINT_AND_STEEL:
BuyEvent(player, event);
break;
default:
break;
}
//Player check
}
}
//Status check
}
}
public void BuyEvent(Player player, InventoryClickEvent event) {
//Created in the class
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-transcribe/src/main/java/com/amazonaws/services/transcribe/model/transform/TranscriptFilterJsonUnmarshaller.java | 4090 | /*
* Copyright 2017-2022 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.transcribe.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.transcribe.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* TranscriptFilter JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TranscriptFilterJsonUnmarshaller implements Unmarshaller<TranscriptFilter, JsonUnmarshallerContext> {
public TranscriptFilter unmarshall(JsonUnmarshallerContext context) throws Exception {
TranscriptFilter transcriptFilter = new TranscriptFilter();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("TranscriptFilterType", targetDepth)) {
context.nextToken();
transcriptFilter.setTranscriptFilterType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("AbsoluteTimeRange", targetDepth)) {
context.nextToken();
transcriptFilter.setAbsoluteTimeRange(AbsoluteTimeRangeJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("RelativeTimeRange", targetDepth)) {
context.nextToken();
transcriptFilter.setRelativeTimeRange(RelativeTimeRangeJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("ParticipantRole", targetDepth)) {
context.nextToken();
transcriptFilter.setParticipantRole(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Negate", targetDepth)) {
context.nextToken();
transcriptFilter.setNegate(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("Targets", targetDepth)) {
context.nextToken();
transcriptFilter.setTargets(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return transcriptFilter;
}
private static TranscriptFilterJsonUnmarshaller instance;
public static TranscriptFilterJsonUnmarshaller getInstance() {
if (instance == null)
instance = new TranscriptFilterJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
GoogleCloudPlatform/retail-common-services | core/src/test/java/com/google/spez/core/SpannerSchemaTest.java | 3756 | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.spez.core;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.testing.RemoteSpannerHelper;
import com.google.spez.spanner.internal.BothanDatabase;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.avro.SchemaBuilder;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
@SuppressWarnings("PMD.BeanMembersShouldSerialize")
@EnabledIfEnvironmentVariable(named = "INTEGRATION_TESTS", matches = "true")
class SpannerSchemaTest extends SpannerIntegrationTest implements WithAssertions {
RemoteSpannerHelper helper;
Database database;
static String TIMESTAMP = "timestamp";
@BeforeEach
void setUp() throws Throwable {
helper = RemoteSpannerHelper.create(InstanceId.of(projectId, INSTANCE_ID));
database =
helper.createTestDatabase(
List.of(
"CREATE TABLE Singers (\n"
+ " SingerId INT64 NOT NULL,\n"
+ " FirstName STRING(1024),\n"
+ " LastName STRING(1024),\n"
+ " SingerInfo BYTES(MAX),\n"
+ " timestamp TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true)\n"
+ ") PRIMARY KEY (SingerId)"));
}
@AfterEach
void tearDown() {
helper.cleanUp();
}
@Test
void getSchema() throws IOException {
var sinkConfig =
new SpezConfig.SinkConfig(
projectId,
INSTANCE_ID,
database.getId().getDatabase(),
"Singers",
"SingerId",
TIMESTAMP,
30,
false,
GoogleCredentials.getApplicationDefault());
var database = BothanDatabase.openDatabase(sinkConfig.getSettings());
SpannerSchema spannerSchema = new SpannerSchema(database, sinkConfig);
var result = spannerSchema.getSchema();
var expectedAvroSchema =
SchemaBuilder.record("Singers")
.namespace("avroNamespace")
.fields()
.name("SingerId")
.type()
.longType()
.noDefault()
.name("FirstName")
.type()
.optional()
.stringType()
.name("LastName")
.type()
.optional()
.stringType()
.name(TIMESTAMP)
.type()
.stringType()
.noDefault()
.endRecord();
assertThat(result.avroSchema()).isEqualTo(expectedAvroSchema);
var expectedSchema =
Map.of(
"FirstName",
"STRING(1024)",
"LastName",
"STRING(1024)",
"SingerId",
"INT64",
"SingerInfo",
"BYTES(MAX)",
TIMESTAMP,
"TIMESTAMP");
assertThat(result.spannerSchema()).containsExactlyInAnyOrderEntriesOf(expectedSchema);
}
}
| apache-2.0 |
biezhi/blade | src/main/java/com/blade/kit/WebKit.java | 1330 | package com.blade.kit;
import com.blade.mvc.http.Request;
import lombok.experimental.UtilityClass;
/**
* Web kit
*
* @author biezhi
* 2017/6/2
*/
@UtilityClass
public class WebKit {
public static final String UNKNOWN_MAGIC = "unknown";
/**
* Get the client IP address by request
*
* @param request Request instance
* @return return ip address
*/
public static String ipAddress(Request request) {
String ipAddress = request.header("x-forwarded-for");
if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
ipAddress = request.header("Proxy-Client-IP");
}
if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
ipAddress = request.header("WL-Proxy-Client-IP");
}
if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
ipAddress = request.header("X-Real-IP");
}
if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
ipAddress = request.header("HTTP_CLIENT_IP");
}
if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
ipAddress = request.header("HTTP_X_FORWARDED_FOR");
}
return ipAddress;
}
}
| apache-2.0 |
deephacks/westty | westty-spi/src/main/java/org/deephacks/westty/spi/HttpHandler.java | 515 | package org.deephacks.westty.spi;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpRequest;
public abstract class HttpHandler extends SimpleChannelUpstreamHandler {
public abstract void messageReceived(ChannelHandlerContext ctx, MessageEvent event,
HttpRequest request) throws Exception;
public abstract boolean accept(String uri);
}
| apache-2.0 |
orika-mapper/orika | core/src/test/java/ma/glasnost/orika/test/community/Issue232Test.java | 1736 | package ma.glasnost.orika.test.community;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.NullFilter;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class Issue232Test {
private MapperFactory mapperFactory;
@Before
public void setUp() throws Exception {
mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.registerFilter(new NullFilter<Map, Map>());
mapperFactory.classMap(FirstClassWithMap.class, SecondClassWithMap.class).byDefault().register();
}
@Test
public void test_map_to_map_with_filter() {
FirstClassWithMap firstMap = new FirstClassWithMap();
firstMap.setMap(new HashMap<>());
firstMap.getMap().put("A", "1");
SecondClassWithMap transformed = mapperFactory.getMapperFacade().map(firstMap, SecondClassWithMap.class);
assertNotNull(transformed);
assertNotNull(transformed.getMap());
assertEquals("1", transformed.getMap().get("A"));
}
public static class FirstClassWithMap {
private Map<String, String> map;
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
public static class SecondClassWithMap {
private Map<String, String> map;
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
}
| apache-2.0 |
citygml4j/citygml4j | src/main/java/org/citygml4j/model/gml/geometry/complexes/CompositeSolid.java | 3760 | /*
* citygml4j - The Open Source Java API for CityGML
* https://github.com/citygml4j
*
* Copyright 2013-2022 Claus Nagel <claus.nagel@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml4j.model.gml.geometry.complexes;
import org.citygml4j.builder.copy.CopyBuilder;
import org.citygml4j.geometry.BoundingBox;
import org.citygml4j.model.common.base.ModelObjects;
import org.citygml4j.model.common.child.ChildList;
import org.citygml4j.model.common.visitor.GMLFunctor;
import org.citygml4j.model.common.visitor.GMLVisitor;
import org.citygml4j.model.common.visitor.GeometryFunctor;
import org.citygml4j.model.common.visitor.GeometryVisitor;
import org.citygml4j.model.gml.GMLClass;
import org.citygml4j.model.gml.geometry.primitives.AbstractSolid;
import org.citygml4j.model.gml.geometry.primitives.SolidProperty;
import java.util.Arrays;
import java.util.List;
public class CompositeSolid extends AbstractSolid {
private List<SolidProperty> solidMember;
public CompositeSolid() {
}
public CompositeSolid(List<? extends AbstractSolid> abstractSolids) {
for (AbstractSolid abstractSolid : abstractSolids)
addSolidMember(new SolidProperty(abstractSolid));
}
public CompositeSolid(AbstractSolid... abstractSolids) {
this(Arrays.asList(abstractSolids));
}
public void addSolidMember(SolidProperty solidMember) {
getSolidMember().add(solidMember);
}
public List<SolidProperty> getSolidMember() {
if (solidMember == null)
solidMember = new ChildList<>(this);
return solidMember;
}
public boolean isSetSolidMember() {
return solidMember != null && !solidMember.isEmpty();
}
public void setSolidMember(List<SolidProperty> solidMember) {
this.solidMember = new ChildList<>(this, solidMember);
}
public void unsetSolidMember() {
solidMember = ModelObjects.setNull(solidMember);
}
public boolean unsetSolidMember(SolidProperty solidMember) {
return isSetSolidMember() && this.solidMember.remove(solidMember);
}
public BoundingBox calcBoundingBox() {
BoundingBox bbox = new BoundingBox();
if (isSetSolidMember()) {
for (SolidProperty solidProperty : getSolidMember())
if (solidProperty.isSetSolid())
bbox.update(solidProperty.getSolid().calcBoundingBox());
}
return bbox;
}
public GMLClass getGMLClass() {
return GMLClass.COMPOSITE_SOLID;
}
public Object copy(CopyBuilder copyBuilder) {
return copyTo(new CompositeSolid(), copyBuilder);
}
@Override
public Object copyTo(Object target, CopyBuilder copyBuilder) {
CompositeSolid copy = (target == null) ? new CompositeSolid() : (CompositeSolid)target;
super.copyTo(copy, copyBuilder);
if (isSetSolidMember()) {
for (SolidProperty part : solidMember) {
SolidProperty copyPart = (SolidProperty)copyBuilder.copy(part);
copy.addSolidMember(copyPart);
if (part != null && copyPart == part)
part.setParent(this);
}
}
return copy;
}
public void accept(GeometryVisitor visitor) {
visitor.visit(this);
}
public <T> T accept(GeometryFunctor<T> visitor) {
return visitor.apply(this);
}
public void accept(GMLVisitor visitor) {
visitor.visit(this);
}
public <T> T accept(GMLFunctor<T> visitor) {
return visitor.apply(this);
}
}
| apache-2.0 |
scudc/Genius-Android | sample/src/main/java/net/qiujuer/sample/TestCaseActivity.java | 10180 | package net.qiujuer.sample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import net.qiujuer.genius.Genius;
import net.qiujuer.genius.app.UiModel;
import net.qiujuer.genius.app.UiTool;
import net.qiujuer.genius.command.Command;
import net.qiujuer.genius.nettool.DnsResolve;
import net.qiujuer.genius.nettool.Ping;
import net.qiujuer.genius.nettool.SpeedRoad;
import net.qiujuer.genius.nettool.Telnet;
import net.qiujuer.genius.nettool.TraceRoute;
import net.qiujuer.genius.util.FixedList;
import net.qiujuer.genius.util.HashUtils;
import net.qiujuer.genius.util.Log;
import net.qiujuer.genius.util.ToolUtils;
import java.util.ArrayList;
import java.util.List;
public class TestCaseActivity extends Activity {
private static final String TAG = TestCaseActivity.class.getSimpleName();
TextView mText = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_case);
mText = (TextView) findViewById(R.id.text);
//添加回调
Log.addCallbackListener(new Log.LogCallbackListener() {
@Override
public void onLogArrived(final Log data) {
//异步显示到界面
UiTool.asyncRunOnUiThread(TestCaseActivity.this, new UiModel() {
@Override
public void doUi() {
if (mText != null)
mText.append("\n" + data.getMsg());
}
});
}
});
//开始测试
testLog();
testHashUtils();
testToolUtils();
testFixedList();
testNetTool();
testCommand();
}
@Override
protected void onDestroy() {
mText = null;
super.onDestroy();
}
/**
* 日志测试
*/
public void testLog() {
//是否调用系统Android Log,发布时可设置为false
Log.setCallLog(true);
//清理存储的文件
Log.clearLogFile();
//是否开启写入文件,存储最大文件数量,单个文件大小(Mb),重定向地址(默认包名目录)
Log.setSaveLog(true, 10, 1, null);
//设置是否监听外部存储插入操作
//开启时插入外部设备(SD)时将拷贝存储的日志文件到外部存储设备
//此操作依赖于是否开启写入文件功能,未开启则此方法无效
//是否开启,SD卡目录
Log.setCopyExternalStorage(true, "Test/Logs");
//设置日志等级
//VERBOSE为5到ERROR为1依次递减
Log.setLevel(Log.ALL);
Log.v(TAG, "测试日志 VERBOSE 级别。");
Log.d(TAG, "测试日志 DEBUG 级别。");
Log.i(TAG, "测试日志 INFO 级别。");
Log.w(TAG, "测试日志 WARN 级别。");
Log.e(TAG, "测试日志 ERROR 级别。");
Log.setLevel(Log.INFO);
Log.v(TAG, "二次测试日志 VERBOSE 级别。");
Log.d(TAG, "二次测试日志 DEBUG 级别。");
Log.i(TAG, "二次测试日志 INFO 级别。");
Log.w(TAG, "二次测试日志 WARN 级别。");
Log.e(TAG, "二次测试日志 ERROR 级别。");
Log.setLevel(Log.ALL);
}
/**
* 测试MD5
*/
public void testHashUtils() {
Log.i(TAG, "HashUtils:QIUJUER的MD5值为:" + HashUtils.getStringMd5("QIUJUER"));
//文件MD5不做演示,传入file类即可
}
/**
* 测试工具类
*/
public void testToolUtils() {
Log.i(TAG, "ToolUtils:getAndroidId:" + ToolUtils.getAndroidId(Genius.getApplication()));
Log.i(TAG, "ToolUtils:getDeviceId:" + ToolUtils.getDeviceId(Genius.getApplication()));
Log.i(TAG, "ToolUtils:getSerialNumber:" + ToolUtils.getSerialNumber());
Log.i(TAG, "ToolUtils:isAvailablePackage(net.qiujuer.sample):" + ToolUtils.isAvailablePackage(Genius.getApplication(), "net.qiujuer.sample"));
}
/**
* 测试固定长度队列
*/
public void testFixedList() {
//初始化最大长度为5
FixedList<Integer> list = new FixedList<Integer>(5);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
//添加4个元素
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
//继续追加2个
list.add(5);
list.add(6);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
//调整最大长度
list.setMaxSize(6);
list.add(7);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
list.add(8);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
//缩小长度,自动删除前面多余部分
list.setMaxSize(3);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
list.add(9);
Log.i(TAG, "FixedSizeList:" + list.size() + " ," + list.getMaxSize());
//添加一个列表进去,自动删除多余部分
List<Integer> addList = new ArrayList<Integer>();
addList.add(10);
addList.add(11);
addList.add(12);
addList.add(13);
list.addAll(addList);
Log.i(TAG, "FixedSizeList:AddList:" + list.toString() + " " + list.size() + " ," + list.getMaxSize());
//采用poll方式弹出元素
Log.i(TAG, "FixedSizeList:Poll:[" + list.poll() + "] " + list.size() + " ," + list.getMaxSize());
Log.i(TAG, "FixedSizeList:Poll:[" + list.poll() + "] " + list.size() + " ," + list.getMaxSize());
Log.i(TAG, "FixedSizeList:Poll:[" + list.poll() + "] " + list.size() + " ," + list.getMaxSize());
//末尾插入元素与add一样
list.addLast(14);
list.addLast(15);
list.addLast(16);
list.addLast(17);
list.addLast(18);
Log.i(TAG, "FixedSizeList:AddLast:" + list.toString() + " " + list.size() + " ," + list.getMaxSize());
//从头部插入,默认删除尾部超出部分
list.addFirst(19);
list.addFirst(20);
Log.i(TAG, "FixedSizeList:AddFirst:" + list.toString() + " " + list.size() + " ," + list.getMaxSize());
//Remove与poll类似不过不返回删除元素,只会删除一个
list.remove();
Log.i(TAG, "FixedSizeList:Remove:" + list.toString() + " " + list.size() + " ," + list.getMaxSize());
//清空操作
list.clear();
Log.i(TAG, "FixedSizeList:Clear:" + list.toString() + " " + list.size() + " ," + list.getMaxSize());
//使用List操作,最大长度2
List<Integer> list1 = new FixedList<Integer>(2);
list1.add(1);
list1.add(2);
Log.i(TAG, "FixedSizeList:List:" + " " + list1.size() + " ," + list1.toString());
list1.add(3);
Log.i(TAG, "FixedSizeList:List:" + " " + list1.size() + " ," + list1.toString());
list1.add(4);
Log.i(TAG, "FixedSizeList:List:" + " " + list1.size() + " ," + list1.toString());
list1.clear();
Log.i(TAG, "FixedSizeList:List:" + " " + list1.size() + " ," + list1.toString());
}
/**
* 测试命令行执行
*/
public void testCommand() {
//同步
Thread thread = new Thread() {
public void run() {
//调用方式与ProcessBuilder传参方式一样
Command command = new Command("/system/bin/ping",
"-c", "4", "-s", "100",
"www.baidu.com");
//同步方式执行
String res = Command.command(command);
Log.i(TAG, "\n\nCommand 同步:" + res);
}
};
thread.setDaemon(true);
thread.start();
//异步
Command command = new Command("/system/bin/ping",
"-c", "4", "-s", "100",
"www.baidu.com");
//异步方式执行
//采用回调方式,无需自己建立线程
//传入回调后自动采用此种方式
Command.command(command, new Command.CommandListener() {
@Override
public void onCompleted(String str) {
Log.i(TAG, "\n\nCommand 异步 onCompleted:\n" + str);
}
@Override
public void onCancel() {
Log.i(TAG, "\n\nCommand 异步 onCancel");
}
@Override
public void onError() {
Log.i(TAG, "\n\nCommand 异步 onError");
}
});
}
/**
* 基本网络功能测试
*/
public void testNetTool() {
//所有目标都可为IP地址
Thread thread = new Thread() {
public void run() {
//包数,包大小,目标,是否解析IP
Ping ping = new Ping(4, 32, "www.baidu.com", true);
ping.start();
Log.i(TAG, "Ping:" + ping.toString());
//目标,可指定解析服务器
DnsResolve dns = new DnsResolve("www.baidu.com");
dns.start();
Log.i(TAG, "DnsResolve:" + dns.toString());
//目标,端口
Telnet telnet = new Telnet("www.baidu.com", 80);
telnet.start();
Log.i(TAG, "Telnet:" + telnet.toString());
//目标
TraceRoute traceRoute = new TraceRoute("www.baidu.com");
traceRoute.start();
Log.i(TAG, "\n\nTraceRoute:" + traceRoute.toString());
//测速
//下载目标,下载大小
SpeedRoad speedRoad = new SpeedRoad("http://down.360safe.com/se/360se_setup.exe", 1024 * 32);
speedRoad.start();
Log.i(TAG, "SpeedRoad:" + speedRoad.getSpeed());
}
};
thread.setDaemon(true);
thread.start();
}
}
| apache-2.0 |
tsib0/aw-reporting | aw-reporting-model/src/main/java/com/google/api/ads/adwords/awreporting/model/entities/ReportCampaign.java | 18840 | // Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.adwords.awreporting.model.entities;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvField;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvReport;
import com.google.api.ads.adwords.awreporting.model.csv.annotation.MoneyField;
import com.google.api.ads.adwords.awreporting.model.util.BigDecimalUtil;
import com.google.api.ads.adwords.lib.jaxb.v201502.ReportDefinitionReportType;
import com.google.common.collect.Lists;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
/**
* Specific report class for ReportCampaign
*
* @author jtoledo@google.com (Julian Toledo)
* @author gustavomoreira@google.com (Gustavo Moreira)
*/
@Entity
@com.googlecode.objectify.annotation.Entity
@Table(name = "AW_ReportCampaign")
@CsvReport(value = ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT)
public class ReportCampaign extends ReportBase {
@Column(name = "CAMPAIGN_ID")
@CsvField(value = "Campaign ID", reportField = "CampaignId")
private Long campaignId;
@Column(name = "CAMPAIGN_NAME", length = 255)
@CsvField(value = "Campaign", reportField = "CampaignName")
private String campaignName;
@Column(name = "CAMPAIGN_STATUS", length = 32)
@CsvField(value = "Campaign state", reportField = "CampaignStatus")
private String campaignStatus;
@Column(name = "BUDGET")
@CsvField(value = "Budget", reportField = "Amount")
@MoneyField
private BigDecimal budget;
@Column(name = "BUDGET_ID")
@CsvField(value = "Budget ID", reportField = "BudgetId")
private Long budgetId;
@Column(name = "CLICKCONVERSIONRATESIGNIFICANCE")
@CsvField(value = "Click conversion rate ACE indicator", reportField = "ClickConversionRateSignificance")
protected BigDecimal clickConversionRateSignificance;
@Column(name = "CONVERSIONRATEMANYPERCLICKSIGNIFICANCE")
@CsvField(value = "Conversion rate ACE indicator", reportField = "ConversionRateManyPerClickSignificance")
protected BigDecimal conversionRateManyPerClickSignificance;
@Column(name = "CONVERSIONMANYPERCLICKSIGNIFICANCE")
@CsvField(value = "Conversion ACE indicator", reportField = "ConversionManyPerClickSignificance")
protected BigDecimal conversionManyPerClickSignificance;
@Column(name = "COSTPERCONVERSIONMANYPERCLICKSIGNIFICANCE")
@CsvField(value = "Cost/conversion ACE indicator", reportField = "CostPerConversionManyPerClickSignificance")
protected BigDecimal costPerConversionManyPerClickSignificance;
@Column(name = "CONVERTEDCLICKSSIGNIFICANCE")
@CsvField(value = "Converted clicks ACE indicator", reportField = "ConvertedClicksSignificance")
private BigDecimal convertedClicksSignificance;
@Column(name = "COSTPERCONVERTEDCLICKSIGNIFICANCE")
@CsvField(value = "Cost/converted click ACE indicator", reportField = "CostPerConvertedClickSignificance")
private BigDecimal costPerConvertedClickSignificance;
@Column(name = "AVERAGE_FREQUENCY")
@CsvField(value = "Avg. impr. freq. per cookie", reportField = "AverageFrequency")
private BigDecimal averageFrequency;
@Column(name = "AVERAGE_PAGEVIEWS")
@CsvField(value = "Pages / visit", reportField = "AveragePageviews")
private BigDecimal averagePageviews;
@Column(name = "AVERAGE_TIME_ON_SITE")
@CsvField(value = "Avg. visit duration (seconds)", reportField = "AverageTimeOnSite")
private BigDecimal averageTimeOnSite;
@Column(name = "BOUNCE_RATE")
@CsvField(value = "Bounce rate", reportField = "BounceRate")
private BigDecimal bounceRate;
@Column(name = "PERCENT_NEW_VISITORS")
@CsvField(value = "% new visits", reportField = "PercentNewVisitors")
private BigDecimal percentNewVisitors;
@Column(name = "SEARCH_IMPRESSION_SHARE")
@CsvField(value = "Search Impr. share", reportField = "SearchImpressionShare")
private BigDecimal searchImpressionShare;
@Column(name = "SEARCH_LOST_IS_BUDGET")
@CsvField(value = "Search Lost IS (budget)", reportField = "SearchBudgetLostImpressionShare")
private BigDecimal searchLostISBudget;
@Column(name = "SEARCH_LOST_IS_RANK")
@CsvField(value = "Search Lost IS (rank)", reportField = "SearchRankLostImpressionShare")
private BigDecimal searchLostISRank;
@Column(name = "CONTENT_IMPRESSION_SHARE")
@CsvField(value = "Content Impr. share", reportField = "ContentImpressionShare")
private BigDecimal contentImpressionShare;
@Column(name = "CONTENT_LOST_IS_BUDGET")
@CsvField(value = "Content Lost IS (budget)", reportField = "ContentBudgetLostImpressionShare")
private BigDecimal contentLostISBudget;
@Column(name = "CONTENT_LOST_IS_RANK")
@CsvField(value = "Content Lost IS (rank)", reportField = "ContentRankLostImpressionShare")
private BigDecimal contentLostISRank;
@Column(name = "SEARCH_EXACT_MATCH_IMPRESSION_SHARE")
@CsvField(value = "Search Exact match IS", reportField = "SearchExactMatchImpressionShare")
private BigDecimal searchExactMatchImpressionShare;
@Lob
@Column(name = "LABELS", length = 2048)
@CsvField(value = "Labels", reportField = "Labels")
private String labels;
@Column(name = "HOUR_OF_DAY")
@CsvField(value = "Hour of day", reportField = "HourOfDay")
private Long hourOfDay;
@Column(name = "ADVERTISING_CHANNEL_TYPE", length = 32)
@CsvField(value = "Advertising Channel", reportField = "AdvertisingChannelType")
protected String advertisingChannelType;
@Column(name = "ADVERTISING_CHANNEL_SUBTYPE", length = 32)
@CsvField(value = "Advertising Sub Channel", reportField = "AdvertisingChannelSubType")
protected String advertisingChannelSubType;
@Column(name = "IMPRESSION_REACH")
@CsvField(value = "Unique cookies", reportField = "ImpressionReach")
private Long impressionReach;
@Column(name = "ACTIVE_VIEW_CPM")
@CsvField(value = "Active View avg. CPM", reportField = "ActiveViewCpm")
@MoneyField
private BigDecimal activeViewCpm;
@Column(name = "ACTIVE_VIEW_IMPRESSIONS")
@CsvField(value = "Active View avg. CPM", reportField = "ActiveViewImpressions")
private Long activeViewImpressions;
@Column(name = "CONVERSION_TRACKER_ID")
@CsvField(value = "Conversion Tracker Id", reportField = "ConversionTrackerId")
private Long conversionTrackerId;
@Column(name = "TRACKING_URL_TEMPLATE", length=2048)
@CsvField(value = "Tracking template", reportField = "TrackingUrlTemplate")
private String trackingUrlTemplate;
@Column(name = "URL_CUSTOM_PARAMETERS", length=2048)
@CsvField(value = "Custom parameter", reportField = "UrlCustomParameters")
private String urlCustomParameters;
/**
* Hibernate needs an empty constructor
*/
public ReportCampaign() {}
public ReportCampaign(Long topAccountId, Long accountId) {
this.topAccountId = topAccountId;
this.accountId = accountId;
}
@Override
public void setId() {
// Generating unique id after having accountId, campaignId and date
if (this.getAccountId() != null && this.getCampaignId() != null) {
this.id = this.getAccountId() + "-" + this.getCampaignId();
}
this.id += setIdDates();
// Adding extra fields for unique ID
if (this.getAdNetwork() != null && this.getAdNetwork().length() > 0) {
this.id += "-" + this.getAdNetwork();
}
if (this.getAdNetworkPartners() != null && this.getAdNetworkPartners().length() > 0) {
this.id += "-" + this.getAdNetworkPartners();
}
if (this.getDevice() != null && this.getDevice().length() > 0) {
this.id += "-" + this.getDevice();
}
if (this.getClickType() != null && this.getClickType().length() > 0) {
this.id += "-" + this.getClickType();
}
if (this.getHourOfDay() != null) {
this.id += "-" + this.getHourOfDay();
}
}
public Long getCampaignId() {
return campaignId;
}
public void setCampaignId(Long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public String getCampaignStatus() {
return campaignStatus;
}
public void setCampaignStatus(String campaignStatus) {
this.campaignStatus = campaignStatus;
}
public BigDecimal getBudget() {
return budget;
}
public void setBudget(BigDecimal budget) {
this.budget = budget;
}
public Long getBudgetId() {
return budgetId;
}
public void setBudgetId(Long budgetId) {
this.budgetId = budgetId;
}
public String getClickConversionRateSignificance() {
return BigDecimalUtil.formatAsReadable(clickConversionRateSignificance);
}
public BigDecimal getClickConversionRateSignificanceBigDecimal() {
return clickConversionRateSignificance;
}
public void setClickConversionRateSignificance(String clickConversionRateSignificance) {
this.clickConversionRateSignificance = BigDecimalUtil.parseFromNumberString(clickConversionRateSignificance);
}
public String getConversionRateManyPerClickSignificance() {
return BigDecimalUtil.formatAsReadable(conversionRateManyPerClickSignificance);
}
public BigDecimal getConversionRateManyPerClickSignificanceBigDecimal() {
return conversionRateManyPerClickSignificance;
}
public void setConversionRateManyPerClickSignificance(
String conversionRateManyPerClickSignificance) {
this.conversionRateManyPerClickSignificance = BigDecimalUtil.parseFromNumberString(conversionRateManyPerClickSignificance);
}
public String getConversionManyPerClickSignificance() {
return BigDecimalUtil.formatAsReadable(conversionManyPerClickSignificance);
}
public BigDecimal getConversionManyPerClickSignificanceBigDecimal() {
return conversionManyPerClickSignificance;
}
public void setConversionManyPerClickSignificance(String conversionManyPerClickSignificance) {
this.conversionManyPerClickSignificance = BigDecimalUtil.parseFromNumberString(conversionManyPerClickSignificance);
}
public String getCostPerConversionManyPerClickSignificance() {
return BigDecimalUtil.formatAsReadable(costPerConversionManyPerClickSignificance);
}
public BigDecimal getCostPerConversionManyPerClickSignificanceBigDecimal() {
return costPerConversionManyPerClickSignificance;
}
public void setCostPerConversionManyPerClickSignificance(
BigDecimal costPerConversionManyPerClickSignificance) {
this.costPerConversionManyPerClickSignificance = costPerConversionManyPerClickSignificance;
}
public String getConvertedClicksSignificance() {
return BigDecimalUtil.formatAsReadable(convertedClicksSignificance);
}
public BigDecimal getConvertedClicksSignificanceBigDecimal() {
return convertedClicksSignificance;
}
public void setConvertedClicksSignificance(String convertedClicksSignificance) {
this.convertedClicksSignificance = BigDecimalUtil.parseFromNumberString(convertedClicksSignificance);
}
public String getCostPerConvertedClickSignificance() {
return BigDecimalUtil.formatAsReadable(costPerConvertedClickSignificance);
}
public BigDecimal getCostPerConvertedClickSignificanceBigDecimal() {
return costPerConvertedClickSignificance;
}
public void setCostPerConvertedClickSignificance(String costPerConvertedClickSignificance) {
this.costPerConvertedClickSignificance = BigDecimalUtil.parseFromNumberString(costPerConvertedClickSignificance);
}
public String getAverageFrequency() {
return BigDecimalUtil.formatAsReadable(averageFrequency);
}
public BigDecimal getAverageFrequencyBigDecimal() {
return averageFrequency;
}
public void setAverageFrequency(String averageFrequency) {
this.averageFrequency = BigDecimalUtil.parseFromNumberString(averageFrequency);
}
public String getAveragePageviews() {
return BigDecimalUtil.formatAsReadable(averagePageviews);
}
public BigDecimal getAveragePageviewsBigDecimal() {
return averagePageviews;
}
public void setAveragePageviews(String averagePageviews) {
this.averagePageviews = BigDecimalUtil.parseFromNumberString(averagePageviews);
}
public String getAverageTimeOnSite() {
return BigDecimalUtil.formatAsReadable(averageTimeOnSite);
}
public BigDecimal getAverageTimeOnSiteBigDecimal() {
return averageTimeOnSite;
}
public void setAverageTimeOnSite(String averageTimeOnSite) {
this.averageTimeOnSite = BigDecimalUtil.parseFromNumberString(averageTimeOnSite);
}
public String getBounceRate() {
return BigDecimalUtil.formatAsReadable(bounceRate);
}
public BigDecimal getBounceRateBigDecimal() {
return bounceRate;
}
public void setBounceRate(String bounceRate) {
this.bounceRate = BigDecimalUtil.parseFromNumberString(bounceRate);
}
public String getPercentNewVisitors() {
return BigDecimalUtil.formatAsReadable(percentNewVisitors);
}
public BigDecimal getPercentNewVisitorsBigDecimal() {
return percentNewVisitors;
}
public void setPercentNewVisitors(String percentNewVisitors) {
this.percentNewVisitors = BigDecimalUtil.parseFromNumberString(percentNewVisitors);
}
public String getSearchImpressionShare() {
return BigDecimalUtil.formatAsReadable(this.searchImpressionShare);
}
public BigDecimal getSearchImpressionShareBigDecimal() {
return searchImpressionShare;
}
public void setSearchImpressionShare(String searchImpressionShare) {
this.searchImpressionShare = BigDecimalUtil.parseFromNumberStringPercentage(searchImpressionShare);
}
public String getSearchLostISBudget() {
return BigDecimalUtil.formatAsReadable(this.searchLostISBudget);
}
public BigDecimal getSearchLostISBudgetBigDecimal() {
return searchLostISBudget;
}
public void setSearchLostISBudget(String lostISBudget) {
this.searchLostISBudget = BigDecimalUtil.parseFromNumberStringPercentage(lostISBudget);
}
public String getSearchLostISRank() {
return BigDecimalUtil.formatAsReadable(this.searchLostISRank);
}
public BigDecimal getSearchLostISRankBigDecimal() {
return searchLostISRank;
}
public void setSearchLostISRank(String lostISRank) {
this.searchLostISRank = BigDecimalUtil.parseFromNumberStringPercentage(lostISRank);
}
public String getContentImpressionShare() {
return BigDecimalUtil.formatAsReadable(this.contentImpressionShare);
}
public BigDecimal getContentImpressionShareBigDecimal() {
return contentImpressionShare;
}
public void setContentImpressionShare(String contentImpressionShare) {
this.contentImpressionShare = BigDecimalUtil.parseFromNumberStringPercentage(contentImpressionShare);
}
public String getContentLostISBudget() {
return BigDecimalUtil.formatAsReadable(this.contentLostISBudget);
}
public BigDecimal getContentLostISBudgetBigDecimal() {
return contentLostISBudget;
}
public void setContentLostISBudget(String lostISBudget) {
this.contentLostISBudget = BigDecimalUtil.parseFromNumberStringPercentage(lostISBudget);
}
public String getContentLostISRank() {
return BigDecimalUtil.formatAsReadable(this.contentLostISRank);
}
public BigDecimal getContentLostISRankBigDecimal() {
return contentLostISRank;
}
public void setContentLostISRank(String lostISRank) {
this.contentLostISRank = BigDecimalUtil.parseFromNumberStringPercentage(lostISRank);
}
public String getSearchExactMatchImpressionShare() {
return BigDecimalUtil.formatAsReadable(this.searchExactMatchImpressionShare);
}
public BigDecimal getSearchExactMatchImpressionShareBigDecimal() {
return searchExactMatchImpressionShare;
}
public void setSearchExactMatchImpressionShare(String searchExactMatchImpressionShare) {
this.searchExactMatchImpressionShare = BigDecimalUtil.parseFromNumberStringPercentage(searchExactMatchImpressionShare);
}
public String getLabels() {
return this.labels;
}
public boolean hasLabel(String label) {
if (labels != null && labels.length() > 0) {
return Lists.newArrayList(labels.split(";")).contains(label);
} else {
return false;
}
}
public void setLabels(String labels) {
this.labels = labels;
}
public Long getHourOfDay() {
return hourOfDay;
}
public void setHourOfDay(Long hourOfDay) {
this.hourOfDay = hourOfDay;
}
public String getAdvertisingChannelType() {
return advertisingChannelType;
}
public void setAdvertisingChannelType(String advertisingChannelType) {
this.advertisingChannelType = advertisingChannelType;
}
public String getAdvertisingChannelSubType() {
return advertisingChannelSubType;
}
public void setAdvertisingChannelSubType(String advertisingChannelSubType) {
this.advertisingChannelSubType = advertisingChannelSubType;
}
public Long getImpressionReach() {
return impressionReach;
}
public void setImpressoinReach(Long impressionReach) {
this.impressionReach = impressionReach;
}
public String getActiveViewCpm() {
return BigDecimalUtil.formatAsReadable(activeViewCpm);
}
public BigDecimal getActiveViewCpmBigDecimal() {
return activeViewCpm;
}
public void setActiveViewCpm(String activeViewCpm) {
this.activeViewCpm = BigDecimalUtil.parseFromNumberStringPercentage(activeViewCpm);
}
public Long getActiveViewImpressions() {
return activeViewImpressions;
}
public void setActiveViewImpressions(Long activeViewImpressions) {
this.activeViewImpressions = activeViewImpressions;
}
public Long getConversionTrackerId() {
return conversionTrackerId;
}
public void setConversionTrackerId(Long conversionTrackerId) {
this.conversionTrackerId = conversionTrackerId;
}
public String getTrackingUrlTemplate() {
return trackingUrlTemplate;
}
public void setTrackingUrlTemplate(String trackingUrlTemplate) {
this.trackingUrlTemplate = trackingUrlTemplate;
}
public String getUrlCustomParameters() {
return urlCustomParameters;
}
public void setUrlCustomParameters(String urlCustomParameters) {
this.urlCustomParameters = urlCustomParameters;
}
}
| apache-2.0 |
thongdv/OEPv2 | portlets/oep-core-datamgt-portlet/docroot/WEB-INF/src/org/oep/core/util/Constaints.java | 2489 | /**
* Copyright (c) 2015 by Open eGovPlatform (http://http://openegovplatform.org/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.oep.core.util;
public class Constaints {
public static final String VIEW_FORM = "View";
public static final String ADD_FORM = "Add";
public static final String EDIT_FORM = "Edit";
public static final String UPLOAD_OK ="OK";
public static final String CLASSNAME ="className";
public static final String OBJECTID ="objectId";
public static final String NGAYTAO ="ngayTao";
public static interface Paging {
public static int DELTA = 10;
public static int CUR = 1;
}
public interface FileType{
public static final String ANHDAIDIEN = "ANHDAIDIEN";
public static final String VIDEO = "VIDEO";
public static final String AUDIO = "AUDIO";
public static final String DOC = "DOC";
public static final String PDF = "PDF";
public static final String FILE = "FILE";
}
public interface UploadFile{
public static final String ERROR_FORDER_NOT_FOUND = "ERROR_FORDER_NOT_FOUND";
public static final String ERROR_FORDER_NOT_CREATED = "ERROR_FORDER_NOT_CREATED";
public static final String ERROR_NOTFOUNT_CATEGORY = "ERROR_NOTFOUNT_CATEGORY";
public static final String OK = "OK";
}
public interface UrlTarget
{
public static final String blank = "_blank"; //Opens new page in a new browser window
public static final String self = "_self"; //Loads the new page in the current window
public static final String parent = "_parent"; //Loads new page into a parent frame
public static final String top = "_top"; //Loads new page into the current browser window, cancelling all frames
}
public static interface Action {
public static final String LOAD = "LOAD";
public static final String UNLOAD = "UNLOAD";
}
public static interface UserType {
public static final int USER_TYPE = 1;
public static final int GROUP_TYPE = 2;
}
}
| apache-2.0 |
mini2Dx/mini2Dx | libgdx-desktop-lwjgl2/src/main/java/com/badlogic/gdx/backends/lwjgl/audio/Mini2DxMp3.java | 4746 | /*******************************************************************************
* Copyright 2011 See LIBGDX_AUTHORS file.
*
* 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.badlogic.gdx.backends.lwjgl.audio;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import javazoom.jl.decoder.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* Modified version of {@link Mp3} to support sound completion events
*/
public class Mini2DxMp3 extends Mp3 {
static public class Music extends Mini2DxOpenALMusic {
// Note: This uses a slightly modified version of JLayer.
private Bitstream bitstream;
private OutputBuffer outputBuffer;
private MP3Decoder decoder;
public Music (Mini2DxOpenALAudio audio, FileHandle file) {
super(audio, file);
if (audio.noDevice) return;
bitstream = new Bitstream(file.read());
decoder = new MP3Decoder();
bufferOverhead = 4096;
try {
Header header = bitstream.readFrame();
if (header == null) throw new GdxRuntimeException("Empty MP3");
int channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
outputBuffer = new OutputBuffer(channels, false);
decoder.setOutputBuffer(outputBuffer);
setup(channels, header.getSampleRate());
} catch (BitstreamException e) {
throw new GdxRuntimeException("error while preloading mp3", e);
}
}
public int read (byte[] buffer) {
try {
boolean setup = bitstream == null;
if (setup) {
bitstream = new Bitstream(file.read());
decoder = new MP3Decoder();
}
int totalLength = 0;
int minRequiredLength = buffer.length - OutputBuffer.BUFFERSIZE * 2;
while (totalLength <= minRequiredLength) {
Header header = bitstream.readFrame();
if (header == null) break;
if (setup) {
int channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
outputBuffer = new OutputBuffer(channels, false);
decoder.setOutputBuffer(outputBuffer);
setup(channels, header.getSampleRate());
setup = false;
}
try {
decoder.decodeFrame(header, bitstream);
} catch (Exception ignored) {
// JLayer's decoder throws ArrayIndexOutOfBoundsException sometimes!?
}
bitstream.closeFrame();
int length = outputBuffer.reset();
System.arraycopy(outputBuffer.getBuffer(), 0, buffer, totalLength, length);
totalLength += length;
}
return totalLength;
} catch (Throwable ex) {
reset();
throw new GdxRuntimeException("Error reading audio data.", ex);
}
}
public void reset () {
if (bitstream == null) return;
try {
bitstream.close();
} catch (BitstreamException ignored) {
}
bitstream = null;
}
}
static public class Sound extends Mini2DxOpenALSound {
// Note: This uses a slightly modified version of JLayer.
public Sound (Mini2DxOpenALAudio audio, FileHandle file) {
this(audio, file.read(), file.path());
}
public Sound (Mini2DxOpenALAudio audio, InputStream stream, String fileName) {
super(audio);
if (audio.noDevice) return;
ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
Bitstream bitstream = new Bitstream(stream);
MP3Decoder decoder = new MP3Decoder();
try {
OutputBuffer outputBuffer = null;
int sampleRate = -1, channels = -1;
while (true) {
Header header = bitstream.readFrame();
if (header == null) break;
if (outputBuffer == null) {
channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
outputBuffer = new OutputBuffer(channels, false);
decoder.setOutputBuffer(outputBuffer);
sampleRate = header.getSampleRate();
}
try {
decoder.decodeFrame(header, bitstream);
} catch (Exception ignored) {
// JLayer's decoder throws ArrayIndexOutOfBoundsException sometimes!?
}
bitstream.closeFrame();
output.write(outputBuffer.getBuffer(), 0, outputBuffer.reset());
}
bitstream.close();
setup(output.toByteArray(), channels, sampleRate);
} catch (Throwable ex) {
throw new GdxRuntimeException("Error reading audio data.", ex);
}
}
}
}
| apache-2.0 |
Lihuanghe/CMPPGate | src/main/java/com/zx/sms/common/util/ChannelUtil.java | 5301 | package com.zx.sms.common.util;
import java.util.ArrayList;
import java.util.List;
import org.marre.sms.SmsMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zx.sms.BaseMessage;
import com.zx.sms.LongSMSMessage;
import com.zx.sms.codec.cmpp.wap.LongMessageFrame;
import com.zx.sms.codec.cmpp.wap.LongMessageFrameHolder;
import com.zx.sms.connect.manager.EndpointConnector;
import com.zx.sms.connect.manager.EndpointEntity;
import com.zx.sms.connect.manager.EndpointManager;
import com.zx.sms.session.AbstractSessionStateManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
public class ChannelUtil {
private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class);
public static ChannelFuture asyncWriteToEntity(final EndpointEntity entity, final Object msg) {
EndpointConnector connector = entity.getSingletonConnector();
return asyncWriteToEntity(connector, msg, null);
}
public static ChannelFuture asyncWriteToEntity(String entity, Object msg) {
EndpointEntity e = EndpointManager.INS.getEndpointEntity(entity);
EndpointConnector connector = e.getSingletonConnector();
return asyncWriteToEntity(connector, msg, null);
}
public static ChannelFuture asyncWriteToEntity(final EndpointEntity entity, final Object msg, GenericFutureListener listner) {
EndpointConnector connector = entity.getSingletonConnector();
return asyncWriteToEntity(connector, msg, listner);
}
public static ChannelFuture asyncWriteToEntity(final String entity, final Object msg, GenericFutureListener listner) {
EndpointEntity e = EndpointManager.INS.getEndpointEntity(entity);
EndpointConnector connector = e.getSingletonConnector();
return asyncWriteToEntity(connector, msg, listner);
}
private static ChannelFuture asyncWriteToEntity(EndpointConnector connector, final Object msg, GenericFutureListener listner) {
if (connector == null || msg == null)
return null;
ChannelFuture promise = connector.asynwrite(msg);
if (promise == null)
return null;
if (listner == null) {
promise.addListener(new GenericFutureListener() {
@Override
public void operationComplete(Future future) throws Exception {
// 如果发送消息失败,记录失败日志
if (!future.isSuccess()) {
StringBuilder sb = new StringBuilder();
sb.append("SendMessage ").append(msg.toString()).append(" Failed. ");
logger.error(sb.toString(), future.cause());
}
}
});
} else {
promise.addListener(listner);
}
return promise;
}
public static <T extends BaseMessage> List<Promise<T>> syncWriteLongMsgToEntity(EndpointEntity e, BaseMessage msg) throws Exception {
EndpointConnector connector = e.getSingletonConnector();
if(connector == null) return null;
if (msg instanceof LongSMSMessage) {
LongSMSMessage<BaseMessage> lmsg = (LongSMSMessage<BaseMessage>) msg;
if (!lmsg.isReport()) {
// 长短信拆分
SmsMessage msgcontent = lmsg.getSmsMessage();
List<LongMessageFrame> frameList = LongMessageFrameHolder.INS.splitmsgcontent(msgcontent);
//保证同一条长短信,通过同一个tcp连接发送
List<BaseMessage> msgs = new ArrayList<BaseMessage>();
for (LongMessageFrame frame : frameList) {
BaseMessage basemsg = (BaseMessage) lmsg.generateMessage(frame);
msgs.add(basemsg);
}
return connector.synwrite(msgs);
}
}
Promise promise = connector.synwrite(msg);
if (promise == null) {
// 为空,可能是连接断了,直接返回
return null;
}
List<Promise<T>> arrPromise = new ArrayList<Promise<T>>();
arrPromise.add(promise);
return arrPromise;
}
/**
* 同步发送长短信类型 <br/>
* 注意:该方法将拆分后的短信直接发送,不会再调用BusinessHandler里的write方法了。
*/
public static <T extends BaseMessage> List<Promise<T>> syncWriteLongMsgToEntity(String entity, BaseMessage msg) throws Exception {
EndpointEntity e = EndpointManager.INS.getEndpointEntity(entity);
if(e==null) {
logger.warn("EndpointEntity {} is null",entity);
return null;
}
return syncWriteLongMsgToEntity(e,msg);
}
/**
* 同步发送消息类型 <br/>
* 注意:该方法将直接发送至编码器,不会再调用BusinessHandler里的write方法了。
* 因此对于Deliver和Submit消息必须自己进行长短信拆分,设置PDU等相关字段
*一般此方法用来发送二进制短信等特殊短信,需要自己生成短信的二进制内容。
*正常短信下发要使用 syncWriteLongMsgToEntity 方法
*/
public static <T extends BaseMessage> Promise<T> syncWriteBinaryMsgToEntity(String entity, BaseMessage msg) throws Exception {
EndpointEntity e = EndpointManager.INS.getEndpointEntity(entity);
EndpointConnector connector = e.getSingletonConnector();
Promise<T> promise = connector.synwrite(msg);
if (promise == null) {
// 为空,可能是连接断了,直接返回
return null;
}
return promise;
}
}
| apache-2.0 |
MAtzmueller/Kadconia | src/de/dhbw/database/DataBaseLinks.java | 3465 | package de.dhbw.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class DataBaseLinks implements DataBaseTable{
// table name
private static final String TABLE_NAME = "links";
// table colums
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_URL = "url";
private static final String KEY_IMAGE = "image";
// create table query
private static final String CREATE_TABLE_LINKS_QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_URL
+ " TEXT," + KEY_IMAGE + " TEXT" + ");";
public String getTableName() {
return TABLE_NAME;
}
public void dropTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void createTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_LINKS_QUERY);
}
public void initTable (SQLiteDatabase db) {
addLink(db, new Link("Forum", "http://forum.kadcon.de", "ic_link_forum"));
addLink(db, new Link("Shop", "http://shop.kadcon.de/", "ic_link_shop"));
//addLink(db, new Link("Bans", "http://kadcon.de/banmanagement/", "ic_link_ban"));
addLink(db, new Link("Facebook", "https://m.facebook.com/Kadcon.de", "ic_link_facebook"));
addLink(db, new Link("Youtube", "http://m.youtube.com/user/kadconDE", "ic_link_youtube"));
addLink(db, new Link("Twitter\n(Kademlia)", "https://mobile.twitter.com/Kademlias", "ic_link_twitter"));
}
@Override
public SQLiteDatabase getReadableDatabase(Context context) {
return (new DataBaseHelper(context)).getReadableDatabase();
}
@Override
public SQLiteDatabase getWritableDatabase(Context context) {
return (new DataBaseHelper(context)).getWritableDatabase();
}
// link functions
private void addLink(SQLiteDatabase db, Link mLink) {
ContentValues mContentValues = new ContentValues();
mContentValues.put(KEY_NAME, mLink.getName());
mContentValues.put(KEY_URL, mLink.getUrl());
mContentValues.put(KEY_IMAGE, mLink.getImage());
db.insert(TABLE_NAME, null, mContentValues);
}
private void addLink(Context context, Link mLink) {
SQLiteDatabase db = getWritableDatabase(context);
addLink(db, mLink);
db.close();
}
public List<Link> getAllLinks(Context context)
{
SQLiteDatabase db = getReadableDatabase(context);
List<Link> mLinkList = new ArrayList<Link>();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Link mLink = new Link();
mLink.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
mLink.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
mLink.setUrl(cursor.getString(cursor.getColumnIndex(KEY_URL)));
mLink.setImage(cursor.getString(cursor.getColumnIndex(KEY_IMAGE)));
// Adding workout to list
mLinkList.add(mLink);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return mLinkList;
}
}
| apache-2.0 |
thomasdarimont/spring-data-bugs | DATAJPA-617/src/test/java/datapagedquery/ApplicationTests.java | 1718 | package datapagedquery;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import datapagedquery.domain.Customer;
import datapagedquery.repository.CustomerRepository;
import datapagedquery.repository.TestRepository;
import datapagedquery.service.CustomerService;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
static Logger log = Logger.getLogger(TestRepository.class.getName());
@Autowired
CustomerRepository repository;
@Autowired
CustomerService service;
@Test
public void testFindAllPaged() {
PageRequest pr = new PageRequest(1, 10);
Page<Customer> page = repository.findAll(pr);
for (Customer c : page.getContent()) {
log.info(c);
}
}
@Test
public void testFindbyNamePatternPaged() {
PageRequest pr = new PageRequest(1, 10);
String keyword = "%customer%";
Page<Customer> page = repository.findByNamePattern(keyword, pr);
for (Customer c : page.getContent()) {
log.info(c);
}
}
@Test
public void testFindAllPagedViaService() {
Page<Customer> page = service.findAll(1, 10);
for (Customer c : page.getContent()) {
log.info(c);
}
}
@Test
public void testFindByPatternPagedViaService() {
Page<Customer> page = service.findByNamePatternPaged("customer", 1, 10);
for (Customer c : page.getContent()) {
log.info(c);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GetCrawlerResultJsonUnmarshaller.java | 2752 | /*
* Copyright 2017-2022 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.glue.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.glue.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetCrawlerResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetCrawlerResultJsonUnmarshaller implements Unmarshaller<GetCrawlerResult, JsonUnmarshallerContext> {
public GetCrawlerResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetCrawlerResult getCrawlerResult = new GetCrawlerResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getCrawlerResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Crawler", targetDepth)) {
context.nextToken();
getCrawlerResult.setCrawler(CrawlerJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getCrawlerResult;
}
private static GetCrawlerResultJsonUnmarshaller instance;
public static GetCrawlerResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetCrawlerResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
labsai/EDDI | semanticparser-impl/src/main/java/ai/labs/parser/internal/matches/MatchingResult.java | 625 | package ai.labs.parser.internal.matches;
import ai.labs.parser.extensions.dictionaries.IDictionary;
import lombok.Getter;
import java.util.LinkedList;
import java.util.List;
/**
* @author ginccc
*/
@Getter
public class MatchingResult {
private List<IDictionary.IFoundWord> result;
private boolean corrected;
public MatchingResult() {
this(false);
}
private MatchingResult(boolean corrected) {
this.corrected = corrected;
result = new LinkedList<>();
}
public void addResult(IDictionary.IFoundWord dictionaryEntries) {
result.add(dictionaryEntries);
}
}
| apache-2.0 |
rafael-chavez/java-client | src/main/java/io/appium/java_client/ios/IOSDriver.java | 9161 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.appium.java_client.ios;
import static io.appium.java_client.MobileCommand.HIDE_KEYBOARD;
import static io.appium.java_client.MobileCommand.LOCK;
import static io.appium.java_client.MobileCommand.SHAKE;
import com.google.common.collect.ImmutableMap;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.FindsByIosUIAutomation;
import io.appium.java_client.ios.internal.JsonToIOSElementConverter;
import io.appium.java_client.remote.MobilePlatform;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.http.HttpClient;
import java.net.URL;
import java.util.List;
/**
* @param <T> the required type of class which implement
* {@link org.openqa.selenium.WebElement}.
* Instances of the defined type will be returned via findElement* and findElements*.
* Warning (!!!). Allowed types:
* {@link org.openqa.selenium.WebElement}
* {@link io.appium.java_client.TouchableElement}
* {@link org.openqa.selenium.remote.RemoteWebElement}
* {@link io.appium.java_client.MobileElement}
* {@link io.appium.java_client.ios.IOSElement}
*/
public class IOSDriver<T extends WebElement>
extends AppiumDriver<T>
implements IOSDeviceActionShortcuts,
FindsByIosUIAutomation<T> {
private static final String IOS_PLATFORM = MobilePlatform.IOS;
/**
* @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor}
* or class that extends it. Default commands or another vendor-specific
* commands may be specified there.
* @param capabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(HttpCommandExecutor executor, Capabilities capabilities) {
super(executor, capabilities, JsonToIOSElementConverter.class);
}
/**
* @param remoteAddress is the address
* of remotely/locally started Appium server
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(URL remoteAddress, Capabilities desiredCapabilities) {
super(remoteAddress, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param remoteAddress is the address
* of remotely/locally started Appium server
* @param httpClientFactory take a look
* at {@link org.openqa.selenium.remote.http.HttpClient.Factory}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(URL remoteAddress, HttpClient.Factory httpClientFactory,
Capabilities desiredCapabilities) {
super(remoteAddress, httpClientFactory,
substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param service take a look
* at {@link io.appium.java_client.service.local.AppiumDriverLocalService}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities) {
super(service, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param service take a look
* at {@link io.appium.java_client.service.local.AppiumDriverLocalService}
* @param httpClientFactory take a look
* at {@link org.openqa.selenium.remote.http.HttpClient.Factory}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory,
Capabilities desiredCapabilities) {
super(service, httpClientFactory,
substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param builder take a look
* at {@link io.appium.java_client.service.local.AppiumServiceBuilder}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities) {
super(builder, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param builder take a look
* at {@link io.appium.java_client.service.local.AppiumServiceBuilder}
* @param httpClientFactory take a look
* at {@link org.openqa.selenium.remote.http.HttpClient.Factory}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory,
Capabilities desiredCapabilities) {
super(builder, httpClientFactory,
substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param httpClientFactory take a look
* at {@link org.openqa.selenium.remote.http.HttpClient.Factory}
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities) {
super(httpClientFactory, substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @param desiredCapabilities take a look
* at {@link org.openqa.selenium.Capabilities}
*/
public IOSDriver(Capabilities desiredCapabilities) {
super(substituteMobilePlatform(desiredCapabilities, IOS_PLATFORM),
JsonToIOSElementConverter.class);
}
/**
* @see io.appium.java_client.TouchShortcuts#swipe(int, int, int, int, int).
*/
@Override public void swipe(int startx, int starty, int endx, int endy, int duration) {
doSwipe(startx, starty, endx - startx, endy - starty, duration);
}
/**
* @see IOSDeviceActionShortcuts#hideKeyboard(String, String).
*/
@Override public void hideKeyboard(String strategy, String keyName) {
String[] parameters = new String[] {"strategy", "key"};
Object[] values = new Object[] {strategy, keyName};
execute(HIDE_KEYBOARD, getCommandImmutableMap(parameters, values));
}
/**
* @see IOSDeviceActionShortcuts#hideKeyboard(String).
*/
@Override public void hideKeyboard(String keyName) {
execute(HIDE_KEYBOARD, ImmutableMap.of("keyName", keyName));
}
/**
* @see IOSDeviceActionShortcuts#shake().
*/
@Override public void shake() {
execute(SHAKE);
}
/**
* @throws WebDriverException
* This method is not applicable with browser/webview UI.
*/
@SuppressWarnings("unchecked")
@Override
public T findElementByIosUIAutomation(String using)
throws WebDriverException {
return (T) findElement("-ios uiautomation", using);
}
/**
* @throws WebDriverException This method is not applicable with browser/webview UI.
*/
@SuppressWarnings("unchecked")
@Override
public List<T> findElementsByIosUIAutomation(String using)
throws WebDriverException {
return (List<T>) findElements("-ios uiautomation", using);
}
/**
* Lock the device (bring it to the lock screen) for a given number of
* seconds.
*
* @param seconds number of seconds to lock the screen for
*/
public void lockDevice(int seconds) {
execute(LOCK, ImmutableMap.of("seconds", seconds));
}
}
| apache-2.0 |
dkellenb/formula-evaluator | src/main/java/com/github/dkellenb/formulaevaluator/term/function/doubletype/DoubleTangentFunctionTerm.java | 1096 | package com.github.dkellenb.formulaevaluator.term.function.doubletype;
import java.util.List;
import com.github.dkellenb.formulaevaluator.FormulaEvaluatorConfiguration;
import com.github.dkellenb.formulaevaluator.definition.Function;
import com.github.dkellenb.formulaevaluator.term.Term;
import com.github.dkellenb.formulaevaluator.term.function.GenericFunctionTerm;
/**
* Double TAN Function.
*/
public class DoubleTangentFunctionTerm extends GenericFunctionTerm<Double> implements DoubleFunction {
/**
* C'tor. This one should be used for external usage
*
* @param term parameter term
*/
public DoubleTangentFunctionTerm(Term<Double> term) {
super(term);
}
/**
* C'tor.
*
* @param parameters parameter terms
*/
DoubleTangentFunctionTerm(List<Term<Double>> parameters) {
super(parameters);
}
@Override
protected Function getFunction() {
return Function.TAN;
}
@Override
public Double calculateDefault(FormulaEvaluatorConfiguration conf, List<Double> parameters) {
return Math.tan(Math.toRadians(parameters.get(0)));
}
}
| apache-2.0 |
eSDK/esdk_cloud_fm_r3_native_java | source/FM/V1R3/esdk_fm_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/impl/autogen/common/QueryHypervisorsByDcRequest.java | 1501 |
package com.huawei.esdk.fusionmanager.local.impl.autogen.common;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for QueryHypervisorsByDcRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="QueryHypervisorsByDcRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="dcId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QueryHypervisorsByDcRequest", namespace = "http://request.model.general.soap.business.common.north.galaxmanager.com/xsd", propOrder = {
"dcId"
})
public class QueryHypervisorsByDcRequest {
protected String dcId;
/**
* Gets the value of the dcId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDcId() {
return dcId;
}
/**
* Sets the value of the dcId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDcId(String value) {
this.dcId = value;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/DescribeTrainingJobResult.java | 119508 | /*
* Copyright 2014-2019 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.sagemaker.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DescribeTrainingJob" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeTrainingJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Name of the model training job.
* </p>
*/
private String trainingJobName;
/**
* <p>
* The Amazon Resource Name (ARN) of the training job.
* </p>
*/
private String trainingJobArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was launched by a
* hyperparameter tuning job.
* </p>
*/
private String tuningJobArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the transform or
* training job.
* </p>
*/
private String labelingJobArn;
/**
* <p>
* Information about the Amazon S3 location that is configured for storing model artifacts.
* </p>
*/
private ModelArtifacts modelArtifacts;
/**
* <p>
* The status of the training job.
* </p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* </p>
*/
private String trainingJobStatus;
/**
* <p>
* Provides detailed information about the state of the training job. For detailed information on the secondary
* status of the training job, see <code>StatusMessage</code> under <a>SecondaryStatusTransition</a>.
* </p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input mode.
* It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3 location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* </ul>
*/
private String secondaryStatus;
/**
* <p>
* If the training job failed, the reason it failed.
* </p>
*/
private String failureReason;
/**
* <p>
* Algorithm-specific parameters.
* </p>
*/
private java.util.Map<String, String> hyperParameters;
/**
* <p>
* Information about the algorithm used for training, and algorithm metadata.
* </p>
*/
private AlgorithmSpecification algorithmSpecification;
/**
* <p>
* The AWS Identity and Access Management (IAM) role configured for the training job.
* </p>
*/
private String roleArn;
/**
* <p>
* An array of <code>Channel</code> objects that describes each data input channel.
* </p>
*/
private java.util.List<Channel> inputDataConfig;
/**
* <p>
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker creates
* subfolders for model artifacts.
* </p>
*/
private OutputDataConfig outputDataConfig;
/**
* <p>
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
* </p>
*/
private ResourceConfig resourceConfig;
/**
* <p>
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more information, see
* <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training Jobs by Using an Amazon
* Virtual Private Cloud</a>.
* </p>
*/
private VpcConfig vpcConfig;
/**
* <p>
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for a spot
* instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API to cap model
* training costs.
* </p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job termination
* for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the results of
* training are not lost.
* </p>
*/
private StoppingCondition stoppingCondition;
/**
* <p>
* A timestamp that indicates when the training job was created.
* </p>
*/
private java.util.Date creationTime;
/**
* <p>
* Indicates the time when the training job starts on training instances. You are billed for the time interval
* between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch Logs might be later
* than this time. The difference is due to the time it takes to download the training data and to the size of the
* training container.
* </p>
*/
private java.util.Date trainingStartTime;
/**
* <p>
* Indicates the time when the training job ends on training instances. You are billed for the time interval between
* the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs, this is the time
* after model artifacts are uploaded. For failed jobs, this is the time when Amazon SageMaker detects a job
* failure.
* </p>
*/
private java.util.Date trainingEndTime;
/**
* <p>
* A timestamp that indicates when the status of the training job was last modified.
* </p>
*/
private java.util.Date lastModifiedTime;
/**
* <p>
* A history of all of the secondary statuses that the training job has transitioned through.
* </p>
*/
private java.util.List<SecondaryStatusTransition> secondaryStatusTransitions;
/**
* <p>
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that the
* training algorithm emitted to Amazon CloudWatch.
* </p>
*/
private java.util.List<MetricData> finalMetricDataList;
/**
* <p>
* If you want to allow inbound or outbound network calls, except for calls between peers within a training cluster
* for distributed training, choose <code>True</code>. If you enable network isolation for training jobs that are
* configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model artifacts through the
* specified VPC, but the training container does not have network access.
* </p>
* <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* </note>
*/
private Boolean enableNetworkIsolation;
/**
* <p>
* To encrypt all communications between ML compute instances in distributed training, choose <code>True</code>.
* Encryption provides greater security for distributed training, but training might take longer. How long it takes
* depends on the amount of communication between compute instances, especially if you use a deep learning
* algorithms in distributed training.
* </p>
*/
private Boolean enableInterContainerTrafficEncryption;
/**
* <p>
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (<code>False</code>).
* </p>
*/
private Boolean enableManagedSpotTraining;
private CheckpointConfig checkpointConfig;
/**
* <p>
* The training time in seconds.
* </p>
*/
private Integer trainingTimeInSeconds;
/**
* <p>
* The billable time in seconds.
* </p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is 80%.
* </p>
*/
private Integer billableTimeInSeconds;
/**
* <p>
* Name of the model training job.
* </p>
*
* @param trainingJobName
* Name of the model training job.
*/
public void setTrainingJobName(String trainingJobName) {
this.trainingJobName = trainingJobName;
}
/**
* <p>
* Name of the model training job.
* </p>
*
* @return Name of the model training job.
*/
public String getTrainingJobName() {
return this.trainingJobName;
}
/**
* <p>
* Name of the model training job.
* </p>
*
* @param trainingJobName
* Name of the model training job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTrainingJobName(String trainingJobName) {
setTrainingJobName(trainingJobName);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the training job.
* </p>
*
* @param trainingJobArn
* The Amazon Resource Name (ARN) of the training job.
*/
public void setTrainingJobArn(String trainingJobArn) {
this.trainingJobArn = trainingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the training job.
* </p>
*
* @return The Amazon Resource Name (ARN) of the training job.
*/
public String getTrainingJobArn() {
return this.trainingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the training job.
* </p>
*
* @param trainingJobArn
* The Amazon Resource Name (ARN) of the training job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTrainingJobArn(String trainingJobArn) {
setTrainingJobArn(trainingJobArn);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was launched by a
* hyperparameter tuning job.
* </p>
*
* @param tuningJobArn
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was
* launched by a hyperparameter tuning job.
*/
public void setTuningJobArn(String tuningJobArn) {
this.tuningJobArn = tuningJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was launched by a
* hyperparameter tuning job.
* </p>
*
* @return The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was
* launched by a hyperparameter tuning job.
*/
public String getTuningJobArn() {
return this.tuningJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was launched by a
* hyperparameter tuning job.
* </p>
*
* @param tuningJobArn
* The Amazon Resource Name (ARN) of the associated hyperparameter tuning job if the training job was
* launched by a hyperparameter tuning job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTuningJobArn(String tuningJobArn) {
setTuningJobArn(tuningJobArn);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the transform or
* training job.
* </p>
*
* @param labelingJobArn
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the
* transform or training job.
*/
public void setLabelingJobArn(String labelingJobArn) {
this.labelingJobArn = labelingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the transform or
* training job.
* </p>
*
* @return The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the
* transform or training job.
*/
public String getLabelingJobArn() {
return this.labelingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the transform or
* training job.
* </p>
*
* @param labelingJobArn
* The Amazon Resource Name (ARN) of the Amazon SageMaker Ground Truth labeling job that created the
* transform or training job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withLabelingJobArn(String labelingJobArn) {
setLabelingJobArn(labelingJobArn);
return this;
}
/**
* <p>
* Information about the Amazon S3 location that is configured for storing model artifacts.
* </p>
*
* @param modelArtifacts
* Information about the Amazon S3 location that is configured for storing model artifacts.
*/
public void setModelArtifacts(ModelArtifacts modelArtifacts) {
this.modelArtifacts = modelArtifacts;
}
/**
* <p>
* Information about the Amazon S3 location that is configured for storing model artifacts.
* </p>
*
* @return Information about the Amazon S3 location that is configured for storing model artifacts.
*/
public ModelArtifacts getModelArtifacts() {
return this.modelArtifacts;
}
/**
* <p>
* Information about the Amazon S3 location that is configured for storing model artifacts.
* </p>
*
* @param modelArtifacts
* Information about the Amazon S3 location that is configured for storing model artifacts.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withModelArtifacts(ModelArtifacts modelArtifacts) {
setModelArtifacts(modelArtifacts);
return this;
}
/**
* <p>
* The status of the training job.
* </p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* </p>
*
* @param trainingJobStatus
* The status of the training job.</p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* @see TrainingJobStatus
*/
public void setTrainingJobStatus(String trainingJobStatus) {
this.trainingJobStatus = trainingJobStatus;
}
/**
* <p>
* The status of the training job.
* </p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* </p>
*
* @return The status of the training job.</p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* @see TrainingJobStatus
*/
public String getTrainingJobStatus() {
return this.trainingJobStatus;
}
/**
* <p>
* The status of the training job.
* </p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* </p>
*
* @param trainingJobStatus
* The status of the training job.</p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingJobStatus
*/
public DescribeTrainingJobResult withTrainingJobStatus(String trainingJobStatus) {
setTrainingJobStatus(trainingJobStatus);
return this;
}
/**
* <p>
* The status of the training job.
* </p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* </p>
*
* @param trainingJobStatus
* The status of the training job.</p>
* <p>
* Amazon SageMaker provides the following training job statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>InProgress</code> - The training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. To see the reason for the failure, see the
* <code>FailureReason</code> field in the response to a <code>DescribeTrainingJobResponse</code> call.
* </p>
* </li>
* <li>
* <p>
* <code>Stopping</code> - The training job is stopping.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* <p>
* For more detailed information, see <code>SecondaryStatus</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrainingJobStatus
*/
public DescribeTrainingJobResult withTrainingJobStatus(TrainingJobStatus trainingJobStatus) {
this.trainingJobStatus = trainingJobStatus.toString();
return this;
}
/**
* <p>
* Provides detailed information about the state of the training job. For detailed information on the secondary
* status of the training job, see <code>StatusMessage</code> under <a>SecondaryStatusTransition</a>.
* </p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input mode.
* It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3 location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* </ul>
*
* @param secondaryStatus
* Provides detailed information about the state of the training job. For detailed information on the
* secondary status of the training job, see <code>StatusMessage</code> under
* <a>SecondaryStatusTransition</a>.</p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input
* mode. It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3
* location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* @see SecondaryStatus
*/
public void setSecondaryStatus(String secondaryStatus) {
this.secondaryStatus = secondaryStatus;
}
/**
* <p>
* Provides detailed information about the state of the training job. For detailed information on the secondary
* status of the training job, see <code>StatusMessage</code> under <a>SecondaryStatusTransition</a>.
* </p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input mode.
* It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3 location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* </ul>
*
* @return Provides detailed information about the state of the training job. For detailed information on the
* secondary status of the training job, see <code>StatusMessage</code> under
* <a>SecondaryStatusTransition</a>.</p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input
* mode. It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3
* location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* @see SecondaryStatus
*/
public String getSecondaryStatus() {
return this.secondaryStatus;
}
/**
* <p>
* Provides detailed information about the state of the training job. For detailed information on the secondary
* status of the training job, see <code>StatusMessage</code> under <a>SecondaryStatusTransition</a>.
* </p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input mode.
* It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3 location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* </ul>
*
* @param secondaryStatus
* Provides detailed information about the state of the training job. For detailed information on the
* secondary status of the training job, see <code>StatusMessage</code> under
* <a>SecondaryStatusTransition</a>.</p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input
* mode. It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3
* location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see SecondaryStatus
*/
public DescribeTrainingJobResult withSecondaryStatus(String secondaryStatus) {
setSecondaryStatus(secondaryStatus);
return this;
}
/**
* <p>
* Provides detailed information about the state of the training job. For detailed information on the secondary
* status of the training job, see <code>StatusMessage</code> under <a>SecondaryStatusTransition</a>.
* </p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input mode.
* It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3 location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* </ul>
*
* @param secondaryStatus
* Provides detailed information about the state of the training job. For detailed information on the
* secondary status of the training job, see <code>StatusMessage</code> under
* <a>SecondaryStatusTransition</a>.</p>
* <p>
* Amazon SageMaker provides primary statuses and secondary statuses that apply to each of them:
* </p>
* <dl>
* <dt>InProgress</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Starting</code> - Starting the training job.
* </p>
* </li>
* <li>
* <p>
* <code>Downloading</code> - An optional stage for algorithms that support <code>File</code> training input
* mode. It indicates that data is being downloaded to the ML storage volumes.
* </p>
* </li>
* <li>
* <p>
* <code>Training</code> - Training is in progress.
* </p>
* </li>
* <li>
* <p>
* <code>Uploading</code> - Training is complete and the model artifacts are being uploaded to the S3
* location.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Completed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Completed</code> - The training job has completed.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Failed</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Failed</code> - The training job has failed. The reason for the failure is returned in the
* <code>FailureReason</code> field of <code>DescribeTrainingJobResponse</code>.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopped</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>MaxRuntimeExceeded</code> - The job stopped because it exceeded the maximum allowed runtime.
* </p>
* </li>
* <li>
* <p>
* <code>MaxWaitTmeExceeded</code> - The job stopped because it exceeded the maximum allowed wait time.
* </p>
* </li>
* <li>
* <p>
* <code>Interrupted</code> - The job stopped because the managed spot training instances were interrupted.
* </p>
* </li>
* <li>
* <p>
* <code>Stopped</code> - The training job has stopped.
* </p>
* </li>
* </ul>
* </dd>
* <dt>Stopping</dt>
* <dd>
* <ul>
* <li>
* <p>
* <code>Stopping</code> - Stopping the training job.
* </p>
* </li>
* </ul>
* </dd>
* </dl>
* <important>
* <p>
* Valid values for <code>SecondaryStatus</code> are subject to change.
* </p>
* </important>
* <p>
* We no longer support the following secondary statuses:
* </p>
* <ul>
* <li>
* <p>
* <code>LaunchingMLInstances</code>
* </p>
* </li>
* <li>
* <p>
* <code>PreparingTrainingStack</code>
* </p>
* </li>
* <li>
* <p>
* <code>DownloadingTrainingImage</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see SecondaryStatus
*/
public DescribeTrainingJobResult withSecondaryStatus(SecondaryStatus secondaryStatus) {
this.secondaryStatus = secondaryStatus.toString();
return this;
}
/**
* <p>
* If the training job failed, the reason it failed.
* </p>
*
* @param failureReason
* If the training job failed, the reason it failed.
*/
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
/**
* <p>
* If the training job failed, the reason it failed.
* </p>
*
* @return If the training job failed, the reason it failed.
*/
public String getFailureReason() {
return this.failureReason;
}
/**
* <p>
* If the training job failed, the reason it failed.
* </p>
*
* @param failureReason
* If the training job failed, the reason it failed.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withFailureReason(String failureReason) {
setFailureReason(failureReason);
return this;
}
/**
* <p>
* Algorithm-specific parameters.
* </p>
*
* @return Algorithm-specific parameters.
*/
public java.util.Map<String, String> getHyperParameters() {
return hyperParameters;
}
/**
* <p>
* Algorithm-specific parameters.
* </p>
*
* @param hyperParameters
* Algorithm-specific parameters.
*/
public void setHyperParameters(java.util.Map<String, String> hyperParameters) {
this.hyperParameters = hyperParameters;
}
/**
* <p>
* Algorithm-specific parameters.
* </p>
*
* @param hyperParameters
* Algorithm-specific parameters.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withHyperParameters(java.util.Map<String, String> hyperParameters) {
setHyperParameters(hyperParameters);
return this;
}
public DescribeTrainingJobResult addHyperParametersEntry(String key, String value) {
if (null == this.hyperParameters) {
this.hyperParameters = new java.util.HashMap<String, String>();
}
if (this.hyperParameters.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.hyperParameters.put(key, value);
return this;
}
/**
* Removes all the entries added into HyperParameters.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult clearHyperParametersEntries() {
this.hyperParameters = null;
return this;
}
/**
* <p>
* Information about the algorithm used for training, and algorithm metadata.
* </p>
*
* @param algorithmSpecification
* Information about the algorithm used for training, and algorithm metadata.
*/
public void setAlgorithmSpecification(AlgorithmSpecification algorithmSpecification) {
this.algorithmSpecification = algorithmSpecification;
}
/**
* <p>
* Information about the algorithm used for training, and algorithm metadata.
* </p>
*
* @return Information about the algorithm used for training, and algorithm metadata.
*/
public AlgorithmSpecification getAlgorithmSpecification() {
return this.algorithmSpecification;
}
/**
* <p>
* Information about the algorithm used for training, and algorithm metadata.
* </p>
*
* @param algorithmSpecification
* Information about the algorithm used for training, and algorithm metadata.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withAlgorithmSpecification(AlgorithmSpecification algorithmSpecification) {
setAlgorithmSpecification(algorithmSpecification);
return this;
}
/**
* <p>
* The AWS Identity and Access Management (IAM) role configured for the training job.
* </p>
*
* @param roleArn
* The AWS Identity and Access Management (IAM) role configured for the training job.
*/
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
/**
* <p>
* The AWS Identity and Access Management (IAM) role configured for the training job.
* </p>
*
* @return The AWS Identity and Access Management (IAM) role configured for the training job.
*/
public String getRoleArn() {
return this.roleArn;
}
/**
* <p>
* The AWS Identity and Access Management (IAM) role configured for the training job.
* </p>
*
* @param roleArn
* The AWS Identity and Access Management (IAM) role configured for the training job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withRoleArn(String roleArn) {
setRoleArn(roleArn);
return this;
}
/**
* <p>
* An array of <code>Channel</code> objects that describes each data input channel.
* </p>
*
* @return An array of <code>Channel</code> objects that describes each data input channel.
*/
public java.util.List<Channel> getInputDataConfig() {
return inputDataConfig;
}
/**
* <p>
* An array of <code>Channel</code> objects that describes each data input channel.
* </p>
*
* @param inputDataConfig
* An array of <code>Channel</code> objects that describes each data input channel.
*/
public void setInputDataConfig(java.util.Collection<Channel> inputDataConfig) {
if (inputDataConfig == null) {
this.inputDataConfig = null;
return;
}
this.inputDataConfig = new java.util.ArrayList<Channel>(inputDataConfig);
}
/**
* <p>
* An array of <code>Channel</code> objects that describes each data input channel.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setInputDataConfig(java.util.Collection)} or {@link #withInputDataConfig(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param inputDataConfig
* An array of <code>Channel</code> objects that describes each data input channel.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withInputDataConfig(Channel... inputDataConfig) {
if (this.inputDataConfig == null) {
setInputDataConfig(new java.util.ArrayList<Channel>(inputDataConfig.length));
}
for (Channel ele : inputDataConfig) {
this.inputDataConfig.add(ele);
}
return this;
}
/**
* <p>
* An array of <code>Channel</code> objects that describes each data input channel.
* </p>
*
* @param inputDataConfig
* An array of <code>Channel</code> objects that describes each data input channel.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withInputDataConfig(java.util.Collection<Channel> inputDataConfig) {
setInputDataConfig(inputDataConfig);
return this;
}
/**
* <p>
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker creates
* subfolders for model artifacts.
* </p>
*
* @param outputDataConfig
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker
* creates subfolders for model artifacts.
*/
public void setOutputDataConfig(OutputDataConfig outputDataConfig) {
this.outputDataConfig = outputDataConfig;
}
/**
* <p>
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker creates
* subfolders for model artifacts.
* </p>
*
* @return The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker
* creates subfolders for model artifacts.
*/
public OutputDataConfig getOutputDataConfig() {
return this.outputDataConfig;
}
/**
* <p>
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker creates
* subfolders for model artifacts.
* </p>
*
* @param outputDataConfig
* The S3 path where model artifacts that you configured when creating the job are stored. Amazon SageMaker
* creates subfolders for model artifacts.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withOutputDataConfig(OutputDataConfig outputDataConfig) {
setOutputDataConfig(outputDataConfig);
return this;
}
/**
* <p>
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
* </p>
*
* @param resourceConfig
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
*/
public void setResourceConfig(ResourceConfig resourceConfig) {
this.resourceConfig = resourceConfig;
}
/**
* <p>
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
* </p>
*
* @return Resources, including ML compute instances and ML storage volumes, that are configured for model training.
*/
public ResourceConfig getResourceConfig() {
return this.resourceConfig;
}
/**
* <p>
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
* </p>
*
* @param resourceConfig
* Resources, including ML compute instances and ML storage volumes, that are configured for model training.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withResourceConfig(ResourceConfig resourceConfig) {
setResourceConfig(resourceConfig);
return this;
}
/**
* <p>
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more information, see
* <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training Jobs by Using an Amazon
* Virtual Private Cloud</a>.
* </p>
*
* @param vpcConfig
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more
* information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training
* Jobs by Using an Amazon Virtual Private Cloud</a>.
*/
public void setVpcConfig(VpcConfig vpcConfig) {
this.vpcConfig = vpcConfig;
}
/**
* <p>
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more information, see
* <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training Jobs by Using an Amazon
* Virtual Private Cloud</a>.
* </p>
*
* @return A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more
* information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect
* Training Jobs by Using an Amazon Virtual Private Cloud</a>.
*/
public VpcConfig getVpcConfig() {
return this.vpcConfig;
}
/**
* <p>
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more information, see
* <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training Jobs by Using an Amazon
* Virtual Private Cloud</a>.
* </p>
*
* @param vpcConfig
* A <a>VpcConfig</a> object that specifies the VPC that this training job has access to. For more
* information, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html">Protect Training
* Jobs by Using an Amazon Virtual Private Cloud</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withVpcConfig(VpcConfig vpcConfig) {
setVpcConfig(vpcConfig);
return this;
}
/**
* <p>
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for a spot
* instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API to cap model
* training costs.
* </p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job termination
* for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the results of
* training are not lost.
* </p>
*
* @param stoppingCondition
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for
* a spot instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API
* to cap model training costs.</p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job
* termination for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the
* results of training are not lost.
*/
public void setStoppingCondition(StoppingCondition stoppingCondition) {
this.stoppingCondition = stoppingCondition;
}
/**
* <p>
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for a spot
* instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API to cap model
* training costs.
* </p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job termination
* for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the results of
* training are not lost.
* </p>
*
* @return Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait
* for a spot instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use
* this API to cap model training costs.</p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job
* termination for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so
* the results of training are not lost.
*/
public StoppingCondition getStoppingCondition() {
return this.stoppingCondition;
}
/**
* <p>
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for a spot
* instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API to cap model
* training costs.
* </p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job termination
* for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the results of
* training are not lost.
* </p>
*
* @param stoppingCondition
* Specifies a limit to how long a model training job can run. It also specifies the maximum time to wait for
* a spot instance. When the job reaches the time limit, Amazon SageMaker ends the training job. Use this API
* to cap model training costs.</p>
* <p>
* To stop a job, Amazon SageMaker sends the algorithm the <code>SIGTERM</code> signal, which delays job
* termination for 120 seconds. Algorithms can use this 120-second window to save the model artifacts, so the
* results of training are not lost.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withStoppingCondition(StoppingCondition stoppingCondition) {
setStoppingCondition(stoppingCondition);
return this;
}
/**
* <p>
* A timestamp that indicates when the training job was created.
* </p>
*
* @param creationTime
* A timestamp that indicates when the training job was created.
*/
public void setCreationTime(java.util.Date creationTime) {
this.creationTime = creationTime;
}
/**
* <p>
* A timestamp that indicates when the training job was created.
* </p>
*
* @return A timestamp that indicates when the training job was created.
*/
public java.util.Date getCreationTime() {
return this.creationTime;
}
/**
* <p>
* A timestamp that indicates when the training job was created.
* </p>
*
* @param creationTime
* A timestamp that indicates when the training job was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withCreationTime(java.util.Date creationTime) {
setCreationTime(creationTime);
return this;
}
/**
* <p>
* Indicates the time when the training job starts on training instances. You are billed for the time interval
* between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch Logs might be later
* than this time. The difference is due to the time it takes to download the training data and to the size of the
* training container.
* </p>
*
* @param trainingStartTime
* Indicates the time when the training job starts on training instances. You are billed for the time
* interval between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch
* Logs might be later than this time. The difference is due to the time it takes to download the training
* data and to the size of the training container.
*/
public void setTrainingStartTime(java.util.Date trainingStartTime) {
this.trainingStartTime = trainingStartTime;
}
/**
* <p>
* Indicates the time when the training job starts on training instances. You are billed for the time interval
* between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch Logs might be later
* than this time. The difference is due to the time it takes to download the training data and to the size of the
* training container.
* </p>
*
* @return Indicates the time when the training job starts on training instances. You are billed for the time
* interval between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch
* Logs might be later than this time. The difference is due to the time it takes to download the training
* data and to the size of the training container.
*/
public java.util.Date getTrainingStartTime() {
return this.trainingStartTime;
}
/**
* <p>
* Indicates the time when the training job starts on training instances. You are billed for the time interval
* between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch Logs might be later
* than this time. The difference is due to the time it takes to download the training data and to the size of the
* training container.
* </p>
*
* @param trainingStartTime
* Indicates the time when the training job starts on training instances. You are billed for the time
* interval between this time and the value of <code>TrainingEndTime</code>. The start time in CloudWatch
* Logs might be later than this time. The difference is due to the time it takes to download the training
* data and to the size of the training container.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTrainingStartTime(java.util.Date trainingStartTime) {
setTrainingStartTime(trainingStartTime);
return this;
}
/**
* <p>
* Indicates the time when the training job ends on training instances. You are billed for the time interval between
* the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs, this is the time
* after model artifacts are uploaded. For failed jobs, this is the time when Amazon SageMaker detects a job
* failure.
* </p>
*
* @param trainingEndTime
* Indicates the time when the training job ends on training instances. You are billed for the time interval
* between the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs,
* this is the time after model artifacts are uploaded. For failed jobs, this is the time when Amazon
* SageMaker detects a job failure.
*/
public void setTrainingEndTime(java.util.Date trainingEndTime) {
this.trainingEndTime = trainingEndTime;
}
/**
* <p>
* Indicates the time when the training job ends on training instances. You are billed for the time interval between
* the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs, this is the time
* after model artifacts are uploaded. For failed jobs, this is the time when Amazon SageMaker detects a job
* failure.
* </p>
*
* @return Indicates the time when the training job ends on training instances. You are billed for the time interval
* between the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs,
* this is the time after model artifacts are uploaded. For failed jobs, this is the time when Amazon
* SageMaker detects a job failure.
*/
public java.util.Date getTrainingEndTime() {
return this.trainingEndTime;
}
/**
* <p>
* Indicates the time when the training job ends on training instances. You are billed for the time interval between
* the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs, this is the time
* after model artifacts are uploaded. For failed jobs, this is the time when Amazon SageMaker detects a job
* failure.
* </p>
*
* @param trainingEndTime
* Indicates the time when the training job ends on training instances. You are billed for the time interval
* between the value of <code>TrainingStartTime</code> and this time. For successful jobs and stopped jobs,
* this is the time after model artifacts are uploaded. For failed jobs, this is the time when Amazon
* SageMaker detects a job failure.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTrainingEndTime(java.util.Date trainingEndTime) {
setTrainingEndTime(trainingEndTime);
return this;
}
/**
* <p>
* A timestamp that indicates when the status of the training job was last modified.
* </p>
*
* @param lastModifiedTime
* A timestamp that indicates when the status of the training job was last modified.
*/
public void setLastModifiedTime(java.util.Date lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
}
/**
* <p>
* A timestamp that indicates when the status of the training job was last modified.
* </p>
*
* @return A timestamp that indicates when the status of the training job was last modified.
*/
public java.util.Date getLastModifiedTime() {
return this.lastModifiedTime;
}
/**
* <p>
* A timestamp that indicates when the status of the training job was last modified.
* </p>
*
* @param lastModifiedTime
* A timestamp that indicates when the status of the training job was last modified.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withLastModifiedTime(java.util.Date lastModifiedTime) {
setLastModifiedTime(lastModifiedTime);
return this;
}
/**
* <p>
* A history of all of the secondary statuses that the training job has transitioned through.
* </p>
*
* @return A history of all of the secondary statuses that the training job has transitioned through.
*/
public java.util.List<SecondaryStatusTransition> getSecondaryStatusTransitions() {
return secondaryStatusTransitions;
}
/**
* <p>
* A history of all of the secondary statuses that the training job has transitioned through.
* </p>
*
* @param secondaryStatusTransitions
* A history of all of the secondary statuses that the training job has transitioned through.
*/
public void setSecondaryStatusTransitions(java.util.Collection<SecondaryStatusTransition> secondaryStatusTransitions) {
if (secondaryStatusTransitions == null) {
this.secondaryStatusTransitions = null;
return;
}
this.secondaryStatusTransitions = new java.util.ArrayList<SecondaryStatusTransition>(secondaryStatusTransitions);
}
/**
* <p>
* A history of all of the secondary statuses that the training job has transitioned through.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSecondaryStatusTransitions(java.util.Collection)} or
* {@link #withSecondaryStatusTransitions(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param secondaryStatusTransitions
* A history of all of the secondary statuses that the training job has transitioned through.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withSecondaryStatusTransitions(SecondaryStatusTransition... secondaryStatusTransitions) {
if (this.secondaryStatusTransitions == null) {
setSecondaryStatusTransitions(new java.util.ArrayList<SecondaryStatusTransition>(secondaryStatusTransitions.length));
}
for (SecondaryStatusTransition ele : secondaryStatusTransitions) {
this.secondaryStatusTransitions.add(ele);
}
return this;
}
/**
* <p>
* A history of all of the secondary statuses that the training job has transitioned through.
* </p>
*
* @param secondaryStatusTransitions
* A history of all of the secondary statuses that the training job has transitioned through.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withSecondaryStatusTransitions(java.util.Collection<SecondaryStatusTransition> secondaryStatusTransitions) {
setSecondaryStatusTransitions(secondaryStatusTransitions);
return this;
}
/**
* <p>
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that the
* training algorithm emitted to Amazon CloudWatch.
* </p>
*
* @return A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that
* the training algorithm emitted to Amazon CloudWatch.
*/
public java.util.List<MetricData> getFinalMetricDataList() {
return finalMetricDataList;
}
/**
* <p>
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that the
* training algorithm emitted to Amazon CloudWatch.
* </p>
*
* @param finalMetricDataList
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that
* the training algorithm emitted to Amazon CloudWatch.
*/
public void setFinalMetricDataList(java.util.Collection<MetricData> finalMetricDataList) {
if (finalMetricDataList == null) {
this.finalMetricDataList = null;
return;
}
this.finalMetricDataList = new java.util.ArrayList<MetricData>(finalMetricDataList);
}
/**
* <p>
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that the
* training algorithm emitted to Amazon CloudWatch.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setFinalMetricDataList(java.util.Collection)} or {@link #withFinalMetricDataList(java.util.Collection)}
* if you want to override the existing values.
* </p>
*
* @param finalMetricDataList
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that
* the training algorithm emitted to Amazon CloudWatch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withFinalMetricDataList(MetricData... finalMetricDataList) {
if (this.finalMetricDataList == null) {
setFinalMetricDataList(new java.util.ArrayList<MetricData>(finalMetricDataList.length));
}
for (MetricData ele : finalMetricDataList) {
this.finalMetricDataList.add(ele);
}
return this;
}
/**
* <p>
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that the
* training algorithm emitted to Amazon CloudWatch.
* </p>
*
* @param finalMetricDataList
* A collection of <code>MetricData</code> objects that specify the names, values, and dates and times that
* the training algorithm emitted to Amazon CloudWatch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withFinalMetricDataList(java.util.Collection<MetricData> finalMetricDataList) {
setFinalMetricDataList(finalMetricDataList);
return this;
}
/**
* <p>
* If you want to allow inbound or outbound network calls, except for calls between peers within a training cluster
* for distributed training, choose <code>True</code>. If you enable network isolation for training jobs that are
* configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model artifacts through the
* specified VPC, but the training container does not have network access.
* </p>
* <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* </note>
*
* @param enableNetworkIsolation
* If you want to allow inbound or outbound network calls, except for calls between peers within a training
* cluster for distributed training, choose <code>True</code>. If you enable network isolation for training
* jobs that are configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model
* artifacts through the specified VPC, but the training container does not have network access.</p> <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
*/
public void setEnableNetworkIsolation(Boolean enableNetworkIsolation) {
this.enableNetworkIsolation = enableNetworkIsolation;
}
/**
* <p>
* If you want to allow inbound or outbound network calls, except for calls between peers within a training cluster
* for distributed training, choose <code>True</code>. If you enable network isolation for training jobs that are
* configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model artifacts through the
* specified VPC, but the training container does not have network access.
* </p>
* <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* </note>
*
* @return If you want to allow inbound or outbound network calls, except for calls between peers within a training
* cluster for distributed training, choose <code>True</code>. If you enable network isolation for training
* jobs that are configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model
* artifacts through the specified VPC, but the training container does not have network access.</p> <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
*/
public Boolean getEnableNetworkIsolation() {
return this.enableNetworkIsolation;
}
/**
* <p>
* If you want to allow inbound or outbound network calls, except for calls between peers within a training cluster
* for distributed training, choose <code>True</code>. If you enable network isolation for training jobs that are
* configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model artifacts through the
* specified VPC, but the training container does not have network access.
* </p>
* <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* </note>
*
* @param enableNetworkIsolation
* If you want to allow inbound or outbound network calls, except for calls between peers within a training
* cluster for distributed training, choose <code>True</code>. If you enable network isolation for training
* jobs that are configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model
* artifacts through the specified VPC, but the training container does not have network access.</p> <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withEnableNetworkIsolation(Boolean enableNetworkIsolation) {
setEnableNetworkIsolation(enableNetworkIsolation);
return this;
}
/**
* <p>
* If you want to allow inbound or outbound network calls, except for calls between peers within a training cluster
* for distributed training, choose <code>True</code>. If you enable network isolation for training jobs that are
* configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model artifacts through the
* specified VPC, but the training container does not have network access.
* </p>
* <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
* </note>
*
* @return If you want to allow inbound or outbound network calls, except for calls between peers within a training
* cluster for distributed training, choose <code>True</code>. If you enable network isolation for training
* jobs that are configured to use a VPC, Amazon SageMaker downloads and uploads customer data and model
* artifacts through the specified VPC, but the training container does not have network access.</p> <note>
* <p>
* The Semantic Segmentation built-in algorithm does not support network isolation.
* </p>
*/
public Boolean isEnableNetworkIsolation() {
return this.enableNetworkIsolation;
}
/**
* <p>
* To encrypt all communications between ML compute instances in distributed training, choose <code>True</code>.
* Encryption provides greater security for distributed training, but training might take longer. How long it takes
* depends on the amount of communication between compute instances, especially if you use a deep learning
* algorithms in distributed training.
* </p>
*
* @param enableInterContainerTrafficEncryption
* To encrypt all communications between ML compute instances in distributed training, choose
* <code>True</code>. Encryption provides greater security for distributed training, but training might take
* longer. How long it takes depends on the amount of communication between compute instances, especially if
* you use a deep learning algorithms in distributed training.
*/
public void setEnableInterContainerTrafficEncryption(Boolean enableInterContainerTrafficEncryption) {
this.enableInterContainerTrafficEncryption = enableInterContainerTrafficEncryption;
}
/**
* <p>
* To encrypt all communications between ML compute instances in distributed training, choose <code>True</code>.
* Encryption provides greater security for distributed training, but training might take longer. How long it takes
* depends on the amount of communication between compute instances, especially if you use a deep learning
* algorithms in distributed training.
* </p>
*
* @return To encrypt all communications between ML compute instances in distributed training, choose
* <code>True</code>. Encryption provides greater security for distributed training, but training might take
* longer. How long it takes depends on the amount of communication between compute instances, especially if
* you use a deep learning algorithms in distributed training.
*/
public Boolean getEnableInterContainerTrafficEncryption() {
return this.enableInterContainerTrafficEncryption;
}
/**
* <p>
* To encrypt all communications between ML compute instances in distributed training, choose <code>True</code>.
* Encryption provides greater security for distributed training, but training might take longer. How long it takes
* depends on the amount of communication between compute instances, especially if you use a deep learning
* algorithms in distributed training.
* </p>
*
* @param enableInterContainerTrafficEncryption
* To encrypt all communications between ML compute instances in distributed training, choose
* <code>True</code>. Encryption provides greater security for distributed training, but training might take
* longer. How long it takes depends on the amount of communication between compute instances, especially if
* you use a deep learning algorithms in distributed training.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withEnableInterContainerTrafficEncryption(Boolean enableInterContainerTrafficEncryption) {
setEnableInterContainerTrafficEncryption(enableInterContainerTrafficEncryption);
return this;
}
/**
* <p>
* To encrypt all communications between ML compute instances in distributed training, choose <code>True</code>.
* Encryption provides greater security for distributed training, but training might take longer. How long it takes
* depends on the amount of communication between compute instances, especially if you use a deep learning
* algorithms in distributed training.
* </p>
*
* @return To encrypt all communications between ML compute instances in distributed training, choose
* <code>True</code>. Encryption provides greater security for distributed training, but training might take
* longer. How long it takes depends on the amount of communication between compute instances, especially if
* you use a deep learning algorithms in distributed training.
*/
public Boolean isEnableInterContainerTrafficEncryption() {
return this.enableInterContainerTrafficEncryption;
}
/**
* <p>
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (<code>False</code>).
* </p>
*
* @param enableManagedSpotTraining
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (
* <code>False</code>).
*/
public void setEnableManagedSpotTraining(Boolean enableManagedSpotTraining) {
this.enableManagedSpotTraining = enableManagedSpotTraining;
}
/**
* <p>
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (<code>False</code>).
* </p>
*
* @return A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (
* <code>False</code>).
*/
public Boolean getEnableManagedSpotTraining() {
return this.enableManagedSpotTraining;
}
/**
* <p>
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (<code>False</code>).
* </p>
*
* @param enableManagedSpotTraining
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (
* <code>False</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withEnableManagedSpotTraining(Boolean enableManagedSpotTraining) {
setEnableManagedSpotTraining(enableManagedSpotTraining);
return this;
}
/**
* <p>
* A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (<code>False</code>).
* </p>
*
* @return A Boolean indicating whether managed spot training is enabled (<code>True</code>) or not (
* <code>False</code>).
*/
public Boolean isEnableManagedSpotTraining() {
return this.enableManagedSpotTraining;
}
/**
* @param checkpointConfig
*/
public void setCheckpointConfig(CheckpointConfig checkpointConfig) {
this.checkpointConfig = checkpointConfig;
}
/**
* @return
*/
public CheckpointConfig getCheckpointConfig() {
return this.checkpointConfig;
}
/**
* @param checkpointConfig
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withCheckpointConfig(CheckpointConfig checkpointConfig) {
setCheckpointConfig(checkpointConfig);
return this;
}
/**
* <p>
* The training time in seconds.
* </p>
*
* @param trainingTimeInSeconds
* The training time in seconds.
*/
public void setTrainingTimeInSeconds(Integer trainingTimeInSeconds) {
this.trainingTimeInSeconds = trainingTimeInSeconds;
}
/**
* <p>
* The training time in seconds.
* </p>
*
* @return The training time in seconds.
*/
public Integer getTrainingTimeInSeconds() {
return this.trainingTimeInSeconds;
}
/**
* <p>
* The training time in seconds.
* </p>
*
* @param trainingTimeInSeconds
* The training time in seconds.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withTrainingTimeInSeconds(Integer trainingTimeInSeconds) {
setTrainingTimeInSeconds(trainingTimeInSeconds);
return this;
}
/**
* <p>
* The billable time in seconds.
* </p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is 80%.
* </p>
*
* @param billableTimeInSeconds
* The billable time in seconds.</p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is
* 80%.
*/
public void setBillableTimeInSeconds(Integer billableTimeInSeconds) {
this.billableTimeInSeconds = billableTimeInSeconds;
}
/**
* <p>
* The billable time in seconds.
* </p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is 80%.
* </p>
*
* @return The billable time in seconds.</p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is
* 80%.
*/
public Integer getBillableTimeInSeconds() {
return this.billableTimeInSeconds;
}
/**
* <p>
* The billable time in seconds.
* </p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is 80%.
* </p>
*
* @param billableTimeInSeconds
* The billable time in seconds.</p>
* <p>
* You can calculate the savings from using managed spot training using the formula
* <code>(1 - BillableTimeInSeconds / TrainingTimeInSeconds) * 100</code>. For example, if
* <code>BillableTimeInSeconds</code> is 100 and <code>TrainingTimeInSeconds</code> is 500, the savings is
* 80%.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeTrainingJobResult withBillableTimeInSeconds(Integer billableTimeInSeconds) {
setBillableTimeInSeconds(billableTimeInSeconds);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTrainingJobName() != null)
sb.append("TrainingJobName: ").append(getTrainingJobName()).append(",");
if (getTrainingJobArn() != null)
sb.append("TrainingJobArn: ").append(getTrainingJobArn()).append(",");
if (getTuningJobArn() != null)
sb.append("TuningJobArn: ").append(getTuningJobArn()).append(",");
if (getLabelingJobArn() != null)
sb.append("LabelingJobArn: ").append(getLabelingJobArn()).append(",");
if (getModelArtifacts() != null)
sb.append("ModelArtifacts: ").append(getModelArtifacts()).append(",");
if (getTrainingJobStatus() != null)
sb.append("TrainingJobStatus: ").append(getTrainingJobStatus()).append(",");
if (getSecondaryStatus() != null)
sb.append("SecondaryStatus: ").append(getSecondaryStatus()).append(",");
if (getFailureReason() != null)
sb.append("FailureReason: ").append(getFailureReason()).append(",");
if (getHyperParameters() != null)
sb.append("HyperParameters: ").append(getHyperParameters()).append(",");
if (getAlgorithmSpecification() != null)
sb.append("AlgorithmSpecification: ").append(getAlgorithmSpecification()).append(",");
if (getRoleArn() != null)
sb.append("RoleArn: ").append(getRoleArn()).append(",");
if (getInputDataConfig() != null)
sb.append("InputDataConfig: ").append(getInputDataConfig()).append(",");
if (getOutputDataConfig() != null)
sb.append("OutputDataConfig: ").append(getOutputDataConfig()).append(",");
if (getResourceConfig() != null)
sb.append("ResourceConfig: ").append(getResourceConfig()).append(",");
if (getVpcConfig() != null)
sb.append("VpcConfig: ").append(getVpcConfig()).append(",");
if (getStoppingCondition() != null)
sb.append("StoppingCondition: ").append(getStoppingCondition()).append(",");
if (getCreationTime() != null)
sb.append("CreationTime: ").append(getCreationTime()).append(",");
if (getTrainingStartTime() != null)
sb.append("TrainingStartTime: ").append(getTrainingStartTime()).append(",");
if (getTrainingEndTime() != null)
sb.append("TrainingEndTime: ").append(getTrainingEndTime()).append(",");
if (getLastModifiedTime() != null)
sb.append("LastModifiedTime: ").append(getLastModifiedTime()).append(",");
if (getSecondaryStatusTransitions() != null)
sb.append("SecondaryStatusTransitions: ").append(getSecondaryStatusTransitions()).append(",");
if (getFinalMetricDataList() != null)
sb.append("FinalMetricDataList: ").append(getFinalMetricDataList()).append(",");
if (getEnableNetworkIsolation() != null)
sb.append("EnableNetworkIsolation: ").append(getEnableNetworkIsolation()).append(",");
if (getEnableInterContainerTrafficEncryption() != null)
sb.append("EnableInterContainerTrafficEncryption: ").append(getEnableInterContainerTrafficEncryption()).append(",");
if (getEnableManagedSpotTraining() != null)
sb.append("EnableManagedSpotTraining: ").append(getEnableManagedSpotTraining()).append(",");
if (getCheckpointConfig() != null)
sb.append("CheckpointConfig: ").append(getCheckpointConfig()).append(",");
if (getTrainingTimeInSeconds() != null)
sb.append("TrainingTimeInSeconds: ").append(getTrainingTimeInSeconds()).append(",");
if (getBillableTimeInSeconds() != null)
sb.append("BillableTimeInSeconds: ").append(getBillableTimeInSeconds());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeTrainingJobResult == false)
return false;
DescribeTrainingJobResult other = (DescribeTrainingJobResult) obj;
if (other.getTrainingJobName() == null ^ this.getTrainingJobName() == null)
return false;
if (other.getTrainingJobName() != null && other.getTrainingJobName().equals(this.getTrainingJobName()) == false)
return false;
if (other.getTrainingJobArn() == null ^ this.getTrainingJobArn() == null)
return false;
if (other.getTrainingJobArn() != null && other.getTrainingJobArn().equals(this.getTrainingJobArn()) == false)
return false;
if (other.getTuningJobArn() == null ^ this.getTuningJobArn() == null)
return false;
if (other.getTuningJobArn() != null && other.getTuningJobArn().equals(this.getTuningJobArn()) == false)
return false;
if (other.getLabelingJobArn() == null ^ this.getLabelingJobArn() == null)
return false;
if (other.getLabelingJobArn() != null && other.getLabelingJobArn().equals(this.getLabelingJobArn()) == false)
return false;
if (other.getModelArtifacts() == null ^ this.getModelArtifacts() == null)
return false;
if (other.getModelArtifacts() != null && other.getModelArtifacts().equals(this.getModelArtifacts()) == false)
return false;
if (other.getTrainingJobStatus() == null ^ this.getTrainingJobStatus() == null)
return false;
if (other.getTrainingJobStatus() != null && other.getTrainingJobStatus().equals(this.getTrainingJobStatus()) == false)
return false;
if (other.getSecondaryStatus() == null ^ this.getSecondaryStatus() == null)
return false;
if (other.getSecondaryStatus() != null && other.getSecondaryStatus().equals(this.getSecondaryStatus()) == false)
return false;
if (other.getFailureReason() == null ^ this.getFailureReason() == null)
return false;
if (other.getFailureReason() != null && other.getFailureReason().equals(this.getFailureReason()) == false)
return false;
if (other.getHyperParameters() == null ^ this.getHyperParameters() == null)
return false;
if (other.getHyperParameters() != null && other.getHyperParameters().equals(this.getHyperParameters()) == false)
return false;
if (other.getAlgorithmSpecification() == null ^ this.getAlgorithmSpecification() == null)
return false;
if (other.getAlgorithmSpecification() != null && other.getAlgorithmSpecification().equals(this.getAlgorithmSpecification()) == false)
return false;
if (other.getRoleArn() == null ^ this.getRoleArn() == null)
return false;
if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false)
return false;
if (other.getInputDataConfig() == null ^ this.getInputDataConfig() == null)
return false;
if (other.getInputDataConfig() != null && other.getInputDataConfig().equals(this.getInputDataConfig()) == false)
return false;
if (other.getOutputDataConfig() == null ^ this.getOutputDataConfig() == null)
return false;
if (other.getOutputDataConfig() != null && other.getOutputDataConfig().equals(this.getOutputDataConfig()) == false)
return false;
if (other.getResourceConfig() == null ^ this.getResourceConfig() == null)
return false;
if (other.getResourceConfig() != null && other.getResourceConfig().equals(this.getResourceConfig()) == false)
return false;
if (other.getVpcConfig() == null ^ this.getVpcConfig() == null)
return false;
if (other.getVpcConfig() != null && other.getVpcConfig().equals(this.getVpcConfig()) == false)
return false;
if (other.getStoppingCondition() == null ^ this.getStoppingCondition() == null)
return false;
if (other.getStoppingCondition() != null && other.getStoppingCondition().equals(this.getStoppingCondition()) == false)
return false;
if (other.getCreationTime() == null ^ this.getCreationTime() == null)
return false;
if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false)
return false;
if (other.getTrainingStartTime() == null ^ this.getTrainingStartTime() == null)
return false;
if (other.getTrainingStartTime() != null && other.getTrainingStartTime().equals(this.getTrainingStartTime()) == false)
return false;
if (other.getTrainingEndTime() == null ^ this.getTrainingEndTime() == null)
return false;
if (other.getTrainingEndTime() != null && other.getTrainingEndTime().equals(this.getTrainingEndTime()) == false)
return false;
if (other.getLastModifiedTime() == null ^ this.getLastModifiedTime() == null)
return false;
if (other.getLastModifiedTime() != null && other.getLastModifiedTime().equals(this.getLastModifiedTime()) == false)
return false;
if (other.getSecondaryStatusTransitions() == null ^ this.getSecondaryStatusTransitions() == null)
return false;
if (other.getSecondaryStatusTransitions() != null && other.getSecondaryStatusTransitions().equals(this.getSecondaryStatusTransitions()) == false)
return false;
if (other.getFinalMetricDataList() == null ^ this.getFinalMetricDataList() == null)
return false;
if (other.getFinalMetricDataList() != null && other.getFinalMetricDataList().equals(this.getFinalMetricDataList()) == false)
return false;
if (other.getEnableNetworkIsolation() == null ^ this.getEnableNetworkIsolation() == null)
return false;
if (other.getEnableNetworkIsolation() != null && other.getEnableNetworkIsolation().equals(this.getEnableNetworkIsolation()) == false)
return false;
if (other.getEnableInterContainerTrafficEncryption() == null ^ this.getEnableInterContainerTrafficEncryption() == null)
return false;
if (other.getEnableInterContainerTrafficEncryption() != null
&& other.getEnableInterContainerTrafficEncryption().equals(this.getEnableInterContainerTrafficEncryption()) == false)
return false;
if (other.getEnableManagedSpotTraining() == null ^ this.getEnableManagedSpotTraining() == null)
return false;
if (other.getEnableManagedSpotTraining() != null && other.getEnableManagedSpotTraining().equals(this.getEnableManagedSpotTraining()) == false)
return false;
if (other.getCheckpointConfig() == null ^ this.getCheckpointConfig() == null)
return false;
if (other.getCheckpointConfig() != null && other.getCheckpointConfig().equals(this.getCheckpointConfig()) == false)
return false;
if (other.getTrainingTimeInSeconds() == null ^ this.getTrainingTimeInSeconds() == null)
return false;
if (other.getTrainingTimeInSeconds() != null && other.getTrainingTimeInSeconds().equals(this.getTrainingTimeInSeconds()) == false)
return false;
if (other.getBillableTimeInSeconds() == null ^ this.getBillableTimeInSeconds() == null)
return false;
if (other.getBillableTimeInSeconds() != null && other.getBillableTimeInSeconds().equals(this.getBillableTimeInSeconds()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTrainingJobName() == null) ? 0 : getTrainingJobName().hashCode());
hashCode = prime * hashCode + ((getTrainingJobArn() == null) ? 0 : getTrainingJobArn().hashCode());
hashCode = prime * hashCode + ((getTuningJobArn() == null) ? 0 : getTuningJobArn().hashCode());
hashCode = prime * hashCode + ((getLabelingJobArn() == null) ? 0 : getLabelingJobArn().hashCode());
hashCode = prime * hashCode + ((getModelArtifacts() == null) ? 0 : getModelArtifacts().hashCode());
hashCode = prime * hashCode + ((getTrainingJobStatus() == null) ? 0 : getTrainingJobStatus().hashCode());
hashCode = prime * hashCode + ((getSecondaryStatus() == null) ? 0 : getSecondaryStatus().hashCode());
hashCode = prime * hashCode + ((getFailureReason() == null) ? 0 : getFailureReason().hashCode());
hashCode = prime * hashCode + ((getHyperParameters() == null) ? 0 : getHyperParameters().hashCode());
hashCode = prime * hashCode + ((getAlgorithmSpecification() == null) ? 0 : getAlgorithmSpecification().hashCode());
hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode());
hashCode = prime * hashCode + ((getInputDataConfig() == null) ? 0 : getInputDataConfig().hashCode());
hashCode = prime * hashCode + ((getOutputDataConfig() == null) ? 0 : getOutputDataConfig().hashCode());
hashCode = prime * hashCode + ((getResourceConfig() == null) ? 0 : getResourceConfig().hashCode());
hashCode = prime * hashCode + ((getVpcConfig() == null) ? 0 : getVpcConfig().hashCode());
hashCode = prime * hashCode + ((getStoppingCondition() == null) ? 0 : getStoppingCondition().hashCode());
hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode());
hashCode = prime * hashCode + ((getTrainingStartTime() == null) ? 0 : getTrainingStartTime().hashCode());
hashCode = prime * hashCode + ((getTrainingEndTime() == null) ? 0 : getTrainingEndTime().hashCode());
hashCode = prime * hashCode + ((getLastModifiedTime() == null) ? 0 : getLastModifiedTime().hashCode());
hashCode = prime * hashCode + ((getSecondaryStatusTransitions() == null) ? 0 : getSecondaryStatusTransitions().hashCode());
hashCode = prime * hashCode + ((getFinalMetricDataList() == null) ? 0 : getFinalMetricDataList().hashCode());
hashCode = prime * hashCode + ((getEnableNetworkIsolation() == null) ? 0 : getEnableNetworkIsolation().hashCode());
hashCode = prime * hashCode + ((getEnableInterContainerTrafficEncryption() == null) ? 0 : getEnableInterContainerTrafficEncryption().hashCode());
hashCode = prime * hashCode + ((getEnableManagedSpotTraining() == null) ? 0 : getEnableManagedSpotTraining().hashCode());
hashCode = prime * hashCode + ((getCheckpointConfig() == null) ? 0 : getCheckpointConfig().hashCode());
hashCode = prime * hashCode + ((getTrainingTimeInSeconds() == null) ? 0 : getTrainingTimeInSeconds().hashCode());
hashCode = prime * hashCode + ((getBillableTimeInSeconds() == null) ? 0 : getBillableTimeInSeconds().hashCode());
return hashCode;
}
@Override
public DescribeTrainingJobResult clone() {
try {
return (DescribeTrainingJobResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
neo4j/neo4j-java-driver | driver/src/test/java/org/neo4j/driver/internal/value/FloatValueTest.java | 3734 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.driver.internal.value;
import org.junit.jupiter.api.Test;
import org.neo4j.driver.internal.types.InternalTypeSystem;
import org.neo4j.driver.internal.types.TypeConstructor;
import org.neo4j.driver.Value;
import org.neo4j.driver.exceptions.value.LossyCoercion;
import org.neo4j.driver.types.TypeSystem;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.junit.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FloatValueTest
{
private TypeSystem typeSystem = InternalTypeSystem.TYPE_SYSTEM;
@Test
void testZeroFloatValue()
{
// Given
FloatValue value = new FloatValue( 0 );
// Then
assertThat( value.asInt(), equalTo( 0 ) );
assertThat( value.asLong(), equalTo( 0L ) );
assertThat( value.asFloat(), equalTo( (float) 0.0 ) );
assertThat( value.asDouble(), equalTo( 0.0 ) );
}
@Test
void testNonZeroFloatValue()
{
// Given
FloatValue value = new FloatValue( 6.28 );
// Then
assertThat( value.asDouble(), equalTo( 6.28 ) );
}
@Test
void testIsFloat()
{
// Given
FloatValue value = new FloatValue( 6.28 );
// Then
assertThat( typeSystem.FLOAT().isTypeOf( value ), equalTo( true ) );
}
@Test
void testEquals()
{
// Given
FloatValue firstValue = new FloatValue( 6.28 );
FloatValue secondValue = new FloatValue( 6.28 );
// Then
assertThat( firstValue, equalTo( secondValue ) );
}
@Test
void testHashCode()
{
// Given
FloatValue value = new FloatValue( 6.28 );
// Then
assertThat( value.hashCode(), notNullValue() );
}
@Test
void shouldNotBeNull()
{
Value value = new FloatValue( 6.28 );
assertFalse( value.isNull() );
}
@Test
void shouldTypeAsFloat()
{
InternalValue value = new FloatValue( 6.28 );
assertThat( value.typeConstructor(), equalTo( TypeConstructor.FLOAT ) );
}
@Test
void shouldThrowIfFloatContainsDecimalWhenConverting()
{
FloatValue value = new FloatValue( 1.1 );
assertThrows( LossyCoercion.class, value::asInt );
}
@Test
void shouldThrowIfLargerThanIntegerMax()
{
FloatValue value1 = new FloatValue( Integer.MAX_VALUE );
FloatValue value2 = new FloatValue( Integer.MAX_VALUE + 1L);
assertThat(value1.asInt(), equalTo(Integer.MAX_VALUE));
assertThrows( LossyCoercion.class, value2::asInt );
}
@Test
void shouldThrowIfSmallerThanIntegerMin()
{
FloatValue value1 = new FloatValue( Integer.MIN_VALUE );
FloatValue value2 = new FloatValue( Integer.MIN_VALUE - 1L );
assertThat(value1.asInt(), equalTo(Integer.MIN_VALUE));
assertThrows( LossyCoercion.class, value2::asInt );
}
}
| apache-2.0 |
bckfnn/taggersty | vertx/src/main/java/io/github/bckfnn/taggersty/vertx/HandlerOutput.java | 1613 | /*
* Copyright 2016 Finn Bock
*
* 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.github.bckfnn.taggersty.vertx;
import java.nio.charset.Charset;
import io.github.bckfnn.taggersty.TagsOutput;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
public class HandlerOutput implements TagsOutput {
private final Buffer buffer = Buffer.buffer();
private final Handler<Buffer> handler;
private final Charset charset;
public HandlerOutput(Handler<Buffer> handler, Charset charset) {
this.handler = handler;
this.charset = charset;
}
@Override
public void write(String s) {
buffer.appendBytes(s.getBytes(charset));
}
@Override
public void write(char[] s) {
for (int i = 0; i < s.length; i++) {
buffer.appendByte((byte) s[i]);
}
}
@Override
public void write(char c) {
buffer.appendByte((byte) c);
}
@Override
public void flush() {
handler.handle(buffer);
}
@Override
public void close() {
handler.handle(buffer);
}
}
| apache-2.0 |
apache/axis2-java | modules/transport/http/test/org/apache/axis2/transport/http/HTTPClient4TransportSenderTest.java | 1861 | /*
* 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.axis2.transport.http;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.TransportSender;
import org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender;
import org.apache.http.client.methods.HttpGet;
public class HTTPClient4TransportSenderTest extends CommonsHTTPTransportSenderTest{
@Override
protected TransportSender getTransportSender() {
return new HTTPClient4TransportSender();
}
public void testCleanup() throws AxisFault {
TransportSender sender = getTransportSender();
MessageContext msgContext = new MessageContext();
HttpGet httpMethod = new HttpGet();
msgContext.setProperty(HTTPConstants.HTTP_METHOD, httpMethod);
assertNotNull("HttpMethod can not be null",
msgContext.getProperty(HTTPConstants.HTTP_METHOD));
sender.cleanup(msgContext);
assertNull("HttpMethod should be null", msgContext.getProperty(HTTPConstants.HTTP_METHOD));
}
}
| apache-2.0 |
paulstapleton/flowable-engine | modules/flowable-task-service/src/main/java/org/flowable/task/service/TaskServiceConfiguration.java | 12672 | /* 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.task.service;
import java.util.List;
import java.util.Map;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.AbstractServiceConfiguration;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.task.api.TaskQueryInterceptor;
import org.flowable.task.api.history.HistoricTaskQueryInterceptor;
import org.flowable.task.service.history.InternalHistoryTaskManager;
import org.flowable.task.service.impl.HistoricTaskServiceImpl;
import org.flowable.task.service.impl.TaskServiceImpl;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntityManager;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntityManagerImpl;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityManager;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityManagerImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntityManager;
import org.flowable.task.service.impl.persistence.entity.TaskEntityManagerImpl;
import org.flowable.task.service.impl.persistence.entity.data.HistoricTaskInstanceDataManager;
import org.flowable.task.service.impl.persistence.entity.data.HistoricTaskLogEntryDataManager;
import org.flowable.task.service.impl.persistence.entity.data.TaskDataManager;
import org.flowable.task.service.impl.persistence.entity.data.impl.MyBatisHistoricTaskLogEntryDataManager;
import org.flowable.task.service.impl.persistence.entity.data.impl.MybatisHistoricTaskInstanceDataManager;
import org.flowable.task.service.impl.persistence.entity.data.impl.MybatisTaskDataManager;
public class TaskServiceConfiguration extends AbstractServiceConfiguration {
public static final String DEFAULT_MYBATIS_MAPPING_FILE = "org/flowable/task/service/db/mapping/mappings.xml";
// SERVICES
// /////////////////////////////////////////////////////////////////
protected TaskService taskService = new TaskServiceImpl(this);
protected HistoricTaskService historicTaskService = new HistoricTaskServiceImpl(this);
protected IdmIdentityService idmIdentityService;
// DATA MANAGERS ///////////////////////////////////////////////////
protected TaskDataManager taskDataManager;
protected HistoricTaskInstanceDataManager historicTaskInstanceDataManager;
protected HistoricTaskLogEntryDataManager historicTaskLogDataManager;
// ENTITY MANAGERS /////////////////////////////////////////////////
protected TaskEntityManager taskEntityManager;
protected HistoricTaskInstanceEntityManager historicTaskInstanceEntityManager;
protected HistoricTaskLogEntryEntityManager historicTaskLogEntryEntityManager;
protected InternalTaskVariableScopeResolver internalTaskVariableScopeResolver;
protected InternalHistoryTaskManager internalHistoryTaskManager;
protected InternalTaskLocalizationManager internalTaskLocalizationManager;
protected InternalTaskAssignmentManager internalTaskAssignmentManager;
protected boolean enableTaskRelationshipCounts;
protected boolean enableLocalization;
protected TaskQueryInterceptor taskQueryInterceptor;
protected HistoricTaskQueryInterceptor historicTaskQueryInterceptor;
protected int taskQueryLimit;
protected int historicTaskQueryLimit;
protected TaskPostProcessor taskPostProcessor;
// Events
protected boolean enableHistoricTaskLogging;
public TaskServiceConfiguration(String engineName) {
super(engineName);
}
// init
// /////////////////////////////////////////////////////////////////////
public void init() {
initDataManagers();
initEntityManagers();
initTaskPostProcessor();
}
// Data managers
///////////////////////////////////////////////////////////
public void initDataManagers() {
if (taskDataManager == null) {
taskDataManager = new MybatisTaskDataManager(this);
}
if (historicTaskInstanceDataManager == null) {
historicTaskInstanceDataManager = new MybatisHistoricTaskInstanceDataManager(this);
}
if (historicTaskLogDataManager == null) {
historicTaskLogDataManager = new MyBatisHistoricTaskLogEntryDataManager(this);
}
}
public void initEntityManagers() {
if (taskEntityManager == null) {
taskEntityManager = new TaskEntityManagerImpl(this, taskDataManager);
}
if (historicTaskInstanceEntityManager == null) {
historicTaskInstanceEntityManager = new HistoricTaskInstanceEntityManagerImpl(this, historicTaskInstanceDataManager);
}
if (historicTaskLogEntryEntityManager == null) {
historicTaskLogEntryEntityManager = new HistoricTaskLogEntryEntityManagerImpl(this, historicTaskLogDataManager);
}
}
public void initTaskPostProcessor() {
if (taskPostProcessor == null) {
taskPostProcessor = taskBuilder -> taskBuilder;
}
}
public TaskService getTaskService() {
return taskService;
}
public TaskServiceConfiguration setTaskService(TaskService taskService) {
this.taskService = taskService;
return this;
}
public HistoricTaskService getHistoricTaskService() {
return historicTaskService;
}
public TaskServiceConfiguration setHistoricTaskService(HistoricTaskService historicTaskService) {
this.historicTaskService = historicTaskService;
return this;
}
public IdmIdentityService getIdmIdentityService() {
return idmIdentityService;
}
public void setIdmIdentityService(IdmIdentityService idmIdentityService) {
this.idmIdentityService = idmIdentityService;
}
public TaskServiceConfiguration getTaskServiceConfiguration() {
return this;
}
public TaskDataManager getTaskDataManager() {
return taskDataManager;
}
public TaskServiceConfiguration setTaskDataManager(TaskDataManager taskDataManager) {
this.taskDataManager = taskDataManager;
return this;
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return historicTaskInstanceDataManager;
}
public TaskServiceConfiguration setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.historicTaskInstanceDataManager = historicTaskInstanceDataManager;
return this;
}
public TaskEntityManager getTaskEntityManager() {
return taskEntityManager;
}
public TaskServiceConfiguration setTaskEntityManager(TaskEntityManager taskEntityManager) {
this.taskEntityManager = taskEntityManager;
return this;
}
public HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return historicTaskInstanceEntityManager;
}
public TaskServiceConfiguration setHistoricTaskInstanceEntityManager(HistoricTaskInstanceEntityManager historicTaskInstanceEntityManager) {
this.historicTaskInstanceEntityManager = historicTaskInstanceEntityManager;
return this;
}
public HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() {
return historicTaskLogEntryEntityManager;
}
public TaskServiceConfiguration setHistoricTaskLogEntryEntityManager(HistoricTaskLogEntryEntityManager historicTaskLogEntryEntityManager) {
this.historicTaskLogEntryEntityManager = historicTaskLogEntryEntityManager;
return this;
}
public InternalTaskVariableScopeResolver getInternalTaskVariableScopeResolver() {
return internalTaskVariableScopeResolver;
}
public void setInternalTaskVariableScopeResolver(InternalTaskVariableScopeResolver internalTaskVariableScopeResolver) {
this.internalTaskVariableScopeResolver = internalTaskVariableScopeResolver;
}
public InternalHistoryTaskManager getInternalHistoryTaskManager() {
return internalHistoryTaskManager;
}
public void setInternalHistoryTaskManager(InternalHistoryTaskManager internalHistoryTaskManager) {
this.internalHistoryTaskManager = internalHistoryTaskManager;
}
public InternalTaskLocalizationManager getInternalTaskLocalizationManager() {
return internalTaskLocalizationManager;
}
public void setInternalTaskLocalizationManager(InternalTaskLocalizationManager internalTaskLocalizationManager) {
this.internalTaskLocalizationManager = internalTaskLocalizationManager;
}
public InternalTaskAssignmentManager getInternalTaskAssignmentManager() {
return internalTaskAssignmentManager;
}
public void setInternalTaskAssignmentManager(InternalTaskAssignmentManager internalTaskAssignmentManager) {
this.internalTaskAssignmentManager = internalTaskAssignmentManager;
}
public boolean isEnableTaskRelationshipCounts() {
return enableTaskRelationshipCounts;
}
public TaskServiceConfiguration setEnableTaskRelationshipCounts(boolean enableTaskRelationshipCounts) {
this.enableTaskRelationshipCounts = enableTaskRelationshipCounts;
return this;
}
public boolean isEnableLocalization() {
return enableLocalization;
}
public TaskServiceConfiguration setEnableLocalization(boolean enableLocalization) {
this.enableLocalization = enableLocalization;
return this;
}
public TaskQueryInterceptor getTaskQueryInterceptor() {
return taskQueryInterceptor;
}
public TaskServiceConfiguration setTaskQueryInterceptor(TaskQueryInterceptor taskQueryInterceptor) {
this.taskQueryInterceptor = taskQueryInterceptor;
return this;
}
public HistoricTaskQueryInterceptor getHistoricTaskQueryInterceptor() {
return historicTaskQueryInterceptor;
}
public TaskServiceConfiguration setHistoricTaskQueryInterceptor(HistoricTaskQueryInterceptor historicTaskQueryInterceptor) {
this.historicTaskQueryInterceptor = historicTaskQueryInterceptor;
return this;
}
public int getTaskQueryLimit() {
return taskQueryLimit;
}
public TaskServiceConfiguration setTaskQueryLimit(int taskQueryLimit) {
this.taskQueryLimit = taskQueryLimit;
return this;
}
public int getHistoricTaskQueryLimit() {
return historicTaskQueryLimit;
}
public TaskServiceConfiguration setHistoricTaskQueryLimit(int historicTaskQueryLimit) {
this.historicTaskQueryLimit = historicTaskQueryLimit;
return this;
}
public boolean isEnableHistoricTaskLogging() {
return enableHistoricTaskLogging;
}
public TaskServiceConfiguration setEnableHistoricTaskLogging(boolean enableHistoricTaskLogging) {
this.enableHistoricTaskLogging = enableHistoricTaskLogging;
return this;
}
@Override
public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
@Override
public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
@Override
public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
@Override
public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
public TaskPostProcessor getTaskPostProcessor() {
return taskPostProcessor;
}
public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) {
this.taskPostProcessor = processor;
return this;
}
}
| apache-2.0 |
tinyvampirepudge/Android_Basis_Demo | Android_Basis_Demo/refresh-layout/src/main/java/com/scwang/smartrefresh/layout/api/RefreshContent.java | 1104 | package com.scwang.smartrefresh.layout.api;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
/**
* 刷新内容组件
* Created by SCWANG on 2017/5/26.
*/
public interface RefreshContent {
void moveSpinner(int spinner);
boolean canRefresh();
boolean canLoadmore();
int getMeasuredWidth();
int getMeasuredHeight();
void measure(int widthSpec, int heightSpec);
void layout(int left, int top, int right, int bottom);
View getView();
View getScrollableView();
ViewGroup.LayoutParams getLayoutParams();
void onActionDown(MotionEvent e);
void onActionUpOrCancel();
void fling(int velocity);
void setUpComponent(RefreshKernel kernel, View fixedHeader, View fixedFooter);
void onInitialHeaderAndFooter(int headerHeight, int footerHeight);
void setScrollBoundaryDecider(ScrollBoundaryDecider boundary);
void setEnableLoadmoreWhenContentNotFull(boolean enable);
AnimatorUpdateListener scrollContentWhenFinished(int spinner);
}
| apache-2.0 |
bluelotussoftware/java-bootcamp | OCA/lesson03/src/main/java/arrays/ArrayTester.java | 3269 | /*
* Copyright 2010 Blue Lotus Software, LLC.
* Copyright 2008-2010 John Yeary <jyeary@bluelotussoftware.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.
* under the License.
*/
/*
* $Id: ArrayTester.java 4 2011-01-10 20:34:25Z jyeary $
*/
package arrays;
import java.util.Arrays;
/**
*
* @author John Yeary
* @version 1.0
*/
public class ArrayTester {
private int[] ints = new int[10];
private String[] strings = new String[10];
public void intPrinter() {
int[] x;
x = new int[10];
System.out.print(Arrays.toString(x));
}
public static void main(String... args) {
ArrayTester arrayTester = new ArrayTester();
System.out.println(Arrays.toString(arrayTester.ints));
System.out.println("~~~~~~~~~~~~~~");
System.out.print(Arrays.toString(arrayTester.strings));
System.out.println("\n~~~~~~~~~~~~~~");
arrayTester.intPrinter();
System.out.println("\n~~~~~~~~~~~~~~");
double[] doubles;
//Will not compile
// System.out.println(Arrays.toString(doubles));
// Local arrays are automatically assigned default values
double[] doubleCheck = new double[3];
int k = 0;
for (double d : doubleCheck) {
System.out.println("d[" + k+++ "] == " + d); // What kind of syntax is this?
}
System.out.println("~~~~~~~~~~~~~~");
Object objects[] = new Object[3];
for (Object o : objects) {
System.out.println("o[" + k--+ "] == " + o);
}
int[][] vals = new int[10][]; // Legal
vals[0] = new int[2];
vals[0][0] = 100;
vals[0][1] = 101;
Object[][][][] defined = new Object[5][4][3][2];
Object[][][][] noObjecto = new Object[5][][][];
// initialization and assignment
int[] puzzles = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int[][] puzzlers = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}, {0}};
Number[] numbers = new Number[7];
numbers[0] = new Byte((byte) 16);
numbers[1] = new Short((short) 32);
numbers[3] = new Integer(1024);
numbers[4] = new Long(2048L);
numbers[5] = new Float(1F);
numbers[6] = new Double(2.0);
System.out.println(Arrays.toString(numbers)); // What do we expect here?
Comparable[] comparables = new Comparable[3];
comparables[0] = "Hello World";
comparables[1] = new Integer(99);
comparables[2] = new Comparable() { // Is this legal?
public int compareTo(Object o) {
if (this.equals(o)) {
return 0;
} else {
return -1;
}
}
};
}
}
| apache-2.0 |
JingchengDu/hbase | hbase-rest/src/test/java/org/apache/hadoop/hbase/rest/RowResourceBase.java | 25576 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.rest;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.rest.client.Client;
import org.apache.hadoop.hbase.rest.client.Cluster;
import org.apache.hadoop.hbase.rest.client.Response;
import org.apache.hadoop.hbase.rest.model.CellModel;
import org.apache.hadoop.hbase.rest.model.CellSetModel;
import org.apache.hadoop.hbase.rest.model.RowModel;
import org.apache.hadoop.hbase.util.Bytes;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
public class RowResourceBase {
protected static final String TABLE = "TestRowResource";
protected static final TableName TABLE_NAME = TableName.valueOf(TABLE);
protected static final String CFA = "a";
protected static final String CFB = "b";
protected static final String COLUMN_1 = CFA + ":1";
protected static final String COLUMN_2 = CFB + ":2";
protected static final String COLUMN_3 = CFA + ":";
protected static final String ROW_1 = "testrow1";
protected static final String VALUE_1 = "testvalue1";
protected static final String ROW_2 = "testrow2";
protected static final String VALUE_2 = "testvalue2";
protected static final String ROW_3 = "testrow3";
protected static final String VALUE_3 = "testvalue3";
protected static final String ROW_4 = "testrow4";
protected static final String VALUE_4 = "testvalue4";
protected static final String VALUE_5 = "5";
protected static final String VALUE_6 = "6";
protected static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
protected static final HBaseRESTTestingUtility REST_TEST_UTIL =
new HBaseRESTTestingUtility();
protected static Client client;
protected static JAXBContext context;
protected static Marshaller xmlMarshaller;
protected static Unmarshaller xmlUnmarshaller;
protected static Configuration conf;
protected static ObjectMapper jsonMapper;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
conf = TEST_UTIL.getConfiguration();
TEST_UTIL.startMiniCluster(3);
REST_TEST_UTIL.startServletContainer(conf);
context = JAXBContext.newInstance(
CellModel.class,
CellSetModel.class,
RowModel.class);
xmlMarshaller = context.createMarshaller();
xmlUnmarshaller = context.createUnmarshaller();
jsonMapper = new JacksonJaxbJsonProvider()
.locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE);
client = new Client(new Cluster().add("localhost",
REST_TEST_UTIL.getServletPort()));
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
REST_TEST_UTIL.shutdownServletContainer();
TEST_UTIL.shutdownMiniCluster();
}
@Before
public void beforeMethod() throws Exception {
Admin admin = TEST_UTIL.getAdmin();
if (admin.tableExists(TABLE_NAME)) {
TEST_UTIL.deleteTable(TABLE_NAME);
}
HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(TABLE));
htd.addFamily(new HColumnDescriptor(CFA));
htd.addFamily(new HColumnDescriptor(CFB));
admin.createTable(htd);
}
@After
public void afterMethod() throws Exception {
Admin admin = TEST_UTIL.getAdmin();
if (admin.tableExists(TABLE_NAME)) {
TEST_UTIL.deleteTable(TABLE_NAME);
}
}
static Response putValuePB(String table, String row, String column,
String value) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return putValuePB(path.toString(), table, row, column, value);
}
static Response putValuePB(String url, String table, String row,
String column, String value) throws IOException {
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(value)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
Response response = client.put(url, Constants.MIMETYPE_PROTOBUF,
cellSetModel.createProtobufOutput());
Thread.yield();
return response;
}
protected static void checkValueXML(String url, String table, String row,
String column, String value) throws IOException, JAXBException {
Response response = getValueXML(url);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
CellSetModel cellSet = (CellSetModel)
xmlUnmarshaller.unmarshal(new ByteArrayInputStream(response.getBody()));
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
protected static void checkValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
Response response = getValueXML(table, row, column);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
CellSetModel cellSet = (CellSetModel)
xmlUnmarshaller.unmarshal(new ByteArrayInputStream(response.getBody()));
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
protected static void checkIncrementValueXML(String table, String row, String column,
long value) throws IOException, JAXBException {
Response response1 = getValueXML(table, row, column);
assertEquals(response1.getCode(), 200);
assertEquals(Constants.MIMETYPE_XML, response1.getHeader("content-type"));
CellSetModel cellSet = (CellSetModel)
xmlUnmarshaller.unmarshal(new ByteArrayInputStream(response1.getBody()));
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toLong(cell.getValue()), value);
}
protected static Response getValuePB(String url) throws IOException {
Response response = client.get(url, Constants.MIMETYPE_PROTOBUF);
return response;
}
protected static Response putValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return putValueXML(path.toString(), table, row, column, value);
}
protected static Response putValueXML(String url, String table, String row,
String column, String value) throws IOException, JAXBException {
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(value)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
StringWriter writer = new StringWriter();
xmlMarshaller.marshal(cellSetModel, writer);
Response response = client.put(url, Constants.MIMETYPE_XML,
Bytes.toBytes(writer.toString()));
Thread.yield();
return response;
}
protected static Response getValuePB(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return getValuePB(path.toString());
}
protected static void checkValuePB(String table, String row, String column,
String value) throws IOException {
Response response = getValuePB(table, row, column);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_PROTOBUF, response.getHeader("content-type"));
CellSetModel cellSet = new CellSetModel();
cellSet.getObjectFromMessage(response.getBody());
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
protected static void checkIncrementValuePB(String table, String row, String column,
long value) throws IOException {
Response response = getValuePB(table, row, column);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_PROTOBUF, response.getHeader("content-type"));
CellSetModel cellSet = new CellSetModel();
cellSet.getObjectFromMessage(response.getBody());
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toLong(cell.getValue()), value);
}
protected static Response checkAndPutValuePB(String url, String table,
String row, String column, String valueToCheck, String valueToPut, HashMap<String,String> otherCells)
throws IOException {
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToPut)));
if(otherCells != null) {
for (Map.Entry<String,String> entry :otherCells.entrySet()) {
rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
}
}
// This Cell need to be added as last cell.
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToCheck)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
Response response = client.put(url, Constants.MIMETYPE_PROTOBUF,
cellSetModel.createProtobufOutput());
Thread.yield();
return response;
}
protected static Response checkAndPutValuePB(String table, String row,
String column, String valueToCheck, String valueToPut) throws IOException {
return checkAndPutValuePB(table,row,column,valueToCheck,valueToPut,null);
}
protected static Response checkAndPutValuePB(String table, String row,
String column, String valueToCheck, String valueToPut, HashMap<String,String> otherCells) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=put");
return checkAndPutValuePB(path.toString(), table, row, column,
valueToCheck, valueToPut, otherCells);
}
protected static Response checkAndPutValueXML(String url, String table,
String row, String column, String valueToCheck, String valueToPut, HashMap<String,String> otherCells)
throws IOException, JAXBException {
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToPut)));
if(otherCells != null) {
for (Map.Entry<String,String> entry :otherCells.entrySet()) {
rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
}
}
// This Cell need to be added as last cell.
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToCheck)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
StringWriter writer = new StringWriter();
xmlMarshaller.marshal(cellSetModel, writer);
Response response = client.put(url, Constants.MIMETYPE_XML,
Bytes.toBytes(writer.toString()));
Thread.yield();
return response;
}
protected static Response checkAndPutValueXML(String table, String row,
String column, String valueToCheck, String valueToPut)
throws IOException, JAXBException {
return checkAndPutValueXML(table,row,column,valueToCheck,valueToPut, null);
}
protected static Response checkAndPutValueXML(String table, String row,
String column, String valueToCheck, String valueToPut, HashMap<String,String> otherCells)
throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=put");
return checkAndPutValueXML(path.toString(), table, row, column,
valueToCheck, valueToPut, otherCells);
}
protected static Response checkAndDeleteXML(String url, String table,
String row, String column, String valueToCheck, HashMap<String,String> cellsToDelete)
throws IOException, JAXBException {
RowModel rowModel = new RowModel(row);
if(cellsToDelete != null) {
for (Map.Entry<String,String> entry :cellsToDelete.entrySet()) {
rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
}
}
// Add this at the end
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToCheck)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
StringWriter writer = new StringWriter();
xmlMarshaller.marshal(cellSetModel, writer);
Response response = client.put(url, Constants.MIMETYPE_XML,
Bytes.toBytes(writer.toString()));
Thread.yield();
return response;
}
protected static Response checkAndDeleteXML(String table, String row,
String column, String valueToCheck) throws IOException, JAXBException {
return checkAndDeleteXML(table, row, column, valueToCheck, null);
}
protected static Response checkAndDeleteXML(String table, String row,
String column, String valueToCheck, HashMap<String,String> cellsToDelete) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=delete");
return checkAndDeleteXML(path.toString(), table, row, column, valueToCheck, cellsToDelete);
}
protected static Response checkAndDeleteJson(String table, String row,
String column, String valueToCheck) throws IOException, JAXBException {
return checkAndDeleteJson(table, row, column, valueToCheck, null);
}
protected static Response checkAndDeleteJson(String table, String row,
String column, String valueToCheck, HashMap<String,String> cellsToDelete) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=delete");
return checkAndDeleteJson(path.toString(), table, row, column, valueToCheck, cellsToDelete);
}
protected static Response checkAndDeleteJson(String url, String table,
String row, String column, String valueToCheck, HashMap<String,String> cellsToDelete)
throws IOException, JAXBException {
RowModel rowModel = new RowModel(row);
if(cellsToDelete != null) {
for (Map.Entry<String,String> entry :cellsToDelete.entrySet()) {
rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
}
}
// Add this at the end
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(valueToCheck)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
String jsonString = jsonMapper.writeValueAsString(cellSetModel);
Response response = client.put(url, Constants.MIMETYPE_JSON,
Bytes.toBytes(jsonString));
Thread.yield();
return response;
}
protected static Response checkAndDeletePB(String table, String row,
String column, String value) throws IOException {
return checkAndDeletePB(table, row, column, value, null);
}
protected static Response checkAndDeletePB(String table, String row,
String column, String value, HashMap<String,String> cellsToDelete) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=delete");
return checkAndDeleteValuePB(path.toString(), table, row, column, value, cellsToDelete);
}
protected static Response checkAndDeleteValuePB(String url, String table,
String row, String column, String valueToCheck, HashMap<String,String> cellsToDelete)
throws IOException {
RowModel rowModel = new RowModel(row);
if(cellsToDelete != null) {
for (Map.Entry<String,String> entry :cellsToDelete.entrySet()) {
rowModel.addCell(new CellModel(Bytes.toBytes(entry.getKey()), Bytes.toBytes(entry.getValue())));
}
}
// Add this at the end
rowModel.addCell(new CellModel(Bytes.toBytes(column), Bytes
.toBytes(valueToCheck)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
Response response = client.put(url, Constants.MIMETYPE_PROTOBUF,
cellSetModel.createProtobufOutput());
Thread.yield();
return response;
}
protected static Response getValueXML(String table, String startRow,
String endRow, String column) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(startRow);
path.append(",");
path.append(endRow);
path.append('/');
path.append(column);
return getValueXML(path.toString());
}
protected static Response getValueXML(String url) throws IOException {
Response response = client.get(url, Constants.MIMETYPE_XML);
return response;
}
protected static Response getValueJson(String url) throws IOException {
Response response = client.get(url, Constants.MIMETYPE_JSON);
return response;
}
protected static Response deleteValue(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
Response response = client.delete(path.toString());
Thread.yield();
return response;
}
protected static Response getValueXML(String table, String row, String column)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return getValueXML(path.toString());
}
protected static Response deleteRow(String table, String row)
throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
Response response = client.delete(path.toString());
Thread.yield();
return response;
}
protected static Response getValueJson(String table, String row,
String column) throws IOException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return getValueJson(path.toString());
}
protected static void checkValueJSON(String table, String row, String column,
String value) throws IOException, JAXBException {
Response response = getValueJson(table, row, column);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
ObjectMapper mapper = new JacksonJaxbJsonProvider()
.locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE);
CellSetModel cellSet = mapper.readValue(response.getBody(), CellSetModel.class);
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toString(cell.getValue()), value);
}
protected static void checkIncrementValueJSON(String table, String row, String column,
long value) throws IOException, JAXBException {
Response response = getValueJson(table, row, column);
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
ObjectMapper mapper = new JacksonJaxbJsonProvider()
.locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE);
CellSetModel cellSet = mapper.readValue(response.getBody(), CellSetModel.class);
RowModel rowModel = cellSet.getRows().get(0);
CellModel cell = rowModel.getCells().get(0);
assertEquals(Bytes.toString(cell.getColumn()), column);
assertEquals(Bytes.toLong(cell.getValue()), value);
}
protected static Response putValueJson(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append('/');
path.append(column);
return putValueJson(path.toString(), table, row, column, value);
}
protected static Response putValueJson(String url, String table, String row, String column,
String value) throws IOException, JAXBException {
RowModel rowModel = new RowModel(row);
rowModel.addCell(new CellModel(Bytes.toBytes(column),
Bytes.toBytes(value)));
CellSetModel cellSetModel = new CellSetModel();
cellSetModel.addRow(rowModel);
String jsonString = jsonMapper.writeValueAsString(cellSetModel);
Response response = client.put(url, Constants.MIMETYPE_JSON,
Bytes.toBytes(jsonString));
Thread.yield();
return response;
}
protected static Response appendValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=append");
return putValueXML(path.toString(), table, row, column, value);
}
protected static Response appendValuePB(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=append");
return putValuePB(path.toString(), table, row, column, value);
}
protected static Response appendValueJson(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=append");
return putValueJson(path.toString(), table, row, column, value);
}
protected static Response incrementValueXML(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=increment");
return putValueXML(path.toString(), table, row, column, value);
}
protected static Response incrementValuePB(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=increment");
return putValuePB(path.toString(), table, row, column, value);
}
protected static Response incrementValueJson(String table, String row, String column,
String value) throws IOException, JAXBException {
StringBuilder path = new StringBuilder();
path.append('/');
path.append(table);
path.append('/');
path.append(row);
path.append("?check=increment");
return putValueJson(path.toString(), table, row, column, value);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-finspacedata/src/main/java/com/amazonaws/services/finspacedata/model/transform/GetWorkingLocationRequestProtocolMarshaller.java | 2696 | /*
* Copyright 2017-2022 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.finspacedata.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.finspacedata.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetWorkingLocationRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetWorkingLocationRequestProtocolMarshaller implements Marshaller<Request<GetWorkingLocationRequest>, GetWorkingLocationRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/workingLocationV1")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AWSFinSpaceData").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetWorkingLocationRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetWorkingLocationRequest> marshall(GetWorkingLocationRequest getWorkingLocationRequest) {
if (getWorkingLocationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetWorkingLocationRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
getWorkingLocationRequest);
protocolMarshaller.startMarshalling();
GetWorkingLocationRequestMarshaller.getInstance().marshall(getWorkingLocationRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
sumanthn/executor | src/main/java/sn/executor/GenieHadoopTaskResponse.java | 108 | package sn.executor;
/**
* Created by Sumanth on 16/10/14.
*/
public class GenieHadoopTaskResponse {
}
| apache-2.0 |
cjnolet/accumulo-recipes | store/event-store/src/main/java/org/calrissian/accumulorecipes/eventstore/iterator/EventIntersectingIterator.java | 1788 | /*
* Copyright (C) 2013 The Calrissian Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.calrissian.accumulorecipes.eventstore.iterator;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.iterators.user.IntersectingIterator;
import java.io.IOException;
public class EventIntersectingIterator extends IntersectingIterator {
protected SortedKeyValueIterator<Key,Value> sourceItr;
protected Key topKey;
public void init(SortedKeyValueIterator<Key,Value> source, java.util.Map<String,String> options, IteratorEnvironment env) throws IOException {
super.init(source, options, env);
sourceItr = source.deepCopy(env);
}
@Override
public Value getTopValue() {
if(hasTop()) {
Key topKey = getTopKey();
String eventUUID = topKey.getColumnQualifier().toString();
System.out.println("UUID:" + eventUUID);
Value event = IteratorUtils.retrieveFullEvent(eventUUID, topKey, sourceItr);
return event;
}
return new Value("".getBytes());
}
}
| apache-2.0 |
twitter-forks/presto | presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/TestPlanRemoteProjections.java | 15432 | /*
* 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.sql.planner.iterative.rule;
import com.facebook.presto.common.CatalogSchemaName;
import com.facebook.presto.common.function.QualifiedFunctionName;
import com.facebook.presto.common.type.StandardTypes;
import com.facebook.presto.functionNamespace.SqlInvokedFunctionNamespaceManagerConfig;
import com.facebook.presto.functionNamespace.testing.InMemoryFunctionNamespaceManager;
import com.facebook.presto.metadata.FunctionManager;
import com.facebook.presto.spi.function.Parameter;
import com.facebook.presto.spi.function.RoutineCharacteristics;
import com.facebook.presto.spi.function.SqlInvokedFunction;
import com.facebook.presto.spi.plan.Assignments;
import com.facebook.presto.spi.plan.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.PlanVariableAllocator;
import com.facebook.presto.sql.planner.assertions.ExpressionMatcher;
import com.facebook.presto.sql.planner.assertions.PlanMatchPattern;
import com.facebook.presto.sql.planner.iterative.rule.test.BaseRuleTest;
import com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.SessionTestUtils.TEST_SESSION;
import static com.facebook.presto.common.type.BooleanType.BOOLEAN;
import static com.facebook.presto.common.type.IntegerType.INTEGER;
import static com.facebook.presto.common.type.StandardTypes.DOUBLE;
import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.spi.function.RoutineCharacteristics.Determinism.DETERMINISTIC;
import static com.facebook.presto.spi.function.RoutineCharacteristics.NullCallClause.RETURNS_NULL_ON_NULL_INPUT;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.project;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.values;
import static com.facebook.presto.sql.planner.iterative.rule.PlanRemotePojections.ProjectionContext;
import static org.testng.Assert.assertEquals;
public class TestPlanRemoteProjections
extends BaseRuleTest
{
public static final QualifiedFunctionName REMOTE_FOO = QualifiedFunctionName.of(new CatalogSchemaName("unittest", "memory"), "remote_foo");
public static final RoutineCharacteristics.Language JAVA = new RoutineCharacteristics.Language("java");
public static final SqlInvokedFunction FUNCTION_REMOTE_FOO_0 = new SqlInvokedFunction(
REMOTE_FOO,
ImmutableList.of(),
parseTypeSignature(StandardTypes.INTEGER),
"remote_foo()",
RoutineCharacteristics.builder().setLanguage(JAVA).setNullCallClause(RETURNS_NULL_ON_NULL_INPUT).build(),
"",
Optional.empty());
public static final SqlInvokedFunction FUNCTION_REMOTE_FOO_1 = new SqlInvokedFunction(
REMOTE_FOO,
ImmutableList.of(new Parameter("x", parseTypeSignature(StandardTypes.INTEGER))),
parseTypeSignature(StandardTypes.INTEGER),
"remote_foo(x)",
RoutineCharacteristics.builder().setLanguage(JAVA).setDeterminism(DETERMINISTIC).setNullCallClause(RETURNS_NULL_ON_NULL_INPUT).build(),
"",
Optional.empty());
public static final SqlInvokedFunction FUNCTION_REMOTE_FOO_2 = new SqlInvokedFunction(
REMOTE_FOO,
ImmutableList.of(new Parameter("x", parseTypeSignature(StandardTypes.INTEGER)), new Parameter("y", parseTypeSignature(StandardTypes.INTEGER))),
parseTypeSignature(StandardTypes.INTEGER),
"remote_foo(x, y)",
RoutineCharacteristics.builder().setLanguage(JAVA).setDeterminism(DETERMINISTIC).setNullCallClause(RETURNS_NULL_ON_NULL_INPUT).build(),
"",
Optional.empty());
public static final SqlInvokedFunction FUNCTION_REMOTE_FOO_3 = new SqlInvokedFunction(
REMOTE_FOO,
ImmutableList.of(new Parameter("x", parseTypeSignature(StandardTypes.INTEGER)), new Parameter("y", parseTypeSignature(StandardTypes.INTEGER)), new Parameter("z", parseTypeSignature(DOUBLE))),
parseTypeSignature(StandardTypes.INTEGER),
"remote_foo(x, y, z)",
RoutineCharacteristics.builder().setLanguage(JAVA).setNullCallClause(RETURNS_NULL_ON_NULL_INPUT).build(),
"",
Optional.empty());
@BeforeClass
public void setup()
{
FunctionManager functionManager = getFunctionManager();
functionManager.addFunctionNamespace("unittest", new InMemoryFunctionNamespaceManager("unittest", new SqlInvokedFunctionNamespaceManagerConfig().setSupportedFunctionLanguages("{\"sql\": \"SQL\",\"java\": \"THRIFT\"}")));
functionManager.createFunction(FUNCTION_REMOTE_FOO_0, true);
functionManager.createFunction(FUNCTION_REMOTE_FOO_1, true);
functionManager.createFunction(FUNCTION_REMOTE_FOO_2, true);
functionManager.createFunction(FUNCTION_REMOTE_FOO_3, true);
}
@Test
void testLocalOnly()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
planBuilder.variable("x", INTEGER);
planBuilder.variable("y", INTEGER);
PlanRemotePojections rule = new PlanRemotePojections(getFunctionManager());
List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignments.builder()
.put(planBuilder.variable("a"), planBuilder.rowExpression("abs(x) + abs(y)"))
.put(planBuilder.variable("b", BOOLEAN), planBuilder.rowExpression("x is null and y is null"))
.build(), new PlanVariableAllocator(planBuilder.getTypes().allVariables()));
assertEquals(rewritten.size(), 1);
assertEquals(rewritten.get(0).getProjections().size(), 2);
}
@Test
void testRemoteOnly()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
PlanRemotePojections rule = new PlanRemotePojections(getFunctionManager());
List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignments.builder()
.put(planBuilder.variable("a"), planBuilder.rowExpression("unittest.memory.remote_foo()"))
.put(planBuilder.variable("b"), planBuilder.rowExpression("unittest.memory.remote_foo(unittest.memory.remote_foo())"))
.build(), new PlanVariableAllocator(planBuilder.getTypes().allVariables()));
assertEquals(rewritten.size(), 2);
assertEquals(rewritten.get(1).getProjections().size(), 2);
}
@Test
void testRemoteAndLocal()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
planBuilder.variable("x", INTEGER);
planBuilder.variable("y", INTEGER);
PlanRemotePojections rule = new PlanRemotePojections(getFunctionManager());
List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignments.builder()
.put(planBuilder.variable("a"), planBuilder.rowExpression("unittest.memory.remote_foo(x, y + unittest.memory.remote_foo(x))"))
.put(planBuilder.variable("b"), planBuilder.rowExpression("abs(x)"))
.put(planBuilder.variable("c"), planBuilder.rowExpression("abs(unittest.memory.remote_foo())"))
.put(planBuilder.variable("d"), planBuilder.rowExpression("unittest.memory.remote_foo(x + y, abs(x))"))
.build(), new PlanVariableAllocator(planBuilder.getTypes().allVariables()));
assertEquals(rewritten.size(), 4);
assertEquals(rewritten.get(3).getProjections().size(), 4);
}
@Test
void testSpecialForm()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
planBuilder.variable("x", INTEGER);
planBuilder.variable("y", INTEGER);
PlanRemotePojections rule = new PlanRemotePojections(getFunctionManager());
List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignments.builder()
.put(planBuilder.variable("a"), planBuilder.rowExpression("unittest.memory.remote_foo(x, y + unittest.memory.remote_foo(x))"))
.put(planBuilder.variable("b"), planBuilder.rowExpression("x IS NULL OR y IS NULL"))
.put(planBuilder.variable("c"), planBuilder.rowExpression("IF(abs(unittest.memory.remote_foo()) > 0, x, y)"))
.put(planBuilder.variable("d"), planBuilder.rowExpression("unittest.memory.remote_foo(x + y, abs(x))"))
.build(), new PlanVariableAllocator(planBuilder.getTypes().allVariables()));
assertEquals(rewritten.size(), 4);
assertEquals(rewritten.get(3).getProjections().size(), 4);
}
@Test
void testRemoteFunctionRewrite()
{
tester().assertThat(new PlanRemotePojections(getFunctionManager()))
.on(p -> {
p.variable("x", INTEGER);
p.variable("y", INTEGER);
return p.project(
Assignments.builder()
.put(p.variable("a"), p.rowExpression("unittest.memory.remote_foo(x)"))
.put(p.variable("b"), p.rowExpression("unittest.memory.remote_foo(unittest.memory.remote_foo())"))
.build(),
p.values(p.variable("x", INTEGER)));
})
.matches(
project(
ImmutableMap.of(
"a", PlanMatchPattern.expression("a"),
"b", PlanMatchPattern.expression("unittest.memory.remote_foo(unittest_memory_remote_foo)")),
project(
ImmutableMap.of(
"a", PlanMatchPattern.expression("unittest.memory.remote_foo(x)"),
"unittest_memory_remote_foo", PlanMatchPattern.expression("unittest.memory.remote_foo()")),
project(
ImmutableMap.of("x", PlanMatchPattern.expression("x")),
values(ImmutableMap.of("x", 0))))));
}
@Test
void testMixedExpressionRewrite()
{
tester().assertThat(new PlanRemotePojections(getFunctionManager()))
.on(p -> {
p.variable("x", INTEGER);
p.variable("y", INTEGER);
return p.project(
Assignments.builder()
.put(p.variable("a"), p.rowExpression("unittest.memory.remote_foo(x, y + unittest.memory.remote_foo(x))")) // identity
.put(p.variable("b"), p.rowExpression("x IS NULL OR y IS NULL")) // complex expression referenced multiple times
.put(p.variable("c"), p.rowExpression("abs(unittest.memory.remote_foo()) > 0")) // complex expression referenced multiple times
.put(p.variable("d"), p.rowExpression("unittest.memory.remote_foo(x + y, abs(x))")) // literal referenced multiple times
.build(),
p.values(p.variable("x", INTEGER), p.variable("y", INTEGER)));
})
.matches(
project(
ImmutableMap.of(
"a", PlanMatchPattern.expression("unittest.memory.remote_foo(x, add)"),
"b", PlanMatchPattern.expression("b"),
"c", PlanMatchPattern.expression("c"),
"d", PlanMatchPattern.expression("d")),
project(
ImmutableMap.of(
"x", PlanMatchPattern.expression("x"),
"add", PlanMatchPattern.expression("y + unittest_memory_remote_foo"),
"b", PlanMatchPattern.expression("b"),
"c", PlanMatchPattern.expression("abs(unittest_memory_remote_foo_7) > expr_8"),
"d", PlanMatchPattern.expression("d")),
project(
ImmutableMap.<String, ExpressionMatcher>builder()
.put("x", PlanMatchPattern.expression("x"))
.put("y", PlanMatchPattern.expression("y"))
.put("unittest_memory_remote_foo", PlanMatchPattern.expression("unittest.memory.remote_foo(x)"))
.put("b", PlanMatchPattern.expression("b"))
.put("unittest_memory_remote_foo_7", PlanMatchPattern.expression("unittest.memory.remote_foo()"))
.put("expr_8", PlanMatchPattern.expression("expr_8"))
.put("d", PlanMatchPattern.expression("unittest.memory.remote_foo(add_14, abs_16)"))
.build(),
project(
ImmutableMap.<String, ExpressionMatcher>builder()
.put("x", PlanMatchPattern.expression("x"))
.put("y", PlanMatchPattern.expression("y"))
.put("b", PlanMatchPattern.expression("x IS NULL OR y is NULL"))
.put("expr_8", PlanMatchPattern.expression("0"))
.put("add_14", PlanMatchPattern.expression("x + y"))
.put("abs_16", PlanMatchPattern.expression("abs(x)"))
.build(),
values(ImmutableMap.of("x", 0, "y", 1)))))));
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-sesv2/src/main/java/com/amazonaws/services/simpleemailv2/model/transform/DeleteSuppressedDestinationRequestMarshaller.java | 2148 | /*
* Copyright 2017-2022 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.simpleemailv2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simpleemailv2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteSuppressedDestinationRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteSuppressedDestinationRequestMarshaller {
private static final MarshallingInfo<String> EMAILADDRESS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("EmailAddress").build();
private static final DeleteSuppressedDestinationRequestMarshaller instance = new DeleteSuppressedDestinationRequestMarshaller();
public static DeleteSuppressedDestinationRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DeleteSuppressedDestinationRequest deleteSuppressedDestinationRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteSuppressedDestinationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteSuppressedDestinationRequest.getEmailAddress(), EMAILADDRESS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
spring-projects/spring-framework | spring-context/src/test/java/example/profilescan/ProfileMetaAnnotatedComponent.java | 830 | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 example.profilescan;
@DevComponent(ProfileMetaAnnotatedComponent.BEAN_NAME)
public class ProfileMetaAnnotatedComponent {
public static final String BEAN_NAME = "profileMetaAnnotatedComponent";
}
| apache-2.0 |
tAsktoys/Archelon | src/main/java/com/tasktoys/archelon/data/dao/jdbc/JdbcActivityDao.java | 4230 | package com.tasktoys.archelon.data.dao.jdbc;
import com.tasktoys.archelon.data.dao.ActivityDao;
import com.tasktoys.archelon.data.entity.Activity;
import com.tasktoys.archelon.data.entity.Activity.ActivityType;
import com.tasktoys.archelon.data.entity.Activity.Builder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/*
* Copyright(C) 2014 tAsktoys. All rights reserved.
*/
/**
*
* @author YuichiroSato
* @since 0.2
*/
@Repository
public class JdbcActivityDao implements ActivityDao {
private JdbcTemplate jdbcTemplate;
/**
* Set data source. It invoke from Spring Framework.
*
* @param dataSource data source
*/
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
static private final String TABLE_NAME = "activity";
Logger log = Logger.getLogger(JdbcActivityDao.class.getName());
/**
* This is columns in database. Each value is ordred by the same order as in
* the database.
*/
private enum Column {
ID, ACTIVITY_TYPE, USER_ID, CREATED_TIME, TARGET_DISCUSSION_ID,
TARGET_USER_ID, TARGET_DISCUSSION_CONTENT_ID, TARGET_POST;
@Override
public String toString() {
return name().toLowerCase();
}
}
@Override
public List<Activity> findLatestActivities(int n) {
String sql = "select * from " + TABLE_NAME
+ " order by " + " created_time " + " desc"
+ " limit " + n;
return responseToActivityList(jdbcTemplate.queryForList(sql));
}
@Override
public List<Activity> findLatestActivitiesByUserId(long userId, int n) {
String sql = "select * from " + TABLE_NAME
+ " where " + "user_id=" + userId
+ " order by " + " created_time " + " desc"
+ " limit " + n;
return responseToActivityList(jdbcTemplate.queryForList(sql));
}
@Override
public void insertActivity(Activity activity) {
String sql = "insert into " + TABLE_NAME + encodeColumnToSet();
jdbcTemplate.update(sql, toObject(activity));
}
private List<Activity> responseToActivityList(List<Map<String, Object>> response) {
List<Activity> activityList = new ArrayList<>();
for (Map<String, Object> map : response) {
Builder builder = new Builder();
builder.id((long) map.get(Column.ID.toString()))
.activityType((int) map.get(Column.ACTIVITY_TYPE.toString()))
.userId((long) map.get(Column.USER_ID.toString()))
.createdTime((Timestamp) map.get(Column.CREATED_TIME.toString()))
.targetDiscussionId((Long) map.get(Column.TARGET_DISCUSSION_ID.toString()))
.targetUserId((Long) map.get(Column.TARGET_USER_ID.toString()))
.targetDiscussionConcentId((String) map.get(Column.TARGET_DISCUSSION_CONTENT_ID.toString()))
.targetPost((Integer) map.get(Column.TARGET_POST.toString()));
activityList.add(builder.build());
}
return activityList;
}
private String encodeColumnToSet() {
String sql = " set ";
for (Column c : Column.values()) {
sql += c.toString() + "=?,";
}
return sql.substring(0, sql.length() - ",".length());
}
private Object[] toObject(Activity activity) {
return new Object[]{
(activity.getId() == Activity.ILLEGAL_ID ? null : activity.getId()),
activity.getActivityType().ordinal(),
(activity.getUserId() == Activity.ILLEGAL_USER_ID ? null : activity.getUserId()),
activity.getCreatedTime(), activity.getTargetDiscussionId(),
activity.getTargetUserId(), activity.getTargetDiscussionContentId(),
activity.getTargetPost()
};
}
}
| apache-2.0 |
pepstock-org/Charba | src/org/pepstock/charba/client/defaults/chart/package-info.java | 812 | /**
Copyright 2017 Andrea "Stock" Stocchero
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.
*/
/**
* Contains the default values of chart options based on type of chart instance.
*
* @author Andrea "Stock" Stocchero
*
*/
package org.pepstock.charba.client.defaults.chart; | apache-2.0 |
azkaban/azkaban | azkaban-common/src/main/java/azkaban/executor/ExecutionRampDao.java | 27150 | /*
* Copyright 2019 LinkedIn 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 azkaban.executor;
import azkaban.db.DatabaseOperator;
import com.google.common.collect.ImmutableMap;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.dbutils.ResultSetHandler;
/**
* The Hookup DB Operation for Flow Ramp
*/
@Singleton
public class ExecutionRampDao {
private final String FAILURE_RESULT_FORMATTER = "[FAILURE] {Reason = %s, Command = %s}";
private final String SUCCESS_RESULT_FORMATTER = "[SUCCESS] {Command = %s}";
private final DatabaseOperator dbOperator;
@Inject
public ExecutionRampDao(final DatabaseOperator dbOperator) {
this.dbOperator = dbOperator;
}
private enum RampTableFields {
FIELD_RAMP_ID("rampId"),
FIELD_RAMP_POLICY("rampPolicy"),
FIELD_MAX_FAILURE_TO_PAUSE("maxFailureToPause"),
FIELD_MAX_FAILURE_TO_RAMP_DOWN("maxFailureToRampDown"),
FIELD_IS_PERCENTAGE_SCALE_FOR_MAX_FAILURE("isPercentageScaleForMaxFailure"),
FIELD_START_TIME("startTime"),
FIELD_END_TIME("endTime"),
FIELD_LAST_UPDATED_TIME("lastUpdatedTime"),
FIELD_NUM_OF_TRAIL("numOfTrail"),
FIELD_NUM_OF_SUCCESS("numOfSuccess"),
FIELD_NUM_OF_FAILURE("numOfFailure"),
FIELD_NUM_OF_IGNORED("numOfIgnored"),
FIELD_IS_PAUSED("isPaused"),
FIELD_RAMP_STAGE("rampStage"),
FIELD_IS_ACTIVE("isActive");
final String value;
RampTableFields(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
/**
* Fetch Executable Ramps
*/
private static class FetchExecutableRamps implements ResultSetHandler<ExecutableRampMap> {
static String FETCH_EXECUTABLE_RAMPS = "SELECT "
+ RampTableFields.FIELD_RAMP_ID.getValue() + ", "
+ RampTableFields.FIELD_RAMP_POLICY.getValue() + ", "
+ RampTableFields.FIELD_MAX_FAILURE_TO_PAUSE.getValue() + ", "
+ RampTableFields.FIELD_MAX_FAILURE_TO_RAMP_DOWN.getValue() + ", "
+ RampTableFields.FIELD_IS_PERCENTAGE_SCALE_FOR_MAX_FAILURE.getValue() + ", "
+ RampTableFields.FIELD_START_TIME.getValue() + ", "
+ RampTableFields.FIELD_END_TIME.getValue() + ", "
+ RampTableFields.FIELD_LAST_UPDATED_TIME.getValue() + ", "
+ RampTableFields.FIELD_NUM_OF_TRAIL.getValue() + ", "
+ RampTableFields.FIELD_NUM_OF_SUCCESS.getValue() + ", "
+ RampTableFields.FIELD_NUM_OF_FAILURE.getValue() + ", "
+ RampTableFields.FIELD_NUM_OF_IGNORED.getValue() + ", "
+ RampTableFields.FIELD_IS_PAUSED.getValue() + ", "
+ RampTableFields.FIELD_RAMP_STAGE.getValue() + ", "
+ RampTableFields.FIELD_IS_ACTIVE.getValue()
+ " FROM ramp ";
@Override
public ExecutableRampMap handle(final ResultSet resultSet) throws SQLException {
final ExecutableRampMap executableRampMap = ExecutableRampMap.createInstance();
if (!resultSet.next()) {
return executableRampMap;
}
do {
executableRampMap.add(
resultSet.getString(RampTableFields.FIELD_RAMP_ID.getValue()),
ExecutableRamp.builder(
resultSet.getString(RampTableFields.FIELD_RAMP_ID.getValue()),
resultSet.getString(RampTableFields.FIELD_RAMP_POLICY.getValue()))
.setMetadata(
ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(resultSet.getInt(RampTableFields.FIELD_MAX_FAILURE_TO_PAUSE.getValue()))
.setMaxFailureToRampDown(resultSet.getInt(RampTableFields.FIELD_MAX_FAILURE_TO_RAMP_DOWN.getValue()))
.setPercentageScaleForMaxFailure(resultSet.getBoolean(RampTableFields.FIELD_IS_PERCENTAGE_SCALE_FOR_MAX_FAILURE.getValue()))
.build()
)
.setState(
ExecutableRamp.State.builder()
.setStartTime(resultSet.getLong(RampTableFields.FIELD_START_TIME.getValue()))
.setEndTime(resultSet.getLong(RampTableFields.FIELD_END_TIME.getValue()))
.setLastUpdatedTime(resultSet.getLong(RampTableFields.FIELD_LAST_UPDATED_TIME.getValue()))
.setNumOfTrail(resultSet.getInt(RampTableFields.FIELD_NUM_OF_TRAIL.getValue()))
.setNumOfSuccess(resultSet.getInt(RampTableFields.FIELD_NUM_OF_SUCCESS.getValue()))
.setNumOfFailure(resultSet.getInt(RampTableFields.FIELD_NUM_OF_FAILURE.getValue()))
.setNumOfIgnored(resultSet.getInt(RampTableFields.FIELD_NUM_OF_IGNORED.getValue()))
.setPaused(resultSet.getBoolean(RampTableFields.FIELD_IS_PAUSED.getValue()))
.setRampStage(resultSet.getInt(RampTableFields.FIELD_RAMP_STAGE.getValue()))
.setActive(resultSet.getBoolean(RampTableFields.FIELD_IS_ACTIVE.getValue()))
.build()
)
.build()
);
} while (resultSet.next());
return executableRampMap;
}
}
public ExecutableRampMap fetchExecutableRampMap()
throws ExecutorManagerException {
try {
return this.dbOperator.query(
FetchExecutableRamps.FETCH_EXECUTABLE_RAMPS,
new FetchExecutableRamps()
);
} catch (final SQLException e) {
throw new ExecutorManagerException("Error on fetching all Ramps", e);
}
}
private enum RampItemsTableFields {
FIELD_RAMP_ID("rampId"),
FIELD_DEPENDENCY("dependency"),
FIELD_RAMP_VALUE("rampValue");
final String value;
RampItemsTableFields(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
/**
* Fetch Executable Ramp Items
*/
private static class FetchExecutableRampItems implements ResultSetHandler<ExecutableRampItemsMap> {
static String FETCH_EXECUTABLE_RAMP_ITEMS = "SELECT "
+ RampItemsTableFields.FIELD_RAMP_ID.getValue() + ", "
+ RampItemsTableFields.FIELD_DEPENDENCY.getValue() + ", "
+ RampItemsTableFields.FIELD_RAMP_VALUE.getValue()
+ " FROM ramp_items ";
@Override
public ExecutableRampItemsMap handle(final ResultSet resultSet) throws SQLException {
final ExecutableRampItemsMap executableRampItemsMap = ExecutableRampItemsMap.createInstance();
if (!resultSet.next()) {
return executableRampItemsMap;
}
do {
executableRampItemsMap.add(
resultSet.getString(RampItemsTableFields.FIELD_RAMP_ID.getValue()),
resultSet.getString(RampItemsTableFields.FIELD_DEPENDENCY.getValue()),
resultSet.getString(RampItemsTableFields.FIELD_RAMP_VALUE.getValue())
);
} while (resultSet.next());
return executableRampItemsMap;
}
}
public ExecutableRampItemsMap fetchExecutableRampItemsMap() throws ExecutorManagerException {
try {
return this.dbOperator.query(
FetchExecutableRampItems.FETCH_EXECUTABLE_RAMP_ITEMS,
new FetchExecutableRampItems()
);
} catch (final SQLException e) {
throw new ExecutorManagerException("Error fetching active Ramp Items", e);
}
}
private enum RampDependenciesTableFields {
FIELD_DEPENDENCY("dependency"),
FIELD_DEFAULT_VALUE("defaultValue"),
FIELD_JOB_TYPES("jobtypes");
final String value;
RampDependenciesTableFields(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
/**
* Fetch Rampable Dependency's default Value
*/
private static class FetchExecutableRampDependencies implements ResultSetHandler<ExecutableRampDependencyMap> {
static String FETCH_EXECUTABLE_RAMP_DEPENDENCIES = "SELECT "
+ RampDependenciesTableFields.FIELD_DEPENDENCY.getValue() + ", "
+ RampDependenciesTableFields.FIELD_DEFAULT_VALUE.getValue() + ", "
+ RampDependenciesTableFields.FIELD_JOB_TYPES.getValue()
+ " FROM ramp_dependency ";
@Override
public ExecutableRampDependencyMap handle(ResultSet resultSet) throws SQLException {
final ExecutableRampDependencyMap executableRampDependencyMap = ExecutableRampDependencyMap.createInstance();
if (!resultSet.next()) {
return executableRampDependencyMap;
}
do {
executableRampDependencyMap
.add(
resultSet.getString(RampDependenciesTableFields.FIELD_DEPENDENCY.getValue()),
resultSet.getString(RampDependenciesTableFields.FIELD_DEFAULT_VALUE.getValue()),
resultSet.getString(RampDependenciesTableFields.FIELD_JOB_TYPES.getValue())
);
} while (resultSet.next());
return executableRampDependencyMap;
}
}
public ExecutableRampDependencyMap fetchExecutableRampDependencyMap()
throws ExecutorManagerException {
try {
return this.dbOperator.query(
FetchExecutableRampDependencies.FETCH_EXECUTABLE_RAMP_DEPENDENCIES,
new FetchExecutableRampDependencies()
);
} catch (final SQLException e) {
throw new ExecutorManagerException("Error fetching default value list of dependencies", e);
}
}
private enum RampExceptionalFlowItemsTableFields {
FIELD_RAMP_ID("rampId"),
FIELD_FLOW_ID("flowId"),
FIELD_TREATMENT("treatment"),
FIELD_TIME_STAMP("timestamp");
final String value;
RampExceptionalFlowItemsTableFields(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
/**
* Fetch Executable Ramp's Exceptional Flow Items
*/
private static class FetchExecutableRampExceptionalFlowItems implements ResultSetHandler<ExecutableRampExceptionalFlowItemsMap> {
static String FETCH_EXECUTABLE_RAMP_EXCEPTIONAL_FLOW_ITEMS = "SELECT "
+ RampExceptionalFlowItemsTableFields.FIELD_RAMP_ID.getValue() + ", "
+ RampExceptionalFlowItemsTableFields.FIELD_FLOW_ID.getValue() + ", "
+ RampExceptionalFlowItemsTableFields.FIELD_TREATMENT.getValue() + ", "
+ RampExceptionalFlowItemsTableFields.FIELD_TIME_STAMP.getValue()
+ " FROM ramp_exceptional_flow_items ";
@Override
public ExecutableRampExceptionalFlowItemsMap handle(ResultSet resultSet) throws SQLException {
final ExecutableRampExceptionalFlowItemsMap executableRampExceptionalFlowItemsMap
= ExecutableRampExceptionalFlowItemsMap.createInstance();
if (!resultSet.next()) {
return executableRampExceptionalFlowItemsMap;
}
do {
executableRampExceptionalFlowItemsMap
.add(
resultSet.getString(1),
resultSet.getString(2),
ExecutableRampStatus.of(resultSet.getString(3)),
resultSet.getLong(4)
);
} while (resultSet.next());
return executableRampExceptionalFlowItemsMap;
}
}
public ExecutableRampExceptionalFlowItemsMap fetchExecutableRampExceptionalFlowItemsMap()
throws ExecutorManagerException {
try {
return this.dbOperator.query(
FetchExecutableRampExceptionalFlowItems.FETCH_EXECUTABLE_RAMP_EXCEPTIONAL_FLOW_ITEMS,
new FetchExecutableRampExceptionalFlowItems()
);
} catch (final SQLException e) {
throw new ExecutorManagerException("Error fetching Executable Ramp Exceptional Flow Items", e);
}
}
private enum RampExceptionalJobItemsTableFields {
FIELD_RAMP_ID("rampId"),
FIELD_FLOW_ID("flowId"),
FIELD_JOB_ID("jobId"),
FIELD_TREATMENT("treatment"),
FIELD_TIME_STAMP("timestamp");
final String value;
RampExceptionalJobItemsTableFields(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
/**
* Fetch Executable Ramp's Exceptional Job Items
*/
private static class FetchExecutableRampExceptionalJobItems implements ResultSetHandler<ExecutableRampExceptionalJobItemsMap> {
static String FETCH_EXECUTABLE_RAMP_EXCEPTIONAL_JOB_ITEMS = "SELECT "
+ RampExceptionalJobItemsTableFields.FIELD_RAMP_ID.getValue() + ", "
+ RampExceptionalJobItemsTableFields.FIELD_FLOW_ID.getValue() + ", "
+ RampExceptionalJobItemsTableFields.FIELD_JOB_ID.getValue() + ", "
+ RampExceptionalJobItemsTableFields.FIELD_TREATMENT.getValue() + ", "
+ RampExceptionalJobItemsTableFields.FIELD_TIME_STAMP.getValue()
+ " FROM ramp_exceptional_job_items ";
@Override
public ExecutableRampExceptionalJobItemsMap handle(ResultSet resultSet) throws SQLException {
final ExecutableRampExceptionalJobItemsMap executableRampExceptionalJobItemsMap
= ExecutableRampExceptionalJobItemsMap.createInstance();
if (!resultSet.next()) {
return executableRampExceptionalJobItemsMap;
}
do {
executableRampExceptionalJobItemsMap.add(
resultSet.getString(1),
resultSet.getString(2),
resultSet.getString(3),
ExecutableRampStatus.of(resultSet.getString(4)),
resultSet.getLong(5)
);
} while (resultSet.next());
return executableRampExceptionalJobItemsMap;
}
}
public ExecutableRampExceptionalJobItemsMap fetchExecutableRampExceptionalJobItemsMap()
throws ExecutorManagerException {
try {
return this.dbOperator.query(
FetchExecutableRampExceptionalJobItems.FETCH_EXECUTABLE_RAMP_EXCEPTIONAL_JOB_ITEMS,
new FetchExecutableRampExceptionalJobItems()
);
} catch (final SQLException e) {
throw new ExecutorManagerException("Error fetching Executable Ramp Exceptional Flow Items", e);
}
}
// ------------------------------------------------------------------
// Ramp DataSets Management Section
// ------------------------------------------------------------------
/**
* Generic Insert Action Function
* @param tableName table name
* @param actionData associated action data which include field name value pairs
* @throws ExecutorManagerException
*/
public void insertAction(final String tableName, Map<String, Object> actionData)
throws ExecutorManagerException {
if (actionData.size() == 0) {
throw new ExecutorManagerException(
String.format("Error on inserting into %s WITHOUT ANY DATA", tableName)
);
}
try {
if ("ramp".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("startTime", System.currentTimeMillis())
.build()
);
} else if ("ramp_exceptional_flow_items".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("timestamp", System.currentTimeMillis())
.build()
);
} else if ("ramp_exceptional_job_items".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("timestamp", System.currentTimeMillis())
.build()
);
}
String fieldListString = "";
String positionListString = "";
ArrayList<Object> values = new ArrayList<>();
for (Entry<String, Object> element : actionData.entrySet()) {
fieldListString += "," + element.getKey();
positionListString += ",?";
values.add(element.getValue());
}
String sqlCommand = String.format(
"INSERT INTO %s (%s) VALUES(%s)",
tableName,
fieldListString.substring(1),
positionListString.substring(1)
);
int rows = this.dbOperator.update(sqlCommand, values.toArray());
if (rows <= 0) {
throw new ExecutorManagerException(
String.format("No record(s) is inserted into %s, with data %s", tableName, actionData)
);
}
} catch (final SQLException e) {
throw new ExecutorManagerException(
String.format("Error on inserting into %s, with data %s", tableName, actionData),
e
);
}
}
/**
* Generic Delete Action Function
* @param tableName table name
* @param constraints associated constraints which include field name value pairs
* @throws ExecutorManagerException
*/
public void deleteAction(final String tableName, Map<String, Object> constraints)
throws ExecutorManagerException {
if (constraints.size() == 0) {
throw new ExecutorManagerException(
String.format("Error on deleting from %s WITHOUT ANY CONDITIONS", tableName)
);
}
try {
String conditionListString = "";
ArrayList<Object> values = new ArrayList<>();
for (Entry<String, Object> element : constraints.entrySet()) {
conditionListString += " AND " + element.getKey() + "=?";
values.add(element.getValue());
}
String sqlCommand = String.format(
"DELETE FROM %s WHERE %s",
tableName,
conditionListString.substring(5)
);
int rows = this.dbOperator.update(sqlCommand, values.toArray());
if (rows <= 0) {
throw new ExecutorManagerException(
String.format("Record(s) do(es) not exist in %s, with constraints %s", tableName, constraints)
);
}
} catch (final SQLException e) {
throw new ExecutorManagerException(
String.format("Error on deleting from %s, with data %s", tableName, constraints),
e
);
}
}
/**
* Generic Update Action Function
* @param tableName table name
* @param actionData associated action data which include field name value pairs
* @param constraints associated constraints which include field name value pairs
* @throws ExecutorManagerException
*/
public void updateAction(final String tableName, Map<String, Object> actionData, Map<String, Object> constraints)
throws ExecutorManagerException {
if (actionData.size() == 0 || constraints.size() == 0) {
throw new ExecutorManagerException(
String.format("Error on updating %s WITHOUT ANY CONDITIONS OR ANY CHANGES", tableName)
);
}
try {
if ("ramp".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("lastUpdatedTime", System.currentTimeMillis())
.build()
);
} else if ("ramp_exceptional_flow_items".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("timestamp", System.currentTimeMillis())
.build()
);
} else if ("ramp_exceptional_job_items".equalsIgnoreCase(tableName)) {
actionData = adjustActionData(
actionData,
ImmutableMap.<String, Object>builder()
.put("timestamp", System.currentTimeMillis())
.build()
);
}
ArrayList<Object> parameters = new ArrayList<>();
String valueListString = "";
for (Entry<String, Object> element : actionData.entrySet()) {
valueListString += ", " + element.getKey() + "=?";
parameters.add(element.getValue());
}
String conditionListString = "";
for (Entry<String, Object> element : constraints.entrySet()) {
conditionListString += " AND " + element.getKey() + "=?";
parameters.add(element.getValue());
}
String sqlCommand = String.format(
"UPDATE %s SET %s WHERE %s",
tableName,
valueListString.substring(2),
conditionListString.substring(5)
);
int rows = this.dbOperator.update(sqlCommand, parameters.toArray());
if (rows <= 0) {
throw new ExecutorManagerException(
String.format("No record(s) is updated for %s, with data %s", tableName, actionData)
);
}
} catch (final SQLException e) {
throw new ExecutorManagerException(
String.format("Error on updating %s, with data %s", tableName, actionData),
e
);
}
}
/**
* Generic data update action for Ramp DataSets
* @param rampActionsMap list of ramp action map
* @return result of each command
*/
public Map<String, String> doRampActions(List<Map<String, Object>> rampActionsMap) {
Map<String, String> result = new HashMap<>();
for(int i = 0; i < rampActionsMap.size(); i++) {
result.put(Integer.toString(i), doRampAction(rampActionsMap.get(i)));
}
return result;
}
private Map<String, Object> adjustActionData(Map<String, Object> actionData, Map<String, Object> defaultValues) {
Map<String, Object> modifiedActionData = new HashMap<>();
actionData.entrySet().stream().forEach(entry -> modifiedActionData.put(entry.getKey(), entry.getValue()));
for (Map.Entry<String, Object> defaultValue : defaultValues.entrySet()) {
if (!modifiedActionData.containsKey(defaultValue.getKey())) {
modifiedActionData.put(defaultValue.getKey(), defaultValue.getValue());
}
}
return modifiedActionData;
}
/**
* Generic data update action for Ramp DataSets
* @param actionDataMap ramp action map
* @return result
* @throws ExecutorManagerException
*/
private String doRampAction(Map<String, Object> actionDataMap) {
String action = (String) actionDataMap.get("action");
String tableName = (String) actionDataMap.get("table");
Map<String, Object> conditions =(Map<String, Object>) actionDataMap.get("conditions");
Map<String, Object> values = (Map<String, Object>) actionDataMap.get("values");
try {
if ("INSERT".equalsIgnoreCase(action)) {
insertAction(tableName, values);
} else if ("DELETE".equalsIgnoreCase(action)) {
deleteAction(tableName, conditions);
} else if ("UPDATE".equalsIgnoreCase(action)) {
updateAction(tableName, values, conditions);
} else {
return String.format(FAILURE_RESULT_FORMATTER, "Invalid Action", actionDataMap.toString());
}
return String.format(SUCCESS_RESULT_FORMATTER, actionDataMap.toString());
} catch (ExecutorManagerException e) {
return String.format(FAILURE_RESULT_FORMATTER, e.toString(), actionDataMap.toString());
}
}
public void updateExecutableRamp(ExecutableRamp executableRamp) throws ExecutorManagerException {
String sqlCommand = "";
try {
// Save all cachedNumTrail, cachedNumSuccess, cachedNumFailure, cachedNumIgnored,
// save isPaused, endTime when it is not zero, lastUpdatedTime when it is changed.
String ramp = executableRamp.getId();
int cachedNumOfTrail = executableRamp.getCachedCount(ExecutableRamp.CountType.TRAIL);
int cachedNumOfSuccess = executableRamp.getCachedCount(ExecutableRamp.CountType.SUCCESS);
int cachedNumOfFailure = executableRamp.getCachedCount(ExecutableRamp.CountType.FAILURE);
int cachedNumOfIgnored = executableRamp.getCachedCount(ExecutableRamp.CountType.IGNORED);
int rampStage = executableRamp.getStage();
long endTime = executableRamp.getEndTime();
boolean isPaused = executableRamp.isPaused();
long lastUpdatedTime = executableRamp.getLastUpdatedTime();
StringBuilder sqlCommandStringBuilder = new StringBuilder();
sqlCommandStringBuilder.append("UPDATE ramp SET ");
sqlCommandStringBuilder.append(String.format("numOfTrail = numOfTrail + %s, ", cachedNumOfTrail));
sqlCommandStringBuilder.append(String.format("numOfFailure = numOfFailure + %s, ", cachedNumOfFailure));
sqlCommandStringBuilder.append(String.format("numOfSuccess = numOfSuccess + %s, ", cachedNumOfSuccess));
sqlCommandStringBuilder.append(String.format("numOfIgnored = numOfIgnored + %s, ", cachedNumOfIgnored));
sqlCommandStringBuilder.append(String.format("rampStage = CASE WHEN rampStage > %s THEN rampStage ELSE %s END, ", rampStage, rampStage));
sqlCommandStringBuilder.append(String.format("endTime = CASE WHEN endTime > %s THEN endTime ELSE %s END, ", endTime, endTime));
sqlCommandStringBuilder.append(String.format("lastUpdatedTime = CASE WHEN lastUpdatedTime > %s THEN lastUpdatedTime ELSE %s END", lastUpdatedTime, lastUpdatedTime));
if (isPaused) {
sqlCommandStringBuilder.append(", isPaused = true");
}
sqlCommandStringBuilder.append(String.format(" WHERE rampId = '%s'", ramp));
sqlCommand = sqlCommandStringBuilder.toString();
int rows = this.dbOperator.update(sqlCommand);
if (rows <= 0) {
throw new ExecutorManagerException(
String.format("No record(s) is updated into ramp, by command [%s]", sqlCommand)
);
}
} catch (final SQLException e) {
throw new ExecutorManagerException(
String.format("Error on update into ramp, by command [%s]", sqlCommand),
e
);
}
}
public void updateExecutedRampFlows(final String ramp, ExecutableRampExceptionalItems executableRampExceptionalItems)
throws ExecutorManagerException {
String sqlCommand = "";
try {
Object[][] parameters = executableRampExceptionalItems.getCachedItems().stream()
.map(item -> {
ArrayList<Object> object = new ArrayList<>();
object.add(ramp);
object.add(item.getKey());
object.add(item.getValue().getStatus().getKey());
object.add(item.getValue().getTimeStamp());
return object.toArray();
})
.collect(Collectors.toList()).toArray(new Object[0][]);
if (parameters.length > 0) {
sqlCommand = "INSERT INTO ramp_exceptional_flow_items (rampId, flowId, treatment, timestamp) VALUES(?,?,?,?)";
this.dbOperator.batch(sqlCommand, parameters);
executableRampExceptionalItems.resetCacheFlag();
}
} catch (final SQLException e) {
throw new ExecutorManagerException(
String.format("Error on update into ramp, by command [%s]", sqlCommand),
e
);
}
}
}
| apache-2.0 |
weiwenqiang/GenesisFreelander | app/src/main/java/com/wwq/genesisfreelander/mvp/presenter/setting/SetCommentPresenter.java | 1493 | package com.wwq.genesisfreelander.mvp.presenter.setting;
import com.wwq.genesisfreelander.model.json.FindTalkEntity;
import com.wwq.genesisfreelander.mvp.contract.setting.SetCommentContract;
import com.wwq.genesisfreelander.mvp.model.setting.SetCommentModel;
import rx.Subscriber;
import rx.Subscription;
/**
* Created by wwq on 2017/6/8.
*/
public class SetCommentPresenter extends SetCommentContract.Presenter {
public SetCommentPresenter(SetCommentContract.View view) {
mView = view;
mModel = new SetCommentModel();
}
@Override
public void getFindTalk(String token, int type, int start) {
Subscription subscribe = mModel.getFindTalk(token, type, start)
.subscribe(new Subscriber<FindTalkEntity>() {
@Override
public void onStart() {
mView.showDialog();
}
@Override
public void onCompleted() {
mView.hideDialog();
}
@Override
public void onError(Throwable e) {
mView.onFail(e.getMessage());
onCompleted();
}
@Override
public void onNext(FindTalkEntity findTalkEntity) {
mView.onSucceed(findTalkEntity);
}
});
addSubscribe(subscribe);
}
} | apache-2.0 |
lephong/iornn-depparse | tools/mstparser/src/main/java/mstparser/io/CONLLWriter.java | 2238 | ///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2007 University of Texas at Austin and (C) 2005
// University of Pennsylvania and Copyright (C) 2002, 2003 University
// of Massachusetts Amherst, Department of Computer Science.
//
// This software is licensed under the terms of the Common Public
// License, Version 1.0 or (at your option) any subsequent version.
//
// The license is approved by the Open Source Initiative, and is
// available from their website at http://www.opensource.org.
///////////////////////////////////////////////////////////////////////////////
package mstparser.io;
import java.io.IOException;
import java.text.DecimalFormat;
import mstparser.DependencyInstance;
/**
* A writer to create files in CONLL format.
*
* <p>
* Created: Sat Nov 10 15:25:10 2001
* </p>
*
* @author Jason Baldridge
* @version $Id: CONLLWriter.java 137 2013-09-10 09:33:47Z wyldfire $
* @see mstparser.io.DependencyWriter
*/
public class CONLLWriter extends DependencyWriter {
public CONLLWriter(boolean labeled) {
this.labeled = labeled;
}
@Override
public void write(DependencyInstance instance) throws IOException {
DecimalFormat df = null;
if (instance.confidenceScores != null) {
df = new DecimalFormat();
df.setMaximumFractionDigits(3);
}
for (int i = 0; i < instance.length(); i++) {
writer.write(Integer.toString(i + 1));
writer.write('\t');
writer.write(instance.forms[i]);
writer.write('\t');
writer.write(instance.forms[i]);
writer.write('\t');
// writer.write(instance.cpostags[i]); writer.write('\t');
writer.write(instance.cpostags[i]);
writer.write('\t');
writer.write(instance.postags[i]);
writer.write('\t');
writer.write("-");
writer.write('\t');
writer.write(Integer.toString(instance.heads[i]));
writer.write('\t');
writer.write(instance.deprels[i]);
writer.write('\t');
writer.write("-\t-");
if (instance.confidenceScores != null) {
writer.write('\t');
writer.write(df.format(instance.confidenceScores[i]));
}
writer.newLine();
}
writer.newLine();
}
}
| apache-2.0 |
jbottel/openstorefront | server/openstorefront/openstorefront-core/model/src/main/java/edu/usu/sdl/openstorefront/core/entity/UserWatch.java | 2441 | /*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research 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 edu.usu.sdl.openstorefront.core.entity;
import edu.usu.sdl.openstorefront.common.util.OpenStorefrontConstant;
import edu.usu.sdl.openstorefront.core.annotation.APIDescription;
import edu.usu.sdl.openstorefront.core.annotation.ConsumeField;
import edu.usu.sdl.openstorefront.core.annotation.FK;
import edu.usu.sdl.openstorefront.core.annotation.PK;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author jlaw
*/
@APIDescription("Hold watch information")
public class UserWatch
extends StandardEntity<UserWatch>
{
@PK(generated = true)
@NotNull
private String userWatchId;
@NotNull
@ConsumeField
private Date lastViewDts;
@NotNull
@ConsumeField
@FK(Component.class)
private String componentId;
@NotNull
@Size(min = 1, max = OpenStorefrontConstant.FIELD_SIZE_USERNAME)
@ConsumeField
@FK(UserProfile.class)
private String username;
@NotNull
@ConsumeField
@APIDescription("Notify when watch is triggered")
private Boolean notifyFlg;
public UserWatch()
{
}
public String getUserWatchId()
{
return userWatchId;
}
public void setUserWatchId(String userWatchId)
{
this.userWatchId = userWatchId;
}
public Date getLastViewDts()
{
return lastViewDts;
}
public void setLastViewDts(Date lastViewDts)
{
this.lastViewDts = lastViewDts;
}
public String getComponentId()
{
return componentId;
}
public void setComponentId(String componentId)
{
this.componentId = componentId;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public Boolean getNotifyFlg()
{
return notifyFlg;
}
public void setNotifyFlg(Boolean notifyFlg)
{
this.notifyFlg = notifyFlg;
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-videointelligence/v1p1beta1/1.31.0/com/google/api/services/videointelligence/v1p1beta1/model/GoogleCloudVideointelligenceV1p2beta1LabelAnnotation.java | 6036 | /*
* 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.videointelligence.v1p1beta1.model;
/**
* Label annotation.
*
* <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 Video Intelligence 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 GoogleCloudVideointelligenceV1p2beta1LabelAnnotation extends com.google.api.client.json.GenericJson {
/**
* Common categories for the detected entity. For example, when the label is `Terrier`, the
* category is likely `dog`. And in some cases there might be more than one categories e.g.,
* `Terrier` could also be a `pet`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p2beta1Entity> categoryEntities;
static {
// hack to force ProGuard to consider GoogleCloudVideointelligenceV1p2beta1Entity used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudVideointelligenceV1p2beta1Entity.class);
}
/**
* Detected entity.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudVideointelligenceV1p2beta1Entity entity;
/**
* All video frames where a label was detected.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelFrame> frames;
/**
* All video segments where a label was detected.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelSegment> segments;
/**
* Feature version.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String version;
/**
* Common categories for the detected entity. For example, when the label is `Terrier`, the
* category is likely `dog`. And in some cases there might be more than one categories e.g.,
* `Terrier` could also be a `pet`.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p2beta1Entity> getCategoryEntities() {
return categoryEntities;
}
/**
* Common categories for the detected entity. For example, when the label is `Terrier`, the
* category is likely `dog`. And in some cases there might be more than one categories e.g.,
* `Terrier` could also be a `pet`.
* @param categoryEntities categoryEntities or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation setCategoryEntities(java.util.List<GoogleCloudVideointelligenceV1p2beta1Entity> categoryEntities) {
this.categoryEntities = categoryEntities;
return this;
}
/**
* Detected entity.
* @return value or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1Entity getEntity() {
return entity;
}
/**
* Detected entity.
* @param entity entity or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation setEntity(GoogleCloudVideointelligenceV1p2beta1Entity entity) {
this.entity = entity;
return this;
}
/**
* All video frames where a label was detected.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelFrame> getFrames() {
return frames;
}
/**
* All video frames where a label was detected.
* @param frames frames or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation setFrames(java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelFrame> frames) {
this.frames = frames;
return this;
}
/**
* All video segments where a label was detected.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelSegment> getSegments() {
return segments;
}
/**
* All video segments where a label was detected.
* @param segments segments or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation setSegments(java.util.List<GoogleCloudVideointelligenceV1p2beta1LabelSegment> segments) {
this.segments = segments;
return this;
}
/**
* Feature version.
* @return value or {@code null} for none
*/
public java.lang.String getVersion() {
return version;
}
/**
* Feature version.
* @param version version or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation setVersion(java.lang.String version) {
this.version = version;
return this;
}
@Override
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation set(String fieldName, Object value) {
return (GoogleCloudVideointelligenceV1p2beta1LabelAnnotation) super.set(fieldName, value);
}
@Override
public GoogleCloudVideointelligenceV1p2beta1LabelAnnotation clone() {
return (GoogleCloudVideointelligenceV1p2beta1LabelAnnotation) super.clone();
}
}
| apache-2.0 |
box/mojito | webapp/src/main/java/com/box/l10n/mojito/service/tm/ImportExportNote.java | 2582 | package com.box.l10n.mojito.service.tm;
import com.box.l10n.mojito.entity.TMTextUnitVariant;
import com.box.l10n.mojito.entity.TMTextUnitVariantComment;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Used to serialize/deserialize the note element used for import/export.
*
* <p>
* The note element is used to store different information and is used instead
* of some XLIFF attributes because Okapi doesn't provide access to all of them.
*
* @author jaurambault
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ImportExportNote {
String sourceComment;
String targetComment;
boolean reviewNeeded = false;
boolean includedInLocalizedFile = true;
TMTextUnitVariant.Status status = TMTextUnitVariant.Status.APPROVED;
List<TMTextUnitVariantComment> variantComments = new ArrayList<>();
DateTime createdDate;
String pluralForm;
String pluralFormOther;
public String getSourceComment() {
return sourceComment;
}
public void setSourceComment(String sourceComment) {
this.sourceComment = sourceComment;
}
public String getTargetComment() {
return targetComment;
}
public void setTargetComment(String targetComment) {
this.targetComment = targetComment;
}
public TMTextUnitVariant.Status getStatus() {
return status;
}
public void setStatus(TMTextUnitVariant.Status status) {
this.status = status;
}
public boolean isIncludedInLocalizedFile() {
return includedInLocalizedFile;
}
public void setIncludedInLocalizedFile(boolean includedInLocalizedFile) {
this.includedInLocalizedFile = includedInLocalizedFile;
}
public List<TMTextUnitVariantComment> getVariantComments() {
return variantComments;
}
public void setVariantComments(List<TMTextUnitVariantComment> variantComments) {
this.variantComments = variantComments;
}
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public String getPluralForm() {
return pluralForm;
}
public void setPluralForm(String pluralForm) {
this.pluralForm = pluralForm;
}
public String getPluralFormOther() {
return pluralFormOther;
}
public void setPluralFormOther(String pluralFormOther) {
this.pluralFormOther = pluralFormOther;
}
}
| apache-2.0 |
creising/CueServer-Client | cli/src/main/java/org/urbanbyte/cueserver/cli/actions/DeleteCueAction.java | 1098 | package org.urbanbyte.cueserver.cli.actions;
import org.urbanbyte.cueserver.CueServerClient;
import org.urbanbyte.cueserver.cli.InputParser;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Example for updating a cue.
* <p>
* author: Chris Reising
*/
public class DeleteCueAction implements Action
{
/** CueServer client */
private final CueServerClient client;
/** For reading input from the user. */
private final InputParser parser = new InputParser();
/**
* Creates a new {@code DetailedPlaybackStatusAction}.
*
* @param client client to retrieve from.
*/
public DeleteCueAction(CueServerClient client)
{
this.client = checkNotNull(client, "client cannot be null.");
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription()
{
return "Delete a cue";
}
/**
* {@inheritDoc}
*/
@Override
public void executeAction()
{
double cueNumber = parser.readDouble("Enter cue number: ");
client.deleteCue(cueNumber);
}
}
| apache-2.0 |
ruediste/rise | framework/src/main/java/com/github/ruediste/rise/component/tree/IViewValue.java | 806 | package com.github.ruediste.rise.component.tree;
import java.util.function.Supplier;
/**
* Represents a value in the view.
*
* <p>
* In Rise, there is a controller and a view state. Whenever the view is
* reloaded, the view state is updated based on the values of the
* {@link Component}s, the request is processed and finally the view is
* updated again from the view state.
*
* <p>
* When the controller decides to trigger the binding, all bindings are applied
* from the view state to the controller state.
*
* <img src="doc-files/viewAndControllerState.png" alt=
* "Overview of Ui State, View State and Controller State">
*
* <p>
* The view state can be represented by variables in the view,
*
*/
public interface IViewValue<T> extends Supplier<T> {
void set(T value);
}
| apache-2.0 |
yintaoxue/read-open-source-code | kettle4.3/src/org/pentaho/di/trans/steps/getslavesequence/GetSlaveSequenceData.java | 1522 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.getslavesequence;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;
/**
* @author Matt
* @since 24-jan-2005
*/
public class GetSlaveSequenceData extends BaseStepData implements StepDataInterface
{
public RowMetaInterface outputRowMeta;
public SlaveServer slaveServer;
public long value;
public long startValue;
public long increment;
public String sequenceName;
/**
*
*/
public GetSlaveSequenceData()
{
super();
}
} | apache-2.0 |
scribble/scribble.github.io | src/main/jbake/assets/docs/scribble/modules/parser/src/main/java/org/scribble/parser/ast/AntlrMessageSigDecl.java | 1710 | package org.scribble.parser.ast;
import org.antlr.runtime.tree.CommonTree;
import org.scribble.ast.MessageSigNameDecl;
import org.scribble.ast.AstFactoryImpl;
import org.scribble.ast.name.qualified.MessageSigNameNode;
import org.scribble.parser.ScribParser;
import org.scribble.parser.ast.name.AntlrSimpleName;
// FIXME: factor out with AntlrDataTypeDecl
public class AntlrMessageSigDecl
{
public static final int SCHEMA_CHILD_INDEX = 0;
public static final int EXTNAME_CHILD_INDEX = 1;
public static final int SOURCE_CHILD_INDEX = 2;
public static final int ALIAS_CHILD_INDEX = 3;
public static MessageSigNameDecl parseMessageSigDecl(ScribParser parser, CommonTree ct)
{
CommonTree tmp1 = getSchemaChild(ct);
String schema = AntlrSimpleName.getName(tmp1);
CommonTree tmp2 = getExtNameChild(ct);
String extName = AntlrExtIdentifier.getName(tmp2);
CommonTree tmp3 = getSourceChild(ct);
String source = AntlrExtIdentifier.getName(tmp3);
MessageSigNameNode alias = AntlrSimpleName.toMessageSigNameNode(getAliasChild(ct));
return AstFactoryImpl.FACTORY.MessageSigNameDecl(ct, schema, extName, source, alias);
}
public static CommonTree getSchemaChild(CommonTree ct)
{
return (CommonTree) ct.getChild(SCHEMA_CHILD_INDEX);
}
public static CommonTree getExtNameChild(CommonTree ct)
{
return (CommonTree) ct.getChild(EXTNAME_CHILD_INDEX);
}
public static CommonTree getSourceChild(CommonTree ct)
{
return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX);
}
public static CommonTree getAliasChild(CommonTree ct)
{
return (CommonTree) ct.getChild(ALIAS_CHILD_INDEX);
}
public static CommonTree getModuleParent(CommonTree ct)
{
return (CommonTree) ct.getParent();
}
}
| apache-2.0 |
Urucas/deskflix | android/Deskflix/app/src/main/java/com/urucas/deskflix/interfaces/VolumeKeysCallback.java | 190 | package com.urucas.deskflix.interfaces;
/**
* Created by Urucas on 8/20/14.
*/
public interface VolumeKeysCallback {
public void onVolumeUp();
public void onVolumeDown();
}
| apache-2.0 |
ebayopensource/turmeric-runtime | integration-tests/SOATests/src/test/java/org/ebayopensource/turmeric/runtime/tests/parser/json/JSONParserTest.java | 24860 | /*******************************************************************************
* Copyright (c) 2006-2010 eBay 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
*******************************************************************************/
package org.ebayopensource.turmeric.runtime.tests.parser.json;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.ebayopensource.turmeric.runtime.binding.impl.parser.NamespaceConvention;
import org.ebayopensource.turmeric.runtime.binding.impl.parser.ParseException;
import org.ebayopensource.turmeric.runtime.binding.impl.parser.json.JSONStreamObjectNodeImpl;
import org.ebayopensource.turmeric.runtime.binding.impl.parser.json.JSONStreamReadContext;
import org.ebayopensource.turmeric.runtime.binding.objectnode.ObjectNode;
import org.ebayopensource.turmeric.runtime.common.impl.binding.jaxb.DataBindingFacade;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author wdeng
*/
public class JSONParserTest {
private final Logger logger = LoggerFactory.getLogger(JSONParserTest.class);
private static final String JSON_INPUT_WITH_NUMBER_AND_BOOLEAN =
"{\"jsonns.ns\":\"http://www.ebay.com/soaframework/test/JAXBDataBinding\"," +
"\"ns.MyMessage\":{\"body\":100,\"recipients\":[" +
"{\"city\":-100,\"emailAddress\":1.00,\"postCode\":-1.2e+12,\"state\":true,\"streetNumber\":false}, " +
"{\"city\":null,\"emailAddress\":{},\"postCode\":\"95126\",\"state\":\"CA\",\"streetNumber\":\"2245\"}" +
"],\"subject\":\"Test SOA JAXB XML ser/deser\"}}\n";
private static final String JSON_INPUT_WITH_ARRAY =
"{\"jsonns.ns\":\"http://www.ebay.com/soaframework/test/JAXBDataBinding\"," +
"\"ns.MyMessage\":{\"body\":\"SOA SOA, SOS.\",\"recipients\":[" +
"{\"city\":\"San Jose\",\"emailAddress\":\"soa@ebay.com\",\"postCode\":\"95125\",\"state\":\"CA\",\"streetNumber\":\"2145\"}, " +
"{\"city\":\"San Jose\",\"emailAddress\":\"api@ebay.com\",\"postCode\":\"95126\",\"state\":\"CA\",\"streetNumber\":\"2245\"}" +
"],\"subject\":\"Test SOA JAXB XML ser/deser\"}}\n";
private static final String JSON_INPUT_WITH_MAP =
"{\"jsonns.ns\":\"http://www.ebay.com/soaframework/test/JAXBDataBinding\"," +
"\"ns.MyMessage\":{\"body\":\"SOA SOA, SOS.\",\"recipients\":" +
"{\"entry\":{\"key\":\"soa@ebay.com\",\"value\":{\"city\":\"San Jose\",\"emailAddress\":" +
"\"soa@ebay.com\",\"postCode\":\"95125\",\"state\":\"CA\",\"streetNumber\":\"2145\"}}}," +
"\"subject\":\"Test SOA JAXB XML ser/deser\"}}\n";
private static final String JSON_BAD_INPUT_WITH_ARRAY =
"{\"jsonns:ns\":\"http://www.ebay.com/soaframework/test/JAXBDataBinding\" " +
"\"ns.MyMessage\"{\"body\":\"SOA SOA, SOS.\",\"recipients\"::" +
"{\"city\":\"San Jose\"\"emailAddress\":\"soa@ebay.com\",\"postCode\":\"95125\",\"state\":\"CA\",\"streetNumber\":\"2145\"}: " +
"{\"city\":\"San Jose\",\"emailAddress\":\"api@ebay.com\",\"postCode\":\"95126\",\"state\":\"CA\",\"streetNumber\":\"2245\"}" +
"],\"subject\":\"Test SOA JAXB XML ser/deser\"}}\n";
private static final String JSON_INPUT_FOR_BUG486468 =
"{\n" +
" \"jsonns.xsi\":\"http://www.w3.org/2001/XMLSchema-instance\",\n" +
" \"jsonns.ns2\":\"http://www.ebay.com/test/soaframework/sample/service/message\",\n" +
" \"jsonns.ns1\":\"http://www.ebay.com/test/soaframework/sample/errors\",\n" +
" \"jsonns.xs\":\"http://www.w3.org/2001/XMLSchema\",\n" +
" \"jsonns.sct\":\"http://www.ebayopensource.org/turmeric/common/v1/types\",\n" +
" \"ns2.MyMessage\":\n" +
" [\n" +
" {\n" +
" \"error\":\n" +
" [\n" +
" {\n" +
" \"ErrorParameters\":\n" +
" [\n" +
" {\n" +
" \"@ParamID\":\"Exception\",\n" +
" \"Value\":\"org.ebayopensource.turmeric.runtime.tests.sample.services.message.Test1Exception\"\n" +
" }\n" +
" ],\n" +
" \"errorClassification\":\"CustomCode\",\n" +
" \"errorCode\":\"2005\",\n" +
" \"longMessage\":\"Internal application error: org.ebayopensource.turmeric.runtime.tests.sample.services.message.Test1Exception: Our test1 exception\",\n" +
" \"severityCode\":\"Error\",\n" +
" \"shortMessage\":\"Internal application error: org.ebayopensource.turmeric.runtime.tests.sample.services.message.Test1Exception: Our test1 exception\"\n" +
" }\n" +
" ],\n" +
" \"recipients\":\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}\n";
private static final String JSON_INPUT_WITH_DEPTH_FIRST_ELEMENT =
"{\"ns.MyMessage\":{\"body\":\"SOA SOA, SOS.\",\"recipients\":" +
"{\"entry\":{\"key\":\"soa@ebay.com\",\"value\":{\"city\":\"San Jose\",\"emailAddress\":" +
"\"soa@ebay.com\",\"postCode\":\"95125\",\"state\":\"CA\",\"streetNumber\":\"2145\"}}}," +
"\"subject\":\"Test SOA JAXB XML ser/deser\"}," +
"\"jsnns.ns\":\"http://www.ebay.com/soaframework/test/JAXBDataBinding\"}\n";
private static final String GOLD_JSON_INPUT_WITH_NUMBER_AND_BOOLEAN =
"root:{\n" +
" jsonns.ns:http://www.ebay.com/soaframework/test/JAXBDataBinding\n" +
" ns.MyMessage:{\n" +
" body:100\n" +
" recipients:{\n" +
" city:-100\n" +
" emailAddress:1.00\n" +
" postCode:-1.2e+12\n" +
" state:true\n" +
" streetNumber:false\n" +
" }\n" +
" recipients:{\n" +
" city:{}\n" +
" emailAddress:{}\n" +
" postCode:95126\n" +
" state:CA\n" +
" streetNumber:2245\n" +
" }\n" +
" subject:Test SOA JAXB XML ser/deser\n" +
" }\n" +
"}\n";
private static final String GOLD_RESULT_HASHMAP =
"root:{\n" +
" jsonns.ns:http://www.ebay.com/soaframework/test/JAXBDataBinding\n" +
" ns.MyMessage:{\n" +
" body:SOA SOA, SOS.\n" +
" recipients:{\n" +
" entry:{\n" +
" key:soa@ebay.com\n" +
" value:{\n" +
" city:San Jose\n" +
" emailAddress:soa@ebay.com\n" +
" postCode:95125\n" +
" state:CA\n" +
" streetNumber:2145\n" +
" }\n" +
" }\n" +
" }\n" +
" subject:Test SOA JAXB XML ser/deser\n" +
" }\n" +
"}\n";
private static final String GOLD_RESULT_ARRAY =
"root:{\n" +
" jsonns.ns:http://www.ebay.com/soaframework/test/JAXBDataBinding\n" +
" ns.MyMessage:{\n" +
" body:SOA SOA, SOS.\n" +
" recipients:{\n" +
" city:San Jose\n" +
" emailAddress:soa@ebay.com\n" +
" postCode:95125\n" +
" state:CA\n" +
" streetNumber:2145\n" +
" }\n" +
" recipients:{\n" +
" city:San Jose\n" +
" emailAddress:api@ebay.com\n" +
" postCode:95126\n" +
" state:CA\n" +
" streetNumber:2245\n" +
" }\n" +
" subject:Test SOA JAXB XML ser/deser\n" +
" }\n" +
"}\n";
private static final String GOLD_JSON_INPUT_PAYPAL_ISSUE =
"root:{\n" +
"\tactionType:PAY\n" +
"\tcurrencyCode:USD\n" +
"\treceiverList:{\n" +
"\t\treceiver:{\n" +
"\t\t\tamount:1.00\n" +
"\t\t\temail:seller_1288085303_biz@gmail.com\n" +
"\t\t}\n" +
"\t}\n" +
"\treturnUrl:http://apigee.com/console/-1/handlePaypalReturn\n" +
"\tcancelUrl:http://apigee.com/console/-1/handlePaypalCancel?\n" +
"\trequestEnvelope:{\n" +
"\t\terrorLanguage:en_US\n" +
"\t\tdetailLevel:ReturnAll\n" +
"\t}\n" +
"}\n";
@Test
public void jSONParserPayPalSpaceIssue() throws Exception {
String JSON_INPUT_PAYPAL_ISSUE =
"{" +
" \"actionType\" : \"PAY\"," +
" \"currencyCode\" : \"USD\"," +
" \"receiverList\" : {" +
" \"receiver\":[{\"amount\":\"1.00\",\"email\":\"seller_1288085303_biz@gmail.com\"}]" +
" }," +
" \"returnUrl\" : \"http://apigee.com/console/-1/handlePaypalReturn\"," +
" \"cancelUrl\" : \"http://apigee.com/console/-1/handlePaypalCancel?\"," +
" \"requestEnvelope\" : {\"errorLanguage\":\"en_US\", \"detailLevel\":\"ReturnAll\"}" +
" }";
logger.debug("**** Starting jSONParserPayPalSpaceIssue");
logger.debug(JSON_INPUT_PAYPAL_ISSUE);
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_PAYPAL_ISSUE.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
ObjectNode clone = root.cloneNode();
root.getChildNodes();
logger.debug(root.getTree());
assertEquals(GOLD_JSON_INPUT_PAYPAL_ISSUE, root.getTree());
logger.debug("**** Ending jSONParserPayPalSpaceIssue");
}
@Test
public void jSONParserPayPalNoSpaceIssue() throws Exception {
String JSON_INPUT_PAYPAL_ISSUE =
"{" +
" \"actionType\": \"PAY\"," +
" \"currencyCode\": \"USD\"," +
" \"receiverList\" : {" +
" \"receiver\":[{\"amount\":\"1.00\",\"email\":\"seller_1288085303_biz@gmail.com\"}]" +
" }," +
" \"returnUrl\": \"http://apigee.com/console/-1/handlePaypalReturn\"," +
" \"cancelUrl\": \"http://apigee.com/console/-1/handlePaypalCancel?\"," +
" \"requestEnvelope\" : {\"errorLanguage\":\"en_US\", \"detailLevel\":\"ReturnAll\"}" +
" }";
logger.debug("**** Starting jSONParserPayPalSpaceIssue");
logger.debug(JSON_INPUT_PAYPAL_ISSUE);
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_PAYPAL_ISSUE.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
ObjectNode clone = root.cloneNode();
root.getChildNodes();
logger.debug(root.getTree());
assertEquals(GOLD_JSON_INPUT_PAYPAL_ISSUE, root.getTree());
logger.debug("**** Ending jSONParserPayPalSpaceIssue");
}
@Test
public void jSONParserWithNumberAndBoolean() throws Exception {
logger.debug("**** Starting jSONParserWithNumberAndBoolean");
logger.debug(JSON_INPUT_WITH_NUMBER_AND_BOOLEAN);
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_NUMBER_AND_BOOLEAN.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
ObjectNode clone = root.cloneNode();
root.getChildNodes();
logger.debug(root.getTree());
assertEquals(GOLD_JSON_INPUT_WITH_NUMBER_AND_BOOLEAN, root.getTree());
// assertEquals(clone.getNodeName().getLocalPart(), root.getNodeName().getLocalPart());
logger.debug("**** Ending jSONParserWithNumberAndBoolean");
}
@Test
public void lazyReadJSONParserWithHashMap() throws Exception {
logger.debug("**** Starting testLazyReadJSONParserWithHashMap");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
logger.debug(GOLD_RESULT_HASHMAP);
logger.debug(root.toString());
assertEquals(GOLD_RESULT_HASHMAP, root.getTree());
logger.debug("**** Ending testLazyReadJSONParserWithHashMap");
}
@Test
public void jSONParserWithHashMap() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
ObjectNode clone = root.cloneNode();
root.getChildNodes();
assertEquals(GOLD_RESULT_HASHMAP, root.getTree());
assertEquals(clone.getNodeName().getLocalPart(), root.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithHashMap");
}
private static final String JSON_INPUT_WITH_PRIMATIVE_TYPE_ARRAY =
"{\"MyObject\":[{\"emailAddress\":[\"dp@ebay.com\"],\"id\":[\"1000\"],\"names\":[\"Dave\",\"David\",\"D\"]}]}";
private static final String GOLD_RESULT_WITH_PRIMATIVE_TYPE_ARRAY =
"root:{\n" +
" MyObject:{\n" +
" emailAddress:dp@ebay.com\n" +
" id:1000\n" +
" names:Dave\n" +
" names:David\n" +
" names:D\n" +
" }\n" +
"}\n";
@Test
public void jSONParserWithPrimativeArray() throws Exception {
logger.debug("**** Starting testJSONParserWithPrimativeArray");
logger.debug(JSON_INPUT_WITH_PRIMATIVE_TYPE_ARRAY);
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_PRIMATIVE_TYPE_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
ObjectNode clone = root.cloneNode();
root.getChildNodes();
assertEquals(GOLD_RESULT_WITH_PRIMATIVE_TYPE_ARRAY, root.getTree());
assertEquals(clone.getNodeName().getLocalPart(), root.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithPrimativeArray");
}
@Test
public void jSONParserWithPrimativeArrayOnDemand() throws Exception {
logger.debug("**** Starting testJSONParserWithPrimativeArrayOnDemand");
logger.debug(JSON_INPUT_WITH_PRIMATIVE_TYPE_ARRAY);
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_PRIMATIVE_TYPE_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
assertEquals(GOLD_RESULT_WITH_PRIMATIVE_TYPE_ARRAY, root.getTree());
logger.debug("**** Ending testJSONParserWithPrimativeArrayOnDemand");
}
@Test
public void jSONParserWithHashMap2() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap2");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
int numChilds = root.getChildNodesSize();
root.getChildNodes();
assertEquals("Incorrect number of children returned", 2, numChilds);
logger.debug("**** Ending testJSONParserWithHashMap2");
}
@Test
public void jSONParserWithHashMap3() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap3");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
assertTrue("Has childrens", root.hasChildNodes());
logger.debug("**** Ending testJSONParserWithHashMap3");
}
@Test
public void jSONParserWithHashMap4() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap4");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
String uriNamespace = null;
root.getChildNode(0);
/* QName chqname = root.getChildNode(0).getNodeName();*/
List<ObjectNode> childList = root.getChildNodes(new QName(uriNamespace, "ns", "jsonns"));
assertEquals("Has one child with jssonns:ns", 1, childList.size());
logger.debug("**** Ending testJSONParserWithHashMap4");
}
@Test
public void jSONParserWithHashMap5() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap5");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
String uriNamespace = null;
root.getChildNode(0);
ObjectNode cnode = root.getChildNode(new QName(uriNamespace, "ns", "jsonns"), 0);
assertEquals("Has one child with jssonns:ns", "ns", cnode.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithHashMap5");
}
@Test
public void jSONParserWithHashMap6() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap6");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
String uriNamespace = null;
ObjectNode cnode = root.getChildNode(new QName(uriNamespace, "ns", "jsonns"), 0);
assertEquals("Has one child with jssonns:ns", "ns", cnode.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithHashMap6");
}
@Test
public void jSONParserWithHashMap7() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap7");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
String uriNamespace = null;
/* QName chqname = root.getChildNode(0).getNodeName();*/
List<ObjectNode> childList = root.getChildNodes(new QName(uriNamespace, "ns", "jsonns"));
assertEquals("Has one child with jssonns:ns", 1, childList.size());
logger.debug("**** Ending testJSONParserWithHashMap7");
}
@Test
public void jSONParserWithHashMap8() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap8");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_MAP.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
String uriNamespace = null;
ObjectNode cnode = root.getChildNode(1);
assertEquals("Has one child with jssonns:ns", "MyMessage", cnode.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithHashMap8");
}
@Test
public void jSONParserWithHashMap9() throws Exception {
logger.debug("**** Starting testJSONParserWithHashMap9");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_DEPTH_FIRST_ELEMENT.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
Iterator<ObjectNode> cnodeIter= root.getChildrenIterator();
ObjectNode cnode = cnodeIter.next();
Iterator<ObjectNode> gcnodeIter = cnode.getChildrenIterator();
gcnodeIter.next();
List<ObjectNode> ggcnode = gcnodeIter.next().getChildNodes();
List<ObjectNode> gggcnode = ggcnode.get(0).getChildNodes();
cnodeIter.next();
assertEquals("Has one child with jssonns:ns", "MyMessage", cnode.getNodeName().getLocalPart());
logger.debug("**** Ending testJSONParserWithHashMap9");
}
@Test
public void lazyReadJSONParserWithArray() throws Exception {
logger.debug("**** Starting testLazyReadJSONParserWithArray");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
assertEquals(GOLD_RESULT_ARRAY, root.getTree());
logger.debug("**** Ending testLazyReadJSONParserWithArray");
}
@Test
public void jSONParserWithArray() throws Exception {
logger.debug("**** Starting testJSONParserWithArray");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_WITH_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
root.getChildNodes();
logger.debug("Tree: \n" + root.getTree());
logger.debug("End Tree");
assertEquals(GOLD_RESULT_ARRAY, root.getTree());
logger.debug("**** Ending testJSONParserWithArray");
}
/**
* @check Exceptions need to be handled
*/
@Test
public void bUG486468() throws Exception {
Exception e = null;
logger.debug("**** Starting testBUG486468");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_INPUT_FOR_BUG486468.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
List<ObjectNode> childList = root.getChildNodes();
logger.debug("**** Ending testBUG486468");
}
/**
* @check Exceptions need to be handled
*/
@Test(expected=org.ebayopensource.turmeric.runtime.binding.impl.parser.ParseException.class)
public void jSONParserWithBadInput1() throws Exception {
logger.debug("**** Starting testJSONParserWithBadInput1");
ByteArrayInputStream is = new ByteArrayInputStream(JSON_BAD_INPUT_WITH_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
root.getChildNodes();
fail("ParseException not thrown as expected");
logger.debug("**** Ending testJSONParserWithBadInput1");
}
/**
* @check Exceptions need to be handled
*/
@Test(expected=org.ebayopensource.turmeric.runtime.binding.impl.parser.ParseException.class)
public void jSONParserWithBadInput2() throws Exception {
class MyBAInputStream extends InputStream {
public MyBAInputStream(byte[] buf){
super();
}
public int read() throws IOException {
throw new IOException();
}
public int read(byte[] b, int off, int len) throws IOException {
throw new IOException();
}
};
logger.debug("**** Starting testJSONParserWithBadInput2");
MyBAInputStream is = new MyBAInputStream(JSON_BAD_INPUT_WITH_ARRAY.getBytes());
NamespaceConvention convention = DataBindingFacade.createDeserializationNSConvention(null);
JSONStreamReadContext ctx = new JSONStreamReadContext(is, convention, Charset.forName("ASCII"));
JSONStreamObjectNodeImpl root = new JSONStreamObjectNodeImpl(ctx);
root.getChildNodes();
fail("ParseException not thrown as expected");
logger.debug("**** Ending testJSONParserWithBadInput2");
}
}
| apache-2.0 |
rsahlin/graphics-by-opengl | graphics-by-opengl-j2se/src/main/java/com/nucleus/opengl/shader/NamedShaderVariable.java | 5511 | package com.nucleus.opengl.shader;
import com.nucleus.opengl.GLESWrapper.GLES20;
import com.nucleus.opengl.GLESWrapper.GLES30;
import com.nucleus.shader.ShaderVariable;
/**
* Data for an active named shader variable, ie variable declared and used in a compiled shader.
* This can be attribute, uniform or block variables.
*
*/
public class NamedShaderVariable extends ShaderVariable {
private final static String ILLEGAL_DATATYPE_ERROR = "Illegal datatype: ";
/**
* Offset to size
*/
public final static int SIZE_OFFSET = 0;
/**
* Offset to type
*/
public final static int TYPE_OFFSET = 1;
public static final int NAME_LENGTH_OFFSET = 2;
/**
* Offset to variable data offset
*/
public final static int DATA_OFFSET = 3;
/**
* Offset to block index
*/
public final static int BLOCK_INDEX_OFFSET = 4;
private String name;
/**
* The gl index of this active variable
*/
private int activeIndex;
/**
* Creates a new ActiveVariable from the specified data.
* This constructor can be used with the data from GLES
*
* @param type Type of shader variable
* @param name Name of variable excluding [] and . chars.
* @param index Index of current active variable
* @param data Array holding data at {@value #SIZE_OFFSET}, {@value #TYPE_OFFSET},
* {@value #DATA_OFFSET} {@value #BLOCK_INDEX_OFFSET}
* @param startIndex Start of data.
* @throws ArrayIndexOutOfBoundsException If sizeOffset or typeOffset is larger than data length, or negative.
*/
public NamedShaderVariable(VariableType type, String name, int index, int[] data, int startIndex) {
super(type, data[startIndex + TYPE_OFFSET], data[startIndex + SIZE_OFFSET]);
this.name = name;
activeIndex = index;
this.offset = data.length > startIndex + DATA_OFFSET ? data[startIndex + DATA_OFFSET] : this.offset;
this.blockIndex = data.length > startIndex + BLOCK_INDEX_OFFSET ? data[startIndex + BLOCK_INDEX_OFFSET]
: this.blockIndex;
}
/**
* Returns the active index of this shader variable, this will be 0 - number of active variables.
*
* @return The index of this variable as an active variable
*/
public int getActiveIndex() {
return activeIndex;
}
/**
* Returns the name of this shader variable
*
* @return
*/
public String getName() {
return name;
}
@Override
public int getSizeInFloats() {
switch (dataType) {
case GLES20.GL_FLOAT:
return size;
case GLES20.GL_FLOAT_VEC2:
return 2 * size;
case GLES20.GL_FLOAT_VEC3:
return 3 * size;
case GLES20.GL_FLOAT_VEC4:
return 4 * size;
case GLES20.GL_FLOAT_MAT2:
return 4 * size;
case GLES20.GL_FLOAT_MAT3:
return 9 * size;
case GLES20.GL_FLOAT_MAT4:
return 16 * size;
case GLES20.GL_SAMPLER_2D:
return size;
case GLES30.GL_SAMPLER_2D_SHADOW:
return size;
}
throw new IllegalArgumentException(ILLEGAL_DATATYPE_ERROR + dataType);
}
@Override
public int getSizeInBytes() {
switch (dataType) {
case GLES20.GL_FLOAT:
return size * 4;
case GLES20.GL_FLOAT_VEC2:
return 2 * size * 4;
case GLES20.GL_FLOAT_VEC3:
return 3 * size * 4;
case GLES20.GL_FLOAT_VEC4:
return 4 * size * 4;
case GLES20.GL_FLOAT_MAT2:
return 4 * size * 4;
case GLES20.GL_FLOAT_MAT3:
return 9 * size * 4;
case GLES20.GL_FLOAT_MAT4:
return 16 * size * 4;
case GLES20.GL_SAMPLER_2D:
return size * 4;
case GLES30.GL_SAMPLER_2D_SHADOW:
return size * 4;
}
throw new IllegalArgumentException(ILLEGAL_DATATYPE_ERROR + dataType);
}
@Override
public int getComponentCount() {
switch (dataType) {
case GLES20.GL_FLOAT:
return 1;
case GLES20.GL_FLOAT_VEC2:
return 2;
case GLES20.GL_FLOAT_VEC3:
return 3;
case GLES20.GL_FLOAT_VEC4:
return 4;
case GLES20.GL_FLOAT_MAT2:
return 2;
case GLES20.GL_FLOAT_MAT3:
return 3;
case GLES20.GL_FLOAT_MAT4:
return 4;
}
throw new IllegalArgumentException(ILLEGAL_DATATYPE_ERROR + dataType);
}
@Override
public String toString() {
return name + " : " + super.toString();
}
@Override
public boolean isSampler() {
if (type == VariableType.UNIFORM) {
switch (dataType) {
case GLES20.GL_SAMPLER_2D:
case GLES20.GL_SAMPLER_CUBE:
case GLES30.GL_SAMPLER_2D_SHADOW:
case GLES30.GL_SAMPLER_2D_ARRAY:
case GLES30.GL_SAMPLER_2D_ARRAY_SHADOW:
case GLES30.GL_SAMPLER_CUBE_SHADOW:
case GLES30.GL_SAMPLER_3D:
return true;
default:
return false;
}
}
return false;
}
}
| apache-2.0 |
ralscha/eds-starter6-mongodb | src/main/java/ch/rasc/eds/starter/service/UserService.java | 10491 | package ch.rasc.eds.starter.service;
import static ch.ralscha.extdirectspring.annotation.ExtDirectMethodType.STORE_MODIFY;
import static ch.ralscha.extdirectspring.annotation.ExtDirectMethodType.STORE_READ;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import javax.validation.Validator;
import org.bson.conversions.Bson;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.bean.ExtDirectStoreReadRequest;
import ch.ralscha.extdirectspring.bean.ExtDirectStoreResult;
import ch.ralscha.extdirectspring.filter.StringFilter;
import ch.rasc.eds.starter.config.MongoDb;
import ch.rasc.eds.starter.config.security.RequireAdminAuthority;
import ch.rasc.eds.starter.entity.Authority;
import ch.rasc.eds.starter.entity.CPersistentLogin;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.PersistentLogin;
import ch.rasc.eds.starter.entity.User;
import ch.rasc.eds.starter.util.QueryUtil;
import ch.rasc.eds.starter.util.ValidationMessages;
import ch.rasc.eds.starter.util.ValidationMessagesResult;
import ch.rasc.eds.starter.util.ValidationUtil;
import de.danielbechler.diff.ObjectDiffer;
import de.danielbechler.diff.ObjectDifferBuilder;
import de.danielbechler.diff.node.DiffNode;
import de.danielbechler.diff.node.DiffNode.State;
@Service
@RequireAdminAuthority
public class UserService {
private final MessageSource messageSource;
private final Validator validator;
private final MongoDb mongoDb;
private final MailService mailService;
public UserService(MongoDb mongoDb, Validator validator, MessageSource messageSource,
MailService mailService) {
this.mongoDb = mongoDb;
this.messageSource = messageSource;
this.validator = validator;
this.mailService = mailService;
}
@ExtDirectMethod(STORE_READ)
public ExtDirectStoreResult<User> read(ExtDirectStoreReadRequest request) {
List<Bson> andFilters = new ArrayList<>();
StringFilter filter = request.getFirstFilterForField("filter");
if (filter != null) {
List<Bson> orFilters = new ArrayList<>();
orFilters.add(Filters.regex(CUser.loginName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.lastName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.firstName, filter.getValue(), "i"));
orFilters.add(Filters.regex(CUser.email, filter.getValue(), "i"));
andFilters.add(Filters.or(orFilters));
}
andFilters.add(Filters.eq(CUser.deleted, false));
long total = this.mongoDb.getCollection(User.class)
.countDocuments(Filters.and(andFilters));
FindIterable<User> find = this.mongoDb.getCollection(User.class)
.find(Filters.and(andFilters));
find.sort(Sorts.orderBy(QueryUtil.getSorts(request)));
find.skip(request.getStart());
find.limit(request.getLimit());
return new ExtDirectStoreResult<>(total, QueryUtil.toList(find));
}
@ExtDirectMethod(STORE_MODIFY)
public ExtDirectStoreResult<User> destroy(User destroyUser) {
ExtDirectStoreResult<User> result = new ExtDirectStoreResult<>();
if (!isLastAdmin(destroyUser.getId())) {
this.mongoDb.getCollection(User.class)
.deleteOne(Filters.eq(CUser.id, destroyUser.getId()));
result.setSuccess(Boolean.TRUE);
deletePersistentLogins(destroyUser.getId());
}
else {
result.setSuccess(Boolean.FALSE);
}
return result;
}
private void deletePersistentLogins(String userId) {
this.mongoDb.getCollection(PersistentLogin.class)
.deleteMany(Filters.eq(CPersistentLogin.userId, userId));
}
@ExtDirectMethod(STORE_MODIFY)
public ValidationMessagesResult<User> update(User updatedEntity, Locale locale) {
List<ValidationMessages> violations = validateEntity(updatedEntity, locale);
violations.addAll(checkIfLastAdmin(updatedEntity, locale));
if (violations.isEmpty()) {
List<Bson> updates = new ArrayList<>();
updates.add(Updates.set(CUser.loginName, updatedEntity.getLoginName()));
updates.add(Updates.set(CUser.email, updatedEntity.getEmail()));
updates.add(Updates.set(CUser.firstName, updatedEntity.getFirstName()));
updates.add(Updates.set(CUser.lastName, updatedEntity.getLastName()));
updates.add(Updates.set(CUser.locale, updatedEntity.getLocale()));
updates.add(Updates.set(CUser.enabled, updatedEntity.isEnabled()));
if (updatedEntity.getAuthorities() != null
&& !updatedEntity.getAuthorities().isEmpty()) {
updates.add(
Updates.set(CUser.authorities, updatedEntity.getAuthorities()));
}
else {
updates.add(Updates.unset(CUser.authorities));
}
updates.add(Updates.setOnInsert(CUser.deleted, false));
this.mongoDb.getCollection(User.class).updateOne(
Filters.eq(CUser.id, updatedEntity.getId()), Updates.combine(updates),
new UpdateOptions().upsert(true));
if (!updatedEntity.isEnabled()) {
deletePersistentLogins(updatedEntity.getId());
}
return new ValidationMessagesResult<>(updatedEntity);
}
ValidationMessagesResult<User> result = new ValidationMessagesResult<>(
updatedEntity);
result.setValidations(violations);
return result;
}
private List<ValidationMessages> checkIfLastAdmin(User updatedEntity, Locale locale) {
User dbUser = this.mongoDb.getCollection(User.class)
.find(Filters.eq(CUser.id, updatedEntity.getId())).first();
List<ValidationMessages> validationErrors = new ArrayList<>();
if (dbUser != null && (!updatedEntity.isEnabled()
|| updatedEntity.getAuthorities() == null
|| !updatedEntity.getAuthorities().contains(Authority.ADMIN.name()))) {
if (isLastAdmin(updatedEntity.getId())) {
ObjectDiffer objectDiffer = ObjectDifferBuilder.startBuilding()
.filtering().returnNodesWithState(State.UNTOUCHED).and().build();
DiffNode diff = objectDiffer.compare(updatedEntity, dbUser);
DiffNode diffNode = diff.getChild(CUser.enabled);
if (!diffNode.isUntouched()) {
updatedEntity.setEnabled(dbUser.isEnabled());
ValidationMessages validationError = new ValidationMessages();
validationError.setField(CUser.enabled);
validationError.setMessage(this.messageSource
.getMessage("user_lastadmin_error", null, locale));
validationErrors.add(validationError);
}
diffNode = diff.getChild(CUser.authorities);
if (!diffNode.isUntouched()) {
updatedEntity.setAuthorities(dbUser.getAuthorities());
ValidationMessages validationError = new ValidationMessages();
validationError.setField(CUser.authorities);
validationError.setMessage(this.messageSource
.getMessage("user_lastadmin_error", null, locale));
validationErrors.add(validationError);
}
}
}
return validationErrors;
}
private List<ValidationMessages> validateEntity(User user, Locale locale) {
List<ValidationMessages> validations = ValidationUtil
.validateEntity(this.validator, user);
if (!isEmailUnique(this.mongoDb, user.getId(), user.getEmail())) {
ValidationMessages validationError = new ValidationMessages();
validationError.setField(CUser.email);
validationError.setMessage(
this.messageSource.getMessage("user_emailtaken", null, locale));
validations.add(validationError);
}
if (!isLoginNameUnique(this.mongoDb, user.getId(), user.getLoginName())) {
ValidationMessages validationError = new ValidationMessages();
validationError.setField(CUser.loginName);
validationError.setMessage(
this.messageSource.getMessage("user_loginnametaken", null, locale));
validations.add(validationError);
}
return validations;
}
private boolean isLastAdmin(String id) {
long count = this.mongoDb.getCollection(User.class)
.countDocuments(Filters.and(Filters.ne(CUser.id, id),
Filters.eq(CUser.deleted, false),
Filters.eq(CUser.authorities, Authority.ADMIN.name()),
Filters.eq(CUser.enabled, true)));
return count == 0;
}
public static boolean isEmailUnique(MongoDb mongoDb, String userId, String email) {
if (StringUtils.hasText(email)) {
long count;
if (userId != null) {
count = mongoDb.getCollection(User.class)
.countDocuments(Filters.and(
Filters.regex(CUser.email, "^" + email + "$", "i"),
Filters.ne(CUser.id, userId)));
}
else {
count = mongoDb.getCollection(User.class)
.countDocuments(Filters.regex(CUser.email, "^" + email + "$", "i"));
}
return count == 0;
}
return true;
}
public static boolean isLoginNameUnique(MongoDb mongoDb, String userId,
String loginName) {
if (StringUtils.hasText(loginName)) {
long count;
if (userId != null) {
count = mongoDb.getCollection(User.class)
.countDocuments(Filters.and(Filters.regex(CUser.loginName,
"^" + loginName + "$", "i"),
Filters.ne(CUser.id, userId)));
}
else {
count = mongoDb.getCollection(User.class).countDocuments(
Filters.regex(CUser.loginName, "^" + loginName + "$", "i"));
}
return count == 0;
}
return false;
}
@ExtDirectMethod
public void unlock(String userId) {
this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId),
Updates.combine(Updates.unset(CUser.lockedOutUntil),
Updates.set(CUser.failedLogins, 0)));
}
@ExtDirectMethod
public void disableTwoFactorAuth(String userId) {
this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId),
Updates.unset(CUser.secret));
}
@ExtDirectMethod
public void sendPassordResetEmail(String userId) {
String token = UUID.randomUUID().toString();
User user = this.mongoDb.getCollection(User.class).findOneAndUpdate(
Filters.eq(CUser.id, userId),
Updates.combine(
Updates.set(CUser.passwordResetTokenValidUntil,
Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusHours(4)
.toInstant())),
Updates.set(CUser.passwordResetToken, token)),
new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
this.mailService.sendPasswortResetEmail(user);
}
}
| apache-2.0 |
jsjdsplj/coolweather | app/src/main/java/com/example/coolweather/gson/Now.java | 388 | package com.example.coolweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by jack on 2017/8/18.
*/
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}
| apache-2.0 |
porcelli-forks/dashbuilder | dashbuilder-backend/dashbuilder-dataset-elasticsearch/src/main/java/org/dashbuilder/dataprovider/backend/elasticsearch/rest/impl/jest/gson/SearchQuerySerializer.java | 3103 | package org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.gson;
import com.google.gson.*;
import org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClient;
import org.dashbuilder.dataset.DataColumn;
import org.dashbuilder.dataset.DataSetMetadata;
import java.lang.reflect.Type;
import java.util.List;
public class SearchQuerySerializer extends AbstractAdapter<SearchQuerySerializer> implements JsonSerializer<ElasticSearchJestClient.SearchQuery> {
protected static final String FIELDS = "fields";
protected static final String FROM = "from";
protected static final String QUERY = "query";
protected static final String SIZE = "size";
protected static final String AGGREGATIONS = "aggregations";
public SearchQuerySerializer(ElasticSearchJestClient client, DataSetMetadata metadata, List<DataColumn> columns) {
super(client, metadata, columns);
}
public JsonObject serialize(ElasticSearchJestClient.SearchQuery searchQuery, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
String[] fields = searchQuery.getFields();
JsonObject query = searchQuery.getQuery();
List<JsonObject> aggregations = searchQuery.getAggregations();
boolean existAggregations = aggregations != null && !aggregations.isEmpty();
// Trimming.
// If aggregations exist, we care about the aggregation results, not document results.
int start = searchQuery.getStart();
int size = searchQuery.getSize();
int sizeToPull = existAggregations ? 0 : size;
int startToPull = existAggregations ? 0 : start;
result.addProperty(FROM, startToPull);
if (sizeToPull > -1) result.addProperty(SIZE, sizeToPull);
// Build the search request in EL expected JSON format.
if (query != null) {
JsonObject queryObject = query.getAsJsonObject(QUERY);
result.add(QUERY, queryObject);
}
if (existAggregations) {
// TODO: Use all aggregations, not just first one.
JsonObject aggregationObject = aggregations.get(0);
JsonObject aggregationsSubObject = aggregationObject.getAsJsonObject(AGGREGATIONS);
result.add(AGGREGATIONS, aggregationsSubObject);
}
// If neither query or aggregations exists (just retrieving all element with optinal sort operation), perform a "match_all" query to EL server.
if (query == null && !existAggregations) {
JsonObject queryObject = new JsonObject();
queryObject.add("match_all", new JsonObject());
result.add("query", queryObject);
}
// Add the fields to retrieve, if apply.
if (!existAggregations && fields != null && fields.length > 0) {
JsonArray fieldsArray = new JsonArray();
for (String field : fields) {
fieldsArray.add(new JsonPrimitive(field));
}
result.add(FIELDS, fieldsArray);
}
return result;
}
} | apache-2.0 |
consulo/consulo-android | android/android/src/org/jetbrains/android/inspections/lint/IntellijRegistrationDetector.java | 4486 | /*
* Copyright (C) 2013 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 org.jetbrains.android.inspections.lint;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.tools.lint.checks.RegistrationDetector;
import com.android.tools.lint.detector.api.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.*;
import lombok.ast.AstVisitor;
import lombok.ast.CompilationUnit;
import lombok.ast.ForwardingAstVisitor;
import lombok.ast.Node;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import static com.android.SdkConstants.*;
/**
* Intellij-specific version of the {@link com.android.tools.lint.checks.RegistrationDetector} which uses the PSI structure
* to check classes.
* <p>
* <ul>
* <li>Unit tests, and compare to the bytecode based results</li>
* </ul>
*/
public class IntellijRegistrationDetector extends RegistrationDetector implements Detector.JavaScanner {
static final Implementation IMPLEMENTATION = new Implementation(
IntellijRegistrationDetector.class,
EnumSet.of(Scope.MANIFEST, Scope.JAVA_FILE));
@Nullable
@Override
public List<Class<? extends Node>> getApplicableNodeTypes() {
return Collections.<Class<? extends Node>>singletonList(CompilationUnit.class);
}
@Nullable
@Override
public AstVisitor createJavaVisitor(@NonNull final JavaContext context) {
return new ForwardingAstVisitor() {
@Override
public boolean visitCompilationUnit(CompilationUnit node) {
check(context);
return true;
}
};
}
private void check(final JavaContext context) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
final PsiFile psiFile = IntellijLintUtils.getPsiFile(context);
if (!(psiFile instanceof PsiJavaFile)) {
return;
}
PsiJavaFile javaFile = (PsiJavaFile)psiFile;
for (PsiClass clz : javaFile.getClasses()) {
check(context, clz);
}
}
});
}
private void check(JavaContext context, PsiClass clz) {
for (PsiClass current = clz.getSuperClass(); current != null; current = current.getSuperClass()) {
// Ignore abstract classes
if (clz.hasModifierProperty(PsiModifier.ABSTRACT) || clz instanceof PsiAnonymousClass) {
continue;
}
String fqcn = current.getQualifiedName();
if (fqcn == null) {
continue;
}
if (CLASS_ACTIVITY.equals(fqcn)
|| CLASS_SERVICE.equals(fqcn)
|| CLASS_CONTENTPROVIDER.equals(fqcn)) {
String internalName = IntellijLintUtils.getInternalName(clz);
if (internalName == null) {
continue;
}
String frameworkClass = ClassContext.getInternalName(fqcn);
Collection<String> registered = mManifestRegistrations != null ? mManifestRegistrations.get(frameworkClass) : null;
if (registered == null || !registered.contains(internalName)) {
report(context, clz, frameworkClass);
}
break;
}
}
for (PsiClass innerClass : clz.getInnerClasses()) {
check(context, innerClass);
}
}
private static void report(JavaContext context, PsiClass clz, String internalName) {
// Unlike the superclass, we don't have to check that the tags are compatible;
// IDEA already checks that as part of its XML validation
if (IntellijLintUtils.isSuppressed(clz, clz.getContainingFile(), ISSUE)) {
return;
}
String tag = classToTag(internalName);
Location location = IntellijLintUtils.getLocation(context.file, clz);
String fqcn = clz.getQualifiedName();
if (fqcn == null) {
fqcn = clz.getName();
}
context.report(ISSUE, location, String.format("The <%1$s> %2$s is not registered in the manifest", tag, fqcn), null);
}
}
| apache-2.0 |
s-webber/projog | src/main/java/org/projog/core/predicate/PredicateFactory.java | 3137 | /*
* Copyright 2013 S. Webber
*
* 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.projog.core.predicate;
import org.projog.core.term.Term;
/**
* Returns specialised implementations of {@link Predicate}.
* <p>
* There are two general types of predicates:
* <ul>
* <li><i>User defined predicates</i> are defined by a mixture of rules and facts constructed from Prolog syntax
* consulted at runtime.</li>
* <li><i>Built-in predicates</i> are written in Java. Built-in predicates can provide facilities that would not be
* possible using pure Prolog syntax. The two predicates that are always available in Projog are
* {@code pj_add_predicate/2} and {@code pj_add_arithmetic_operator/2}. The {@code pj_add_predicate/2} predicate allows
* other predicates to be "plugged-in" to Projog.</li>
* </ul>
* <p>
* <b>Note:</b> Rather than directly implementing {@code PredicateFactory} it is recommended to extend either
* {@link org.projog.core.predicate.AbstractSingleResultPredicate} or
* {@link org.projog.core.predicate.AbstractPredicateFactory}.
* </p>
*
* @see Predicates#addPredicateFactory(PredicateKey, String)
*/
public interface PredicateFactory {
/**
* Returns a {@link Predicate} to be used in the evaluation of a goal.
*
* @param args the arguments to use in the evaluation of the goal
* @return Predicate to be used in the evaluation of the goal
* @see Predicate#evaluate()
*/
Predicate getPredicate(Term[] args);
/**
* Should instances of this implementation be re-evaluated when backtracking?
* <p>
* Some goals (e.g. {@code X is 1}) are only meant to be evaluated once (the statement is either true or false) while
* others (e.g. {@code repeat(3)}) are meant to be evaluated multiple times. For instances of {@code Predicate} that
* are designed to possibly have {@link Predicate#evaluate()} called on them multiple times for the same individual
* query this method should return {@code true}. For instances of {@code Predicate} that are designed to only be
* evaluated once per individual query this method should return {@code false}.
*
* @return {@code true} if an attempt should be made to re-evaluate instances of implementing classes when
* backtracking, {@code false} otherwise
*/
boolean isRetryable();
/**
* Will attempting to re-evaluate this implementation always result in a cut?
*
* @return {@code true} if a cut will always be encountered when attempting to re-evaluate, {@code false} otherwise
*/
default boolean isAlwaysCutOnBacktrack() {
return false;
}
}
| apache-2.0 |
simplegeo/hadoop-pig | src/org/apache/pig/backend/hadoop/executionengine/HExecutionEngine.java | 22338 | /*
* 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.pig.backend.hadoop.executionengine;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketImplFactory;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.mapred.JobConf;
import org.apache.pig.ExecType;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigException;
import org.apache.pig.SortInfo;
import org.apache.pig.backend.datastorage.DataStorage;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.executionengine.ExecJob;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.backend.hadoop.datastorage.HDataStorage;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.LogToPhyTranslationVisitor;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.io.FileSpec;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.LogicalPlan;
import org.apache.pig.impl.plan.NodeIdGenerator;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.pig.impl.util.ObjectSerializer;
import org.apache.pig.impl.util.Utils;
import org.apache.pig.newplan.DependencyOrderWalker;
import org.apache.pig.newplan.Operator;
import org.apache.pig.newplan.OperatorPlan;
import org.apache.pig.newplan.logical.LogicalPlanMigrationVistor;
import org.apache.pig.newplan.logical.expression.ConstantExpression;
import org.apache.pig.newplan.logical.expression.LogicalExpressionPlan;
import org.apache.pig.newplan.logical.optimizer.SchemaResetter;
import org.apache.pig.newplan.logical.optimizer.ProjectionPatcher.ProjectionFinder;
import org.apache.pig.newplan.logical.relational.LOLimit;
import org.apache.pig.newplan.logical.relational.LOSort;
import org.apache.pig.newplan.logical.relational.LOSplit;
import org.apache.pig.newplan.logical.relational.LOSplitOutput;
import org.apache.pig.newplan.logical.relational.LOStore;
import org.apache.pig.newplan.logical.relational.LogicalRelationalNodesVisitor;
import org.apache.pig.newplan.logical.rules.InputOutputFileValidator;
import org.apache.pig.newplan.optimizer.Rule;
import org.apache.pig.tools.pigstats.OutputStats;
import org.apache.pig.tools.pigstats.PigStats;
public class HExecutionEngine {
public static final String JOB_TRACKER_LOCATION = "mapred.job.tracker";
private static final String FILE_SYSTEM_LOCATION = "fs.default.name";
private static final String HADOOP_SITE = "hadoop-site.xml";
private static final String CORE_SITE = "core-site.xml";
private final Log log = LogFactory.getLog(getClass());
public static final String LOCAL = "local";
protected PigContext pigContext;
protected DataStorage ds;
@SuppressWarnings("deprecation")
protected JobConf jobConf;
// key: the operator key from the logical plan that originated the physical plan
// val: the operator key for the root of the phyisical plan
protected Map<OperatorKey, OperatorKey> logicalToPhysicalKeys;
// map from LOGICAL key to into about the execution
protected Map<OperatorKey, MapRedResult> materializedResults;
public HExecutionEngine(PigContext pigContext) {
this.pigContext = pigContext;
this.logicalToPhysicalKeys = new HashMap<OperatorKey, OperatorKey>();
this.materializedResults = new HashMap<OperatorKey, MapRedResult>();
this.ds = null;
// to be set in the init method
this.jobConf = null;
}
@SuppressWarnings("deprecation")
public JobConf getJobConf() {
return this.jobConf;
}
public Map<OperatorKey, MapRedResult> getMaterializedResults() {
return this.materializedResults;
}
public DataStorage getDataStorage() {
return this.ds;
}
public void init() throws ExecException {
init(this.pigContext.getProperties());
}
@SuppressWarnings("deprecation")
public void init(Properties properties) throws ExecException {
//First set the ssh socket factory
setSSHFactory();
String cluster = null;
String nameNode = null;
Configuration configuration = null;
// We need to build a configuration object first in the manner described below
// and then get back a properties object to inspect the JOB_TRACKER_LOCATION
// and FILE_SYSTEM_LOCATION. The reason to do this is if we looked only at
// the existing properties object, we may not get the right settings. So we want
// to read the configurations in the order specified below and only then look
// for JOB_TRACKER_LOCATION and FILE_SYSTEM_LOCATION.
// Hadoop by default specifies two resources, loaded in-order from the classpath:
// 1. hadoop-default.xml : Read-only defaults for hadoop.
// 2. hadoop-site.xml: Site-specific configuration for a given hadoop installation.
// Now add the settings from "properties" object to override any existing properties
// All of the above is accomplished in the method call below
JobConf jc = null;
if ( this.pigContext.getExecType() == ExecType.MAPREDUCE ) {
// Check existence of hadoop-site.xml or core-site.xml
Configuration testConf = new Configuration();
ClassLoader cl = testConf.getClassLoader();
URL hadoop_site = cl.getResource( HADOOP_SITE );
URL core_site = cl.getResource( CORE_SITE );
if( hadoop_site == null && core_site == null ) {
throw new ExecException("Cannot find hadoop configurations in classpath (neither hadoop-site.xml nor core-site.xml was found in the classpath)." +
"If you plan to use local mode, please put -x local option in command line",
4010);
}
jc = new JobConf();
jc.addResource("pig-cluster-hadoop-site.xml");
// Trick to invoke static initializer of DistributedFileSystem to add hdfs-default.xml
// into configuration
new DistributedFileSystem();
//the method below alters the properties object by overriding the
//hadoop properties with the values from properties and recomputing
//the properties
recomputeProperties(jc, properties);
} else {
// If we are running in local mode we dont read the hadoop conf file
jc = new JobConf(false);
jc.addResource("core-default.xml");
jc.addResource("mapred-default.xml");
recomputeProperties(jc, properties);
properties.setProperty(JOB_TRACKER_LOCATION, LOCAL );
properties.setProperty(FILE_SYSTEM_LOCATION, "file:///");
}
cluster = properties.getProperty(JOB_TRACKER_LOCATION);
nameNode = properties.getProperty(FILE_SYSTEM_LOCATION);
if (cluster != null && cluster.length() > 0) {
if(!cluster.contains(":") && !cluster.equalsIgnoreCase(LOCAL)) {
cluster = cluster + ":50020";
}
properties.setProperty(JOB_TRACKER_LOCATION, cluster);
}
if (nameNode!=null && nameNode.length() > 0) {
if(!nameNode.contains(":") && !nameNode.equalsIgnoreCase(LOCAL)) {
nameNode = nameNode + ":8020";
}
properties.setProperty(FILE_SYSTEM_LOCATION, nameNode);
}
log.info("Connecting to hadoop file system at: " + (nameNode==null? LOCAL: nameNode) ) ;
ds = new HDataStorage(properties);
// The above HDataStorage constructor sets DEFAULT_REPLICATION_FACTOR_KEY in properties.
configuration = ConfigurationUtil.toConfiguration(properties);
if(cluster != null && !cluster.equalsIgnoreCase(LOCAL)){
log.info("Connecting to map-reduce job tracker at: " + properties.get(JOB_TRACKER_LOCATION));
}
// Set job-specific configuration knobs
jobConf = new JobConf(configuration);
}
public Properties getConfiguration() throws ExecException {
return this.pigContext.getProperties();
}
public void updateConfiguration(Properties newConfiguration)
throws ExecException {
init(newConfiguration);
}
public void close() throws ExecException {}
public Map<String, Object> getStatistics() throws ExecException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
public PhysicalPlan compile(LogicalPlan plan,
Properties properties) throws FrontendException {
if (plan == null) {
int errCode = 2041;
String msg = "No Plan to compile";
throw new FrontendException(msg, errCode, PigException.BUG);
}
try {
if (getConfiguration().getProperty("pig.usenewlogicalplan", "true").equals("true")) {
log.info("pig.usenewlogicalplan is set to true. New logical plan will be used.");
// translate old logical plan to new plan
LogicalPlanMigrationVistor visitor = new LogicalPlanMigrationVistor(plan);
visitor.visit();
org.apache.pig.newplan.logical.relational.LogicalPlan newPlan = visitor.getNewLogicalPlan();
SchemaResetter schemaResetter = new SchemaResetter(newPlan);
schemaResetter.visit();
HashSet<String> optimizerRules = null;
try {
optimizerRules = (HashSet<String>) ObjectSerializer
.deserialize(pigContext.getProperties().getProperty(
"pig.optimizer.rules"));
} catch (IOException ioe) {
int errCode = 2110;
String msg = "Unable to deserialize optimizer rules.";
throw new FrontendException(msg, errCode, PigException.BUG, ioe);
}
// run optimizer
org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer optimizer =
new org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer(newPlan, 100, optimizerRules);
optimizer.optimize();
// compute whether output data is sorted or not
SortInfoSetter sortInfoSetter = new SortInfoSetter(newPlan);
sortInfoSetter.visit();
if (pigContext.inExplain==false) {
// Validate input/output file. Currently no validation framework in
// new logical plan, put this validator here first.
// We might decide to move it out to a validator framework in future
InputOutputFileValidator validator = new InputOutputFileValidator(newPlan, pigContext);
validator.validate();
}
// translate new logical plan to physical plan
org.apache.pig.newplan.logical.relational.LogToPhyTranslationVisitor translator =
new org.apache.pig.newplan.logical.relational.LogToPhyTranslationVisitor(newPlan);
translator.setPigContext(pigContext);
translator.visit();
return translator.getPhysicalPlan();
}else{
LogToPhyTranslationVisitor translator =
new LogToPhyTranslationVisitor(plan);
translator.setPigContext(pigContext);
translator.visit();
return translator.getPhysicalPlan();
}
} catch (Exception ve) {
int errCode = 2042;
String msg = "Error in new logical plan. Try -Dpig.usenewlogicalplan=false.";
throw new FrontendException(msg, errCode, PigException.BUG, ve);
}
}
public static class SortInfoSetter extends LogicalRelationalNodesVisitor {
public SortInfoSetter(OperatorPlan plan) throws FrontendException {
super(plan, new DependencyOrderWalker(plan));
}
@Override
public void visit(LOStore store) throws FrontendException {
Operator storePred = store.getPlan().getPredecessors(store).get(0);
if(storePred == null){
int errCode = 2051;
String msg = "Did not find a predecessor for Store." ;
throw new FrontendException(msg, errCode, PigException.BUG);
}
SortInfo sortInfo = null;
if(storePred instanceof LOLimit) {
storePred = store.getPlan().getPredecessors(storePred).get(0);
} else if (storePred instanceof LOSplitOutput) {
LOSplitOutput splitOutput = (LOSplitOutput)storePred;
// We assume this is the LOSplitOutput we injected for this case:
// b = order a by $0; store b into '1'; store b into '2';
// In this case, we should mark both '1' and '2' as sorted
LogicalExpressionPlan conditionPlan = splitOutput.getFilterPlan();
if (conditionPlan.getSinks().size()==1) {
Operator root = conditionPlan.getSinks().get(0);
if (root instanceof ConstantExpression) {
Object value = ((ConstantExpression)root).getValue();
if (value instanceof Boolean && (Boolean)value==true) {
Operator split = splitOutput.getPlan().getPredecessors(splitOutput).get(0);
if (split instanceof LOSplit)
storePred = store.getPlan().getPredecessors(split).get(0);
}
}
}
}
// if this predecessor is a sort, get
// the sort info.
if(storePred instanceof LOSort) {
try {
sortInfo = ((LOSort)storePred).getSortInfo();
} catch (FrontendException e) {
throw new FrontendException(e);
}
}
store.setSortInfo(sortInfo);
}
}
public List<ExecJob> execute(PhysicalPlan plan,
String jobName) throws ExecException, FrontendException {
MapReduceLauncher launcher = new MapReduceLauncher();
List<ExecJob> jobs = new ArrayList<ExecJob>();
Map<String, PhysicalOperator> leafMap = new HashMap<String, PhysicalOperator>();
for (PhysicalOperator physOp : plan.getLeaves()) {
log.info(physOp);
if (physOp instanceof POStore) {
FileSpec spec = ((POStore) physOp).getSFile();
if (spec != null)
leafMap.put(spec.toString(), physOp);
}
}
try {
PigStats stats = launcher.launchPig(plan, jobName, pigContext);
for (OutputStats output : stats.getOutputStats()) {
POStore store = output.getPOStore();
String alias = store.getAlias();
if (output.isSuccessful()) {
jobs.add(new HJob(ExecJob.JOB_STATUS.COMPLETED, pigContext, store, alias, stats));
} else {
HJob j = new HJob(ExecJob.JOB_STATUS.FAILED, pigContext, store, alias, stats);
j.setException(launcher.getError(store.getSFile()));
jobs.add(j);
}
}
return jobs;
} catch (Exception e) {
// There are a lot of exceptions thrown by the launcher. If this
// is an ExecException, just let it through. Else wrap it.
if (e instanceof ExecException){
throw (ExecException)e;
} else if (e instanceof FrontendException) {
throw (FrontendException)e;
} else {
int errCode = 2043;
String msg = "Unexpected error during execution.";
throw new ExecException(msg, errCode, PigException.BUG, e);
}
} finally {
launcher.reset();
}
}
public void explain(PhysicalPlan plan, PrintStream stream, String format, boolean verbose) {
try {
MapRedUtil.checkLeafIsStore(plan, pigContext);
MapReduceLauncher launcher = new MapReduceLauncher();
launcher.explain(plan, pigContext, stream, format, verbose);
} catch (Exception ve) {
throw new RuntimeException(ve);
}
}
@SuppressWarnings("unchecked")
private void setSSHFactory(){
Properties properties = this.pigContext.getProperties();
String g = properties.getProperty("ssh.gateway");
if (g == null || g.length() == 0) return;
try {
Class clazz = Class.forName("org.apache.pig.shock.SSHSocketImplFactory");
SocketImplFactory f = (SocketImplFactory)clazz.getMethod("getFactory", new Class[0]).invoke(0, new Object[0]);
Socket.setSocketImplFactory(f);
}
catch (SocketException e) {}
catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* Method to recompute pig properties by overriding hadoop properties
* with pig properties
* @param conf JobConf with appropriate hadoop resource files
* @param properties Pig properties that will override hadoop properties; properties might be modified
*/
@SuppressWarnings("deprecation")
private void recomputeProperties(JobConf jobConf, Properties properties) {
// We need to load the properties from the hadoop configuration
// We want to override these with any existing properties we have.
if (jobConf != null && properties != null) {
Properties hadoopProperties = new Properties();
Iterator<Map.Entry<String, String>> iter = jobConf.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
hadoopProperties.put(entry.getKey(), entry.getValue());
}
//override hadoop properties with user defined properties
Enumeration<Object> propertiesIter = properties.keys();
while (propertiesIter.hasMoreElements()) {
String key = (String) propertiesIter.nextElement();
String val = properties.getProperty(key);
// We do not put user.name, See PIG-1419
if (!key.equals("user.name"))
hadoopProperties.put(key, val);
}
//clear user defined properties and re-populate
properties.clear();
Enumeration<Object> hodPropertiesIter = hadoopProperties.keys();
while (hodPropertiesIter.hasMoreElements()) {
String key = (String) hodPropertiesIter.nextElement();
String val = hadoopProperties.getProperty(key);
properties.put(key, val);
}
}
}
public static FileSpec checkLeafIsStore(
PhysicalPlan plan,
PigContext pigContext) throws ExecException {
try {
PhysicalOperator leaf = plan.getLeaves().get(0);
FileSpec spec = null;
if(!(leaf instanceof POStore)){
String scope = leaf.getOperatorKey().getScope();
POStore str = new POStore(new OperatorKey(scope,
NodeIdGenerator.getGenerator().getNextNodeId(scope)));
spec = new FileSpec(FileLocalizer.getTemporaryPath(
pigContext).toString(),
new FuncSpec(Utils.getTmpFileCompressorName(pigContext)));
str.setSFile(spec);
plan.addAsLeaf(str);
} else{
spec = ((POStore)leaf).getSFile();
}
return spec;
} catch (Exception e) {
int errCode = 2045;
String msg = "Internal error. Not able to check if the leaf node is a store operator.";
throw new ExecException(msg, errCode, PigException.BUG, e);
}
}
}
| apache-2.0 |
yschimke/rsocket-java | rsocket-transport-aeron/src/main/java/io/rsocket/aeron/internal/reactivestreams/AeronChannel.java | 3018 | /*
* Copyright 2016 Netflix, 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 io.rsocket.aeron.internal.reactivestreams;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.rsocket.aeron.internal.EventLoop;
import java.util.Objects;
import org.agrona.DirectBuffer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** */
public class AeronChannel implements ReactiveStreamsRemote.Channel<DirectBuffer>, AutoCloseable {
private final String name;
private final Publication destination;
private final Subscription source;
private final AeronOutPublisher outPublisher;
private final EventLoop eventLoop;
/**
* Creates on end of a bi-directional channel
*
* @param name name of the channel
* @param destination {@code Publication} to send data to
* @param source Aeron {@code Subscription} to listen to data on
* @param eventLoop {@link EventLoop} used to poll data on
* @param sessionId sessionId between the {@code Publication} and the remote {@code Subscription}
*/
public AeronChannel(
String name,
Publication destination,
Subscription source,
EventLoop eventLoop,
int sessionId) {
this.destination = destination;
this.source = source;
this.name = name;
this.eventLoop = eventLoop;
this.outPublisher = new AeronOutPublisher(name, sessionId, source, eventLoop);
}
/**
* Subscribes to a stream of DirectBuffers and sends the to an Aeron Publisher
*
* @param in
* @return
*/
public Mono<Void> send(Flux<? extends DirectBuffer> in) {
AeronInSubscriber inSubscriber = new AeronInSubscriber(name, destination);
Objects.requireNonNull(in, "in must not be null");
return Mono.create(
sink -> in.doOnComplete(sink::success).doOnError(sink::error).subscribe(inSubscriber));
}
/**
* Returns ReactiveStreamsRemote.Out of DirectBuffer that can only be subscribed to once per
* channel
*
* @return ReactiveStreamsRemote.Out of DirectBuffer
*/
public Flux<? extends DirectBuffer> receive() {
return outPublisher;
}
@Override
public void close() throws Exception {
try {
destination.close();
source.close();
} catch (Throwable t) {
throw new Exception(t);
}
}
@Override
public String toString() {
return "AeronChannel{" + "name='" + name + '\'' + '}';
}
@Override
public boolean isActive() {
return !destination.isClosed() && !source.isClosed();
}
}
| apache-2.0 |
pengzhiming/AndroidApp | app/src/main/java/com/yl/merchat/widget/web/DWebView.java | 4792 | package com.yl.merchat.widget.web;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.yl.merchat.util.FilePathUtil;
/**
* Created by zm on 2018/9/10.
*/
public class DWebView<T> extends WebView {
T data;
public DWebView(Context context) {
this(context, null);
}
public DWebView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.getSettings().setJavaScriptEnabled(true);
this.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
String cacheDirPath = FilePathUtil.getCacheWeb();
this.getSettings().setAppCachePath(cacheDirPath);
this.getSettings().setDomStorageEnabled(true);
this.getSettings().setDatabaseEnabled(true);
this.getSettings().setAppCacheEnabled(true);
this.getSettings().setAllowFileAccess(true);
// this.getSettings().setUseWideViewPort(true);
this.getSettings().setLoadWithOverviewMode(true);
this.setWebViewClient(new JWebViewClient());
this.setWebChromeClient(new JWebChromeClient());
fixWebView();
}
@TargetApi(11)
private void fixWebView() {
if (Build.VERSION.SDK_INT > 10 && Build.VERSION.SDK_INT < 17) {
removeJavascriptInterface("searchBoxJavaBridge_");
}
}
class JWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.cancelShowLoading();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (onJWebViewOverrideUrlLoadingLinstener != null) {
OverrideUrlLoadingState overrideUrlLoadingState = onJWebViewOverrideUrlLoadingLinstener.shouldOverrideUrlLoading(view, url);
if(overrideUrlLoadingState != OverrideUrlLoadingState.Default) {
return overrideUrlLoadingState == OverrideUrlLoadingState.False ? false : true;
}
}
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
}
class JWebChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.cancelShowLoading();
}
} else {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.showLoading(newProgress);
}
}
/**
* 设置Javascript的异常监控
*
* @param webView 指定被监控的webView
* @param autoInject 是否自动注入Bugly.js文件
* @return true 设置成功;false 设置失败
*/
super.onProgressChanged(view, newProgress);
}
}
public enum OverrideUrlLoadingState {
Default, False, Ture
}
OnJWebViewOverrideUrlLoadingLinstener onJWebViewOverrideUrlLoadingLinstener;
public void setOnJWebViewOverrideUrlLoadingLinstener(OnJWebViewOverrideUrlLoadingLinstener onJWebViewOverrideUrlLoadingLinstener) {
this.onJWebViewOverrideUrlLoadingLinstener = onJWebViewOverrideUrlLoadingLinstener;
}
public interface OnJWebViewOverrideUrlLoadingLinstener {
OverrideUrlLoadingState shouldOverrideUrlLoading(WebView view, String url);
}
OnJWebViewProgressLinstener onJWebViewProgressLinstener;
public void setOnJWebViewProgressLinstener(OnJWebViewProgressLinstener onJWebViewProgressLinstener) {
this.onJWebViewProgressLinstener = onJWebViewProgressLinstener;
}
public interface OnJWebViewProgressLinstener {
void showLoading(int newProgress);
void cancelShowLoading();
}
}
| apache-2.0 |
terrancesnyder/solr-analytics | lucene/core/src/java/org/apache/lucene/search/TopDocsCollector.java | 7103 | package org.apache.lucene.search;
/*
* 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.
*/
import org.apache.lucene.util.PriorityQueue;
/**
* A base class for all collectors that return a {@link TopDocs} output. This
* collector allows easy extension by providing a single constructor which
* accepts a {@link PriorityQueue} as well as protected members for that
* priority queue and a counter of the number of total hits.<br>
* Extending classes can override any of the methods to provide their own
* implementation, as well as avoid the use of the priority queue entirely by
* passing null to {@link #TopDocsCollector(PriorityQueue)}. In that case
* however, you might want to consider overriding all methods, in order to avoid
* a NullPointerException.
*/
public abstract class TopDocsCollector<T extends ScoreDoc> extends Collector {
/** This is used in case topDocs() is called with illegal parameters, or there
* simply aren't (enough) results. */
protected static final TopDocs EMPTY_TOPDOCS = new TopDocs(0, new ScoreDoc[0], Float.NaN);
/**
* The priority queue which holds the top documents. Note that different
* implementations of PriorityQueue give different meaning to 'top documents'.
* HitQueue for example aggregates the top scoring documents, while other PQ
* implementations may hold documents sorted by other criteria.
*/
protected PriorityQueue<T> pq;
/** The total number of documents that the collector encountered. */
protected int totalHits;
protected TopDocsCollector(PriorityQueue<T> pq) {
this.pq = pq;
}
/**
* Populates the results array with the ScoreDoc instances. This can be
* overridden in case a different ScoreDoc type should be returned.
*/
protected void populateResults(ScoreDoc[] results, int howMany) {
for (int i = howMany - 1; i >= 0; i--) {
results[i] = pq.pop();
}
}
/**
* Returns a {@link TopDocs} instance containing the given results. If
* <code>results</code> is null it means there are no results to return,
* either because there were 0 calls to collect() or because the arguments to
* topDocs were invalid.
*/
protected TopDocs newTopDocs(ScoreDoc[] results, int start) {
return results == null ? EMPTY_TOPDOCS : new TopDocs(totalHits, results);
}
/** The total number of documents that matched this query. */
public int getTotalHits() {
return totalHits;
}
/** The number of valid PQ entries */
protected int topDocsSize() {
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
return totalHits < pq.size() ? totalHits : pq.size();
}
/** Returns the top docs that were collected by this collector. */
public TopDocs topDocs() {
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
return topDocs(0, topDocsSize());
}
/**
* Returns the documents in the rage [start .. pq.size()) that were collected
* by this collector. Note that if start >= pq.size(), an empty TopDocs is
* returned.<br>
* This method is convenient to call if the application always asks for the
* last results, starting from the last 'page'.<br>
* <b>NOTE:</b> you cannot call this method more than once for each search
* execution. If you need to call it more than once, passing each time a
* different <code>start</code>, you should call {@link #topDocs()} and work
* with the returned {@link TopDocs} object, which will contain all the
* results this search execution collected.
*/
public TopDocs topDocs(int start) {
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
return topDocs(start, topDocsSize());
}
/**
* Returns the documents in the rage [start .. start+howMany) that were
* collected by this collector. Note that if start >= pq.size(), an empty
* TopDocs is returned, and if pq.size() - start < howMany, then only the
* available documents in [start .. pq.size()) are returned.<br>
* This method is useful to call in case pagination of search results is
* allowed by the search application, as well as it attempts to optimize the
* memory used by allocating only as much as requested by howMany.<br>
* <b>NOTE:</b> you cannot call this method more than once for each search
* execution. If you need to call it more than once, passing each time a
* different range, you should call {@link #topDocs()} and work with the
* returned {@link TopDocs} object, which will contain all the results this
* search execution collected.
*/
public TopDocs topDocs(int start, int howMany) {
// In case pq was populated with sentinel values, there might be less
// results than pq.size(). Therefore return all results until either
// pq.size() or totalHits.
int size = topDocsSize();
// Don't bother to throw an exception, just return an empty TopDocs in case
// the parameters are invalid or out of range.
// TODO: shouldn't we throw IAE if apps give bad params here so they dont
// have sneaky silent bugs?
if (start < 0 || start >= size || howMany <= 0) {
return newTopDocs(null, start);
}
// We know that start < pqsize, so just fix howMany.
howMany = Math.min(size - start, howMany);
ScoreDoc[] results = new ScoreDoc[howMany];
// pq's pop() returns the 'least' element in the queue, therefore need
// to discard the first ones, until we reach the requested range.
// Note that this loop will usually not be executed, since the common usage
// should be that the caller asks for the last howMany results. However it's
// needed here for completeness.
for (int i = pq.size() - start - howMany; i > 0; i--) { pq.pop(); }
// Get the requested results from pq.
populateResults(results, howMany);
return newTopDocs(results, start);
}
}
| apache-2.0 |
nasa/OpenSPIFe | gov.nasa.ensemble.core.plan.resources/test/gov/nasa/ensemble/core/plan/resources/TestActivityEffect.java | 6538 | /*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* 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 gov.nasa.ensemble.core.plan.resources;
import gov.nasa.ensemble.core.jscience.Profile;
import gov.nasa.ensemble.core.jscience.util.DateUtils;
import gov.nasa.ensemble.core.jscience.util.ProfileUtil;
import gov.nasa.ensemble.core.model.plan.EActivity;
import gov.nasa.ensemble.core.model.plan.EPlan;
import gov.nasa.ensemble.core.model.plan.temporal.TemporalMember;
import gov.nasa.ensemble.core.model.plan.translator.WrapperUtils;
import gov.nasa.ensemble.core.plan.resources.profile.ResourceProfileMember;
import gov.nasa.ensemble.core.plan.resources.util.ResourceUtils;
import gov.nasa.ensemble.dictionary.EActivityDef;
import gov.nasa.ensemble.emf.transaction.TransactionUtils;
import java.util.Date;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EStructuralFeature;
public class TestActivityEffect extends AbstractResourceTest {
private static final Date OFFSET_TEST_ACTIVITY_START_TIME = DateUtils.add(PLAN_START, ONE_HOUR.times(2));
private static final Date OFFSET_TEST_ACTIVITY_END_TIME = DateUtils.add(OFFSET_TEST_ACTIVITY_START_TIME, ONE_HOUR);
public void testOffsetEffectsOfNominalActivity() {
load(URI.createPlatformPluginURI("gov.nasa.ensemble.core.plan.resources/datafiles/test/TestActivityEffect__offsetEffect.dictionary", true));
EActivityDef noOffestDef = getActivityDef("NoOffset");
final EActivity noOffset = PLAN_FACTORY.createActivity(noOffestDef);
final EPlan plan = createPlan(noOffset);
TransactionUtils.writing(plan, new Runnable() {
@Override
public void run() {
plan.getMember(TemporalMember.class).setStartTime(PLAN_START);
noOffset.getMember(TemporalMember.class).setStartTime(OFFSET_TEST_ACTIVITY_START_TIME);
noOffset.getMember(TemporalMember.class).setDuration(ONE_HOUR);
}
});
recomputePlan(plan);
TransactionUtils.reading(plan, new Runnable() {
@Override
public void run() {
Profile<?> profile = ResourceUtils.getProfile(plan, "Control");
assertNotNull(profile);
assertEquals(null, profile.getValue(DateUtils.subtract(OFFSET_TEST_ACTIVITY_START_TIME, ONE_HOUR)));
assertEquals(Boolean.TRUE, profile.getValue(OFFSET_TEST_ACTIVITY_START_TIME));
assertEquals(Boolean.FALSE, profile.getValue(OFFSET_TEST_ACTIVITY_END_TIME));
assertEquals(Boolean.FALSE, profile.getValue(DateUtils.add(OFFSET_TEST_ACTIVITY_END_TIME, ONE_HOUR)));
}
});
}
public void testOffsetEffectsOfOffsetActivity() {
load(URI.createPlatformPluginURI("gov.nasa.ensemble.core.plan.resources/datafiles/test/TestActivityEffect__offsetEffect.dictionary", true));
EActivityDef oneHourOffestDef = getActivityDef("OneHourOffset");
final EActivity oneHourOffest = PLAN_FACTORY.createActivity(oneHourOffestDef);
final EPlan plan = createPlan(oneHourOffest);
TransactionUtils.writing(plan, new Runnable() {
@Override
public void run() {
plan.getMember(TemporalMember.class).setStartTime(PLAN_START);
oneHourOffest.getMember(TemporalMember.class).setStartTime(DateUtils.add(PLAN_START, ONE_HOUR.times(2)));
oneHourOffest.getMember(TemporalMember.class).setDuration(ONE_HOUR);
}
});
recomputePlan(plan);
TransactionUtils.reading(plan, new Runnable() {
@Override
public void run() {
Profile<?> profile = ResourceUtils.getProfile(plan, "Control");
assertNotNull(profile);
assertEquals(null, profile.getValue(DateUtils.subtract(OFFSET_TEST_ACTIVITY_START_TIME, ONE_HOUR.times(2))));
assertEquals(Boolean.TRUE, profile.getValue(DateUtils.subtract(OFFSET_TEST_ACTIVITY_START_TIME, ONE_HOUR)));
assertEquals(Boolean.TRUE, profile.getValue(OFFSET_TEST_ACTIVITY_START_TIME));
assertEquals(Boolean.TRUE, profile.getValue(OFFSET_TEST_ACTIVITY_END_TIME));
assertEquals(Boolean.FALSE, profile.getValue(DateUtils.add(OFFSET_TEST_ACTIVITY_END_TIME, ONE_HOUR)));
}
});
}
public void testStateResourceEffectFromParameter() throws Exception {
load(URI.createURI("platform:/plugin/gov.nasa.ensemble.core.plan.resources/datafiles/test/SPF_4545.dictionary"));
final EEnum issControlModeEnum = (EEnum) AD.getEClassifier("ISS_CONTROL_MODE");
assertNotNull(issControlModeEnum);
final EEnumLiteral ustEnumLiteral = issControlModeEnum.getEEnumLiteralByLiteral("UST");
EActivityDef handoverDef = getActivityDef("Handover");
EStructuralFeature toControlFeature = handoverDef.getEStructuralFeature("toControl");
assertNotNull(toControlFeature);
assertTrue(toControlFeature instanceof EAttribute);
final EActivity handover = PLAN_FACTORY.createActivity(handoverDef);
handover.setName("handover");
handover.getData().eSet(toControlFeature, ustEnumLiteral);
final EPlan plan = createPlan(handover);
TransactionUtils.writing(plan, new Runnable() {
@Override
public void run() {
plan.getMember(TemporalMember.class).setStartTime(PLAN_START);
handover.getMember(TemporalMember.class).setStartTime(PLAN_START);
handover.getMember(TemporalMember.class).setDuration(ONE_HOUR);
}
});
recomputePlan(plan);
TransactionUtils.reading(plan, new Runnable() {
@Override
public void run() {
Profile<?> profile = ResourceUtils.getProfile(plan, "Control");
assertNotNull(profile);
assertEquals(ustEnumLiteral, profile.getValue(DateUtils.add(PLAN_START, ONE_HOUR)));
}
});
}
@SuppressWarnings("unused")
private void debugProfiles(EPlan plan) {
for (Profile<?> p : WrapperUtils.getMember(plan, ResourceProfileMember.class).getResourceProfiles()) {
ProfileUtil.debugProfile(p);
}
}
}
| apache-2.0 |
NovaOrdis/playground | spring/spring-boot-with-initializr-from-intellij/src/test/java/playground/spring/springBootWithInitializrFromIntellij/AppApplicationTests.java | 377 | package playground.spring.springBootWithInitializrFromIntellij;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppApplicationTests {
@Test
public void contextLoads() {
}
}
| apache-2.0 |
Kenkron/burrowers | main/java/kenkron/burrowers/EntityAIBurrow.java | 10123 | package kenkron.burrowers;
import java.util.ArrayList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.item.ItemStack;
import net.minecraft.pathfinding.PathEntity;
import net.minecraft.pathfinding.PathPoint;
import net.minecraft.util.Direction;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
/**This AI represents a burrowing task for the mobs that
* just can't navigate to the player, but */
public class EntityAIBurrow extends EntityAIBase{
/**The Class of the Entity that this AI targets.*/
protected Class classTarget;
/**Long memory means this creature will remain agressive
* even if it can't path to its target (eg. ZombiePigmen)*/
protected boolean longMemory;
/**Speed modifier for moving towards the target.
* If 1.0, the attacker will not speed up to attack.*/
protected double speedTowardsTarget;
/**The entity that is attacking.*/
protected EntityCreature attacker;
/**The world in which the attacker lives*/
protected World world;
/**The path through the world to the target.*/
protected PathEntity pathToTarget;
/**not sure about this. Goes to ten if no path is found.*/
protected int failedPathFindingPenalty;
/**seems to go higher if it's harder to reach the target*/
protected int obstructionLevel;
/**the position of the feet of the attacker*/
protected double x,y,z;
/**(presumably) a timer for attacking.*/
protected int digTick;
/**the time it takes a zombie to dig*/
public static final int DIG_TIME=20;
public EntityAIBurrow(EntityCreature par1EntityCreature, Class par2Class, double speed, boolean persistant)
{
this(par1EntityCreature, speed, persistant);
this.classTarget = par2Class;
}
public EntityAIBurrow(EntityCreature par1EntityCreature, double speed, boolean persistant)
{
this.attacker = par1EntityCreature;
this.world = par1EntityCreature.worldObj;
this.speedTowardsTarget = speed;
this.longMemory = persistant;
this.setMutexBits(3);
}
@Override
public boolean shouldExecute() {
EntityLivingBase target = this.attacker.getAttackTarget();
if (target == null)
{
return false;
}
else if (!target.isEntityAlive())
{
return false;
}
else if (this.classTarget != null && !this.classTarget.isAssignableFrom(target.getClass()))
{
return false;
}
else
{
if (-- this.obstructionLevel <= 0)
{
this.pathToTarget = this.attacker.getNavigator().getPathToEntityLiving(target);
this.obstructionLevel = 4 + this.attacker.getRNG().nextInt(7);
return this.pathToTarget != null;
}
else
{
return true;
}
}
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting()
{
this.attacker.getNavigator().setPath(this.pathToTarget, this.speedTowardsTarget);
this.obstructionLevel = 0;
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean continueExecuting()
{
EntityLivingBase target = this.attacker.getAttackTarget();
if (target == null){
return false;
}
if (!target.isEntityAlive()){
return false;
}
return this.attacker.getNavigator().noPath() &&
this.attacker.isWithinHomeDistance(
MathHelper.floor_double(target.posX),
MathHelper.floor_double(target.posY),
MathHelper.floor_double(target.posZ));
}
/**
* Resets the task
*/
public void resetTask()
{
this.attacker.getNavigator().clearPathEntity();
}
/**
* Updates the task
*/
public void updateTask()
{
EntityLivingBase entitylivingbase = this.attacker.getAttackTarget();
this.attacker.getLookHelper().setLookPositionWithEntity(entitylivingbase, 30.0F, 30.0F);
double d0 = this.attacker.getDistanceSq(entitylivingbase.posX, entitylivingbase.boundingBox.minY, entitylivingbase.posZ);
double d1 = (double)(this.attacker.width * 2.0F * this.attacker.width * 2.0F + entitylivingbase.width);
--this.obstructionLevel;
//if information is outdated/unititialized
if (this.obstructionLevel <= 0 &&
(this.x == 0.0D && this.y == 0.0D &&
this.z == 0.0D ||
entitylivingbase.getDistanceSq(this.x, this.y, this.z) >= 1.0D ||
this.attacker.getRNG().nextFloat() < 0.05F))
{
//initialize some information
this.x = entitylivingbase.posX;
this.y = entitylivingbase.boundingBox.minY;
this.z = entitylivingbase.posZ;
this.obstructionLevel = failedPathFindingPenalty + 4 + this.attacker.getRNG().nextInt(7);
if (this.attacker.getNavigator().getPath() != null)
{
PathPoint finalPathPoint = this.attacker.getNavigator().getPath().getFinalPathPoint();
if (finalPathPoint != null && entitylivingbase.getDistanceSq(finalPathPoint.xCoord, finalPathPoint.yCoord, finalPathPoint.zCoord) < 1)
{
failedPathFindingPenalty = 0;
}
else
{
failedPathFindingPenalty += 10;
}
}
else
{
failedPathFindingPenalty += 10;
}
if (d0 > 1024.0D)
{
this.obstructionLevel += 10;
}
else if (d0 > 256.0D)
{
this.obstructionLevel += 5;
}
if (!this.attacker.getNavigator().tryMoveToEntityLiving(entitylivingbase, this.speedTowardsTarget))
{
this.obstructionLevel += 15;
}
}
//this is the code for digging!
this.digTick = Math.max(this.digTick - 1, 0);
EntityLivingBase target = attacker.getAttackTarget();
double distance=10;
if (attacker.getNavigator().getPath()!=null &&
attacker.getNavigator().getPath().getFinalPathPoint()!=null){
PathPoint destination = this.attacker.getNavigator().getPath().getFinalPathPoint();
distance = target.getDistanceSq(destination.xCoord, destination.yCoord, destination.zCoord);
}
if (this.digTick<=0)
System.out.println("distance to target: "+distance);
if (this.digTick <= 0 &&
target!=null &&
distance>2)
{
System.out.println("time to dig!");
this.digTick = 20;
int x=(int)Math.floor(attacker.posX);
int y=(int)Math.floor(attacker.posY);
int z=(int)Math.floor(attacker.posZ);
double deltax = target.posX-attacker.posX;
double deltaz = target.posZ-attacker.posZ;
int monsterDirection=0;
if(Math.abs(deltax)>Math.abs(deltaz)){
//use x
if (x>0){
//east
monsterDirection=3;
}else{
//west
monsterDirection=1;
}
}else{
//use z
if (z>0){
//south
monsterDirection=0;
}else{
//north
monsterDirection=2;
}
}
//int monsterDirection = Direction.getMovementDirection(attacker..xCoord, attacker.getLookVec().zCoord);
int xoff = Direction.offsetX[monsterDirection];
int zoff = Direction.offsetZ[monsterDirection];
Block above = world.getBlock(x,y+2,z);
Block aboveForeward = world.getBlock(x+xoff,y+2,z+zoff);
Block eyeLevel = world.getBlock(x+xoff,y+1,z+zoff);
Block footLevel = world.getBlock(x+xoff,y,z+zoff);
Block floorForward = world.getBlock(x+xoff, y-1, z+zoff);
int targety = (int)Math.floor(target.posY);
//it's time to dig!
//try the eye level block first
if (!eyeLevel.isAir(world, x+xoff, y+1, z+zoff)){
System.out.println("I need to see");
breakBlock(world, eyeLevel, x+xoff, y+1, z+zoff);
}
//next above
else if (targety>y&&
!(above.isAir(world, x, y+2, z))){
System.out.println("I will jump to you");
breakBlock(world, above, x, y+2, z);
}
//then the above forward
else if (targety>y &&
!aboveForeward.isAir(world, x+xoff, y+2, z+zoff)){
breakBlock(world, aboveForeward, x+xoff, y+2, z+zoff);
}
//next the foot level
else if (!(targety>y)&&
!(world.isAirBlock(x+xoff, y, z+zoff))){
System.out.println("my feet need room");
breakBlock(world,footLevel,x+xoff,y,z+zoff);
}
//then the below corner
else if (targety>y &&
!floorForward.isAir(world, x+xoff, y-1, z+zoff)){
System.out.println("hat corners");
breakBlock(world, floorForward, x+xoff, y-1, z+zoff);
}
}
}
public void breakBlock(World w, Block b, int x,int y,int z){
ArrayList<ItemStack> drops=b.getDrops(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
b.dropBlockAsItem(w, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.removeTileEntity(x, y, z);
world.setBlockToAir(x, y, z);
}
}
| apache-2.0 |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java | 6312 | package com.rocko.update;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler();
File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH);
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
sendNotification();
final String apkSavePath = Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME;
final String downloadUrl = Urls.baseUrl + Urls.downloadApk;// getResources().getString(R.string.base_url)
// +
// getResources().getString(R.string.downloadApkUrl);
new Thread(new Runnable() {
public void run() {
try {
DownloadTask.downloadFile(getApplicationContext(), downloadUrl, apkSavePath, downloadHandler);
} catch (Exception e) {
DebugLog.e(e.getMessage());
e.printStackTrace();
}
}
}).start();
}
/**
* 发送通知
*/
private void sendNotification() {
// 通知栏服务
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification_update);
notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
notification.contentIntent = pendingIntent;
notification.contentView = view;
notification.contentView.setProgressBar(R.id.pb_notification, 100, 0, false);
notification.contentView.setTextViewText(R.id.txt_notificaton_down_go, "0%");
notificationManager.notify(0, notification);
}
/**
* 安装apk的意图
*
* @param flags
* @return
*/
private PendingIntent getInstallPendingIntent(int flags) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME)), "application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, flags);
return pendingIntent;
}
private class DownloadHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
// 下载进度
case DOWNLOAD_PROGRESS:
DebugLog.v("下载进度:" + msg.arg1 + "%");
notification.contentView.setProgressBar(R.id.pb_notification, 100, msg.arg1, false);
notification.contentView.setTextViewText(R.id.txt_notificaton_down_go, msg.arg1 + "%");
notificationManager.notify(0, notification);
break;
// 下载完成
case DOWNLOAD_FINISH:
DebugLog.v("下载更新完成");
notification.contentView.setProgressBar(R.id.pb_notification, 100, 100, false);
notification.contentView.setTextViewText(R.id.txt_notificaton_down_go, "100%");
notification.contentView.setTextViewText(R.id.txt_notificaton_down, "下载完成 点击安装");
notification.contentIntent = getInstallPendingIntent(Notification.FLAG_AUTO_CANCEL);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
/* 安装 */
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(Configs.EXTERNAL_STORAGE_DIRECTORY
+ Configs.UPDATE_DOWNLOAD_PATH + Configs.NEW_APK_FILE_NAME)),
"application/vnd.android.package-archive");
UpdateService.this.startActivity(intent);
UpdateManager.clearQuote();
UpdateService.this.stopSelf();
break;
// 下载失败
case DOWNLOAD_FAILED:
notification.contentView.setTextViewText(R.id.txt_notificaton_down, "下载失败");
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
UpdateManager.clearQuote();
UpdateService.this.stopSelf();
break;
default:
break;
}
}
}
}
| apache-2.0 |
yurloc/assertj-core | src/test/java/org/assertj/core/api/GenericInterface.java | 751 | /*
* Created on Apr 22, 2012
*
* 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.
*
* Copyright @2010-2011 the original author or authors.
*/
package org.assertj.core.api;
/**
* @author Mikhail Mazursky
*/
public interface GenericInterface<X> {
}
| apache-2.0 |
tobyweston/tempus-fugit | src/main/java/com/google/code/tempusfugit/temporal/RealClock.java | 937 | /*
* Copyright (c) 2009-2018, toby weston & tempus-fugit committers
*
* 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.code.tempusfugit.temporal;
import java.util.Date;
public class RealClock implements Clock {
public RealClock() {
}
public static RealClock today() {
return new RealClock();
}
@Override
public Date now() {
return new Date();
}
}
| apache-2.0 |
mikkoi/maven-enforcer-property-usage | src/main/java/com/github/mikkoi/maven/plugins/enforcer/rule/propertyusage/configuration/FileSpecs.java | 4117 | package com.github.mikkoi.maven.plugins.enforcer.rule.propertyusage.configuration;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringUtils;
import javax.annotation.Nonnull;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.stream.Collectors;
/**
* Handle FileSpecs.
*/
public class FileSpecs {
private FileSpecs() {
// This class cannot be instantiated.
throw new AssertionError();
}
public static String absoluteCwdAndFile(@Nonnull final String filename) {
return Paths.get(System.getProperty("user.dir"), filename).toAbsolutePath().normalize().toString();
}
/**
* Process collection of file names.
* If file name is a file, get its absolute path.
* If not, assume it is either a directory or a wildcard name, and
* scan it with DirectoryScanner.
*
* @param files A Collection of Strings
* @return A Collection of Strings
*/
@Nonnull
public static Collection<String> getAbsoluteFilenames(
@Nonnull final Collection<String> files,
@Nonnull final Path basedir,
@Nonnull final Log log
) {
Collection<String> allFilenames = new HashSet<>();
if(!files.isEmpty()) {
// We have to process away files with an absolute path because
// DirectoryScanner can't handle them (as they may not be in basedir)
// So we take away all files that exist.
for (String fileSpec : files) {
if (StringUtils.isBlank(fileSpec)) {
log.error(logFileIterationMsg(fileSpec, "is blank. Error in configuration") + "!");
continue;
}
File file = new File(fileSpec);
if (file.exists() && file.isFile()) {
log.debug(logFileIterationMsg(fileSpec, "is a file") + ".");
allFilenames.add(file.getAbsolutePath()); // If item is already in Set, discarded automatically.
} else if (file.exists() && file.isDirectory()) {
log.debug(logFileIterationMsg(fileSpec, "is a directory") + ".");
DirectoryScanner ds = initializeDS(Paths.get(fileSpec));
ds.scan();
allFilenames.addAll(Arrays.stream(ds.getIncludedFiles()).map(includedFile -> new File(includedFile).getAbsolutePath()).collect(Collectors.toSet()));
} else if (file.exists()) {
log.error(logFileIterationMsg(fileSpec, "is not a file or directory. Do not know what to do") + "!");
} else {
log.debug(logFileIterationMsg(fileSpec, "does not exist. Assume wildcards") + ".");
DirectoryScanner ds = initializeDS(basedir);
ds.setIncludes(new String[]{fileSpec});
ds.scan();
Collection<String> foundFiles = Arrays.stream(ds.getIncludedFiles()).map(includedFile -> Paths.get(basedir.toString(), includedFile).toString()).collect(Collectors.toSet());
log.debug(" Found files:[");
for (final String foundFile : foundFiles) {
log.debug(" " + foundFile);
}
log.debug(" ]");
allFilenames.addAll(foundFiles);
}
}
}
return allFilenames;
}
private static DirectoryScanner initializeDS(@Nonnull final Path path) {
DirectoryScanner ds = new DirectoryScanner();
ds.setCaseSensitive(true);
ds.setFollowSymlinks(true);
ds.addDefaultExcludes();
ds.setBasedir(path.toAbsolutePath().toString());
return ds;
}
@Nonnull
private static String logFileIterationMsg(@Nonnull final String filename, @Nonnull final String comment) {
return "File spec '" + filename + "' " + comment;
}
}
| apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/ExpectedAttributeValue.java | 150773 | /*
* Copyright 2010-2016 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.dynamodbv2.model;
import java.io.Serializable;
/**
* <p>
* Represents a condition to be compared with an attribute value. This condition
* can be used with <i>DeleteItem</i>, <i>PutItem</i> or <i>UpdateItem</i>
* operations; if the comparison evaluates to true, the operation succeeds; if
* not, the operation fails. You can use <i>ExpectedAttributeValue</i> in one of
* two different ways:
* </p>
* <ul>
* <li>
* <p>
* Use <i>AttributeValueList</i> to specify one or more values to compare
* against an attribute. Use <i>ComparisonOperator</i> to specify how you want
* to perform the comparison. If the comparison evaluates to true, then the
* conditional operation succeeds.
* </p>
* </li>
* <li>
* <p>
* Use <i>Value</i> to specify a value that DynamoDB will compare against an
* attribute. If the values match, then <i>ExpectedAttributeValue</i> evaluates
* to true and the conditional operation succeeds. Optionally, you can also set
* <i>Exists</i> to false, indicating that you <i>do not</i> expect to find the
* attribute value in the table. In this case, the conditional operation
* succeeds only if the comparison evaluates to false.
* </p>
* </li>
* </ul>
* <p>
* <i>Value</i> and <i>Exists</i> are incompatible with
* <i>AttributeValueList</i> and <i>ComparisonOperator</i>. Note that if you use
* both sets of parameters at once, DynamoDB will return a
* <i>ValidationException</i> exception.
* </p>
*/
public class ExpectedAttributeValue implements Serializable, Cloneable {
private AttributeValue value;
/**
* <p>
* Causes DynamoDB to evaluate the value before attempting a conditional
* operation:
* </p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that
* attribute value already exists in the table. If it is found, then the
* operation succeeds. If it is not found, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value does
* not exist, then the assumption is valid and the operation succeeds. If
* the value is found, despite the assumption that it does not exist, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you supply
* a <i>Value</i> all by itself, DynamoDB assumes the attribute exists: You
* don't have to set <i>Exists</i> to <code>true</code>, because it is
* implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to check.
* (You expect a value to exist, but don't specify what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a <i>Value</i>.
* (You cannot expect an attribute to have a value, while also expecting it
* not to exist.)
* </p>
* </li>
* </ul>
*/
private Boolean exists;
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*/
private String comparisonOperator;
/**
* <p>
* One or more values to evaluate against the supplied attribute. The number
* of values in the list depends on the <i>ComparisonOperator</i> being
* used.
* </p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than are based
* on ASCII character code values. For example, <code>a</code> is greater
* than <code>A</code>, and <code>a</code> is greater than <code>B</code>.
* For a list of code values, see <a
* href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as unsigned when
* it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer Guide</i>.
* </p>
*/
private java.util.List<AttributeValue> attributeValueList;
/**
* Default constructor for ExpectedAttributeValue object. Callers should use
* the setter or fluent setter (with...) methods to initialize the object
* after creating it.
*/
public ExpectedAttributeValue() {
}
/**
* Constructs a new ExpectedAttributeValue object. Callers should use the
* setter or fluent setter (with...) methods to initialize any additional
* object members.
*
* @param value
*/
public ExpectedAttributeValue(AttributeValue value) {
setValue(value);
}
/**
* Constructs a new ExpectedAttributeValue object. Callers should use the
* setter or fluent setter (with...) methods to initialize any additional
* object members.
*
* @param exists
* Causes DynamoDB to evaluate the value before attempting a
* conditional operation:</p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see
* if that attribute value already exists in the table. If it is
* found, then the operation succeeds. If it is not found, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value
* does not exist, then the assumption is valid and the operation
* succeeds. If the value is found, despite the assumption that it
* does not exist, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you
* supply a <i>Value</i> all by itself, DynamoDB assumes the
* attribute exists: You don't have to set <i>Exists</i> to
* <code>true</code>, because it is implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to
* check. (You expect a value to exist, but don't specify what
* that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a
* <i>Value</i>. (You cannot expect an attribute to have a value,
* while also expecting it not to exist.)
* </p>
* </li>
*/
public ExpectedAttributeValue(Boolean exists) {
setExists(exists);
}
/**
* @param value
*/
public void setValue(AttributeValue value) {
this.value = value;
}
/**
* @return
*/
public AttributeValue getValue() {
return this.value;
}
/**
* @param value
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ExpectedAttributeValue withValue(AttributeValue value) {
setValue(value);
return this;
}
/**
* <p>
* Causes DynamoDB to evaluate the value before attempting a conditional
* operation:
* </p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that
* attribute value already exists in the table. If it is found, then the
* operation succeeds. If it is not found, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value does
* not exist, then the assumption is valid and the operation succeeds. If
* the value is found, despite the assumption that it does not exist, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you supply
* a <i>Value</i> all by itself, DynamoDB assumes the attribute exists: You
* don't have to set <i>Exists</i> to <code>true</code>, because it is
* implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to check.
* (You expect a value to exist, but don't specify what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a <i>Value</i>.
* (You cannot expect an attribute to have a value, while also expecting it
* not to exist.)
* </p>
* </li>
* </ul>
*
* @param exists
* Causes DynamoDB to evaluate the value before attempting a
* conditional operation:</p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see
* if that attribute value already exists in the table. If it is
* found, then the operation succeeds. If it is not found, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value
* does not exist, then the assumption is valid and the operation
* succeeds. If the value is found, despite the assumption that it
* does not exist, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you
* supply a <i>Value</i> all by itself, DynamoDB assumes the
* attribute exists: You don't have to set <i>Exists</i> to
* <code>true</code>, because it is implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to
* check. (You expect a value to exist, but don't specify what
* that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a
* <i>Value</i>. (You cannot expect an attribute to have a value,
* while also expecting it not to exist.)
* </p>
* </li>
*/
public void setExists(Boolean exists) {
this.exists = exists;
}
/**
* <p>
* Causes DynamoDB to evaluate the value before attempting a conditional
* operation:
* </p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that
* attribute value already exists in the table. If it is found, then the
* operation succeeds. If it is not found, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value does
* not exist, then the assumption is valid and the operation succeeds. If
* the value is found, despite the assumption that it does not exist, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you supply
* a <i>Value</i> all by itself, DynamoDB assumes the attribute exists: You
* don't have to set <i>Exists</i> to <code>true</code>, because it is
* implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to check.
* (You expect a value to exist, but don't specify what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a <i>Value</i>.
* (You cannot expect an attribute to have a value, while also expecting it
* not to exist.)
* </p>
* </li>
* </ul>
*
* @return Causes DynamoDB to evaluate the value before attempting a
* conditional operation:</p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see
* if that attribute value already exists in the table. If it is
* found, then the operation succeeds. If it is not found, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value
* does not exist, then the assumption is valid and the operation
* succeeds. If the value is found, despite the assumption that it
* does not exist, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If
* you supply a <i>Value</i> all by itself, DynamoDB assumes the
* attribute exists: You don't have to set <i>Exists</i> to
* <code>true</code>, because it is implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i>
* to check. (You expect a value to exist, but don't specify
* what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a
* <i>Value</i>. (You cannot expect an attribute to have a value,
* while also expecting it not to exist.)
* </p>
* </li>
*/
public Boolean getExists() {
return this.exists;
}
/**
* <p>
* Causes DynamoDB to evaluate the value before attempting a conditional
* operation:
* </p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that
* attribute value already exists in the table. If it is found, then the
* operation succeeds. If it is not found, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value does
* not exist, then the assumption is valid and the operation succeeds. If
* the value is found, despite the assumption that it does not exist, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you supply
* a <i>Value</i> all by itself, DynamoDB assumes the attribute exists: You
* don't have to set <i>Exists</i> to <code>true</code>, because it is
* implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to check.
* (You expect a value to exist, but don't specify what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a <i>Value</i>.
* (You cannot expect an attribute to have a value, while also expecting it
* not to exist.)
* </p>
* </li>
* </ul>
*
* @param exists
* Causes DynamoDB to evaluate the value before attempting a
* conditional operation:</p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see
* if that attribute value already exists in the table. If it is
* found, then the operation succeeds. If it is not found, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value
* does not exist, then the assumption is valid and the operation
* succeeds. If the value is found, despite the assumption that it
* does not exist, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you
* supply a <i>Value</i> all by itself, DynamoDB assumes the
* attribute exists: You don't have to set <i>Exists</i> to
* <code>true</code>, because it is implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to
* check. (You expect a value to exist, but don't specify what
* that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a
* <i>Value</i>. (You cannot expect an attribute to have a value,
* while also expecting it not to exist.)
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ExpectedAttributeValue withExists(Boolean exists) {
setExists(exists);
return this;
}
/**
* <p>
* Causes DynamoDB to evaluate the value before attempting a conditional
* operation:
* </p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that
* attribute value already exists in the table. If it is found, then the
* operation succeeds. If it is not found, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value does
* not exist, then the assumption is valid and the operation succeeds. If
* the value is found, despite the assumption that it does not exist, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If you supply
* a <i>Value</i> all by itself, DynamoDB assumes the attribute exists: You
* don't have to set <i>Exists</i> to <code>true</code>, because it is
* implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i> to check.
* (You expect a value to exist, but don't specify what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a <i>Value</i>.
* (You cannot expect an attribute to have a value, while also expecting it
* not to exist.)
* </p>
* </li>
* </ul>
*
* @return Causes DynamoDB to evaluate the value before attempting a
* conditional operation:</p>
* <ul>
* <li>
* <p>
* If <i>Exists</i> is <code>true</code>, DynamoDB will check to see
* if that attribute value already exists in the table. If it is
* found, then the operation succeeds. If it is not found, the
* operation fails with a <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* <li>
* <p>
* If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the
* attribute value does not exist in the table. If in fact the value
* does not exist, then the assumption is valid and the operation
* succeeds. If the value is found, despite the assumption that it
* does not exist, the operation fails with a
* <i>ConditionalCheckFailedException</i>.
* </p>
* </li>
* </ul>
* <p>
* The default setting for <i>Exists</i> is <code>true</code>. If
* you supply a <i>Value</i> all by itself, DynamoDB assumes the
* attribute exists: You don't have to set <i>Exists</i> to
* <code>true</code>, because it is implied.
* </p>
* <p>
* DynamoDB returns a <i>ValidationException</i> if:
* </p>
* <ul>
* <li>
* <p>
* <i>Exists</i> is <code>true</code> but there is no <i>Value</i>
* to check. (You expect a value to exist, but don't specify
* what that value is.)
* </p>
* </li>
* <li>
* <p>
* <i>Exists</i> is <code>false</code> but you also provide a
* <i>Value</i>. (You cannot expect an attribute to have a value,
* while also expecting it not to exist.)
* </p>
* </li>
*/
public Boolean isExists() {
return this.exists;
}
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*
* @param comparisonOperator
* A comparator for evaluating attributes in the
* <i>AttributeValueList</i>. For example, equals, greater than, less
* than, etc.</p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, Binary,
* String Set, Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, Binary, String Set,
* Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> of a different type than the one provided in
* the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, or Binary (not a set
* type). If an item contains an <i>AttributeValue</i> element of a
* different type than the one provided in the request, the value
* does not match. For example, <code>{"S":"6"}</code> does not equal
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not
* compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists.
* <code>NOT_NULL</code> is supported for all datatypes, including
* lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NOT_NULL</code>, the result is a
* Boolean <i>true</i>. This result is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist.
* <code>NULL</code> is supported for all datatypes, including lists
* and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NULL</code>, the result is a
* Boolean <i>false</i>. This is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a
* set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is of
* type String, then the operator checks for a substring match. If
* the target attribute of the comparison is of type Binary, then the
* operator looks for a subsequence of the target that matches the
* input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then
* the operator evaluates to true if it finds an exact match with any
* member of the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence,
* or absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is a
* String, then the operator checks for the absence of a substring
* match. If the target attribute of the comparison is Binary, then
* the operator checks for the absence of a subsequence of the target
* that matches the input. If the target attribute of the comparison
* is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it
* <i>does not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String or Binary (not a Number or a
* set type). The target attribute of the comparison must be of type
* String or Binary (not a Number or a set type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more
* <i>AttributeValue</i> elements of type String, Number, or Binary
* (not a set type). These attributes are compared against an
* existing set type attribute of an item. If any elements of the
* input set are present in the item attribute, the expression
* evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value,
* and less than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i>
* elements of the same type, either String, Number, or Binary (not a
* set type). A target attribute matches if the target value is
* greater than, or equal to, the first element and less than, or
* equal to, the second element. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* @see ComparisonOperator
*/
public void setComparisonOperator(String comparisonOperator) {
this.comparisonOperator = comparisonOperator;
}
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*
* @return A comparator for evaluating attributes in the
* <i>AttributeValueList</i>. For example, equals, greater than,
* less than, etc.</p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, Binary,
* String Set, Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, Binary, String Set,
* Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code>
* does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, or Binary (not a
* set type). If an item contains an <i>AttributeValue</i> element
* of a different type than the one provided in the request, the
* value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code>
* does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code>
* does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists.
* <code>NOT_NULL</code> is supported for all datatypes, including
* lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is
* null, and you evaluate it using <code>NOT_NULL</code>, the result
* is a Boolean <i>true</i>. This result is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist.
* <code>NULL</code> is supported for all datatypes, including lists
* and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is
* null, and you evaluate it using <code>NULL</code>, the result is
* a Boolean <i>false</i>. This is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a
* set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is of
* type String, then the operator checks for a substring match. If
* the target attribute of the comparison is of type Binary, then
* the operator looks for a subsequence of the target that matches
* the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then
* the operator evaluates to true if it finds an exact match with
* any member of the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a
* map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence,
* or absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is a
* String, then the operator checks for the absence of a substring
* match. If the target attribute of the comparison is Binary, then
* the operator checks for the absence of a subsequence of the
* target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it
* <i>does not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a
* map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String or Binary (not a Number or a
* set type). The target attribute of the comparison must be of type
* String or Binary (not a Number or a set type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more
* <i>AttributeValue</i> elements of type String, Number, or Binary
* (not a set type). These attributes are compared against an
* existing set type attribute of an item. If any elements of the
* input set are present in the item attribute, the expression
* evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value,
* and less than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i>
* elements of the same type, either String, Number, or Binary (not
* a set type). A target attribute matches if the target value is
* greater than, or equal to, the first element and less than, or
* equal to, the second element. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>
* . Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* @see ComparisonOperator
*/
public String getComparisonOperator() {
return this.comparisonOperator;
}
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*
* @param comparisonOperator
* A comparator for evaluating attributes in the
* <i>AttributeValueList</i>. For example, equals, greater than, less
* than, etc.</p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, Binary,
* String Set, Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, Binary, String Set,
* Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> of a different type than the one provided in
* the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, or Binary (not a set
* type). If an item contains an <i>AttributeValue</i> element of a
* different type than the one provided in the request, the value
* does not match. For example, <code>{"S":"6"}</code> does not equal
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not
* compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists.
* <code>NOT_NULL</code> is supported for all datatypes, including
* lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NOT_NULL</code>, the result is a
* Boolean <i>true</i>. This result is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist.
* <code>NULL</code> is supported for all datatypes, including lists
* and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NULL</code>, the result is a
* Boolean <i>false</i>. This is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a
* set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is of
* type String, then the operator checks for a substring match. If
* the target attribute of the comparison is of type Binary, then the
* operator looks for a subsequence of the target that matches the
* input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then
* the operator evaluates to true if it finds an exact match with any
* member of the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence,
* or absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is a
* String, then the operator checks for the absence of a substring
* match. If the target attribute of the comparison is Binary, then
* the operator checks for the absence of a subsequence of the target
* that matches the input. If the target attribute of the comparison
* is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it
* <i>does not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String or Binary (not a Number or a
* set type). The target attribute of the comparison must be of type
* String or Binary (not a Number or a set type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more
* <i>AttributeValue</i> elements of type String, Number, or Binary
* (not a set type). These attributes are compared against an
* existing set type attribute of an item. If any elements of the
* input set are present in the item attribute, the expression
* evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value,
* and less than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i>
* elements of the same type, either String, Number, or Binary (not a
* set type). A target attribute matches if the target value is
* greater than, or equal to, the first element and less than, or
* equal to, the second element. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ComparisonOperator
*/
public ExpectedAttributeValue withComparisonOperator(
String comparisonOperator) {
setComparisonOperator(comparisonOperator);
return this;
}
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*
* @param comparisonOperator
* A comparator for evaluating attributes in the
* <i>AttributeValueList</i>. For example, equals, greater than, less
* than, etc.</p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, Binary,
* String Set, Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, Binary, String Set,
* Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> of a different type than the one provided in
* the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, or Binary (not a set
* type). If an item contains an <i>AttributeValue</i> element of a
* different type than the one provided in the request, the value
* does not match. For example, <code>{"S":"6"}</code> does not equal
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not
* compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists.
* <code>NOT_NULL</code> is supported for all datatypes, including
* lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NOT_NULL</code>, the result is a
* Boolean <i>true</i>. This result is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist.
* <code>NULL</code> is supported for all datatypes, including lists
* and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NULL</code>, the result is a
* Boolean <i>false</i>. This is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a
* set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is of
* type String, then the operator checks for a substring match. If
* the target attribute of the comparison is of type Binary, then the
* operator looks for a subsequence of the target that matches the
* input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then
* the operator evaluates to true if it finds an exact match with any
* member of the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence,
* or absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is a
* String, then the operator checks for the absence of a substring
* match. If the target attribute of the comparison is Binary, then
* the operator checks for the absence of a subsequence of the target
* that matches the input. If the target attribute of the comparison
* is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it
* <i>does not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String or Binary (not a Number or a
* set type). The target attribute of the comparison must be of type
* String or Binary (not a Number or a set type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more
* <i>AttributeValue</i> elements of type String, Number, or Binary
* (not a set type). These attributes are compared against an
* existing set type attribute of an item. If any elements of the
* input set are present in the item attribute, the expression
* evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value,
* and less than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i>
* elements of the same type, either String, Number, or Binary (not a
* set type). A target attribute matches if the target value is
* greater than, or equal to, the first element and less than, or
* equal to, the second element. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* @see ComparisonOperator
*/
public void setComparisonOperator(ComparisonOperator comparisonOperator) {
this.comparisonOperator = comparisonOperator.toString();
}
/**
* <p>
* A comparator for evaluating attributes in the <i>AttributeValueList</i>.
* For example, equals, greater than, less than, etc.
* </p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes,
* including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, Binary, String Set, Number Set, or Binary
* Set. If an item contains an <i>AttributeValue</i> element of a different
* type than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, Binary, String Set, Number Set, or Binary Set. If an
* item contains an <i>AttributeValue</i> of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not equal <code>{"NS":["6", "2", "1"]}</code>
* .
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String, Number, or Binary (not a set type). If an item contains an
* <i>AttributeValue</i> element of a different type than the one provided
* in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If an item
* contains an <i>AttributeValue</i> element of a different type than the
* one provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also,
* <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its data type.
* If the data type of attribute "<code>a</code>" is null, and you evaluate
* it using <code>NOT_NULL</code>, the result is a Boolean <i>true</i>. This
* result is because the attribute "<code>a</code>" exists; its data type is
* not relevant to the <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist. <code>NULL</code> is
* supported for all datatypes, including lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its data
* type. If the data type of attribute "<code>a</code>" is null, and you
* evaluate it using <code>NULL</code>, the result is a Boolean
* <i>false</i>. This is because the attribute "<code>a</code>" exists; its
* data type is not relevant to the <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is of type String, then the operator checks
* for a substring match. If the target attribute of the comparison is of
* type Binary, then the operator looks for a subsequence of the target that
* matches the input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the
* operator evaluates to true if it finds an exact match with any member of
* the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>" can be a list; however, "
* <code>b</code>" cannot be a set, a map, or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or
* absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i>
* element of type String, Number, or Binary (not a set type). If the target
* attribute of the comparison is a String, then the operator checks for the
* absence of a substring match. If the target attribute of the comparison
* is Binary, then the operator checks for the absence of a subsequence of
* the target that matches the input. If the target attribute of the
* comparison is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it <i>does
* not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map, or a
* list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of
* type String or Binary (not a Number or a set type). The target attribute
* of the comparison must be of type String or Binary (not a Number or a set
* type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i>
* elements of type String, Number, or Binary (not a set type). These
* attributes are compared against an existing set type attribute of an
* item. If any elements of the input set are present in the item attribute,
* the expression evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value, and less
* than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements
* of the same type, either String, Number, or Binary (not a set type). A
* target attribute matches if the target value is greater than, or equal
* to, the first element and less than, or equal to, the second element. If
* an item contains an <i>AttributeValue</i> element of a different type
* than the one provided in the request, the value does not match. For
* example, <code>{"S":"6"}</code> does not compare to
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* </ul>
*
* @param comparisonOperator
* A comparator for evaluating attributes in the
* <i>AttributeValueList</i>. For example, equals, greater than, less
* than, etc.</p>
* <p>
* The following comparison operators are available:
* </p>
* <p>
* <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN</code>
* </p>
* <p>
* The following are descriptions of each comparison operator.
* </p>
* <ul>
* <li>
* <p>
* <code>EQ</code> : Equal. <code>EQ</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, Binary,
* String Set, Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NE</code> : Not equal. <code>NE</code> is supported for all
* datatypes, including lists and maps.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, Binary, String Set,
* Number Set, or Binary Set. If an item contains an
* <i>AttributeValue</i> of a different type than the one provided in
* the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not equal
* <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LE</code> : Less than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>LT</code> : Less than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String, Number, or Binary (not a set
* type). If an item contains an <i>AttributeValue</i> element of a
* different type than the one provided in the request, the value
* does not match. For example, <code>{"S":"6"}</code> does not equal
* <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not
* compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GE</code> : Greater than or equal.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>GT</code> : Greater than.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If an item contains an <i>AttributeValue</i>
* element of a different type than the one provided in the request,
* the value does not match. For example, <code>{"S":"6"}</code> does
* not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code>
* does not compare to <code>{"NS":["6", "2", "1"]}</code>.
* </p>
* <p/></li>
* <li>
* <p>
* <code>NOT_NULL</code> : The attribute exists.
* <code>NOT_NULL</code> is supported for all datatypes, including
* lists and maps.
* </p>
* <note>
* <p>
* This operator tests for the existence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NOT_NULL</code>, the result is a
* Boolean <i>true</i>. This result is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NOT_NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>NULL</code> : The attribute does not exist.
* <code>NULL</code> is supported for all datatypes, including lists
* and maps.
* </p>
* <note>
* <p>
* This operator tests for the nonexistence of an attribute, not its
* data type. If the data type of attribute "<code>a</code>" is null,
* and you evaluate it using <code>NULL</code>, the result is a
* Boolean <i>false</i>. This is because the attribute "
* <code>a</code>" exists; its data type is not relevant to the
* <code>NULL</code> comparison operator.
* </p>
* </note></li>
* <li>
* <p>
* <code>CONTAINS</code> : Checks for a subsequence, or value in a
* set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is of
* type String, then the operator checks for a substring match. If
* the target attribute of the comparison is of type Binary, then the
* operator looks for a subsequence of the target that matches the
* input. If the target attribute of the comparison is a set ("
* <code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then
* the operator evaluates to true if it finds an exact match with any
* member of the set.
* </p>
* <p>
* CONTAINS is supported for lists: When evaluating "
* <code>a CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>NOT_CONTAINS</code> : Checks for absence of a subsequence,
* or absence of a value in a set.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> element of type String, Number, or Binary
* (not a set type). If the target attribute of the comparison is a
* String, then the operator checks for the absence of a substring
* match. If the target attribute of the comparison is Binary, then
* the operator checks for the absence of a subsequence of the target
* that matches the input. If the target attribute of the comparison
* is a set ("<code>SS</code>", "<code>NS</code>", or "
* <code>BS</code>"), then the operator evaluates to true if it
* <i>does not</i> find an exact match with any member of the set.
* </p>
* <p>
* NOT_CONTAINS is supported for lists: When evaluating "
* <code>a NOT CONTAINS b</code>", "<code>a</code>
* " can be a list; however, "<code>b</code>" cannot be a set, a map,
* or a list.
* </p>
* </li>
* <li>
* <p>
* <code>BEGINS_WITH</code> : Checks for a prefix.
* </p>
* <p>
* <i>AttributeValueList</i> can contain only one
* <i>AttributeValue</i> of type String or Binary (not a Number or a
* set type). The target attribute of the comparison must be of type
* String or Binary (not a Number or a set type).
* </p>
* <p/></li>
* <li>
* <p>
* <code>IN</code> : Checks for matching elements within two sets.
* </p>
* <p>
* <i>AttributeValueList</i> can contain one or more
* <i>AttributeValue</i> elements of type String, Number, or Binary
* (not a set type). These attributes are compared against an
* existing set type attribute of an item. If any elements of the
* input set are present in the item attribute, the expression
* evaluates to true.
* </p>
* </li>
* <li>
* <p>
* <code>BETWEEN</code> : Greater than or equal to the first value,
* and less than or equal to the second value.
* </p>
* <p>
* <i>AttributeValueList</i> must contain two <i>AttributeValue</i>
* elements of the same type, either String, Number, or Binary (not a
* set type). A target attribute matches if the target value is
* greater than, or equal to, the first element and less than, or
* equal to, the second element. If an item contains an
* <i>AttributeValue</i> element of a different type than the one
* provided in the request, the value does not match. For example,
* <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>.
* Also, <code>{"N":"6"}</code> does not compare to
* <code>{"NS":["6", "2", "1"]}</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ComparisonOperator
*/
public ExpectedAttributeValue withComparisonOperator(
ComparisonOperator comparisonOperator) {
setComparisonOperator(comparisonOperator);
return this;
}
/**
* <p>
* One or more values to evaluate against the supplied attribute. The number
* of values in the list depends on the <i>ComparisonOperator</i> being
* used.
* </p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than are based
* on ASCII character code values. For example, <code>a</code> is greater
* than <code>A</code>, and <code>a</code> is greater than <code>B</code>.
* For a list of code values, see <a
* href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as unsigned when
* it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer Guide</i>.
* </p>
*
* @return One or more values to evaluate against the supplied attribute.
* The number of values in the list depends on the
* <i>ComparisonOperator</i> being used.</p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than
* are based on ASCII character code values. For example,
* <code>a</code> is greater than <code>A</code>, and <code>a</code>
* is greater than <code>B</code>. For a list of code values, see <a
* href
* ="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http
* ://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as
* unsigned when it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer
* Guide</i>.
*/
public java.util.List<AttributeValue> getAttributeValueList() {
return attributeValueList;
}
/**
* <p>
* One or more values to evaluate against the supplied attribute. The number
* of values in the list depends on the <i>ComparisonOperator</i> being
* used.
* </p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than are based
* on ASCII character code values. For example, <code>a</code> is greater
* than <code>A</code>, and <code>a</code> is greater than <code>B</code>.
* For a list of code values, see <a
* href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as unsigned when
* it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer Guide</i>.
* </p>
*
* @param attributeValueList
* One or more values to evaluate against the supplied attribute. The
* number of values in the list depends on the
* <i>ComparisonOperator</i> being used.</p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than
* are based on ASCII character code values. For example,
* <code>a</code> is greater than <code>A</code>, and <code>a</code>
* is greater than <code>B</code>. For a list of code values, see <a
* href
* ="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http
* ://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as
* unsigned when it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer
* Guide</i>.
*/
public void setAttributeValueList(
java.util.Collection<AttributeValue> attributeValueList) {
if (attributeValueList == null) {
this.attributeValueList = null;
return;
}
this.attributeValueList = new java.util.ArrayList<AttributeValue>(
attributeValueList);
}
/**
* <p>
* One or more values to evaluate against the supplied attribute. The number
* of values in the list depends on the <i>ComparisonOperator</i> being
* used.
* </p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than are based
* on ASCII character code values. For example, <code>a</code> is greater
* than <code>A</code>, and <code>a</code> is greater than <code>B</code>.
* For a list of code values, see <a
* href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as unsigned when
* it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer Guide</i>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setAttributeValueList(java.util.Collection)} or
* {@link #withAttributeValueList(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param attributeValueList
* One or more values to evaluate against the supplied attribute. The
* number of values in the list depends on the
* <i>ComparisonOperator</i> being used.</p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than
* are based on ASCII character code values. For example,
* <code>a</code> is greater than <code>A</code>, and <code>a</code>
* is greater than <code>B</code>. For a list of code values, see <a
* href
* ="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http
* ://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as
* unsigned when it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer
* Guide</i>.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ExpectedAttributeValue withAttributeValueList(
AttributeValue... attributeValueList) {
if (this.attributeValueList == null) {
setAttributeValueList(new java.util.ArrayList<AttributeValue>(
attributeValueList.length));
}
for (AttributeValue ele : attributeValueList) {
this.attributeValueList.add(ele);
}
return this;
}
/**
* <p>
* One or more values to evaluate against the supplied attribute. The number
* of values in the list depends on the <i>ComparisonOperator</i> being
* used.
* </p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than are based
* on ASCII character code values. For example, <code>a</code> is greater
* than <code>A</code>, and <code>a</code> is greater than <code>B</code>.
* For a list of code values, see <a
* href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as unsigned when
* it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer Guide</i>.
* </p>
*
* @param attributeValueList
* One or more values to evaluate against the supplied attribute. The
* number of values in the list depends on the
* <i>ComparisonOperator</i> being used.</p>
* <p>
* For type Number, value comparisons are numeric.
* </p>
* <p>
* String value comparisons for greater than, equals, or less than
* are based on ASCII character code values. For example,
* <code>a</code> is greater than <code>A</code>, and <code>a</code>
* is greater than <code>B</code>. For a list of code values, see <a
* href
* ="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters"
* >http
* ://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.
* </p>
* <p>
* For Binary, DynamoDB treats each byte of the binary data as
* unsigned when it compares binary values.
* </p>
* <p>
* For information on specifying data types in JSON, see <a href=
* "http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html"
* >JSON Data Format</a> in the <i>Amazon DynamoDB Developer
* Guide</i>.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ExpectedAttributeValue withAttributeValueList(
java.util.Collection<AttributeValue> attributeValueList) {
setAttributeValueList(attributeValueList);
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 (getValue() != null)
sb.append("Value: " + getValue() + ",");
if (getExists() != null)
sb.append("Exists: " + getExists() + ",");
if (getComparisonOperator() != null)
sb.append("ComparisonOperator: " + getComparisonOperator() + ",");
if (getAttributeValueList() != null)
sb.append("AttributeValueList: " + getAttributeValueList());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ExpectedAttributeValue == false)
return false;
ExpectedAttributeValue other = (ExpectedAttributeValue) obj;
if (other.getValue() == null ^ this.getValue() == null)
return false;
if (other.getValue() != null
&& other.getValue().equals(this.getValue()) == false)
return false;
if (other.getExists() == null ^ this.getExists() == null)
return false;
if (other.getExists() != null
&& other.getExists().equals(this.getExists()) == false)
return false;
if (other.getComparisonOperator() == null
^ this.getComparisonOperator() == null)
return false;
if (other.getComparisonOperator() != null
&& other.getComparisonOperator().equals(
this.getComparisonOperator()) == false)
return false;
if (other.getAttributeValueList() == null
^ this.getAttributeValueList() == null)
return false;
if (other.getAttributeValueList() != null
&& other.getAttributeValueList().equals(
this.getAttributeValueList()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getValue() == null) ? 0 : getValue().hashCode());
hashCode = prime * hashCode
+ ((getExists() == null) ? 0 : getExists().hashCode());
hashCode = prime
* hashCode
+ ((getComparisonOperator() == null) ? 0
: getComparisonOperator().hashCode());
hashCode = prime
* hashCode
+ ((getAttributeValueList() == null) ? 0
: getAttributeValueList().hashCode());
return hashCode;
}
@Override
public ExpectedAttributeValue clone() {
try {
return (ExpectedAttributeValue) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
taochen/ssascaling | src/main/java/org/ssascaling/ModelFunctionConfigGenerator.java | 977 | package org.ssascaling;
public class ModelFunctionConfigGenerator {
private static double[] otherFunctionANN = {
6000, //15000
5,
0.15,
0.01
};
private static double[] throughputFunctionANN = {
6000,
5,
0.25,
0.01
};
/**
* We assume the identical configuration first
*/
private static double[][] functionResult = {
/*ANN*/new double[]{},
/*ARMAX*/new double[]{},
/*RT*/new double[]{}
};
private static double[][] structureResult = {
/*ANN*/new double[]{3, 9,/*30*/ 0.35},
/*ARMAX*/new double[]{1,3},
/*RT*/new double[]{}
};
public static double[][] getFunctionConfiguration(String name){
double[][] local = functionResult;
if ("Throughput".equals(name)) {
local[ModelFunction.ANN] = throughputFunctionANN;
} else {
local[ModelFunction.ANN] = otherFunctionANN;
}
return local;
}
public static double[][] getStructureConfiguration(String name){
return structureResult;
}
}
| apache-2.0 |
4u7/couchbase-lite-java-core | src/main/java/com/couchbase/lite/support/RemoteRequest.java | 14798 | package com.couchbase.lite.support;
import com.couchbase.lite.Database;
import com.couchbase.lite.Manager;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorImpl;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.URIUtils;
import com.couchbase.lite.util.Utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.zip.GZIPInputStream;
/**
* @exclude
*/
public class RemoteRequest implements Runnable {
// Don't compress data shorter than this (not worth the CPU time, plus it might not shrink)
public static final int MIN_JSON_LENGTH_TO_COMPRESS = 100;
protected ScheduledExecutorService workExecutor;
protected final HttpClientFactory clientFactory;
protected String method;
protected URL url;
protected Object body;
protected Authenticator authenticator;
protected RemoteRequestCompletionBlock onPreCompletion;
protected RemoteRequestCompletionBlock onCompletion;
protected RemoteRequestCompletionBlock onPostCompletion;
protected HttpUriRequest request;
protected Map<String, Object> requestHeaders;
// if true, we wont log any 404 errors (useful when getting remote checkpoint doc)
private boolean dontLog404;
// if true, send compressed (gzip) request
private boolean compressedRequest = false;
private String str = null;
public RemoteRequest(ScheduledExecutorService workExecutor,
HttpClientFactory clientFactory, String method, URL url,
Object body, Database db, Map<String, Object> requestHeaders, RemoteRequestCompletionBlock onCompletion) {
this.clientFactory = clientFactory;
this.method = method;
this.url = url;
this.body = body;
this.onCompletion = onCompletion;
this.workExecutor = workExecutor;
this.requestHeaders = requestHeaders;
this.request = createConcreteRequest();
Log.v(Log.TAG_SYNC, "%s: RemoteRequest created, url: %s", this, url);
}
@Override
public void run() {
Log.v(Log.TAG_SYNC, "%s: RemoteRequest run() called, url: %s", this, url);
HttpClient httpClient = clientFactory.getHttpClient();
try {
preemptivelySetAuthCredentials(httpClient);
request.addHeader("Accept", "multipart/related, application/json");
request.addHeader("User-Agent", Manager.getUserAgent());
request.addHeader("Accept-Encoding", "gzip, deflate");
addRequestHeaders(request);
setBody(request);
executeRequest(httpClient, request);
Log.v(Log.TAG_SYNC, "%s: RemoteRequest run() finished, url: %s", this, url);
} catch (Throwable e) {
Log.e(Log.TAG_SYNC, "RemoteRequest.run() exception: %s", e);
} finally {
// shutdown connection manager (close all connections)
if (httpClient != null && httpClient.getConnectionManager() != null)
httpClient.getConnectionManager().shutdown();
}
}
public void abort() {
Log.w(Log.TAG_REMOTE_REQUEST, "%s: aborting request: %s", this, request);
if (request != null) {
request.abort();
} else {
Log.w(Log.TAG_REMOTE_REQUEST, "%s: Unable to abort request since underlying request is null", this);
}
}
public HttpUriRequest getRequest() {
return request;
}
protected void addRequestHeaders(HttpUriRequest request) {
if (requestHeaders != null) {
for (String requestHeaderKey : requestHeaders.keySet()) {
request.addHeader(requestHeaderKey, requestHeaders.get(requestHeaderKey).toString());
}
}
}
public void setOnPostCompletion(RemoteRequestCompletionBlock onPostCompletion) {
this.onPostCompletion = onPostCompletion;
}
public void setOnPreCompletion(RemoteRequestCompletionBlock onPreCompletion) {
this.onPreCompletion = onPreCompletion;
}
protected HttpUriRequest createConcreteRequest() {
HttpUriRequest request = null;
if ("GET".equalsIgnoreCase(method)) {
request = new HttpGet(url.toExternalForm());
} else if ("PUT".equalsIgnoreCase(method)) {
request = new HttpPut(url.toExternalForm());
} else if ("POST".equalsIgnoreCase(method)) {
request = new HttpPost(url.toExternalForm());
}
return request;
}
/**
* Set Authenticator for BASIC Authentication
*/
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
protected void executeRequest(HttpClient httpClient, HttpUriRequest requestParam) {
Object fullBody = null;
Throwable error = null;
HttpResponse response = null;
try {
Log.v(Log.TAG_SYNC, "%s: RemoteRequest calling httpClient.execute, url: %s", this, url);
if (requestParam.isAborted()) {
Log.v(Log.TAG_SYNC, "%s: RemoteRequest has already been aborted", this);
respondWithResult(fullBody, new Exception(String.format("%s: Request %s has been aborted", this, requestParam)), response);
return;
}
Log.v(Log.TAG_SYNC, "%s: RemoteRequest calling httpClient.execute, client: %s url: %s", this, httpClient, url);
response = httpClient.execute(requestParam);
Log.v(Log.TAG_SYNC, "%s: RemoteRequest called httpClient.execute, url: %s", this, url);
// add in cookies to global store
try {
if (httpClient instanceof DefaultHttpClient) {
DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
this.clientFactory.addCookies(defaultHttpClient.getCookieStore().getCookies());
}
} catch (Exception e) {
Log.e(Log.TAG_REMOTE_REQUEST, "Unable to add in cookies to global store", e);
}
StatusLine status = response.getStatusLine();
if (status.getStatusCode() >= 300) {
try {
if (!dontLog404) {
Log.e(Log.TAG_REMOTE_REQUEST, "Got error status: %d for %s. Reason: %s", status.getStatusCode(), url, status.getReasonPhrase());
}
error = new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
respondWithResult(fullBody, error, response);
return;
} finally {
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
} else {
HttpEntity entity = response.getEntity();
try {
if (entity != null) {
InputStream inputStream = entity.getContent();
try {
// decompress if contentEncoding is gzip
if (Utils.isGzip(entity))
inputStream = new GZIPInputStream(inputStream);
fullBody = Manager.getObjectMapper().readValue(inputStream, Object.class);
respondWithResult(fullBody, error, response);
return;
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
}
} finally {
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
}
} catch (Exception e) {
Log.e(Log.TAG_REMOTE_REQUEST, "%s: executeRequest() Exception: %s. url: %s", this, e, url);
error = e;
}
finally {
Log.v(Log.TAG_SYNC, "%s: RemoteRequest finally block. url: %s", this, url);
}
// error scenario
respondWithResult(fullBody, error, response);
}
protected void preemptivelySetAuthCredentials(HttpClient httpClient) {
boolean isUrlBasedUserInfo = false;
String userInfo = url.getUserInfo();
if (userInfo != null) {
isUrlBasedUserInfo = true;
} else {
if (authenticator != null) {
AuthenticatorImpl auth = (AuthenticatorImpl) authenticator;
userInfo = auth.authUserInfo();
}
}
if (userInfo != null) {
if (userInfo.contains(":") && !":".equals(userInfo.trim())) {
String[] userInfoElements = userInfo.split(":");
String username = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[0]) : userInfoElements[0];
String password = "";
if(userInfoElements.length >= 2)
password = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[1]) : userInfoElements[1];
final Credentials credentials = new UsernamePasswordCredentials(username, password);
if (httpClient instanceof DefaultHttpClient) {
DefaultHttpClient dhc = (DefaultHttpClient) httpClient;
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(credentials);
}
}
};
dhc.addRequestInterceptor(preemptiveAuth, 0);
}
} else {
Log.w(Log.TAG_REMOTE_REQUEST, "RemoteRequest Unable to parse user info, not setting credentials");
}
}
}
public void respondWithResult(final Object result, final Throwable error, final HttpResponse response) {
try {
if (onPreCompletion != null) {
onPreCompletion.onCompletion(response, null, error);
}
onCompletion.onCompletion(response, result, error);
if (onPostCompletion != null) {
onPostCompletion.onCompletion(response, null, error);
}
} catch (Exception e) {
// don't let this crash the thread
Log.e(Log.TAG_REMOTE_REQUEST,
"RemoteRequestCompletionBlock throw Exception",
e);
}
}
public void setDontLog404(boolean dontLog404) {
this.dontLog404 = dontLog404;
}
public boolean isCompressedRequest() {
return compressedRequest;
}
public void setCompressedRequest(boolean compressedRequest) {
this.compressedRequest = compressedRequest;
}
protected void setBody(HttpUriRequest request) {
// set body if appropriate
if (body != null && request instanceof HttpEntityEnclosingRequestBase) {
byte[] bodyBytes = null;
try {
bodyBytes = Manager.getObjectMapper().writeValueAsBytes(body);
} catch (Exception e) {
Log.e(Log.TAG_REMOTE_REQUEST, "Error serializing body of request", e);
}
ByteArrayEntity entity = null;
if(isCompressedRequest() && bodyBytes.length > MIN_JSON_LENGTH_TO_COMPRESS){
entity = setCompressedBody(bodyBytes);
}
if(entity == null){
entity = setUncompressedBody(bodyBytes);
}
((HttpEntityEnclosingRequestBase) request).setEntity(entity);
}
}
/**
* gzip
*
* in CBLRemoteRequest.m
* - (BOOL) compressBody
*/
protected static ByteArrayEntity setCompressedBody(byte[] bodyBytes){
if(bodyBytes.length < MIN_JSON_LENGTH_TO_COMPRESS){
return null;
}
// Gzipping
byte[] encodedBytes = Utils.compressByGzip(bodyBytes);
if(encodedBytes == null || encodedBytes.length >= bodyBytes.length) {
return null;
}
ByteArrayEntity entity = new ByteArrayEntity(encodedBytes);
entity.setContentType("application/json");
entity.setContentEncoding("gzip");
encodedBytes = null;
bodyBytes = null;
return entity;
}
protected static ByteArrayEntity setUncompressedBody(byte[] bodyBytes){
ByteArrayEntity entity = new ByteArrayEntity(bodyBytes);
entity.setContentType("application/json");
return entity;
}
@Override
public String toString() {
if (str == null) {
String remoteURL = url.toExternalForm().replaceAll("://.*:.*@", "://---:---@");
str = String.format("RemoteRequest{%s, %s}", method, remoteURL);
}
return str;
}
}
| apache-2.0 |
Elegie/luchess | projects/luchess-web-framework/src/main/java/io/elegie/luchess/web/framework/routing/ControllerUtil.java | 5597 | package io.elegie.luchess.web.framework.routing;
import io.elegie.luchess.web.framework.payload.Result;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides utility methods to work with controllers. These methods
* may be relocated elsewhere, once we get enough feedback about the use of the
* framework.
*/
public final class ControllerUtil {
private static final Logger LOG = LoggerFactory.getLogger(ControllerUtil.class);
private ControllerUtil() {
}
// --- Discover controllers inside a package ------------------------------
private static final String CLASS_SUFFIX = ".class";
/**
* Discovers all controllers from a given package, searching recursively.
*
* @param scannedPackage
* The root package to be searched.
* @return A list of all controllers contained within the package (or its
* children).
*/
public static List<Class<?>> findControllersByPackage(String scannedPackage) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String scannedPath = scannedPackage.replace('.', '/');
Enumeration<URL> resources;
try {
resources = classLoader.getResources(scannedPath);
} catch (IOException e) {
String message = "Cannot find resources from \"%s\".";
message = String.format(message, scannedPackage);
throw new IllegalArgumentException(message, e);
}
List<Class<?>> classes = new LinkedList<>();
while (resources.hasMoreElements()) {
String path = resources.nextElement().getFile();
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
String message = "Cannot decode %s. Trying without decoding.";
message = String.format(message, path);
LOG.warn(message, e);
}
File file = new File(path);
classes.addAll(find(file, scannedPackage));
}
return classes;
}
private static List<Class<?>> find(File file, String scannedPackage) {
List<Class<?>> classes = new LinkedList<>();
if (file.isDirectory()) {
for (File nestedFile : file.listFiles()) {
classes.addAll(find(nestedFile, scannedPackage));
}
} else if (file.getName().endsWith(CLASS_SUFFIX) && !file.getName().contains("$")) {
int endIndex = file.getName().length() - CLASS_SUFFIX.length();
String className = file.getName().substring(0, endIndex);
try {
final String resource = scannedPackage + '.' + className;
Class<?> controllerClass = Class.forName(resource);
if (!Modifier.isAbstract(controllerClass.getModifiers()) && findControllerMethod(controllerClass) != null) {
classes.add(controllerClass);
}
} catch (ClassNotFoundException | ControllerException e) {
String message = "Ignoring class %s as potential controller.";
message = String.format(message, className);
LOG.error(message, e);
}
} else {
String message = "Ignoring file (%s), not a directory and not a class.";
message = String.format(message, file);
LOG.warn(message);
}
return classes;
}
// --- Find and check controller method -----------------------------------
/**
* Given an object, find the controller method (inspecting all of its public
* methods), or return null if no such method is found.
*
* @param controller
* The class of the object to assert as a controller.
* @return The controller method, or null if no such method.
* @throws ControllerException
* When a controller method has been specified on the class, but
* appears to be malformed.
*/
public static Method findControllerMethod(Class<?> controller) throws ControllerException {
Method[] methods = controller.getMethods();
for (Method method : methods) {
Controller annotation = method.getAnnotation(Controller.class);
if (annotation != null) {
checkReturnType(method);
checkParameters(method);
return method;
}
}
return null;
}
private static void checkReturnType(Method method) throws ControllerException {
if (!Result.class.isAssignableFrom(method.getReturnType())) {
String message = "Controller method %s should return a Result.";
message = String.format(message, method.getName());
throw new ControllerException(message);
}
}
private static void checkParameters(Method method) throws ControllerException {
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length > 1) {
String message = "Controller method %s may not have more than one parameters.";
message = String.format(message, method.getName());
throw new ControllerException(message);
}
}
}
| apache-2.0 |
liancanxiong/ImageLoader | src/test/java/com/brilliantbear/imageloder/ExampleUnitTest.java | 335 | package com.brilliantbear.imageloder;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
ryankennedy/telemetry | telemetry-example/src/main/java/com/hypnoticocelot/telemetry/example/ExampleConfiguration.java | 160 | package com.hypnoticocelot.telemetry.example;
import com.yammer.dropwizard.config.Configuration;
public class ExampleConfiguration extends Configuration {
}
| apache-2.0 |
MZaratin-Larus/neo4art | neo4art-core/src/main/java/org/neo4art/core/batch/ArtistIndexCreator.java | 1548 | /**
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neo4art.core.batch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.neo4art.core.repository.ArtistBatchInserterRepository;
import org.neo4art.core.repository.ArtistRepository;
import org.neo4art.graphdb.connection.Neo4ArtBatchInserterSingleton;
/**
* @author Lorenzo Speranzoni
* @since 3 May 2015
*/
public class ArtistIndexCreator
{
private static Log logger = LogFactory.getLog(ArtistIndexCreator.class);
public static void main(String[] args)
{
try
{
ArtistRepository artistRepository = new ArtistBatchInserterRepository();
artistRepository.createArtistLegacyIndex();
}
catch (Exception e)
{
e.printStackTrace();
logger.error("Error creating legacy index for artists: " + e.getMessage());
}
finally
{
Neo4ArtBatchInserterSingleton.shutdownBatchInserterInstance();
}
}
}
| apache-2.0 |
jacarrichan/eoffice | src/main/java/com/palmelf/eoffice/dao/flow/ProTypeDao.java | 190 | package com.palmelf.eoffice.dao.flow;
import com.palmelf.core.dao.BaseDao;
import com.palmelf.eoffice.model.flow.ProType;
public abstract interface ProTypeDao extends BaseDao<ProType> {
}
| apache-2.0 |
ruks/geowave | core/ingest/src/main/java/mil/nga/giat/geowave/core/ingest/kafka/AvroKafkaEncoder.java | 972 | package mil.nga.giat.geowave.core.ingest.kafka;
import kafka.serializer.Encoder;
import kafka.utils.VerifiableProperties;
import org.apache.avro.specific.SpecificRecordBase;
/**
* Default encoder used by Kafka to serialize Avro generated Java object to
* binary. This class is specified as a property in the Kafka config setup.
*
* Key: serializer.class
*
* Value: mil.nga.giat.geowave.core.ingest.kafka.AvroKafkaEncoder
*
* @param <T>
* - Base Avro class extended by all generated class files
*/
public class AvroKafkaEncoder<T extends SpecificRecordBase> implements
Encoder<T>
{
private final GenericAvroSerializer<T> serializer = new GenericAvroSerializer<T>();
public AvroKafkaEncoder(
final VerifiableProperties verifiableProperties ) {
// This constructor must be present to avoid runtime errors
}
@Override
public byte[] toBytes(
final T object ) {
return serializer.serialize(
object,
object.getSchema());
}
} | apache-2.0 |
McLeodMoores/starling | projects/component/src/main/java/com/opengamma/component/factory/master/InMemoryRegionMasterComponentFactory.java | 19314 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.component.factory.master;
import static com.opengamma.component.factory.master.DBMasterComponentUtils.isValidJmsConfiguration;
import java.util.LinkedHashMap;
import java.util.Map;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.springframework.context.Lifecycle;
import com.opengamma.component.ComponentInfo;
import com.opengamma.component.ComponentRepository;
import com.opengamma.component.factory.AbstractComponentFactory;
import com.opengamma.component.factory.ComponentInfoAttributes;
import com.opengamma.core.change.BasicChangeManager;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.core.change.JmsChangeManager;
import com.opengamma.id.ObjectIdSupplier;
import com.opengamma.master.region.RegionMaster;
import com.opengamma.master.region.impl.DataRegionMasterResource;
import com.opengamma.master.region.impl.InMemoryRegionMaster;
import com.opengamma.master.region.impl.RegionFileReader;
import com.opengamma.master.region.impl.RemoteRegionMaster;
import com.opengamma.util.jms.JmsConnector;
/**
* Component factory for the database region master.
*/
@BeanDefinition
public class InMemoryRegionMasterComponentFactory extends AbstractComponentFactory {
/**
* The classifier that the factory should publish under.
*/
@PropertyDefinition(validate = "notNull")
private String _classifier;
/**
* Whether to use change management. If true, requires jms settings to be non-null.
*/
@PropertyDefinition
private boolean _enableChangeManagement = true;
/**
* The flag determining whether the component should be published by REST (default true).
*/
@PropertyDefinition
private boolean _publishRest = true;
/**
* The JMS connector.
*/
@PropertyDefinition
private JmsConnector _jmsConnector;
/**
* The JMS change manager topic.
*/
@PropertyDefinition
private String _jmsChangeManagerTopic;
/**
* The scheme used by the {@code UniqueId}.
*/
@PropertyDefinition
private String _uniqueIdScheme;
//-------------------------------------------------------------------------
@Override
public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) {
final ComponentInfo info = new ComponentInfo(RegionMaster.class, getClassifier());
// create
final String scheme = getUniqueIdScheme() != null ? getUniqueIdScheme() : InMemoryRegionMaster.DEFAULT_OID_SCHEME;
ChangeManager cm = new BasicChangeManager();
if (isEnableChangeManagement() && isValidJmsConfiguration(getClassifier(), getClass(), getJmsConnector(), getJmsChangeManagerTopic())) {
cm = new JmsChangeManager(getJmsConnector(), getJmsChangeManagerTopic());
repo.registerLifecycle((Lifecycle) cm);
if (getJmsConnector().getClientBrokerUri() != null) {
info.addAttribute(ComponentInfoAttributes.JMS_BROKER_URI, getJmsConnector().getClientBrokerUri().toString());
}
info.addAttribute(ComponentInfoAttributes.JMS_CHANGE_MANAGER_TOPIC, getJmsChangeManagerTopic());
}
final InMemoryRegionMaster master = new InMemoryRegionMaster(new ObjectIdSupplier(scheme), cm);
RegionFileReader.createPopulated(master);
// register
info.addAttribute(ComponentInfoAttributes.LEVEL, 1);
if (isPublishRest()) {
info.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteRegionMaster.class);
}
info.addAttribute(ComponentInfoAttributes.UNIQUE_ID_SCHEME, scheme);
repo.registerComponent(info, master);
// publish
if (isPublishRest()) {
repo.getRestComponents().publish(info, new DataRegionMasterResource(master));
}
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code InMemoryRegionMasterComponentFactory}.
* @return the meta-bean, not null
*/
public static InMemoryRegionMasterComponentFactory.Meta meta() {
return InMemoryRegionMasterComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(InMemoryRegionMasterComponentFactory.Meta.INSTANCE);
}
@Override
public InMemoryRegionMasterComponentFactory.Meta metaBean() {
return InMemoryRegionMasterComponentFactory.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the classifier that the factory should publish under.
* @return the value of the property, not null
*/
public String getClassifier() {
return _classifier;
}
/**
* Sets the classifier that the factory should publish under.
* @param classifier the new value of the property, not null
*/
public void setClassifier(String classifier) {
JodaBeanUtils.notNull(classifier, "classifier");
this._classifier = classifier;
}
/**
* Gets the the {@code classifier} property.
* @return the property, not null
*/
public final Property<String> classifier() {
return metaBean().classifier().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets whether to use change management. If true, requires jms settings to be non-null.
* @return the value of the property
*/
public boolean isEnableChangeManagement() {
return _enableChangeManagement;
}
/**
* Sets whether to use change management. If true, requires jms settings to be non-null.
* @param enableChangeManagement the new value of the property
*/
public void setEnableChangeManagement(boolean enableChangeManagement) {
this._enableChangeManagement = enableChangeManagement;
}
/**
* Gets the the {@code enableChangeManagement} property.
* @return the property, not null
*/
public final Property<Boolean> enableChangeManagement() {
return metaBean().enableChangeManagement().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the flag determining whether the component should be published by REST (default true).
* @return the value of the property
*/
public boolean isPublishRest() {
return _publishRest;
}
/**
* Sets the flag determining whether the component should be published by REST (default true).
* @param publishRest the new value of the property
*/
public void setPublishRest(boolean publishRest) {
this._publishRest = publishRest;
}
/**
* Gets the the {@code publishRest} property.
* @return the property, not null
*/
public final Property<Boolean> publishRest() {
return metaBean().publishRest().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the JMS connector.
* @return the value of the property
*/
public JmsConnector getJmsConnector() {
return _jmsConnector;
}
/**
* Sets the JMS connector.
* @param jmsConnector the new value of the property
*/
public void setJmsConnector(JmsConnector jmsConnector) {
this._jmsConnector = jmsConnector;
}
/**
* Gets the the {@code jmsConnector} property.
* @return the property, not null
*/
public final Property<JmsConnector> jmsConnector() {
return metaBean().jmsConnector().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the JMS change manager topic.
* @return the value of the property
*/
public String getJmsChangeManagerTopic() {
return _jmsChangeManagerTopic;
}
/**
* Sets the JMS change manager topic.
* @param jmsChangeManagerTopic the new value of the property
*/
public void setJmsChangeManagerTopic(String jmsChangeManagerTopic) {
this._jmsChangeManagerTopic = jmsChangeManagerTopic;
}
/**
* Gets the the {@code jmsChangeManagerTopic} property.
* @return the property, not null
*/
public final Property<String> jmsChangeManagerTopic() {
return metaBean().jmsChangeManagerTopic().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the scheme used by the {@code UniqueId}.
* @return the value of the property
*/
public String getUniqueIdScheme() {
return _uniqueIdScheme;
}
/**
* Sets the scheme used by the {@code UniqueId}.
* @param uniqueIdScheme the new value of the property
*/
public void setUniqueIdScheme(String uniqueIdScheme) {
this._uniqueIdScheme = uniqueIdScheme;
}
/**
* Gets the the {@code uniqueIdScheme} property.
* @return the property, not null
*/
public final Property<String> uniqueIdScheme() {
return metaBean().uniqueIdScheme().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public InMemoryRegionMasterComponentFactory clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
InMemoryRegionMasterComponentFactory other = (InMemoryRegionMasterComponentFactory) obj;
return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) &&
(isEnableChangeManagement() == other.isEnableChangeManagement()) &&
(isPublishRest() == other.isPublishRest()) &&
JodaBeanUtils.equal(getJmsConnector(), other.getJmsConnector()) &&
JodaBeanUtils.equal(getJmsChangeManagerTopic(), other.getJmsChangeManagerTopic()) &&
JodaBeanUtils.equal(getUniqueIdScheme(), other.getUniqueIdScheme()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash * 31 + JodaBeanUtils.hashCode(getClassifier());
hash = hash * 31 + JodaBeanUtils.hashCode(isEnableChangeManagement());
hash = hash * 31 + JodaBeanUtils.hashCode(isPublishRest());
hash = hash * 31 + JodaBeanUtils.hashCode(getJmsConnector());
hash = hash * 31 + JodaBeanUtils.hashCode(getJmsChangeManagerTopic());
hash = hash * 31 + JodaBeanUtils.hashCode(getUniqueIdScheme());
return hash ^ super.hashCode();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(224);
buf.append("InMemoryRegionMasterComponentFactory{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
@Override
protected void toString(StringBuilder buf) {
super.toString(buf);
buf.append("classifier").append('=').append(JodaBeanUtils.toString(getClassifier())).append(',').append(' ');
buf.append("enableChangeManagement").append('=').append(JodaBeanUtils.toString(isEnableChangeManagement())).append(',').append(' ');
buf.append("publishRest").append('=').append(JodaBeanUtils.toString(isPublishRest())).append(',').append(' ');
buf.append("jmsConnector").append('=').append(JodaBeanUtils.toString(getJmsConnector())).append(',').append(' ');
buf.append("jmsChangeManagerTopic").append('=').append(JodaBeanUtils.toString(getJmsChangeManagerTopic())).append(',').append(' ');
buf.append("uniqueIdScheme").append('=').append(JodaBeanUtils.toString(getUniqueIdScheme())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code InMemoryRegionMasterComponentFactory}.
*/
public static class Meta extends AbstractComponentFactory.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code classifier} property.
*/
private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite(
this, "classifier", InMemoryRegionMasterComponentFactory.class, String.class);
/**
* The meta-property for the {@code enableChangeManagement} property.
*/
private final MetaProperty<Boolean> _enableChangeManagement = DirectMetaProperty.ofReadWrite(
this, "enableChangeManagement", InMemoryRegionMasterComponentFactory.class, Boolean.TYPE);
/**
* The meta-property for the {@code publishRest} property.
*/
private final MetaProperty<Boolean> _publishRest = DirectMetaProperty.ofReadWrite(
this, "publishRest", InMemoryRegionMasterComponentFactory.class, Boolean.TYPE);
/**
* The meta-property for the {@code jmsConnector} property.
*/
private final MetaProperty<JmsConnector> _jmsConnector = DirectMetaProperty.ofReadWrite(
this, "jmsConnector", InMemoryRegionMasterComponentFactory.class, JmsConnector.class);
/**
* The meta-property for the {@code jmsChangeManagerTopic} property.
*/
private final MetaProperty<String> _jmsChangeManagerTopic = DirectMetaProperty.ofReadWrite(
this, "jmsChangeManagerTopic", InMemoryRegionMasterComponentFactory.class, String.class);
/**
* The meta-property for the {@code uniqueIdScheme} property.
*/
private final MetaProperty<String> _uniqueIdScheme = DirectMetaProperty.ofReadWrite(
this, "uniqueIdScheme", InMemoryRegionMasterComponentFactory.class, String.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"classifier",
"enableChangeManagement",
"publishRest",
"jmsConnector",
"jmsChangeManagerTopic",
"uniqueIdScheme");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return _classifier;
case 981110710: // enableChangeManagement
return _enableChangeManagement;
case -614707837: // publishRest
return _publishRest;
case -1495762275: // jmsConnector
return _jmsConnector;
case -758086398: // jmsChangeManagerTopic
return _jmsChangeManagerTopic;
case -1737146991: // uniqueIdScheme
return _uniqueIdScheme;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends InMemoryRegionMasterComponentFactory> builder() {
return new DirectBeanBuilder<InMemoryRegionMasterComponentFactory>(new InMemoryRegionMasterComponentFactory());
}
@Override
public Class<? extends InMemoryRegionMasterComponentFactory> beanType() {
return InMemoryRegionMasterComponentFactory.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code classifier} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> classifier() {
return _classifier;
}
/**
* The meta-property for the {@code enableChangeManagement} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> enableChangeManagement() {
return _enableChangeManagement;
}
/**
* The meta-property for the {@code publishRest} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> publishRest() {
return _publishRest;
}
/**
* The meta-property for the {@code jmsConnector} property.
* @return the meta-property, not null
*/
public final MetaProperty<JmsConnector> jmsConnector() {
return _jmsConnector;
}
/**
* The meta-property for the {@code jmsChangeManagerTopic} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> jmsChangeManagerTopic() {
return _jmsChangeManagerTopic;
}
/**
* The meta-property for the {@code uniqueIdScheme} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> uniqueIdScheme() {
return _uniqueIdScheme;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return ((InMemoryRegionMasterComponentFactory) bean).getClassifier();
case 981110710: // enableChangeManagement
return ((InMemoryRegionMasterComponentFactory) bean).isEnableChangeManagement();
case -614707837: // publishRest
return ((InMemoryRegionMasterComponentFactory) bean).isPublishRest();
case -1495762275: // jmsConnector
return ((InMemoryRegionMasterComponentFactory) bean).getJmsConnector();
case -758086398: // jmsChangeManagerTopic
return ((InMemoryRegionMasterComponentFactory) bean).getJmsChangeManagerTopic();
case -1737146991: // uniqueIdScheme
return ((InMemoryRegionMasterComponentFactory) bean).getUniqueIdScheme();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
((InMemoryRegionMasterComponentFactory) bean).setClassifier((String) newValue);
return;
case 981110710: // enableChangeManagement
((InMemoryRegionMasterComponentFactory) bean).setEnableChangeManagement((Boolean) newValue);
return;
case -614707837: // publishRest
((InMemoryRegionMasterComponentFactory) bean).setPublishRest((Boolean) newValue);
return;
case -1495762275: // jmsConnector
((InMemoryRegionMasterComponentFactory) bean).setJmsConnector((JmsConnector) newValue);
return;
case -758086398: // jmsChangeManagerTopic
((InMemoryRegionMasterComponentFactory) bean).setJmsChangeManagerTopic((String) newValue);
return;
case -1737146991: // uniqueIdScheme
((InMemoryRegionMasterComponentFactory) bean).setUniqueIdScheme((String) newValue);
return;
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((InMemoryRegionMasterComponentFactory) bean)._classifier, "classifier");
super.validate(bean);
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| apache-2.0 |
martenscs/optaplanner-osgi | org.optaplanner.examples.projectjobscheduling/src/org/optaplanner/examples/projectjobscheduling/Activator.java | 981 | package org.optaplanner.examples.projectjobscheduling;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
public static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
ProjectJobSchedulingPerformanceTest test = new ProjectJobSchedulingPerformanceTest();
test.setBundleContext(bundleContext);
test.setUp();
test.createSolutionDao();
test.createSolverConfigResource();
test.solveAll();
}
/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
| apache-2.0 |
ibissource/iaf | core/src/test/java/nl/nn/adapterframework/align/OverridesMapTest.java | 1781 | package nl.nn.adapterframework.align;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class OverridesMapTest {
OverridesMap<String> map;
@Before
public void setUp() throws Exception {
map = new OverridesMap<String>();
}
AlignmentContext parse(String path) {
AlignmentContext result=null;
for (String element: path.split("/")) {
result = new AlignmentContext(result, null, element, null, null, null, 0, null, false);
}
return result;
}
public void testSubst(String parsedPath, String child, String expectedValue) {
testSubst(parsedPath, child, expectedValue, expectedValue!=null);
}
public void testSubst(String parsedPath, String child, String expectedValue, boolean expectsChild) {
AlignmentContext context=parsedPath==null?null:parse(parsedPath);
assertEquals("value for '"+child+"' after '"+parsedPath+"'",expectedValue,map.getMatchingValue(context, child));
assertEquals("has something for '"+child+"' after '"+parsedPath+"'",expectsChild,map.hasSubstitutionsFor(context, child));
}
@Test
public void test() {
map.registerSubstitute("Party/Id", "PartyId");
map.registerSubstitute("Address/Id", "AdressId");
map.registerSubstitute("Id", "DefaultId");
map.registerSubstitute("Data", "Data");
map.registerSubstitute("Root/Sub", "SubValue");
testSubst(null,"Id","DefaultId");
testSubst(null,"Party",null, true);
testSubst(null,"Data","Data");
testSubst(null,"Sub",null);
testSubst("Root","Id","DefaultId");
testSubst("Root","Party",null, true);
testSubst("Root","Data","Data");
testSubst("Root","Sub","SubValue");
testSubst("Root/Party","Id","PartyId");
testSubst("Root/Party","Party",null, true);
testSubst("Root/Party","Data","Data");
}
}
| apache-2.0 |
InspurUSA/kudu | java/kudu-client/src/test/java/org/apache/kudu/client/TestPartialRow.java | 21274 | // 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.kudu.client;
import static org.apache.kudu.test.ClientTestUtil.getSchemaWithAllTypes;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import org.junit.Rule;
import org.junit.Test;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.test.junit.RetryRule;
public class TestPartialRow {
@Rule
public RetryRule retryRule = new RetryRule();
@Test
public void testGetters() {
PartialRow partialRow = getPartialRowWithAllTypes();
assertEquals(true, partialRow.getBoolean("bool"));
assertEquals(42, partialRow.getByte("int8"));
assertEquals(43, partialRow.getShort("int16"));
assertEquals(44, partialRow.getInt("int32"));
assertEquals(45, partialRow.getLong("int64"));
assertEquals(new Timestamp(1234567890), partialRow.getTimestamp("timestamp"));
assertEquals(52.35F, partialRow.getFloat("float"), 0.0f);
assertEquals(53.35, partialRow.getDouble("double"), 0.0);
assertEquals("fun with ütf\0", partialRow.getString("string"));
assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, partialRow.getBinaryCopy("binary-array"));
assertArrayEquals(new byte[] { 5, 6, 7, 8, 9 }, partialRow.getBinaryCopy("binary-bytebuffer"));
assertEquals(ByteBuffer.wrap(new byte[] { 0, 1, 2, 3, 4 }), partialRow.getBinary("binary-array"));
assertEquals(ByteBuffer.wrap(new byte[] { 5, 6, 7, 8, 9 }), partialRow.getBinary("binary-bytebuffer"));
assertTrue(partialRow.isSet("null"));
assertTrue(partialRow.isNull("null"));
assertEquals(BigDecimal.valueOf(12345, 3), partialRow.getDecimal("decimal"));
}
@Test
public void testGetObject() {
PartialRow partialRow = getPartialRowWithAllTypes();
assertTrue(partialRow.getObject("bool") instanceof Boolean);
assertEquals(true, partialRow.getObject("bool"));
assertTrue(partialRow.getObject("int8") instanceof Byte);
assertEquals((byte) 42, partialRow.getObject("int8"));
assertTrue(partialRow.getObject("int16") instanceof Short);
assertEquals((short)43, partialRow.getObject("int16"));
assertTrue(partialRow.getObject("int32") instanceof Integer);
assertEquals(44, partialRow.getObject("int32"));
assertTrue(partialRow.getObject("int64") instanceof Long);
assertEquals((long) 45, partialRow.getObject("int64"));
assertTrue(partialRow.getObject("timestamp") instanceof Timestamp);
assertEquals(new Timestamp(1234567890), partialRow.getObject("timestamp"));
assertTrue(partialRow.getObject("float") instanceof Float);
assertEquals(52.35F, (float) partialRow.getObject("float"), 0.0f);
assertTrue(partialRow.getObject("double") instanceof Double);
assertEquals(53.35, (double) partialRow.getObject("double"), 0.0);
assertTrue(partialRow.getObject("string") instanceof String);
assertEquals("fun with ütf\0", partialRow.getObject("string"));
assertTrue(partialRow.getObject("binary-array") instanceof byte[]);
assertArrayEquals(new byte[] { 0, 1, 2, 3, 4 }, partialRow.getBinaryCopy("binary-array"));
assertTrue(partialRow.getObject("binary-bytebuffer") instanceof byte[]);
assertEquals(ByteBuffer.wrap(new byte[] { 5, 6, 7, 8, 9 }), partialRow.getBinary("binary-bytebuffer"));
assertNull(partialRow.getObject("null"));
assertTrue(partialRow.getObject("decimal") instanceof BigDecimal);
assertEquals(BigDecimal.valueOf(12345, 3), partialRow.getObject("decimal"));
}
@Test(expected = IllegalArgumentException.class)
public void testGetNullColumn() {
PartialRow partialRow = getPartialRowWithAllTypes();
assertTrue(partialRow.isSet("null"));
assertTrue(partialRow.isNull("null"));
partialRow.getString("null");
}
@Test(expected = IllegalArgumentException.class)
public void testSetNonNullableColumn() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.setNull("int32");
}
@Test
public void testGetUnsetColumn() {
Schema schema = getSchemaWithAllTypes();
PartialRow partialRow = schema.newPartialRow();
for (ColumnSchema columnSchema : schema.getColumns()) {
assertFalse(partialRow.isSet("null"));
assertFalse(partialRow.isNull("null"));
try {
callGetByName(partialRow, columnSchema.getName(), columnSchema.getType());
fail("Expected IllegalArgumentException for type: " + columnSchema.getType());
} catch (IllegalArgumentException ex) {
// This is the expected exception.
}
}
}
@Test
public void testGetMissingColumnName() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callGetByName(partialRow, "not-a-column", columnSchema.getType());
fail("Expected IllegalArgumentException for type: " + columnSchema.getType());
} catch (IllegalArgumentException ex) {
// This is the expected exception.
}
}
}
@Test
public void testGetMissingColumnIndex() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callGetByIndex(partialRow, 999, columnSchema.getType());
fail("Expected IndexOutOfBoundsException for type: " + columnSchema.getType());
} catch (IndexOutOfBoundsException ex) {
// This is the expected exception.
}
}
}
@Test
public void testGetWrongTypeColumn() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callGetByName(partialRow, columnSchema.getName(), getShiftedType(columnSchema.getType()));
fail("Expected IllegalArgumentException for type: " + columnSchema.getType());
} catch (IllegalArgumentException ex) {
// This is the expected exception.
}
}
}
@Test
public void testAddMissingColumnName() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callAddByName(partialRow, "not-a-column", columnSchema.getType());
fail("Expected IllegalArgumentException for type: " + columnSchema.getType());
} catch (IllegalArgumentException ex) {
// This is the expected exception.
}
}
}
@Test
public void testAddMissingColumnIndex() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callAddByIndex(partialRow, 999, columnSchema.getType());
fail("Expected IndexOutOfBoundsException for type: " + columnSchema.getType());
} catch (IndexOutOfBoundsException ex) {
// This is the expected exception.
}
}
}
@Test
public void testAddWrongTypeColumn() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callAddByName(partialRow, columnSchema.getName(), getShiftedType(columnSchema.getType()));
fail("Expected IllegalArgumentException for type: " + columnSchema.getType());
} catch (IllegalArgumentException ex) {
// This is the expected exception.
}
}
}
@Test
public void testAddToFrozenRow() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.freeze();
for (ColumnSchema columnSchema : partialRow.getSchema().getColumns()) {
try {
callAddByName(partialRow, columnSchema.getName(), columnSchema.getType());
fail("Expected IllegalStateException for type: " + columnSchema.getType());
} catch (IllegalStateException ex) {
// This is the expected exception.
}
}
}
@Test(expected = IllegalArgumentException.class)
public void testIsNullMissingColumnName() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.isNull("not-a-column");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testIsNullMissingColumnIndex() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.isNull(999);
}
@Test(expected = IllegalArgumentException.class)
public void testIsSetMissingColumnName() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.isSet("not-a-column");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testIsSetMissingColumnIndex() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.isSet(999);
}
@Test(expected = IllegalArgumentException.class)
public void testAddInvalidPrecisionDecimal() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.addDecimal("decimal", BigDecimal.valueOf(123456, 3));
}
@Test(expected = IllegalArgumentException.class)
public void testAddInvalidScaleDecimal() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.addDecimal("decimal", BigDecimal.valueOf(12345, 4));
}
@Test(expected = IllegalArgumentException.class)
public void testAddInvalidCoercedScaleDecimal() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.addDecimal("decimal", BigDecimal.valueOf(12345, 2));
}
@Test
public void testAddCoercedScaleAndPrecisionDecimal() {
PartialRow partialRow = getPartialRowWithAllTypes();
partialRow.addDecimal("decimal", BigDecimal.valueOf(222, 1));
BigDecimal decimal = partialRow.getDecimal("decimal");
assertEquals("22.200", decimal.toString());
}
@Test
public void testToString() {
Schema schema = getSchemaWithAllTypes();
PartialRow row = schema.newPartialRow();
assertEquals("()", row.toString());
row.addInt("int32", 42);
row.addByte("int8", (byte) 42);
assertEquals("(int8 int8=42, int32 int32=42)", row.toString());
row.addString("string", "fun with ütf\0");
assertEquals("(int8 int8=42, int32 int32=42, string string=\"fun with ütf\\0\")",
row.toString());
ByteBuffer binary = ByteBuffer.wrap(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
binary.position(2);
binary.limit(5);
row.addBinary("binary-bytebuffer", binary);
assertEquals("(int8 int8=42, int32 int32=42, string string=\"fun with ütf\\0\", " +
"binary binary-bytebuffer=[2, 3, 4])",
row.toString());
row.addDouble("double", 52.35);
assertEquals("(int8 int8=42, int32 int32=42, double double=52.35, " +
"string string=\"fun with ütf\\0\", binary binary-bytebuffer=[2, 3, 4])",
row.toString());
row.addDecimal("decimal", BigDecimal.valueOf(12345, 3));
assertEquals("(int8 int8=42, int32 int32=42, double double=52.35, " +
"string string=\"fun with ütf\\0\", binary binary-bytebuffer=[2, 3, 4], " +
"decimal(5, 3) decimal=12.345)",
row.toString());
}
@Test
public void testIncrementColumn() {
PartialRow partialRow = getPartialRowWithAllTypes();
// Boolean
int boolIndex = getColumnIndex(partialRow, "bool");
partialRow.addBoolean(boolIndex, false);
assertTrue(partialRow.incrementColumn(boolIndex));
assertEquals(true, partialRow.getBoolean(boolIndex));
assertFalse(partialRow.incrementColumn(boolIndex));
// Int8
int int8Index = getColumnIndex(partialRow, "int8");
partialRow.addByte(int8Index, (byte)(Byte.MAX_VALUE - 1));
assertTrue(partialRow.incrementColumn(int8Index));
assertEquals(Byte.MAX_VALUE, partialRow.getByte(int8Index));
assertFalse(partialRow.incrementColumn(int8Index));
// Int16
int int16Index = getColumnIndex(partialRow, "int16");
partialRow.addShort(int16Index, (short)(Short.MAX_VALUE - 1));
assertTrue(partialRow.incrementColumn(int16Index));
assertEquals(Short.MAX_VALUE, partialRow.getShort(int16Index));
assertFalse(partialRow.incrementColumn(int16Index));
// Int32
int int32Index = getColumnIndex(partialRow, "int32");
partialRow.addInt(int32Index, Integer.MAX_VALUE - 1);
assertTrue(partialRow.incrementColumn(int32Index));
assertEquals(Integer.MAX_VALUE, partialRow.getInt(int32Index));
assertFalse(partialRow.incrementColumn(int32Index));
// Int64
int int64Index = getColumnIndex(partialRow, "int64");
partialRow.addLong(int64Index, Long.MAX_VALUE - 1);
assertTrue(partialRow.incrementColumn(int64Index));
assertEquals(Long.MAX_VALUE, partialRow.getLong(int64Index));
assertFalse(partialRow.incrementColumn(int64Index));
// Float
int floatIndex = getColumnIndex(partialRow, "float");
partialRow.addFloat(floatIndex, Float.MAX_VALUE);
assertTrue(partialRow.incrementColumn(floatIndex));
assertEquals(Float.POSITIVE_INFINITY, partialRow.getFloat(floatIndex), 0.0f);
assertFalse(partialRow.incrementColumn(floatIndex));
// Float
int doubleIndex = getColumnIndex(partialRow, "double");
partialRow.addDouble(doubleIndex, Double.MAX_VALUE);
assertTrue(partialRow.incrementColumn(doubleIndex));
assertEquals(Double.POSITIVE_INFINITY, partialRow.getDouble(doubleIndex), 0.0);
assertFalse(partialRow.incrementColumn(doubleIndex));
// Decimal
int decimalIndex = getColumnIndex(partialRow, "decimal");
// Decimal with precision 5, scale 3 has a max of 99.999
partialRow.addDecimal(decimalIndex, new BigDecimal("99.998"));
assertTrue(partialRow.incrementColumn(decimalIndex));
assertEquals(new BigDecimal("99.999"), partialRow.getDecimal(decimalIndex));
assertFalse(partialRow.incrementColumn(decimalIndex));
// String
int stringIndex = getColumnIndex(partialRow, "string");
partialRow.addString(stringIndex, "hello");
assertTrue(partialRow.incrementColumn(stringIndex));
assertEquals("hello\0", partialRow.getString(stringIndex));
// Binary
int binaryIndex = getColumnIndex(partialRow, "binary-array");
partialRow.addBinary(binaryIndex, new byte[] { 0, 1, 2, 3, 4 });
assertTrue(partialRow.incrementColumn(binaryIndex));
assertArrayEquals(new byte[] { 0, 1, 2, 3, 4, 0 }, partialRow.getBinaryCopy(binaryIndex));
}
@Test
public void testSetMin() {
PartialRow partialRow = getPartialRowWithAllTypes();
for (int i = 0; i < partialRow.getSchema().getColumnCount(); i++) {
partialRow.setMin(i);
}
assertEquals(false, partialRow.getBoolean("bool"));
assertEquals(Byte.MIN_VALUE, partialRow.getByte("int8"));
assertEquals(Short.MIN_VALUE, partialRow.getShort("int16"));
assertEquals(Integer.MIN_VALUE, partialRow.getInt("int32"));
assertEquals(Long.MIN_VALUE, partialRow.getLong("int64"));
assertEquals(Long.MIN_VALUE, partialRow.getLong("timestamp"));
assertEquals(-Float.MAX_VALUE, partialRow.getFloat("float"), 0.0f);
assertEquals(-Double.MAX_VALUE, partialRow.getDouble("double"), 0.0);
assertEquals("", partialRow.getString("string"));
assertArrayEquals(new byte[0], partialRow.getBinaryCopy("binary-array"));
assertArrayEquals(new byte[0], partialRow.getBinaryCopy("binary-bytebuffer"));
assertEquals(BigDecimal.valueOf(-99999, 3), partialRow.getDecimal("decimal"));
}
private int getColumnIndex(PartialRow partialRow, String columnName) {
return partialRow.getSchema().getColumnIndex(columnName);
}
private PartialRow getPartialRowWithAllTypes() {
Schema schema = getSchemaWithAllTypes();
// Ensure we aren't missing any types
assertEquals(13, schema.getColumnCount());
PartialRow row = schema.newPartialRow();
row.addByte("int8", (byte) 42);
row.addShort("int16", (short) 43);
row.addInt("int32", 44);
row.addLong("int64", 45);
row.addTimestamp("timestamp", new Timestamp(1234567890));
row.addBoolean("bool", true);
row.addFloat("float", 52.35F);
row.addDouble("double", 53.35);
row.addString("string", "fun with ütf\0");
row.addBinary("binary-array", new byte[] { 0, 1, 2, 3, 4 });
ByteBuffer binaryBuffer = ByteBuffer.wrap(new byte[] { 5, 6, 7, 8, 9 });
row.addBinary("binary-bytebuffer", binaryBuffer);
row.setNull("null");
row.addDecimal("decimal", BigDecimal.valueOf(12345, 3));
return row;
}
// Shift the type one position to force the wrong type for all types.
private Type getShiftedType(Type type) {
int shiftedPosition = (type.ordinal() + 1) % Type.values().length;
return Type.values()[shiftedPosition];
}
private Object callGetByName(PartialRow partialRow, String columnName, Type type) {
switch (type) {
case INT8: return partialRow.getByte(columnName);
case INT16: return partialRow.getShort(columnName);
case INT32: return partialRow.getInt(columnName);
case INT64: return partialRow.getLong(columnName);
case UNIXTIME_MICROS: return partialRow.getTimestamp(columnName);
case STRING: return partialRow.getString(columnName);
case BINARY: return partialRow.getBinary(columnName);
case FLOAT: return partialRow.getFloat(columnName);
case DOUBLE: return partialRow.getDouble(columnName);
case BOOL: return partialRow.getBoolean(columnName);
case DECIMAL: return partialRow.getDecimal(columnName);
default:
throw new UnsupportedOperationException();
}
}
private Object callGetByIndex(PartialRow partialRow, int columnIndex, Type type) {
switch (type) {
case INT8: return partialRow.getByte(columnIndex);
case INT16: return partialRow.getShort(columnIndex);
case INT32: return partialRow.getInt(columnIndex);
case INT64: return partialRow.getLong(columnIndex);
case UNIXTIME_MICROS: return partialRow.getTimestamp(columnIndex);
case STRING: return partialRow.getString(columnIndex);
case BINARY: return partialRow.getBinary(columnIndex);
case FLOAT: return partialRow.getFloat(columnIndex);
case DOUBLE: return partialRow.getDouble(columnIndex);
case BOOL: return partialRow.getBoolean(columnIndex);
case DECIMAL: return partialRow.getDecimal(columnIndex);
default:
throw new UnsupportedOperationException();
}
}
private void callAddByName(PartialRow partialRow, String columnName, Type type) {
switch (type) {
case INT8: partialRow.addByte(columnName, (byte) 42); break;
case INT16: partialRow.addShort(columnName, (short) 43); break;
case INT32: partialRow.addInt(columnName, 44); break;
case INT64: partialRow.addLong(columnName, 45); break;
case UNIXTIME_MICROS: partialRow.addTimestamp(columnName, new Timestamp(1234567890)); break;
case STRING: partialRow.addString(columnName, "fun with ütf\0"); break;
case BINARY: partialRow.addBinary(columnName, new byte[] { 0, 1, 2, 3, 4 }); break;
case FLOAT: partialRow.addFloat(columnName, 52.35F); break;
case DOUBLE: partialRow.addDouble(columnName, 53.35); break;
case BOOL: partialRow.addBoolean(columnName, true); break;
case DECIMAL: partialRow.addDecimal(columnName, BigDecimal.valueOf(12345, 3)); break;
default:
throw new UnsupportedOperationException();
}
}
private void callAddByIndex(PartialRow partialRow, int columnIndex, Type type) {
switch (type) {
case INT8: partialRow.addByte(columnIndex, (byte) 42); break;
case INT16: partialRow.addShort(columnIndex, (short) 43); break;
case INT32: partialRow.addInt(columnIndex, 44); break;
case INT64: partialRow.addLong(columnIndex, 45); break;
case UNIXTIME_MICROS: partialRow.addTimestamp(columnIndex, new Timestamp(1234567890)); break;
case STRING: partialRow.addString(columnIndex, "fun with ütf\0"); break;
case BINARY: partialRow.addBinary(columnIndex, new byte[] { 0, 1, 2, 3, 4 }); break;
case FLOAT: partialRow.addFloat(columnIndex, 52.35F); break;
case DOUBLE: partialRow.addDouble(columnIndex, 53.35); break;
case BOOL: partialRow.addBoolean(columnIndex, true); break;
case DECIMAL: partialRow.addDecimal(columnIndex, BigDecimal.valueOf(12345, 3)); break;
default:
throw new UnsupportedOperationException();
}
}
}
| apache-2.0 |
ibuildthecloud/dstack | code/framework/object/src/main/java/io/github/ibuildthecloud/dstack/object/postinit/ObjectDefaultsPostInstantiationHandler.java | 2194 | package io.github.ibuildthecloud.dstack.object.postinit;
import io.github.ibuildthecloud.dstack.object.ObjectDefaultsProvider;
import io.github.ibuildthecloud.dstack.util.type.InitializationTask;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObjectDefaultsPostInstantiationHandler implements ObjectPostInstantiationHandler, InitializationTask {
private static final Logger log = LoggerFactory.getLogger(ObjectDefaultsPostInstantiationHandler.class);
List<ObjectDefaultsProvider> defaultProviders;
Map<Class<?>,Map<String,Object>> defaults = new HashMap<Class<?>, Map<String,Object>>();
@Override
public <T> T postProcess(T obj, Class<T> clz, Map<String,Object> properties) {
try {
applyDefaults(clz, obj);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to apply defaults to [" + obj + "]", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Failed to apply defaults to [" + obj + "]", e);
}
return obj;
}
protected void applyDefaults(Class<?> clz, Object instance) throws IllegalAccessException, InvocationTargetException {
Map<String,Object> defaultValues = defaults.get(instance.getClass());
if ( defaultValues == null ) {
return;
}
log.debug("Applying defaults [{}] to [{}]", defaultValues, instance);
BeanUtils.copyProperties(instance, defaultValues);
}
@Override
public void start() {
for ( ObjectDefaultsProvider provider : defaultProviders ) {
defaults.putAll(provider.getDefaults());
}
}
@Override
public void stop() {
}
public List<ObjectDefaultsProvider> getDefaultProviders() {
return defaultProviders;
}
@Inject
public void setDefaultProviders(List<ObjectDefaultsProvider> defaultProviders) {
this.defaultProviders = defaultProviders;
}
}
| apache-2.0 |
leonardvandriel/Reversible | src/com/leovandriel/reversible/proxy/DebugProxyCollection.java | 2866 | package com.leovandriel.reversible.proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.leovandriel.reversible.action.Action;
import com.leovandriel.reversible.action.AdvancedRunner;
public class DebugProxyCollection<T> implements Collection<T> {
private Collection<T> target;
private AdvancedRunner runner;
public DebugProxyCollection(Collection<T> target, AdvancedRunner runner) {
this.target = target;
this.runner = runner;
}
public boolean add(T e) {
throw new UnsupportedOperationException("Unable to undo this operation, collection implementation unknown.");
}
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException("Unable to undo this operation, collection implementation unknown.");
}
public class Clear implements Action<Void> {
private List<T> backup;
public Void run() {
backup = new ArrayList<T>(target);
target.clear();
return null;
}
public void unrun() {
if (!target.isEmpty()) {
throw new IllegalStateException("Target modified, should be empty");
}
target.addAll(backup);
}
@Override
public String toString() {
return this.getClass().getSimpleName() + '(' + ')';
}
}
public void clear() {
runner.run(new Clear());
}
public boolean contains(Object o) {
return target.contains(o);
}
public boolean containsAll(Collection<?> c) {
return target.containsAll(c);
}
public boolean isEmpty() {
return target.isEmpty();
}
public class IteratorImpl implements Iterator<T> {
private Iterator<T> iterator = target.iterator();
public boolean hasNext() {
return iterator.hasNext();
}
public T next() {
return iterator.next();
}
public void remove() {
if (!runner.isRunningAction()) {
throw new IllegalStateException("Modification should only happen within action runs");
}
iterator.remove();
}
}
public Iterator<T> iterator() {
return new IteratorImpl();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException("Unable to undo this operation, collection implementation unknown.");
}
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("Unable to undo this operation, collection implementation unknown.");
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("Unable to undo this operation, collection implementation unknown.");
}
public int size() {
return target.size();
}
public Object[] toArray() {
return target.toArray();
}
public <U> U[] toArray(U[] a) {
return target.toArray(a);
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public boolean equals(Object o) {
return target.equals(o);
}
@Override
public String toString() {
return target.toString();
}
}
| apache-2.0 |
benmfaul/XRTB | src/com/xrtb/jmq/Pull.java | 679 | package com.xrtb.jmq;
import javax.servlet.http.HttpServletResponse;
import org.zeromq.ZMQ;
public class Pull {
public Pull(HttpServletResponse response, String port, String timeout, String limit) throws Exception {
int lim = 1;
if (limit != null) {
lim = Integer.parseInt(limit);
}
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket rcv = context.socket(ZMQ.PULL);
rcv.bind("tcp://*:" + port);
if (timeout != null) {
int t = Integer.parseInt(timeout);
rcv.setReceiveTimeOut(t);
}
int k = 0;
while(k < lim || lim == 0) {
String str = rcv.recvStr();
response.getWriter().println(str);
k++;
}
rcv.close();
context.term();
}
} | apache-2.0 |
haikuowuya/android_system_code | src/javax/xml/soap/SOAPElement.java | 21983 | /*
* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.xml.soap;
import java.util.Iterator;
import javax.xml.namespace.QName;
/**
* An object representing an element of a SOAP message that is allowed but not
* specifically prescribed by a SOAP specification. This interface serves as the
* base interface for those objects that are specifically prescribed by a SOAP
* specification.
* <p>
* Methods in this interface that are required to return SAAJ specific objects
* may "silently" replace nodes in the tree as required to successfully return
* objects of the correct type. See {@link #getChildElements()} and
* {@link <a HREF="package-summary.html#package_description">javax.xml.soap<a>}
* for details.
*/
public interface SOAPElement extends Node, org.w3c.dom.Element {
/**
* Creates a new <code>SOAPElement</code> object initialized with the
* given <code>Name</code> object and adds the new element to this
* <code>SOAPElement</code> object.
* <P>
* This method may be deprecated in a future release of SAAJ in favor of
* addChildElement(javax.xml.namespace.QName)
*
* @param name a <code>Name</code> object with the XML name for the
* new element
*
* @return the new <code>SOAPElement</code> object that was created
* @exception SOAPException if there is an error in creating the
* <code>SOAPElement</code> object
* @see SOAPElement#addChildElement(javax.xml.namespace.QName)
*/
public SOAPElement addChildElement(Name name) throws SOAPException;
/**
* Creates a new <code>SOAPElement</code> object initialized with the given
* <code>QName</code> object and adds the new element to this <code>SOAPElement</code>
* object. The <i>namespace</i>, <i>localname</i> and <i>prefix</i> of the new
* <code>SOAPElement</code> are all taken from the <code>qname</code> argument.
*
* @param qname a <code>QName</code> object with the XML name for the
* new element
*
* @return the new <code>SOAPElement</code> object that was created
* @exception SOAPException if there is an error in creating the
* <code>SOAPElement</code> object
* @see SOAPElement#addChildElement(Name)
* @since SAAJ 1.3
*/
public SOAPElement addChildElement(QName qname) throws SOAPException;
/**
* Creates a new <code>SOAPElement</code> object initialized with the
* specified local name and adds the new element to this
* <code>SOAPElement</code> object.
* The new <code>SOAPElement</code> inherits any in-scope default namespace.
*
* @param localName a <code>String</code> giving the local name for
* the element
* @return the new <code>SOAPElement</code> object that was created
* @exception SOAPException if there is an error in creating the
* <code>SOAPElement</code> object
*/
public SOAPElement addChildElement(String localName) throws SOAPException;
/**
* Creates a new <code>SOAPElement</code> object initialized with the
* specified local name and prefix and adds the new element to this
* <code>SOAPElement</code> object.
*
* @param localName a <code>String</code> giving the local name for
* the new element
* @param prefix a <code>String</code> giving the namespace prefix for
* the new element
*
* @return the new <code>SOAPElement</code> object that was created
* @exception SOAPException if the <code>prefix</code> is not valid in the
* context of this <code>SOAPElement</code> or if there is an error in creating the
* <code>SOAPElement</code> object
*/
public SOAPElement addChildElement(String localName, String prefix)
throws SOAPException;
/**
* Creates a new <code>SOAPElement</code> object initialized with the
* specified local name, prefix, and URI and adds the new element to this
* <code>SOAPElement</code> object.
*
* @param localName a <code>String</code> giving the local name for
* the new element
* @param prefix a <code>String</code> giving the namespace prefix for
* the new element
* @param uri a <code>String</code> giving the URI of the namespace
* to which the new element belongs
*
* @return the new <code>SOAPElement</code> object that was created
* @exception SOAPException if there is an error in creating the
* <code>SOAPElement</code> object
*/
public SOAPElement addChildElement(String localName, String prefix,
String uri)
throws SOAPException;
/**
* Add a <code>SOAPElement</code> as a child of this
* <code>SOAPElement</code> instance. The <code>SOAPElement</code>
* is expected to be created by a
* <code>SOAPFactory</code>. Callers should not rely on the
* element instance being added as is into the XML
* tree. Implementations could end up copying the content
* of the <code>SOAPElement</code> passed into an instance of
* a different <code>SOAPElement</code> implementation. For
* instance if <code>addChildElement()</code> is called on a
* <code>SOAPHeader</code>, <code>element</code> will be copied
* into an instance of a <code>SOAPHeaderElement</code>.
*
* <P>The fragment rooted in <code>element</code> is either added
* as a whole or not at all, if there was an error.
*
* <P>The fragment rooted in <code>element</code> cannot contain
* elements named "Envelope", "Header" or "Body" and in the SOAP
* namespace. Any namespace prefixes present in the fragment
* should be fully resolved using appropriate namespace
* declarations within the fragment itself.
*
* @param element the <code>SOAPElement</code> to be added as a
* new child
*
* @exception SOAPException if there was an error in adding this
* element as a child
*
* @return an instance representing the new SOAP element that was
* actually added to the tree.
*/
public SOAPElement addChildElement(SOAPElement element)
throws SOAPException;
/**
* Detaches all children of this <code>SOAPElement</code>.
* <p>
* This method is useful for rolling back the construction of partially
* completed <code>SOAPHeaders</code> and <code>SOAPBodys</code> in
* preparation for sending a fault when an error condition is detected. It
* is also useful for recycling portions of a document within a SOAP
* message.
*
* @since SAAJ 1.2
*/
public abstract void removeContents();
/**
* Creates a new <code>Text</code> object initialized with the given
* <code>String</code> and adds it to this <code>SOAPElement</code> object.
*
* @param text a <code>String</code> object with the textual content to be added
*
* @return the <code>SOAPElement</code> object into which
* the new <code>Text</code> object was inserted
* @exception SOAPException if there is an error in creating the
* new <code>Text</code> object or if it is not legal to
* attach it as a child to this
* <code>SOAPElement</code>
*/
public SOAPElement addTextNode(String text) throws SOAPException;
/**
* Adds an attribute with the specified name and value to this
* <code>SOAPElement</code> object.
*
* @param name a <code>Name</code> object with the name of the attribute
* @param value a <code>String</code> giving the value of the attribute
* @return the <code>SOAPElement</code> object into which the attribute was
* inserted
*
* @exception SOAPException if there is an error in creating the
* Attribute, or it is invalid to set
an attribute with <code>Name</code>
<code>name</code> on this SOAPElement.
* @see SOAPElement#addAttribute(javax.xml.namespace.QName, String)
*/
public SOAPElement addAttribute(Name name, String value)
throws SOAPException;
/**
* Adds an attribute with the specified name and value to this
* <code>SOAPElement</code> object.
*
* @param qname a <code>QName</code> object with the name of the attribute
* @param value a <code>String</code> giving the value of the attribute
* @return the <code>SOAPElement</code> object into which the attribute was
* inserted
*
* @exception SOAPException if there is an error in creating the
* Attribute, or it is invalid to set
an attribute with <code>QName</code>
<code>qname</code> on this SOAPElement.
* @see SOAPElement#addAttribute(Name, String)
* @since SAAJ 1.3
*/
public SOAPElement addAttribute(QName qname, String value)
throws SOAPException;
/**
* Adds a namespace declaration with the specified prefix and URI to this
* <code>SOAPElement</code> object.
*
* @param prefix a <code>String</code> giving the prefix of the namespace
* @param uri a <code>String</code> giving the uri of the namespace
* @return the <code>SOAPElement</code> object into which this
* namespace declaration was inserted.
*
* @exception SOAPException if there is an error in creating the
* namespace
*/
public SOAPElement addNamespaceDeclaration(String prefix, String uri)
throws SOAPException;
/**
* Returns the value of the attribute with the specified name.
*
* @param name a <code>Name</code> object with the name of the attribute
* @return a <code>String</code> giving the value of the specified
* attribute, Null if there is no such attribute
* @see SOAPElement#getAttributeValue(javax.xml.namespace.QName)
*/
public String getAttributeValue(Name name);
/**
* Returns the value of the attribute with the specified qname.
*
* @param qname a <code>QName</code> object with the qname of the attribute
* @return a <code>String</code> giving the value of the specified
* attribute, Null if there is no such attribute
* @see SOAPElement#getAttributeValue(Name)
* @since SAAJ 1.3
*/
public String getAttributeValue(QName qname);
/**
* Returns an <code>Iterator</code> over all of the attribute
* <code>Name</code> objects in this
* <code>SOAPElement</code> object. The iterator can be used to get
* the attribute names, which can then be passed to the method
* <code>getAttributeValue</code> to retrieve the value of each
* attribute.
*
* @see SOAPElement#getAllAttributesAsQNames()
* @return an iterator over the names of the attributes
*/
public Iterator getAllAttributes();
/**
* Returns an <code>Iterator</code> over all of the attributes
* in this <code>SOAPElement</code> as <code>QName</code> objects.
* The iterator can be used to get the attribute QName, which can then
* be passed to the method <code>getAttributeValue</code> to retrieve
* the value of each attribute.
*
* @return an iterator over the QNames of the attributes
* @see SOAPElement#getAllAttributes()
* @since SAAJ 1.3
*/
public Iterator getAllAttributesAsQNames();
/**
* Returns the URI of the namespace that has the given prefix.
*
* @param prefix a <code>String</code> giving the prefix of the namespace
* for which to search
* @return a <code>String</code> with the uri of the namespace that has
* the given prefix
*/
public String getNamespaceURI(String prefix);
/**
* Returns an <code>Iterator</code> over the namespace prefix
* <code>String</code>s declared by this element. The prefixes returned by
* this iterator can be passed to the method
* <code>getNamespaceURI</code> to retrieve the URI of each namespace.
*
* @return an iterator over the namespace prefixes in this
* <code>SOAPElement</code> object
*/
public Iterator getNamespacePrefixes();
/**
* Returns an <code>Iterator</code> over the namespace prefix
* <code>String</code>s visible to this element. The prefixes returned by
* this iterator can be passed to the method
* <code>getNamespaceURI</code> to retrieve the URI of each namespace.
*
* @return an iterator over the namespace prefixes are within scope of this
* <code>SOAPElement</code> object
*
* @since SAAJ 1.2
*/
public Iterator getVisibleNamespacePrefixes();
/**
* Creates a <code>QName</code> whose namespace URI is the one associated
* with the parameter, <code>prefix</code>, in the context of this
* <code>SOAPElement</code>. The remaining elements of the new
* <code>QName</code> are taken directly from the parameters,
* <code>localName</code> and <code>prefix</code>.
*
* @param localName
* a <code>String</code> containing the local part of the name.
* @param prefix
* a <code>String</code> containing the prefix for the name.
*
* @return a <code>QName</code> with the specified <code>localName</code>
* and <code>prefix</code>, and with a namespace that is associated
* with the <code>prefix</code> in the context of this
* <code>SOAPElement</code>. This namespace will be the same as
* the one that would be returned by
* <code>{@link #getNamespaceURI(String)}</code> if it were given
* <code>prefix</code> as it's parameter.
*
* @exception SOAPException if the <code>QName</code> cannot be created.
*
* @since SAAJ 1.3
*/
public QName createQName(String localName, String prefix)
throws SOAPException;
/**
* Returns the name of this <code>SOAPElement</code> object.
*
* @return a <code>Name</code> object with the name of this
* <code>SOAPElement</code> object
*/
public Name getElementName();
/**
* Returns the qname of this <code>SOAPElement</code> object.
*
* @return a <code>QName</code> object with the qname of this
* <code>SOAPElement</code> object
* @see SOAPElement#getElementName()
* @since SAAJ 1.3
*/
public QName getElementQName();
/**
* Changes the name of this <code>Element</code> to <code>newName</code> if
* possible. SOAP Defined elements such as SOAPEnvelope, SOAPHeader, SOAPBody
* etc. cannot have their names changed using this method. Any attempt to do
* so will result in a SOAPException being thrown.
*<P>
* Callers should not rely on the element instance being renamed as is.
* Implementations could end up copying the content of the
* <code>SOAPElement</code> to a renamed instance.
*
* @param newName the new name for the <code>Element</code>.
*
* @exception SOAPException if changing the name of this <code>Element</code>
* is not allowed.
* @return The renamed Node
*
* @since SAAJ 1.3
*/
public SOAPElement setElementQName(QName newName) throws SOAPException;
/**
* Removes the attribute with the specified name.
*
* @param name the <code>Name</code> object with the name of the
* attribute to be removed
* @return <code>true</code> if the attribute was
* removed successfully; <code>false</code> if it was not
* @see SOAPElement#removeAttribute(javax.xml.namespace.QName)
*/
public boolean removeAttribute(Name name);
/**
* Removes the attribute with the specified qname.
*
* @param qname the <code>QName</code> object with the qname of the
* attribute to be removed
* @return <code>true</code> if the attribute was
* removed successfully; <code>false</code> if it was not
* @see SOAPElement#removeAttribute(Name)
* @since SAAJ 1.3
*/
public boolean removeAttribute(QName qname);
/**
* Removes the namespace declaration corresponding to the given prefix.
*
* @param prefix a <code>String</code> giving the prefix for which
* to search
* @return <code>true</code> if the namespace declaration was
* removed successfully; <code>false</code> if it was not
*/
public boolean removeNamespaceDeclaration(String prefix);
/**
* Returns an <code>Iterator</code> over all the immediate child
* {@link Node}s of this element. This includes <code>javax.xml.soap.Text</code>
* objects as well as <code>SOAPElement</code> objects.
* <p>
* Calling this method may cause child <code>Element</code>,
* <code>SOAPElement</code> and <code>org.w3c.dom.Text</code> nodes to be
* replaced by <code>SOAPElement</code>, <code>SOAPHeaderElement</code>,
* <code>SOAPBodyElement</code> or <code>javax.xml.soap.Text</code> nodes as
* appropriate for the type of this parent node. As a result the calling
* application must treat any existing references to these child nodes that
* have been obtained through DOM APIs as invalid and either discard them or
* refresh them with the values returned by this <code>Iterator</code>. This
* behavior can be avoided by calling the equivalent DOM APIs. See
* {@link <a HREF="package-summary.html#package_description">javax.xml.soap<a>}
* for more details.
*
* @return an iterator with the content of this <code>SOAPElement</code>
* object
*/
public Iterator getChildElements();
/**
* Returns an <code>Iterator</code> over all the immediate child
* {@link Node}s of this element with the specified name. All of these
* children will be <code>SOAPElement</code> nodes.
* <p>
* Calling this method may cause child <code>Element</code>,
* <code>SOAPElement</code> and <code>org.w3c.dom.Text</code> nodes to be
* replaced by <code>SOAPElement</code>, <code>SOAPHeaderElement</code>,
* <code>SOAPBodyElement</code> or <code>javax.xml.soap.Text</code> nodes as
* appropriate for the type of this parent node. As a result the calling
* application must treat any existing references to these child nodes that
* have been obtained through DOM APIs as invalid and either discard them or
* refresh them with the values returned by this <code>Iterator</code>. This
* behavior can be avoided by calling the equivalent DOM APIs. See
* {@link <a HREF="package-summary.html#package_description">javax.xml.soap<a>}
* for more details.
*
* @param name a <code>Name</code> object with the name of the child
* elements to be returned
*
* @return an <code>Iterator</code> object over all the elements
* in this <code>SOAPElement</code> object with the
* specified name
* @see SOAPElement#getChildElements(javax.xml.namespace.QName)
*/
public Iterator getChildElements(Name name);
/**
* Returns an <code>Iterator</code> over all the immediate child
* {@link Node}s of this element with the specified qname. All of these
* children will be <code>SOAPElement</code> nodes.
* <p>
* Calling this method may cause child <code>Element</code>,
* <code>SOAPElement</code> and <code>org.w3c.dom.Text</code> nodes to be
* replaced by <code>SOAPElement</code>, <code>SOAPHeaderElement</code>,
* <code>SOAPBodyElement</code> or <code>javax.xml.soap.Text</code> nodes as
* appropriate for the type of this parent node. As a result the calling
* application must treat any existing references to these child nodes that
* have been obtained through DOM APIs as invalid and either discard them or
* refresh them with the values returned by this <code>Iterator</code>. This
* behavior can be avoided by calling the equivalent DOM APIs. See
* {@link <a HREF="package-summary.html#package_description">javax.xml.soap<a>}
* for more details.
*
* @param qname a <code>QName</code> object with the qname of the child
* elements to be returned
*
* @return an <code>Iterator</code> object over all the elements
* in this <code>SOAPElement</code> object with the
* specified qname
* @see SOAPElement#getChildElements(Name)
* @since SAAJ 1.3
*/
public Iterator getChildElements(QName qname);
/**
* Sets the encoding style for this <code>SOAPElement</code> object
* to one specified.
*
* @param encodingStyle a <code>String</code> giving the encoding style
*
* @exception IllegalArgumentException if there was a problem in the
* encoding style being set.
* @exception SOAPException if setting the encodingStyle is invalid for this SOAPElement.
* @see #getEncodingStyle
*/
public void setEncodingStyle(String encodingStyle)
throws SOAPException;
/**
* Returns the encoding style for this <code>SOAPElement</code> object.
*
* @return a <code>String</code> giving the encoding style
*
* @see #setEncodingStyle
*/
public String getEncodingStyle();
}
| apache-2.0 |
mp911de/spring-vault | spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java | 6972 | /*
* Copyright 2016-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.vault.authentication;
import java.time.Duration;
import org.springframework.util.Assert;
import org.springframework.vault.support.VaultToken;
/**
* Value object for a Vault token obtained by a login method.
*
* @author Mark Paluch
*/
public class LoginToken extends VaultToken {
private final boolean renewable;
/**
* Duration in seconds.
*/
private final Duration leaseDuration;
private LoginToken(char[] token, Duration duration, boolean renewable) {
super(token);
this.leaseDuration = duration;
this.renewable = renewable;
}
/**
* Create a new {@link LoginToken}.
*
* @param token must not be {@literal null}.
* @return the created {@link VaultToken}
*/
public static LoginToken of(String token) {
Assert.hasText(token, "Token must not be empty");
return of(token.toCharArray(), Duration.ZERO);
}
/**
* Create a new {@link LoginToken}.
*
* @param token must not be {@literal null}.
* @return the created {@link VaultToken}
* @since 1.1
*/
public static LoginToken of(char[] token) {
return of(token, Duration.ZERO);
}
/**
* Create a new {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDurationSeconds the lease duration in seconds, must not be negative.
* @return the created {@link VaultToken}
* @deprecated since 2.0, use {@link #of(char[], Duration)} for time unit safety.
*/
@Deprecated
public static LoginToken of(String token, long leaseDurationSeconds) {
Assert.hasText(token, "Token must not be empty");
Assert.isTrue(leaseDurationSeconds >= 0, "Lease duration must not be negative");
return of(token.toCharArray(), Duration.ofSeconds(leaseDurationSeconds));
}
/**
* Create a new {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDurationSeconds the lease duration in seconds, must not be negative.
* @return the created {@link VaultToken}
* @since 1.1
* @deprecated since 2.0, use {@link #of(char[], Duration)} for time unit safety.
*/
@Deprecated
public static LoginToken of(char[] token, long leaseDurationSeconds) {
Assert.notNull(token, "Token must not be null");
Assert.isTrue(token.length > 0, "Token must not be empty");
Assert.isTrue(leaseDurationSeconds >= 0, "Lease duration must not be negative");
return new LoginToken(token, Duration.ofSeconds(leaseDurationSeconds), false);
}
/**
* Create a new {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
*
* @param leaseDuration the lease duration, must not be negative and not be
* {@literal null}.
* @return the created {@link VaultToken}
* @since 2.0
*/
public static LoginToken of(char[] token, Duration leaseDuration) {
Assert.notNull(token, "Token must not be null");
Assert.isTrue(token.length > 0, "Token must not be empty");
Assert.notNull(leaseDuration, "Lease duration must not be null");
Assert.isTrue(!leaseDuration.isNegative(), "Lease duration must not be negative");
return new LoginToken(token, leaseDuration, false);
}
/**
* Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDurationSeconds the lease duration in seconds, must not be negative.
* @return the created {@link VaultToken}
* @deprecated since 2.0, use {@link #renewable(char[], Duration)} for time unit
* safety.
*/
@Deprecated
public static LoginToken renewable(String token, long leaseDurationSeconds) {
Assert.hasText(token, "Token must not be empty");
Assert.isTrue(leaseDurationSeconds >= 0, "Lease duration must not be negative");
return renewable(token.toCharArray(), Duration.ofSeconds(leaseDurationSeconds));
}
/**
* Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDurationSeconds the lease duration in seconds, must not be negative.
* @return the created {@link VaultToken}
* @since 2.0
* @deprecated since 2.0, use {@link #renewable(char[], Duration)} for time unit
* safety.
*/
@Deprecated
public static LoginToken renewable(char[] token, long leaseDurationSeconds) {
Assert.notNull(token, "Token must not be null");
Assert.isTrue(token.length > 0, "Token must not be empty");
Assert.isTrue(leaseDurationSeconds >= 0, "Lease duration must not be negative");
return new LoginToken(token, Duration.ofSeconds(leaseDurationSeconds), true);
}
/**
* Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDuration the lease duration, must not be {@literal null} or negative.
* @return the created {@link VaultToken}
* @since 2.0
*/
public static LoginToken renewable(VaultToken token, Duration leaseDuration) {
Assert.notNull(token, "Token must not be null");
return renewable(token.toCharArray(), leaseDuration);
}
/**
* Create a new renewable {@link LoginToken} with a {@code leaseDurationSeconds}.
*
* @param token must not be {@literal null}.
* @param leaseDuration the lease duration, must not be {@literal null} or negative.
* @return the created {@link VaultToken}
* @since 2.0
*/
public static LoginToken renewable(char[] token, Duration leaseDuration) {
Assert.notNull(token, "Token must not be null");
Assert.isTrue(token.length > 0, "Token must not be empty");
Assert.notNull(leaseDuration, "Lease duration must not be null");
Assert.isTrue(!leaseDuration.isNegative(), "Lease duration must not be negative");
return new LoginToken(token, leaseDuration, true);
}
/**
* @return the lease duration in seconds. May be {@literal 0} if none.
*/
public Duration getLeaseDuration() {
return leaseDuration;
}
/**
* @return {@literal true} if this token is renewable; {@literal false} otherwise.
*/
public boolean isRenewable() {
return renewable;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getSimpleName());
sb.append(" [renewable=").append(renewable);
sb.append(", leaseDuration=").append(leaseDuration);
sb.append(']');
return sb.toString();
}
}
| apache-2.0 |
arthurzaczek/launcherforblind | src/net/zaczek/launcherforblind/activitysupport/AbstractArrayActivity.java | 1817 | package net.zaczek.launcherforblind.activitysupport;
import net.zaczek.launcherforblind.listentries.ListEntry;
import android.util.Log;
/*
* Abstract list activity for dealing with simple lists
*/
public abstract class AbstractArrayActivity extends AbstractActivity {
private static final String TAG = "launcherforblind";
private ListEntry[] mList;
private int mIndex = -1;
protected abstract ListEntry[] getList();
protected abstract void giveFeedback(String label);
protected ListEntry getCurrentListEntry() {
if (mList != null && mIndex >= 0 && mIndex < mList.length) {
return mList[mIndex];
} else {
return null;
}
}
@Override
protected void onResume() {
super.onResume();
mList = getList();
if (mList != null && mList.length > 0) {
mIndex = 0;
if (!announceHelp()) {
select();
} else {
final String label = mList[mIndex].getLabel();
Log.i(TAG, "Selecting " + label);
giveFeedback(label);
}
} else {
mIndex = -1;
}
}
private void select() {
final ListEntry entry = mList[mIndex];
final String label = entry.getLabel();
Log.i(TAG, "Selecting " + label);
vibe();
giveFeedback(label);
say(entry.getLabelToSay());
}
@Override
protected void onExecute() {
final ListEntry entry = mList[mIndex];
say(entry.getTextToSay());
entry.onSelected();
}
@Override
protected void onScrollDown() {
super.onScrollDown();
if (mIndex == -1)
return;
if (mIndex < mList.length - 1) {
mIndex++;
} else {
mIndex = 0;
}
select();
}
@Override
protected void onScrollUp() {
super.onScrollUp();
if (mIndex == -1)
return;
if (mIndex > 0) {
mIndex--;
} else {
mIndex = mList.length - 1;
}
select();
}
@Override
protected void onDoubleTap() {
super.onDoubleTap();
onExecute();
}
}
| apache-2.0 |