repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
knutwalker/dswarm | converter/src/main/java/org/dswarm/converter/mf/stream/GDMEncoder.java | 10014 | /**
* Copyright (C) 2013 – 2015 SLUB Dresden & Avantgarde Labs GmbH (<code@dswarm.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.dswarm.converter.mf.stream;
import java.util.Map;
import java.util.Stack;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.culturegraph.mf.exceptions.MetafactureException;
import org.culturegraph.mf.framework.DefaultStreamPipe;
import org.culturegraph.mf.framework.ObjectReceiver;
import org.culturegraph.mf.framework.StreamReceiver;
import org.culturegraph.mf.framework.annotations.Description;
import org.culturegraph.mf.framework.annotations.In;
import org.culturegraph.mf.framework.annotations.Out;
import org.dswarm.common.types.Tuple;
import org.dswarm.graph.json.LiteralNode;
import org.dswarm.graph.json.Model;
import org.dswarm.graph.json.Node;
import org.dswarm.graph.json.Predicate;
import org.dswarm.graph.json.Resource;
import org.dswarm.graph.json.ResourceNode;
import org.dswarm.persistence.model.internal.gdm.GDMModel;
import org.dswarm.persistence.model.resource.DataModel;
import org.dswarm.persistence.model.resource.utils.DataModelUtils;
import org.dswarm.persistence.model.schema.utils.SchemaUtils;
import org.dswarm.persistence.util.GDMUtil;
/**
* Converts records to GDM-JSON.
*
* @author polowins
* @author tgaengler
* @author phorn
*/
@Description("converts records to GDM-JSON")
@In(StreamReceiver.class)
@Out(GDMModel.class)
public final class GDMEncoder extends DefaultStreamPipe<ObjectReceiver<GDMModel>> {
private static final String RESOURCE_BASE_URI = SchemaUtils.BASE_URI + "resource/";
private String currentId;
private final Model internalGDMModel;
private ResourceNode recordNode;
private ResourceNode entityNode;
private Resource currentResource;
private Stack<Tuple<ResourceNode, Predicate>> entityStack;
private Stack<Resource> resourceStack;
private ResourceNode recordType;
private Resource recordResource;
private final Optional<DataModel> dataModel;
private final Optional<String> dataModelUri;
private final Map<String, Predicate> predicates = Maps.newHashMap();
private final Map<String, AtomicLong> valueCounter = Maps.newHashMap();
private final Map<String, ResourceNode> types = Maps.newHashMap();
private final Map<String, String> uris = Maps.newHashMap();
public GDMEncoder(final Optional<DataModel> dataModel) {
super();
this.dataModel = dataModel;
dataModelUri = init(dataModel);
internalGDMModel = new Model();
resourceStack = new Stack<>();
}
@Override
public void startRecord(final String identifier) {
assert !isClosed();
currentId = SchemaUtils.isValidUri(identifier) ? identifier : SchemaUtils.mintRecordUri(identifier, currentId, dataModel);
recordResource = getOrCreateResource(currentId);
recordNode = new ResourceNode(currentId);
resourceStack.push(recordResource);
currentResource = recordResource;
// init
entityStack = new Stack<>();
}
@Override
public void endRecord() {
assert !isClosed();
resourceStack.clear();
currentResource = null;
// write triples
final GDMModel gdmModel;
if (recordType != null) {
gdmModel = new GDMModel(internalGDMModel, currentId, recordType.getUri());
} else {
gdmModel = new GDMModel(internalGDMModel, currentId);
}
currentId = null;
recordNode = null;
recordType = null;
getReceiver().process(gdmModel);
// TODO: remove this, when everything works fine
// System.out.println("###############################");
// try {
// System.out.println(Util.getJSONObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(internalGDMModel));
// } catch (JsonProcessingException e) {
// e.printStackTrace();
// }
// System.out.println("###############################");
}
@Override
public void startEntity(final String name) {
assert !isClosed();
final Predicate entityPredicate = getPredicate(name);
final String entityUri = mintEntityUri();
final Resource entityResource = getOrCreateResource(entityUri);
entityNode = new ResourceNode(entityUri);
if (entityStack.empty()) {
addStatement(recordNode, entityPredicate, entityNode);
} else {
final Tuple<ResourceNode, Predicate> parentEntityTuple = entityStack.peek();
addStatement(parentEntityTuple.v1(), entityPredicate, entityNode);
}
currentResource = entityResource;
// TODO: not, this should be done in a different way (i.e. the type should already be assigned from somewhere else and not minted on demand!)
// addStatement(entityNode, getPredicate(GDMUtil.RDF_type), getType(name + SchemaUtils.TYPE_POSTFIX));
entityStack.push(new Tuple<>(entityNode, entityPredicate));
resourceStack.push(entityResource);
}
@Override
public void endEntity() {
assert !isClosed();
resourceStack.pop();
currentResource = resourceStack.peek();
entityStack.pop();
if (!entityStack.isEmpty()) {
entityNode = entityStack.peek().v1();
} else {
entityNode = null;
}
}
@Override
public void literal(final String name, final String value) {
// System.out.println("in literal with name = '" + name + "' :: value = '" + value + "'");
assert !isClosed();
// create triple
// name = predicate
// value = literal or object
// TODO: only literals atm, i.e., how to determine other resources?
// => still valid: how to determine other resources!
// ==> @phorn proposed to utilise "<" ">" to identify resource ids (uris)
if (name == null) {
return;
}
final String propertyUri;
if (SchemaUtils.isValidUri(name)) {
propertyUri = name;
} else {
propertyUri = SchemaUtils.mintUri(dataModelUri.get(), name);
}
if (value != null && !value.isEmpty()) {
final Predicate attributeProperty = getPredicate(propertyUri);
final LiteralNode literalObject = new LiteralNode(value);
final Node currentNode = entityStack.empty() ? recordNode : entityNode;
if (null != currentNode) {
// TODO: this is only a HOTFIX for creating resources from resource type uris
if (!GDMUtil.RDF_type.equals(propertyUri)) {
currentResource.addStatement(currentNode, attributeProperty, literalObject);
} else {
// check, whether value is really a URI
if (SchemaUtils.isValidUri(value)) {
final ResourceNode typeResource = new ResourceNode(value);// ResourceFactory.createResource(value);
currentResource.addStatement(currentNode, attributeProperty, typeResource);
if (currentResource.equals(recordResource)) {
recordType = typeResource;
}
} else {
currentResource.addStatement(currentNode, attributeProperty, literalObject);
}
}
} else {
throw new MetafactureException("couldn't get a resource for adding this property");
}
}
}
private Optional<String> init(final Optional<DataModel> dataModel) {
if (!dataModel.isPresent()) {
return Optional.fromNullable(StringUtils.stripEnd(DataModelUtils.determineDataModelSchemaBaseURI(null), SchemaUtils.HASH));
}
return dataModel.transform(new Function<DataModel, String>() {
@Override
public String apply(final DataModel dm) {
return StringUtils.stripEnd(DataModelUtils.determineDataModelSchemaBaseURI(dm), SchemaUtils.HASH);
}
});
}
private String mintEntityUri() {
return RESOURCE_BASE_URI + UUID.randomUUID().toString();
}
private Predicate getPredicate(final String predicateId) {
final String predicateURI = getURI(predicateId);
if (!predicates.containsKey(predicateURI)) {
final Predicate predicate = new Predicate(predicateURI);
predicates.put(predicateURI, predicate);
}
return predicates.get(predicateURI);
}
private void addStatement(final Node subject, final Predicate predicate, final Node object) {
String key;
if (subject instanceof ResourceNode) {
key = ((ResourceNode) subject).getUri();
} else {
key = subject.getId().toString();
}
key += "::" + predicate.getUri();
if (!valueCounter.containsKey(key)) {
final AtomicLong valueCounterForKey = new AtomicLong(0);
valueCounter.put(key, valueCounterForKey);
}
final Long order = valueCounter.get(key).incrementAndGet();
currentResource.addStatement(subject, predicate, object, order);
}
private String getURI(final String id) {
if (!uris.containsKey(id)) {
final String uri = SchemaUtils.isValidUri(id) ? id : SchemaUtils.mintTermUri(null, id, dataModelUri);
uris.put(id, uri);
}
return uris.get(id);
}
private ResourceNode getType(final String typeId) {
final String typeURI = getURI(typeId);
if (!types.containsKey(typeURI)) {
final ResourceNode type = new ResourceNode(typeURI);
types.put(typeURI, type);
}
return types.get(typeURI);
}
private Resource getOrCreateResource(final String resourceURI) {
final Resource resourceFromModel = internalGDMModel.getResource(resourceURI);
if (resourceFromModel != null) {
return resourceFromModel;
}
final Resource newResource = new Resource(resourceURI);
internalGDMModel.addResource(newResource);
return newResource;
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p239/Production4786.java | 1891 | package org.gradle.test.performance.mediummonolithicjavaproject.p239;
public class Production4786 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
bhecquet/seleniumRobot | core/src/main/java/com/seleniumtests/connectors/selenium/ISeleniumGridConnector.java | 2345 | package com.seleniumtests.connectors.selenium;
import java.awt.Point;
import java.io.File;
import java.util.List;
import org.openqa.selenium.Capabilities;
public interface ISeleniumGridConnector {
public void uploadMobileApp(Capabilities caps);
/**
* Upload a file given file path
* @param filePath
*/
public void uploadFile(String filePath);
/**
* Upload a file given file path
* @param filePath
*/
public String uploadFileToNode(String filePath, boolean returnLocalFile);
/**
* Kill process
* @param processName
*/
public void killProcess(String processName);
/**
* Execute command
* @param program name of the program
* @param args arguments of the program
*/
public String executeCommand(String program, String ... args);
/**
* Execute command with timeout
* @param program name of the program
* @param timeout if null, default timeout will be applied
* @param args arguments of the program
*/
public String executeCommand(String program, Integer timeout, String ... args) ;
/**
* Upload a file to a browser uplpoad window
* @param filePath
*/
public void uploadFileToBrowser(String fileName, String base64Content) ;
/**
* Left clic on desktop at x,y
* @param x x coordinate
* @param y y coordinate
*/
public void leftClic(int x, int y) ;
/**
* double clic on desktop at x,y
* @param x x coordinate
* @param y y coordinate
*/
public void doubleClick(int x, int y) ;
/**
* Get position of mouse pointer
* @return
*/
public Point getMouseCoordinates();
/**
* right clic on desktop at x,y
* @param x x coordinate
* @param y y coordinate
*/
public void rightClic(int x, int y) ;
/**
* Take screenshot of the full desktop and return a base64 string of the image
* @return
*/
public String captureDesktopToBuffer() ;
/**
* Send keys to desktop
* @param keys
*/
public void sendKeysWithKeyboard(List<Integer> keyCodes);
public void startVideoCapture();
public File stopVideoCapture(String outputFile) ;
public List<Integer> getProcessList(String processName);
/**
*
* @return true if grid is active. Raises an exception if it's not there anymore
*/
public boolean isGridActive();
/**
* Write text to desktop using keyboard
* @param text
*/
public void writeText(String text);
}
| apache-2.0 |
derekhiggins/ovirt-engine | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/view/popup/host/HostBondPopupView.java | 10087 | package org.ovirt.engine.ui.webadmin.section.main.view.popup.host;
import org.ovirt.engine.core.common.businessentities.NetworkBootProtocol;
import org.ovirt.engine.core.common.businessentities.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.Network;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView;
import org.ovirt.engine.ui.common.widget.Align;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel;
import org.ovirt.engine.ui.common.widget.editor.EntityModelCheckBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelLabelEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelTextBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor;
import org.ovirt.engine.ui.common.widget.renderer.NullSafeRenderer;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostBondInterfaceModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.ApplicationResources;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.host.HostBondPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.widget.editor.EnumRadioEditor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.inject.Inject;
public class HostBondPopupView extends AbstractModelBoundPopupView<HostBondInterfaceModel> implements HostBondPopupPresenterWidget.ViewDef {
interface Driver extends SimpleBeanEditorDriver<HostBondInterfaceModel, HostBondPopupView> {
Driver driver = GWT.create(Driver.class);
}
interface ViewUiBinder extends UiBinder<SimpleDialogPanel, HostBondPopupView> {
ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
}
@UiField(provided = true)
@Path(value = "bond.selectedItem")
ListModelListBoxEditor<Object> bondEditor;
@UiField(provided = true)
@Path(value = "network.selectedItem")
ListModelListBoxEditor<Object> networkEditor;
@UiField(provided = true)
@Path(value = "bondingOptions.selectedItem")
ListModelListBoxEditor<Object> bondingModeEditor;
@UiField
@Ignore
EntityModelTextBoxEditor customEditor;
@UiField(provided = true)
EnumRadioEditor<NetworkBootProtocol> bootProtocol;
@UiField
@Ignore
EntityModelLabelEditor bootProtocolLabel;
@UiField
@Path(value = "address.entity")
EntityModelTextBoxEditor address;
@UiField
@Path(value = "subnet.entity")
EntityModelTextBoxEditor subnet;
@UiField
@Path(value = "gateway.entity")
EntityModelTextBoxEditor gateway;
@UiField(provided = true)
@Path(value = "checkConnectivity.entity")
EntityModelCheckBoxEditor checkConnectivity;
@UiField
@Ignore
Label message;
@UiField
@Ignore
HTML info;
@UiField
@Ignore
DockLayoutPanel layoutPanel;
@UiField
@Ignore
VerticalPanel mainPanel;
@UiField
@Ignore
VerticalPanel infoPanel;
@UiField(provided = true)
@Path(value = "commitChanges.entity")
EntityModelCheckBoxEditor commitChanges;
@Inject
public HostBondPopupView(EventBus eventBus, ApplicationResources resources, final ApplicationConstants constants) {
super(eventBus, resources);
bondEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
@Override
protected String renderNullSafe(Object object) {
return ((VdsNetworkInterface) object).getName();
}
});
networkEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
@Override
protected String renderNullSafe(Object object) {
return ((Network) object).getname();
}
});
bondingModeEditor = new ListModelListBoxEditor<Object>(new NullSafeRenderer<Object>() {
@SuppressWarnings("unchecked")
@Override
protected String renderNullSafe(Object object) {
KeyValuePairCompat<String, EntityModel> pair = (KeyValuePairCompat<String, EntityModel>) object;
String key = pair.getKey();
if ("custom".equals(key)) { //$NON-NLS-1$
return constants.customHostPopup() + ":"; //$NON-NLS-1$
}
EntityModel value = pair.getValue();
return (String) value.getEntity();
}
});
bootProtocol = new EnumRadioEditor<NetworkBootProtocol>(NetworkBootProtocol.class, eventBus);
checkConnectivity = new EntityModelCheckBoxEditor(Align.RIGHT);
commitChanges = new EntityModelCheckBoxEditor(Align.RIGHT);
initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
bondEditor.setLabel(constants.bondNameHostPopup() + ":"); //$NON-NLS-1$
networkEditor.setLabel(constants.networkHostPopup() + ":"); //$NON-NLS-1$
bondingModeEditor.setLabel(constants.bondingModeHostPopup() + ":"); //$NON-NLS-1$
customEditor.setLabel(constants.customModeHostPopup() + ":"); //$NON-NLS-1$
bootProtocolLabel.setLabel(constants.bootProtocolHostPopup() + ":"); //$NON-NLS-1$
bootProtocolLabel.asEditor().getSubEditor().setValue(" "); //$NON-NLS-1$
address.setLabel(constants.ipHostPopup() + ":"); //$NON-NLS-1$
subnet.setLabel(constants.subnetMaskHostPopup() + ":"); //$NON-NLS-1$
gateway.setLabel(constants.defaultGwHostPopup() + ":"); //$NON-NLS-1$
checkConnectivity.setLabel(constants.checkConHostPopup() + ":"); //$NON-NLS-1$
info.setHTML(constants.changesTempHostPopup());
commitChanges.setLabel(constants.saveNetConfigHostPopup());
Driver.driver.initialize(this);
}
@Override
public void edit(final HostBondInterfaceModel object) {
Driver.driver.edit(object);
if (!object.getBootProtocolAvailable()) {
bootProtocol.asWidget().setVisible(false);
bootProtocolLabel.setVisible(false);
}
bootProtocol.setEnabled(NetworkBootProtocol.None, object.getNoneBootProtocolAvailable());
updateBondOptions(object.getBondingOptions());
object.getPropertyChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
HostBondInterfaceModel model = (HostBondInterfaceModel) sender;
String propertyName = ((PropertyChangedEventArgs) args).PropertyName;
if ("NoneBootProtocolAvailable".equals(propertyName)) { //$NON-NLS-1$
bootProtocol.setEnabled(NetworkBootProtocol.None, model.getNoneBootProtocolAvailable());
}
else if ("Message".equals(propertyName)) { //$NON-NLS-1$
message.setText(model.getMessage());
}
}
});
object.getBondingOptions().getSelectedItemChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
ListModel list = (ListModel) sender;
updateBondOptions(list);
}
});
customEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<Object>() {
@SuppressWarnings("unchecked")
@Override
public void onValueChange(ValueChangeEvent<Object> event) {
for (Object item : object.getBondingOptions().getItems()) {
KeyValuePairCompat<String, EntityModel> pair = (KeyValuePairCompat<String, EntityModel>) item;
if ("custom".equals(pair.getKey())) { //$NON-NLS-1$
pair.getValue().setEntity(event.getValue());
}
}
}
});
bondingModeEditor.setVisible(true);
bondingModeEditor.asWidget().setVisible(true);
if (object.isCompactMode()) {
// hide widgets
info.setVisible(false);
message.setVisible(false);
checkConnectivity.setVisible(false);
commitChanges.setVisible(false);
// resize
layoutPanel.remove(infoPanel);
layoutPanel.setWidgetSize(mainPanel, 300);
asPopupPanel().setPixelSize(400, 400);
}
}
@Override
public HostBondInterfaceModel flush() {
return Driver.driver.flush();
}
@Override
public void focusInput() {
networkEditor.setFocus(true);
}
@Override
public void setMessage(String message) {
}
private void updateBondOptions(ListModel list) {
@SuppressWarnings("unchecked")
KeyValuePairCompat<String, EntityModel> pair =
(KeyValuePairCompat<String, EntityModel>) list.getSelectedItem();
if ("custom".equals(pair.getKey())) { //$NON-NLS-1$
customEditor.setVisible(true);
Object entity = pair.getValue().getEntity();
customEditor.asEditor().getSubEditor().setValue(entity == null ? "" : entity); //$NON-NLS-1$
} else {
customEditor.setVisible(false);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-fms/src/main/java/com/amazonaws/services/fms/model/transform/ActionTargetJsonUnmarshaller.java | 2937 | /*
* 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.fms.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.fms.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ActionTarget JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ActionTargetJsonUnmarshaller implements Unmarshaller<ActionTarget, JsonUnmarshallerContext> {
public ActionTarget unmarshall(JsonUnmarshallerContext context) throws Exception {
ActionTarget actionTarget = new ActionTarget();
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("ResourceId", targetDepth)) {
context.nextToken();
actionTarget.setResourceId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Description", targetDepth)) {
context.nextToken();
actionTarget.setDescription(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 actionTarget;
}
private static ActionTargetJsonUnmarshaller instance;
public static ActionTargetJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ActionTargetJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
gosu-lang/gosu-lang | gosu-core/src/main/java/gw/internal/gosu/parser/ParseTree.java | 22987 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
/**
*/
package gw.internal.gosu.parser;
import gw.internal.gosu.parser.expressions.NewExpression;
import gw.internal.gosu.parser.statements.FunctionStatement;
import gw.lang.parser.IParseTree;
import gw.lang.parser.IParsedElement;
import gw.lang.parser.IParsedElementWithAtLeastOneDeclaration;
import gw.lang.parser.IScriptPartId;
import gw.lang.parser.ISourceCodeTokenizer;
import gw.lang.parser.IToken;
import gw.lang.parser.exceptions.ParseIssue;
import gw.lang.parser.expressions.IMemberAccessExpression;
import gw.lang.parser.IParseIssue;
import gw.lang.parser.IStatement;
import gw.lang.parser.statements.IFunctionStatement;
import gw.lang.reflect.IType;
import gw.util.DynamicArray;
import gw.util.GosuObjectUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Intended to specify the location of a parsed element within the source.
*/
public final class ParseTree implements IParseTree
{
private static final DynamicArray<ParseTree> EMPTY_PARSE_TREE_LIST = new DynamicArray<ParseTree>(0);
private transient ParsedElement _pe;
private DynamicArray<ParseTree> _children;
private int _iOffset;
private int _iLength;
private transient IScriptPartId _scriptPart;
public ParseTree( ParsedElement pe, int iOffset, int iLength, IScriptPartId scriptPart )
{
_pe = pe;
_iOffset = iOffset;
_iLength = iLength;
_scriptPart = scriptPart;
_children = EMPTY_PARSE_TREE_LIST;
}
public IType getEnclosingType()
{
return _scriptPart == null ? null : _scriptPart.getContainingType();
}
public IScriptPartId getScriptPartId()
{
return _scriptPart;
}
/**
* @return The zero-based offset of the parsed element within the source.
*/
public int getOffset()
{
return _iOffset;
}
/**
* @return The length of the parsed element in the source.
*/
public int getLength()
{
return _iLength;
}
public void setLength( int iLength )
{
_iLength = iLength;
}
/**
* @return The one based line number of the beginning of the parsed element
*/
public int getLineNum()
{
return _pe.getLineNum();
}
/**
* @return The offset from the beginning of the line where the parsed element starts
*/
public int getColumn()
{
return _pe.getColumn();
}
/**
* @return The parsed element to which this location corresponds.
*/
public ParsedElement getParsedElement()
{
return _pe;
}
/**
* @return The most distant position this location occupies i.e., offset + length - 1.
*/
public int getExtent()
{
return getOffset() + getLength() - 1;
}
/**
* @param iPosition Any position within the source.
*
* @return True if this location contains the position.
*/
public boolean contains( int iPosition )
{
return contains( iPosition, iPosition );
}
/**
* @param l A location to check.
*
* @return True if the space occupied by this location is a superset of the
* space occupied by the specified location.
*/
public boolean contains( IParseTree l )
{
return contains( l.getOffset(), l.getExtent() );
}
private boolean contains( int start, int end )
{
return start >= getOffset() &&
end <= getExtent();
}
public boolean containsOrBorders( int iPosition, boolean strict )
{
return containsOrBorders( iPosition, iPosition, strict );
}
public boolean containsOrBorders( IParseTree l, boolean strict )
{
return containsOrBorders( l.getOffset(), l.getExtent(), strict );
}
private boolean containsOrBorders( int start, int end, boolean strict )
{
int rightBounds;
if( strict )
{
rightBounds = getOffset() + getLength();
}
else
{
ParseTree nextSibling = getNextSibling();
if( nextSibling != null )
{
rightBounds = nextSibling.getOffset() - 1;
}
else
{
rightBounds = getOffset() + getLength();
}
}
return start >= getOffset() &&
end <= rightBounds;
}
public ParseTree getDeepestLocation( boolean statementsOnly, int iStart, int iEnd, boolean strict )
{
if( !containsOrBorders( iStart, iEnd, strict ) )
{
return null;
}
ParseTree deepest = null;
if(!statementsOnly || (_pe instanceof IStatement)) {
deepest = this;
}
if( _children != null )
{
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
ParseTree l = child.getDeepestLocation( statementsOnly, iStart, iEnd, strict );
if( Search.isDeeper( deepest, l ) )
{
deepest = l;
}
}
}
Statement embededStmt = (Statement)Search.getHiddenStatement( getParsedElement() );
if( embededStmt != null && embededStmt.getLocation() != null )
{
ParseTree l = embededStmt.getLocation().getDeepestLocation( statementsOnly, iStart, iEnd, strict );
if( Search.isDeeper( deepest, l ) )
{
deepest = l;
}
}
return deepest;
}
public boolean isAncestorOf( IParseTree l )
{
while( l != null && l.getParent() != l )
{
if( (l = l.getParent()) == this )
{
return true;
}
}
return false;
}
private ParseTree getDeepestLocation( boolean statementsOnly, int iPosition, boolean strict )
{
return getDeepestLocation( statementsOnly, iPosition, iPosition, strict );
}
/**
* @param iPosition The location to check.
* @param strict Whether to match strictly or accept white spaces to the right
*
* @return The deepest descendent location containing the specified location.
*/
public ParseTree getDeepestLocation( int iPosition, boolean strict )
{
return getDeepestLocation( iPosition, iPosition, strict );
}
/**
* @param iStart The start of the segment (inclusive)
* @param iEnd The end of the segment (inclusive)
* @param strict Whether to match strictly or accept white spaces to the right
*
* @return The deepest descendent location containing the segment.
*/
public ParseTree getDeepestLocation( int iStart, int iEnd, boolean strict )
{
return getDeepestLocation( false, iStart, iEnd, strict );
}
/**
* @param iPosition The location to check.
* @param strict Whether to match strictly or accept white spaces to the right
*
* @return The deepest descendent statement location containing the specified location.
*/
public ParseTree getDeepestStatementLocation( int iPosition, boolean strict )
{
return getDeepestLocation( true, iPosition, strict );
}
/**
* @param iLineNum The one based line number to check.
* @param clsSkip A statement sublcass to ignore. Optional.
*
* @return The first statement beginning at the specified line number, or null
* if no statements start at the line number.
*/
public ParseTree getStatementAtLine( int iLineNum, Class clsSkip )
{
if( _pe instanceof NewExpression )
{
NewExpression newExpression = (NewExpression)_pe;
IType type = newExpression.getType();
if( type instanceof IGosuClassInternal && newExpression.isAnonymousClass() )
{
return (ParseTree)((IGosuClassInternal)type).getClassStatement().getLocation().getStatementAtLine( iLineNum, clsSkip );
}
}
if( (_pe instanceof Statement) && // Note we must analyze expressions e.g., block expressions can have statements
!(_pe instanceof FunctionStatement && ((FunctionStatement)_pe).getDynamicFunctionSymbol() instanceof ProgramClassFunctionSymbol) &&
(getLineNum() == iLineNum) &&
(clsSkip == null || !clsSkip.isAssignableFrom( _pe.getClass() )) )
{
return this;
}
ParseTree deepest = null;
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
ParseTree l = child.getStatementAtLine( iLineNum, clsSkip );
if( Search.isDeeper( deepest, l ) )
{
deepest = l;
}
}
return deepest;
}
/**
* Adds a child location to this location. Note the location must cover only
* a subset of this locations area.
*
* @param l The location to add.
*/
public void addChild( IParseTree l )
{
addChild( -1, l );
}
public void addChild( int iIndex, IParseTree l )
{
if( l == null )
{
throw new NullPointerException( "Attempted to add a Null child location." );
}
if( !contains( l ) && l.getLength() > 0 )
{
throw new IllegalArgumentException( "Attempted to add a child location whose bounds extend beyond the containing location: " +
"(" + getOffset() + ", " + getExtent() + ") does not contain (" + l.getOffset() + ", " + l.getExtent() + ")" );
}
if( _children == EMPTY_PARSE_TREE_LIST )
{
_children = new DynamicArray<ParseTree>( 2 );
}
l.setParent( this );
if( iIndex >= 0 )
{
_children.add( iIndex, (ParseTree)l );
}
else
{
_children.add( (ParseTree)l );
}
}
public void removeChild( IParseTree l )
{
if( (l != null) && (_children != null) )
{
_children.remove( l );
l.setParent( null );
}
}
/**
* @return The list of child locations covered by this location.
*/
public List<IParseTree> getChildren()
{
return (List<IParseTree>) (_children == null ? Collections.<IParseTree>emptyList() : Collections.unmodifiableList( _children ));
}
public int getChildCount()
{
return _children == null ? 0 : _children.size;
}
/**
* Sets the parent location. Note the parent location must cover a superset of the
* specified location's area.
*
* @param l The parent location.
*/
public void setParent( IParseTree l )
{
if( l != null && !l.contains( this ) && getLength() > 0 )
{
throw new IllegalArgumentException( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." );
}
if( _pe != null )
{
ParsedElement parentElement = (ParsedElement)_pe.getParent();
if( parentElement != null )
{
ParseTree oldParent = parentElement.getLocation();
if( oldParent != null )
{
oldParent._children.remove( this );
}
}
_pe.setParent( l == null ? null : ((ParseTree)l)._pe );
}
}
/**
* @return This location's parent location. Note the parent covers a superset of the
* this location's area.
*/
public IParseTree getParent()
{
return _pe != null && _pe.getParent() != null ? _pe.getParent().getLocation() : null;
}
/**
* Like getParent, but won't infinitely recurse if the parent turns out to be equal to this, which can happen
* when the expression in question is a program (since the outer program has the same location as the main statement).
*/
public IParseTree getParentOtherThanThis()
{
IParseTree parent = getParent();
return (parent == this ? null : parent);
}
/**
* Is just the physical location equal?
*
* @param location Location to check
*
* @return True if the given physical location's offset and extents are equal to this one's
*/
public boolean areOffsetAndExtentEqual( IParseTree location )
{
return location != null &&
location.getOffset() == getOffset() &&
location.getExtent() == getExtent();
}
public String toString()
{
return "Offset: " + getOffset() + "\n" +
"Length: " + getLength() + "\n" +
(_pe != null ? _pe.getClass().getSimpleName() : "ParsedElement") + ": " + _pe;
}
public void initLocation( ParsedElement pe, int iOffset, int iLength )
{
_pe = _pe == null ? pe : _pe;
_iOffset = iOffset;
_iLength = iLength;
}
public void compactParseTree() {
if( _children != null )
{
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
child.compactParseTree();
}
_children.trimToSize();
}
}
public void clearParseTreeInformation()
{
// Don't clear block expressions. Yuck!!!!!
if (getParsedElement() == null || getParsedElement().shouldClearParseInfo())
{
if( _children != null )
{
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
child.clearParseTreeInformation();
}
}
_children = EMPTY_PARSE_TREE_LIST;
if( _pe != null )
{
_pe.setLocation( null );
}
_pe = null;
}
}
public boolean areAllChildrenAfterPosition( int caret )
{
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
if( child.getOffset() < caret )
{
return false;
}
}
return true;
}
public List<IParseTree> getDominatingLocationList()
{
ArrayList<IParseTree> dominatingLocations = new ArrayList<IParseTree>();
if( getParent() != null )
{
List<IParseTree> parentDominators = getParent().getDominatingLocationList();
dominatingLocations.addAll( parentDominators );
dominatingLocations.add( getParent() );
dominatingLocations.addAll( getParent().getChildrenBefore( this ) );
}
return dominatingLocations;
}
public List<IParseTree> getChildrenBefore( IParseTree parseTree )
{
ArrayList<IParseTree> childrenBefore = new ArrayList<IParseTree>();
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
if( child.getOffset() < parseTree.getOffset() )
{
childrenBefore.add( child );
}
}
return childrenBefore;
}
public boolean isSiblingOf( IParseTree deepestAtEnd )
{
return getParent() != null && GosuObjectUtil.equals( getParent(), deepestAtEnd.getParent() );
}
public ParseTree getChildAfter( int point )
{
int minDistance = Integer.MAX_VALUE;
ParseTree closestTrailingChild = null;
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
int dist = child.getOffset() - point;
if( dist > 0 && dist < minDistance )
{
minDistance = dist;
closestTrailingChild = child;
}
}
return closestTrailingChild;
}
public ParseTree getChildBefore( int point )
{
int minDistance = Integer.MAX_VALUE;
ParseTree closestTrailingChild = null;
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
int dist = point - child.getOffset();
if( dist > 0 && dist < minDistance )
{
minDistance = dist;
closestTrailingChild = child;
}
}
return closestTrailingChild;
}
public ParseTree getChildBefore( IParseTree child )
{
return getChildBefore( child.getOffset() );
}
public ParseTree getChildAfter( IParseTree child )
{
return getChildAfter( child.getExtent() );
}
public ParseTree getFirstChildWithParsedElementType( Class<? extends IParsedElement> aClass )
{
ParseTree returnChild = null;
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
if( aClass.isInstance( child.getParsedElement() ) && (returnChild == null || child.getOffset() < returnChild.getOffset()) )
{
returnChild = child;
}
}
return returnChild;
}
public ParseTree getLastChildWithParsedElementType( Class<? extends IParsedElement> aClass )
{
ParseTree returnChild = null;
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
if( aClass.isInstance( child.getParsedElement() ) && (returnChild == null || child.getOffset() > returnChild.getOffset()) )
{
returnChild = child;
}
}
return returnChild;
}
public ParseTree getLastChild()
{
return getChildBefore( getExtent() );
}
public ParseTree getNextSibling()
{
IParseTree parent = getParent();
if( parent == null || parent == this )
{
return null;
}
return (ParseTree)getParent().getChildAfter( this );
}
public ParseTree getPreviousSibling()
{
if( getParent() == null )
{
return null;
}
return (ParseTree)getParent().getChildBefore( this );
}
public ParseTree getDeepestFirstChild()
{
ParseTree parseTree = this;
while( parseTree.getFirstChildWithParsedElementType( ParsedElement.class ) != null )
{
parseTree = parseTree.getFirstChildWithParsedElementType( ParsedElement.class );
}
return parseTree;
}
public Collection<IParseTree> findDescendantsWithParsedElementType( Class type )
{
ArrayList<IParseTree> matches = new ArrayList<IParseTree>();
findDescendantsWithParsedElementType( matches, type );
return matches;
}
public void addUnder( IParseTree parent )
{
int offset = parent.getOffset();
int lineNumOffset = parent.getParsedElement().getLineNum() - 1;
int columnOffset = parent.getParsedElement().getColumn();
adjustOffset( offset, lineNumOffset, columnOffset );
setParent( parent );
_scriptPart = parent.getScriptPartId();
parent.addChild( this );
}
void adjustOffset( int offset, int lineNumOffset, int columnOffset )
{
if( getLineNum() > 1 )
{
columnOffset = 0;
}
recursivelyAdjustOffset( offset, lineNumOffset, columnOffset );
if( _pe != null )
{
for( IParseIssue parseIssue : _pe.getParseIssues() )
{
((ParseIssue)parseIssue).adjustOffset( offset, lineNumOffset, columnOffset );
}
}
}
private void recursivelyAdjustOffset( int offset, int lineNumOffset, int columnOffset )
{
if( getLineNum() > 1 )
{
columnOffset = 0;
}
_iOffset += offset;
if( _pe != null )
{
_pe.adjustLineNum( lineNumOffset );
_pe.adjustColumn( columnOffset );
}
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
child.recursivelyAdjustOffset( offset, lineNumOffset, columnOffset );
}
if( _pe instanceof IMemberAccessExpression )
{
IMemberAccessExpression mae = (IMemberAccessExpression)_pe;
mae.setStartOffset( mae.getStartOffset() + offset );
}
if( _pe instanceof IParsedElementWithAtLeastOneDeclaration )
{
IParsedElementWithAtLeastOneDeclaration peo = (IParsedElementWithAtLeastOneDeclaration) _pe;
for( String name : peo.getDeclarations() )
{
String charSeq = (String)name;
peo.setNameOffset( peo.getNameOffset( charSeq ) + offset, charSeq );
}
}
}
private void findDescendantsWithParsedElementType( ArrayList<IParseTree> matches, Class type )
{
if( type.isAssignableFrom( _pe.getClass() ) )
{
matches.add( this );
}
for(int i = 0; i < _children.size; i++)
{
ParseTree child = (ParseTree) _children.data[i];
child.findDescendantsWithParsedElementType( matches, type );
}
}
public IFunctionStatement getEnclosingFunctionStatement()
{
for( ParseTree csr = this; csr != null; csr = (ParseTree)csr.getParentOtherThanThis() )
{
ParsedElement pe = csr.getParsedElement();
if( pe instanceof IFunctionStatement )
{
return (IFunctionStatement)pe;
}
}
return null;
}
public final IParseTree getMatchingElement(int iStart, int iLength) {
if (_iOffset == iStart && _iLength == iLength) {
return this;
}
if (_children != null) {
for (int i = 0; i < _children.size; i++) {
ParseTree child = (ParseTree) _children.data[i];
IParseTree tree = child.getMatchingElement(iStart, iLength);
if (tree != null) {
return tree;
}
}
}
return null;
}
public String getTreeOutline()
{
return getTreeOutline( "" );
}
private String getTreeOutline( String strIndent )
{
List<IToken> tokens = getParsedElement().getTokens();
StringBuilder source = new StringBuilder();
source.append( "\n" + strIndent + "- <" + getParsedElement().getClass().getSimpleName() + "> Offset: " + getOffset() + " Extent: " + getExtent() );
strIndent = strIndent + " ";
StringBuilder tokenContent = new StringBuilder();
appendTokensForOutline( null, tokens, tokenContent );
if( tokenContent.length() > 0 )
{
source.append( "\n" + strIndent + "- " );
source.append( tokenContent );
}
for( IParseTree child : getChildrenSorted( ) )
{
source.append( ((ParseTree)child).getTreeOutline( strIndent ) );
tokenContent = new StringBuilder();
appendTokensForOutline( (ParseTree)child, tokens, tokenContent );
if( tokenContent.length() > 0 )
{
source.append( "\n" + strIndent + "- " );
source.append( tokenContent );
}
}
return source.toString();
}
private void appendTokensForOutline( ParseTree child, List<IToken> tokens, StringBuilder source )
{
StringBuilder sbTokens = new StringBuilder();
addTokens( child, tokens, sbTokens );
source.append( sbTokens.toString().replace( '\n', '\u014A' ).replace( '\r', '\u019D' ).replace( ' ', '\u1D13' ) );
}
public String getTextFromTokens()
{
List<IToken> tokens = getParsedElement().getTokens();
StringBuilder source = new StringBuilder();
addTokens( null, tokens, source );
for( IParseTree child : getChildrenSorted( ) )
{
source.append( child.getTextFromTokens() );
addTokens( (ParseTree)child, tokens, source );
}
return source.toString();
}
private void addTokens( ParseTree after, List<IToken> tokens, StringBuilder source )
{
for( IToken t : tokens )
{
if( t.getAfter() == after || (after != null && after.isAncestor( t.getAfter() )) )
{
if( t.getType() == ISourceCodeTokenizer.TT_EOF )
{
// Skip EOF
continue;
}
source.append( t.getText() );
}
}
}
public List<IParseTree> getChildrenSorted( )
{
List<IParseTree> children = new ArrayList<IParseTree>( _children );
Collections.sort( children,
new Comparator<IParseTree>()
{
public int compare( IParseTree o1, IParseTree o2 )
{
return o1.getOffset() - o2.getOffset();
}
} );
return children;
}
public boolean isAncestor(IParseTree child) {
if (child == null) {
return false;
}
if (this == child) {
return true;
}
if (child == child.getParent()) {
return false;
}
return isAncestor(child.getParent());
}
public ParseTree getChild( int index )
{
return _children.get( index );
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-eventbridge/src/main/java/com/amazonaws/services/eventbridge/model/transform/ListRulesRequestMarshaller.java | 2902 | /*
* 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.eventbridge.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.eventbridge.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListRulesRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListRulesRequestMarshaller {
private static final MarshallingInfo<String> NAMEPREFIX_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NamePrefix").build();
private static final MarshallingInfo<String> EVENTBUSNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EventBusName").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("NextToken").build();
private static final MarshallingInfo<Integer> LIMIT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Limit").build();
private static final ListRulesRequestMarshaller instance = new ListRulesRequestMarshaller();
public static ListRulesRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ListRulesRequest listRulesRequest, ProtocolMarshaller protocolMarshaller) {
if (listRulesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRulesRequest.getNamePrefix(), NAMEPREFIX_BINDING);
protocolMarshaller.marshall(listRulesRequest.getEventBusName(), EVENTBUSNAME_BINDING);
protocolMarshaller.marshall(listRulesRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listRulesRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
Myasuka/systemml | src/main/java/org/apache/sysml/runtime/matrix/mapred/ReduceBase.java | 16182 | /*
* 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.sysml.runtime.matrix.mapred;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.DMLUnsupportedOperationException;
import org.apache.sysml.runtime.functionobjects.Plus;
import org.apache.sysml.runtime.instructions.mr.AggregateInstruction;
import org.apache.sysml.runtime.instructions.mr.MRInstruction;
import org.apache.sysml.runtime.instructions.mr.TernaryInstruction;
import org.apache.sysml.runtime.matrix.data.MatrixIndexes;
import org.apache.sysml.runtime.matrix.data.MatrixValue;
import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;
import org.apache.sysml.runtime.matrix.data.TaggedMatrixValue;
import org.apache.sysml.runtime.matrix.operators.AggregateOperator;
import org.apache.sysml.runtime.util.MapReduceTool;
public class ReduceBase extends MRBaseForCommonInstructions
{
//aggregate instructions
protected HashMap<Byte, ArrayList<AggregateInstruction>>
agg_instructions=new HashMap<Byte, ArrayList<AggregateInstruction>>();
//default aggregate operation
protected static final AggregateOperator DEFAULT_AGG_OP = new AggregateOperator(0, Plus.getPlusFnObject());
//default aggregate instruction
protected AggregateInstruction defaultAggIns=
new AggregateInstruction(DEFAULT_AGG_OP, (byte)0, (byte)0, "DEFAULT_AGG_OP");
//mixsure of instructions performed in reducer
protected ArrayList<MRInstruction> mixed_instructions = null;
//the final result indexes that needed to be outputted
protected byte[] resultIndexes=null;
protected byte[] resultDimsUnknown=null;
//output converters
protected CollectMultipleConvertedOutputs collectFinalMultipleOutputs;
//a counter to calculate the time spent in a reducer or a combiner
public static enum Counters {COMBINE_OR_REDUCE_TIME };
//the counters to record how many nonZero cells have been produced for each output
protected long[] resultsNonZeros=null;
protected long[] resultsMaxRowDims=null;
protected long[] resultsMaxColDims=null;
protected String dimsUnknownFilePrefix;
//cached reporter to report the number of nonZeros for each reduce task
protected Reporter cachedReporter=null;
protected boolean firsttime=true;
protected String reducerID;
//just for stable aggregation function
//a cache to hold the corrections for aggregation results
protected CachedValueMap correctionCache=new CachedValueMap();
protected void commonSetup(Reporter reporter)
{
if(firsttime)
{
cachedReporter=reporter;
firsttime=false;
}
}
public void configure(JobConf job)
{
super.configure(job);
reducerID = job.get("mapred.task.id");
dimsUnknownFilePrefix = job.get("dims.unknown.file.prefix");
//get the indexes of the final output matrices
resultIndexes=MRJobConfiguration.getResultIndexes(job);
resultDimsUnknown = MRJobConfiguration.getResultDimsUnknown(job);
//initialize SystemML Counters (defined in MRJobConfiguration)
resultsNonZeros=new long[resultIndexes.length];
resultsMaxRowDims=new long[resultIndexes.length];
resultsMaxColDims=new long[resultIndexes.length];
collectFinalMultipleOutputs = MRJobConfiguration.getMultipleConvertedOutputs(job);
//parse aggregate operations
AggregateInstruction[] agg_insts=null;
try {
agg_insts = MRJobConfiguration.getAggregateInstructions(job);
//parse unary and binary operations
MRInstruction[] tmp = MRJobConfiguration.getInstructionsInReducer(job);
if( tmp != null ) {
mixed_instructions=new ArrayList<MRInstruction>();
Collections.addAll(mixed_instructions, tmp);
}
} catch (DMLUnsupportedOperationException e) {
throw new RuntimeException(e);
} catch (DMLRuntimeException e) {
throw new RuntimeException(e);
}
//load data from distributed cache (if required, reuse if jvm_reuse)
try {
setupDistCacheFiles(job);
}
catch(IOException ex)
{
throw new RuntimeException(ex);
}
//reorganize the aggregate instructions, so that they are all associatied with each input
if(agg_insts!=null)
{
for(AggregateInstruction ins: agg_insts)
{
//associate instruction to its input
ArrayList<AggregateInstruction> vec=agg_instructions.get(ins.input);
if(vec==null)
{
vec = new ArrayList<AggregateInstruction>();
agg_instructions.put(ins.input, vec);
}
vec.add(ins);
if(ins.input==ins.output)
continue;
//need to add new aggregate instructions so that partial aggregation can be applied
//this is important for combiner in the reducer side
AggregateInstruction partialIns=
new AggregateInstruction(ins.getOperator(), ins.output, ins.output, ins.toString());
vec=agg_instructions.get(partialIns.input);
if(vec==null)
{
vec=new ArrayList<AggregateInstruction>();
agg_instructions.put(partialIns.input, vec);
}
vec.add(partialIns);
}
}
}
protected void collectOutput_N_Increase_Counter(MatrixIndexes indexes, MatrixValue value,
int i, Reporter reporter) throws IOException
{
collectOutput_N_Increase_Counter(indexes, value, i, reporter, collectFinalMultipleOutputs,
resultDimsUnknown, resultsNonZeros, resultsMaxRowDims, resultsMaxColDims);
}
protected ArrayList<Integer> getOutputIndexes(byte outputTag)
{
ArrayList<Integer> ret = new ArrayList<Integer>();
for(int i=0; i<resultIndexes.length; i++)
if(resultIndexes[i]==outputTag)
ret.add(i);
return ret;
}
protected static ArrayList<Integer> getOutputIndexes(byte outputTag, byte[] resultIndexes)
{
ArrayList<Integer> ret=new ArrayList<Integer>();
for(int i=0; i<resultIndexes.length; i++)
if(resultIndexes[i]==outputTag)
ret.add(i);
return ret;
}
public void close() throws IOException
{
if(cachedReporter!=null)
{
String[] parts = reducerID.split("_");
String jobID = "job_" + parts[1] + "_" + parts[2];
int taskid;
if ( parts[0].equalsIgnoreCase("task")) {
taskid = Integer.parseInt(parts[parts.length-1]);
}
else if ( parts[0].equalsIgnoreCase("attempt")) {
taskid = Integer.parseInt(parts[parts.length-2]);
}
else {
throw new RuntimeException("Unrecognized format for reducerID: " + reducerID);
}
//System.out.println("Inside ReduceBase.close(): ID = " + reducerID + ", taskID = " + taskid);
boolean dimsUnknown = false;
for(int i=0; i<resultIndexes.length; i++) {
cachedReporter.incrCounter(MRJobConfiguration.NUM_NONZERO_CELLS, Integer.toString(i), resultsNonZeros[i]);
if ( resultDimsUnknown!=null && resultDimsUnknown[i] != (byte) 0 ) {
dimsUnknown = true;
// Each counter is of the form: (group, name)
// where group = max_rowdim_resultindex; name = taskid
//System.out.println("--> before i="+i+", row = " + cachedReporter.getCounter("max_rowdim_"+i, ""+taskid).getCounter() + ", col = " + cachedReporter.getCounter("max_coldim_"+i, ""+taskid).getCounter());
//cachedReporter.getCounter(MRJobConfiguration.MAX_ROW_DIMENSION, Integer.toString(i)).increment(resultsMaxRowDims[i]);
//cachedReporter.getCounter(MRJobConfiguration.MAX_COL_DIMENSION, Integer.toString(i)).increment(resultsMaxColDims[i]);
//System.out.println("--> after i="+i+", row = " + cachedReporter.getCounter("max_rowdim_"+i, ""+taskid).getCounter() + ", col = " + cachedReporter.getCounter("max_coldim_"+i, ""+taskid).getCounter());
}
}
//System.out.println("DimsUnknown = " + dimsUnknown);
if ( dimsUnknown ) {
// every task creates a file with max_row and max_col dimensions found in that task
MapReduceTool.writeDimsFile(dimsUnknownFilePrefix + "/" + jobID + "_dimsFile/" + "r_" + taskid , resultDimsUnknown, resultsMaxRowDims, resultsMaxColDims);
}
}
collectFinalMultipleOutputs.close();
}
protected void processReducerInstructions() throws IOException
{
//perform mixed operations
try {
processMixedInstructions(mixed_instructions);
} catch (Exception e) {
throw new IOException(e);
}
}
protected void outputInCombinerFromCachedValues(MatrixIndexes indexes, TaggedMatrixValue taggedbuffer,
OutputCollector<MatrixIndexes, TaggedMatrixValue> out) throws IOException
{
for(byte output: cachedValues.getIndexesOfAll())
{
ArrayList<IndexedMatrixValue> outValues=cachedValues.get(output);
if(outValues==null)
continue;
for(IndexedMatrixValue outValue: outValues)
{
taggedbuffer.setBaseObject(outValue.getValue());
taggedbuffer.setTag(output);
out.collect(indexes, taggedbuffer);
//System.out.println("**** combiner output: "+indexes+", "+taggedbuffer);
}
}
}
protected void outputResultsFromCachedValues(Reporter reporter) throws IOException
{
for(int i=0; i<resultIndexes.length; i++)
{
byte output=resultIndexes[i];
ArrayList<IndexedMatrixValue> outValues=cachedValues.get(output);
if(outValues==null)
continue;
for(IndexedMatrixValue outValue: outValues)
collectOutput_N_Increase_Counter(outValue.getIndexes(),
outValue.getValue(), i, reporter);
// LOG.info("output: "+outValue.getIndexes()+" -- "+outValue.getValue()+" ~~ tag: "+output);
// System.out.println("Reducer output: "+outValue.getIndexes()+" -- "+outValue.getValue()+" ~~ tag: "+output);
}
}
//process one aggregate instruction
/* private void processAggregateHelp(MatrixIndexes indexes, TaggedMatrixValue tagged,
AggregateInstruction instruction)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
AggregateOperator aggOp=(AggregateOperator)instruction.getOperator();
IndexedMatrixValue out=cachedValues.get(instruction.output);
IndexedMatrixValue correction=null;
if(aggOp.correctionExists)
correction=correctionCache.get(instruction.output);
if(out==null)
{
out=cachedValues.holdPlace(instruction.output, valueClass);
out.getIndexes().setIndexes(indexes);
if(aggOp.correctionExists )
{
if(correction==null)
correction=correctionCache.holdPlace(instruction.output, valueClass);
OperationsOnMatrixValues.startAggregation(out.getValue(), correction.getValue(), aggOp,
tagged.getBaseObject().getNumRows(), tagged.getBaseObject().getNumColumns(),
tagged.getBaseObject().isInSparseFormat());
}else
OperationsOnMatrixValues.startAggregation(out.getValue(), null, aggOp,
tagged.getBaseObject().getNumRows(), tagged.getBaseObject().getNumColumns(),
tagged.getBaseObject().isInSparseFormat());
}
if(aggOp.correctionExists)
OperationsOnMatrixValues.incrementalAggregation(out.getValue(), correction.getValue(),
tagged.getBaseObject(), (AggregateOperator)instruction.getOperator());
else
OperationsOnMatrixValues.incrementalAggregation(out.getValue(), null,
tagged.getBaseObject(), (AggregateOperator)instruction.getOperator());
}
*/
//process one aggregate instruction
private void processAggregateHelp(long row, long col, MatrixValue value,
AggregateInstruction instruction, boolean imbededCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
AggregateOperator aggOp=(AggregateOperator)instruction.getOperator();
//there should be just one value in cache.
IndexedMatrixValue out=cachedValues.getFirst(instruction.output);
IndexedMatrixValue correction=null;
if(aggOp.correctionExists)// && !imbededCorrection)
{
correction=correctionCache.getFirst(instruction.output);
}
if(out==null)
{
out=cachedValues.holdPlace(instruction.output, valueClass);
out.getIndexes().setIndexes(row, col);
//System.out.println("out: "+out);
if(aggOp.correctionExists)// && !imbededCorrection)
{
if(correction==null)
correction=correctionCache.holdPlace(instruction.output, valueClass);
OperationsOnMatrixValues.startAggregation(out.getValue(), correction.getValue(), aggOp,
value.getNumRows(), value.getNumColumns(),
value.isInSparseFormat(), imbededCorrection);
}else
OperationsOnMatrixValues.startAggregation(out.getValue(), null, aggOp,
value.getNumRows(), value.getNumColumns(),
value.isInSparseFormat(), imbededCorrection);
//System.out.println("after start: "+out);
}
//System.out.println("value to add: "+value);
if(aggOp.correctionExists)// && !imbededCorrection)
{
//System.out.println("incremental aggregation maxindex/minindex");
OperationsOnMatrixValues.incrementalAggregation(out.getValue(), correction.getValue(),
value, (AggregateOperator)instruction.getOperator(), imbededCorrection);
}
else
OperationsOnMatrixValues.incrementalAggregation(out.getValue(), null,
value, (AggregateOperator)instruction.getOperator(), imbededCorrection);
//System.out.println("after increment: "+out);
}
//process all the aggregate instructions for one group of values
protected void processAggregateInstructions(MatrixIndexes indexes, Iterator<TaggedMatrixValue> values)
throws IOException
{
processAggregateInstructions(indexes, values, false);
}
//process all the aggregate instructions for one group of values
protected void processAggregateInstructions(MatrixIndexes indexes, Iterator<TaggedMatrixValue> values, boolean imbededCorrection)
throws IOException
{
try
{
while(values.hasNext())
{
TaggedMatrixValue value=values.next();
byte input=value.getTag();
ArrayList<AggregateInstruction> instructions=agg_instructions.get(input);
//if there is no specified aggregate operation on an input, by default apply sum
if(instructions==null)
{
defaultAggIns.input=input;
defaultAggIns.output=input;
processAggregateHelp(indexes.getRowIndex(), indexes.getColumnIndex(),
value.getBaseObject(), defaultAggIns, imbededCorrection);
}else //otherwise, perform the specified aggregate instructions
{
for(AggregateInstruction ins: instructions)
processAggregateHelp(indexes.getRowIndex(), indexes.getColumnIndex(),
value.getBaseObject(), ins, imbededCorrection);
}
}
}
catch(Exception e)
{
throw new IOException(e);
}
}
/**
*
* @return
*/
protected boolean containsTernaryInstruction()
{
if( mixed_instructions != null )
for(MRInstruction inst : mixed_instructions)
if( inst instanceof TernaryInstruction )
return true;
return false;
}
protected boolean dimsKnownForTernaryInstructions() {
if( mixed_instructions != null )
for(MRInstruction inst : mixed_instructions)
if( inst instanceof TernaryInstruction && !((TernaryInstruction)inst).knownOutputDims() )
return false;
return true;
}
/**
*
* @param job
*/
protected void prepareMatrixCharacteristicsTernaryInstruction(JobConf job)
{
if( mixed_instructions != null )
for(MRInstruction inst : mixed_instructions)
if( inst instanceof TernaryInstruction )
{
TernaryInstruction tinst = (TernaryInstruction) inst;
if( tinst.input1!=-1 )
dimensions.put(tinst.input1, MRJobConfiguration.getMatrixCharacteristicsForInput(job, tinst.input1));
//extend as required, currently only ctableexpand needs blocksizes
}
}
}
| apache-2.0 |
AMaiyndy/employees | src/main/java/ru/technoserv/dao/DepartmentDao.java | 3026 | package ru.technoserv.dao;
import ru.technoserv.domain.DepWithChildren;
import ru.technoserv.domain.Department;
import ru.technoserv.domain.EmployeeHistory;
import java.util.List;
public interface DepartmentDao {
/**
* Создание нового отдела
*
* @param department подразделение, которое должно быть
* создано
*/
Integer create(Department department);
/**
* Поиск отдела по id
*
* @param depId id искомого отдела
* @return отдел, id которого равняется depId
*/
Department readById(Integer depId);
/**
* Обновление информации по отделу
*
* @param department обновляемый отдел
* @return обновленный отдел
*/
Department updateDept(Department department);
/**
* Удаление отдела, id которого равняется depId
*
* @param depId id удаляемого отдела
*/
void delete(Integer depId);
/**
* Поиск руководителя отдела с id, равным depId
*
* @param depId id отдела, в отношении которого ведется
* поиск руководителя отдела
* @return руководитель отдела с id, равным depId
*/
EmployeeHistory getDeptHead(Integer depId);
/**
* Поиск всех отделов
*
* @return список всех отделов
*/
List<Department> getDepartmentsList();
/**
* Поиск всех дочерних отделов на всех уровнях иерархии
* отдела, id которого равняется depId
*
* @param depId id отдела, в отношении которого ведется
* поиск дочерних отделов
* @return список всех дочерних отделов на всех
* уровнях иерархии отдела, id которого
* равняется depId
*/
List<Department> getAllSubDepts(Integer depId);
/**
* Поиск всех дочерних отделов на один уровень ниже в
* иерархии отдела, id которого равняется depId
*
* @param depId id отдела, в отношении которого ведется
* поиск дочерних отделов
* @return список всех дочерних отделов на один
* уровень ниже в иерархии отдела, id
* которого равняется depId
*/
List<Department> getLevelBelowSubDepts(Integer depId);
List<DepWithChildren> getHierarchy();
}
| apache-2.0 |
8090boy/gomall.la | legendshop_util/src/java/com/legendshop/util/handler/DefaultMapFactoryBean.java | 847 | package com.legendshop.util.handler;
import java.util.Map;
public class DefaultMapFactoryBean extends org.springframework.beans.factory.config.MapFactoryBean {
/** The default key. */
private String defaultKey;
/**
* Create a RbpDefaultKeyMap object with default key.
*
* @return the object
*/
@Override
protected Map createInstance() {
Map<?, ?> map = (Map<?, ?>) super.createInstance();
if (map instanceof DefaultKeyMap) {
((DefaultKeyMap<?, ?>) map).setDefaultKey(this.defaultKey);
}
return map;
}
/**
* Gets the default key.
*
* @return the defaultKey
*/
public String getDefaultKey() {
return this.defaultKey;
}
/**
* Sets the default key.
*
* @param defaultKey
* the defaultKey to set
*/
public void setDefaultKey(String defaultKey) {
this.defaultKey = defaultKey;
}
} | apache-2.0 |
YumoDevTest/AndroidOpenTest | ui/src/main/java/com/yumodev/ui/recyclerview/DragRecyclerView/YmItemTouchHelper.java | 298 | package com.yumodev.ui.recyclerview.DragRecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
/**
* Created by yumodev on 17/4/17.
*/
public class YmItemTouchHelper extends ItemTouchHelper {
public YmItemTouchHelper(Callback callback) {
super(callback);
}
}
| apache-2.0 |
googleapis/java-automl | proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/Operations.java | 19545 | /*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1beta1/operations.proto
package com.google.cloud.automl.v1beta1;
public final class Operations {
private Operations() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_OperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_OperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_DeleteOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_DeleteOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_DeployModelOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_DeployModelOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_UndeployModelOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_UndeployModelOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_CreateModelOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_CreateModelOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ImportDataOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ImportDataOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_ExportDataOutputInfo_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_ExportDataOutputInfo_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_BatchPredictOutputInfo_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_BatchPredictOutputInfo_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_ExportModelOutputInfo_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_ExportModelOutputInfo_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_ExportEvaluatedExamplesOutputInfo_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_ExportEvaluatedExamplesOutputInfo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n,google/cloud/automl/v1beta1/operations"
+ ".proto\022\033google.cloud.automl.v1beta1\032$goo"
+ "gle/cloud/automl/v1beta1/io.proto\032\'googl"
+ "e/cloud/automl/v1beta1/model.proto\0322goog"
+ "le/cloud/automl/v1beta1/model_evaluation"
+ ".proto\032\033google/protobuf/empty.proto\032\037goo"
+ "gle/protobuf/timestamp.proto\032\027google/rpc"
+ "/status.proto\032\034google/api/annotations.pr"
+ "oto\"\213\010\n\021OperationMetadata\022N\n\016delete_deta"
+ "ils\030\010 \001(\01324.google.cloud.automl.v1beta1."
+ "DeleteOperationMetadataH\000\022Y\n\024deploy_mode"
+ "l_details\030\030 \001(\01329.google.cloud.automl.v1"
+ "beta1.DeployModelOperationMetadataH\000\022]\n\026"
+ "undeploy_model_details\030\031 \001(\0132;.google.cl"
+ "oud.automl.v1beta1.UndeployModelOperatio"
+ "nMetadataH\000\022Y\n\024create_model_details\030\n \001("
+ "\01329.google.cloud.automl.v1beta1.CreateMo"
+ "delOperationMetadataH\000\022W\n\023import_data_de"
+ "tails\030\017 \001(\01328.google.cloud.automl.v1beta"
+ "1.ImportDataOperationMetadataH\000\022[\n\025batch"
+ "_predict_details\030\020 \001(\0132:.google.cloud.au"
+ "toml.v1beta1.BatchPredictOperationMetada"
+ "taH\000\022W\n\023export_data_details\030\025 \001(\01328.goog"
+ "le.cloud.automl.v1beta1.ExportDataOperat"
+ "ionMetadataH\000\022Y\n\024export_model_details\030\026 "
+ "\001(\01329.google.cloud.automl.v1beta1.Export"
+ "ModelOperationMetadataH\000\022r\n!export_evalu"
+ "ated_examples_details\030\032 \001(\0132E.google.clo"
+ "ud.automl.v1beta1.ExportEvaluatedExample"
+ "sOperationMetadataH\000\022\030\n\020progress_percent"
+ "\030\r \001(\005\022,\n\020partial_failures\030\002 \003(\0132\022.googl"
+ "e.rpc.Status\022/\n\013create_time\030\003 \001(\0132\032.goog"
+ "le.protobuf.Timestamp\022/\n\013update_time\030\004 \001"
+ "(\0132\032.google.protobuf.TimestampB\t\n\007detail"
+ "s\"\031\n\027DeleteOperationMetadata\"\036\n\034DeployMo"
+ "delOperationMetadata\" \n\036UndeployModelOpe"
+ "rationMetadata\"\036\n\034CreateModelOperationMe"
+ "tadata\"\035\n\033ImportDataOperationMetadata\"\357\001"
+ "\n\033ExportDataOperationMetadata\022b\n\013output_"
+ "info\030\001 \001(\0132M.google.cloud.automl.v1beta1"
+ ".ExportDataOperationMetadata.ExportDataO"
+ "utputInfo\032l\n\024ExportDataOutputInfo\022\036\n\024gcs"
+ "_output_directory\030\001 \001(\tH\000\022!\n\027bigquery_ou"
+ "tput_dataset\030\002 \001(\tH\000B\021\n\017output_location\""
+ "\303\002\n\035BatchPredictOperationMetadata\022J\n\014inp"
+ "ut_config\030\001 \001(\01324.google.cloud.automl.v1"
+ "beta1.BatchPredictInputConfig\022f\n\013output_"
+ "info\030\002 \001(\0132Q.google.cloud.automl.v1beta1"
+ ".BatchPredictOperationMetadata.BatchPred"
+ "ictOutputInfo\032n\n\026BatchPredictOutputInfo\022"
+ "\036\n\024gcs_output_directory\030\001 \001(\tH\000\022!\n\027bigqu"
+ "ery_output_dataset\030\002 \001(\tH\000B\021\n\017output_loc"
+ "ation\"\273\001\n\034ExportModelOperationMetadata\022d"
+ "\n\013output_info\030\002 \001(\0132O.google.cloud.autom"
+ "l.v1beta1.ExportModelOperationMetadata.E"
+ "xportModelOutputInfo\0325\n\025ExportModelOutpu"
+ "tInfo\022\034\n\024gcs_output_directory\030\001 \001(\t\"\356\001\n("
+ "ExportEvaluatedExamplesOperationMetadata"
+ "\022|\n\013output_info\030\002 \001(\0132g.google.cloud.aut"
+ "oml.v1beta1.ExportEvaluatedExamplesOpera"
+ "tionMetadata.ExportEvaluatedExamplesOutp"
+ "utInfo\032D\n!ExportEvaluatedExamplesOutputI"
+ "nfo\022\037\n\027bigquery_output_dataset\030\002 \001(\tB\245\001\n"
+ "\037com.google.cloud.automl.v1beta1P\001ZAgoog"
+ "le.golang.org/genproto/googleapis/cloud/"
+ "automl/v1beta1;automl\312\002\033Google\\Cloud\\Aut"
+ "oMl\\V1beta1\352\002\036Google::Cloud::AutoML::V1b"
+ "eta1b\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.cloud.automl.v1beta1.Io.getDescriptor(),
com.google.cloud.automl.v1beta1.ModelOuterClass.getDescriptor(),
com.google.cloud.automl.v1beta1.ModelEvaluationOuterClass.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
com.google.protobuf.TimestampProto.getDescriptor(),
com.google.rpc.StatusProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_cloud_automl_v1beta1_OperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_automl_v1beta1_OperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_OperationMetadata_descriptor,
new java.lang.String[] {
"DeleteDetails",
"DeployModelDetails",
"UndeployModelDetails",
"CreateModelDetails",
"ImportDataDetails",
"BatchPredictDetails",
"ExportDataDetails",
"ExportModelDetails",
"ExportEvaluatedExamplesDetails",
"ProgressPercent",
"PartialFailures",
"CreateTime",
"UpdateTime",
"Details",
});
internal_static_google_cloud_automl_v1beta1_DeleteOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_automl_v1beta1_DeleteOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_DeleteOperationMetadata_descriptor,
new java.lang.String[] {});
internal_static_google_cloud_automl_v1beta1_DeployModelOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_automl_v1beta1_DeployModelOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_DeployModelOperationMetadata_descriptor,
new java.lang.String[] {});
internal_static_google_cloud_automl_v1beta1_UndeployModelOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_automl_v1beta1_UndeployModelOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_UndeployModelOperationMetadata_descriptor,
new java.lang.String[] {});
internal_static_google_cloud_automl_v1beta1_CreateModelOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_automl_v1beta1_CreateModelOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_CreateModelOperationMetadata_descriptor,
new java.lang.String[] {});
internal_static_google_cloud_automl_v1beta1_ImportDataOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_automl_v1beta1_ImportDataOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ImportDataOperationMetadata_descriptor,
new java.lang.String[] {});
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_descriptor,
new java.lang.String[] {
"OutputInfo",
});
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_ExportDataOutputInfo_descriptor =
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_ExportDataOutputInfo_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportDataOperationMetadata_ExportDataOutputInfo_descriptor,
new java.lang.String[] {
"GcsOutputDirectory", "BigqueryOutputDataset", "OutputLocation",
});
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_descriptor,
new java.lang.String[] {
"InputConfig", "OutputInfo",
});
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_BatchPredictOutputInfo_descriptor =
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_BatchPredictOutputInfo_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_BatchPredictOperationMetadata_BatchPredictOutputInfo_descriptor,
new java.lang.String[] {
"GcsOutputDirectory", "BigqueryOutputDataset", "OutputLocation",
});
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(8);
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_descriptor,
new java.lang.String[] {
"OutputInfo",
});
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_ExportModelOutputInfo_descriptor =
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_ExportModelOutputInfo_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportModelOperationMetadata_ExportModelOutputInfo_descriptor,
new java.lang.String[] {
"GcsOutputDirectory",
});
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(9);
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_descriptor,
new java.lang.String[] {
"OutputInfo",
});
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_ExportEvaluatedExamplesOutputInfo_descriptor =
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_ExportEvaluatedExamplesOutputInfo_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_ExportEvaluatedExamplesOperationMetadata_ExportEvaluatedExamplesOutputInfo_descriptor,
new java.lang.String[] {
"BigqueryOutputDataset",
});
com.google.cloud.automl.v1beta1.Io.getDescriptor();
com.google.cloud.automl.v1beta1.ModelOuterClass.getDescriptor();
com.google.cloud.automl.v1beta1.ModelEvaluationOuterClass.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
com.google.protobuf.TimestampProto.getDescriptor();
com.google.rpc.StatusProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
Cognifide/bobcat | bb-traffic/src/main/java/com/cognifide/qa/bb/proxy/record/har/predicates/PathPrefixPredicate.java | 1756 | /*-
* #%L
* Bobcat
* %%
* Copyright (C) 2016 Cognifide Ltd.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.cognifide.qa.bb.proxy.record.har.predicates;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.common.base.Predicate;
import net.lightbody.bmp.core.har.HarEntry;
/**
* Predicate that matches HarEntries with matching URL path prefix
*/
public class PathPrefixPredicate implements Predicate<HarEntry> {
private final String pathPrefix;
/**
* Constructor. Initializes PathPrefixPredicate with pathPrefix.
*
* @param pathPrefix path prefix
*/
public PathPrefixPredicate(String pathPrefix) {
this.pathPrefix = pathPrefix;
}
@Override
public boolean apply(HarEntry harEntry) {
URL url;
String urlString = harEntry.getRequest().getUrl();
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(String.format("Malformed URL '%s'", urlString), e);
}
String path = url.getPath();
return path.startsWith(pathPrefix);
}
@Override
public String toString() {
return String.format("PathPrefixPredicate(resource path starts with %s)", this.pathPrefix);
}
}
| apache-2.0 |
NeverNight/SimplesPatterns.Java | src/com/arthurb/combining/factory/QuackCounter.java | 1271 | package com.arthurb.combining.factory;
// QuackCounter - декоратор. Как и в паттерне Адаптер, необходимо реализовать целевой интерфейс
public class QuackCounter implements Quackable {
private Quackable duck; // Переменная для хранения декорируемого объекта
private static int numberOfQuacks; // Для подсчета ВСЕХ кряков используется статическая переменная
// В конструкторе получаем ссылку на декорируемую реализацию Quackable
public QuackCounter(Quackable duck) {
this.duck = duck;
}
@Override
public void quack() {
duck.quack(); // Вызов quack() делегируется декорируемой реализации Quackable...
numberOfQuacks++; // ...после чего увеличиваем счетчик
}
// Декоратор дополняется статическим методом, который возвращает количество кряков во всех реализациях Quackable
static int getQuacks() {
return numberOfQuacks;
}
}
| apache-2.0 |
cecom/PACIFy | impl/src/test/java/com/geewhiz/pacify/BugFixing.java | 2179 | /*-
* ========================LICENSE_START=================================
* com.geewhiz.pacify.impl
* %%
* Copyright (C) 2011 - 2017 Sven Oppermann
* %%
* 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.
* =========================LICENSE_END==================================
*/
package com.geewhiz.pacify;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.geewhiz.pacify.defect.Defect;
import com.geewhiz.pacify.utils.LoggingUtils;
public class BugFixing extends TestBase {
Map<String, String> propertiesToUseWhileResolving = new HashMap<String, String>();
@Before
public void before() {
Logger logger = LogManager.getLogger();
LoggingUtils.setLogLevel(logger, Level.ERROR);
propertiesToUseWhileResolving.put("foobar", "foobarValue");
}
@Test
public void Bug1() {
String testFolder = "1_Bugfixing/Bug1";
LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder, createPropertyResolveManager(propertiesToUseWhileResolving));
Assert.assertEquals("We shouldnt get any defects.", 0, defects.size());
}
@Test
public void Bug2() {
String testFolder = "1_Bugfixing/Bug2";
LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder, createPropertyResolveManager(propertiesToUseWhileResolving));
Assert.assertEquals("We shouldnt get any defects.", 0, defects.size());
}
}
| apache-2.0 |
katsuster/strview | view/src/net/katsuster/strview/util/SimpleRange.java | 5005 | package net.katsuster.strview.util;
/**
* <p>
* リスト上の半開区間 [start, end) を表すクラスです。
* </p>
*
* <p>
* end = start + length です。
* </p>
*/
public class SimpleRange<T extends LargeList>
implements Range<T> {
private T buffer;
private long start;
private long length;
/**
* <p>
* バッファ、開始点、終了点を指定せず半開区間を構築します。
* </p>
*/
public SimpleRange() {
this(null, 0, 0);
}
/**
* <p>
* バッファを指定せず、開始点と終了点を指定して半開区間を構築します。
* </p>
*
* @param s 区間の開始地点
* @param l 区間の長さ
*/
public SimpleRange(long s, long l) {
this(null, s, l);
}
/**
* <p>
* バッファ、開始点、終了点を指定して半開区間を構築します。
* </p>
*
* @param b バッファ
* @param s 区間の開始地点
* @param l 区間の長さ
*/
public SimpleRange(T b, long s, long l) {
if (s < 0) {
throw new IllegalArgumentException("start:" + s + " is negative.");
}
if (l != Range.LENGTH_UNKNOWN && l < 0) {
throw new NegativeArraySizeException("length:" + l + " is negative.");
}
buffer = b;
start = s;
length = l;
}
/**
* <p>
* 半開区間を構築します。
* </p>
*
* @param obj 区間
*/
public SimpleRange(Range<T> obj) {
this(obj.getBuffer(), obj.getStart(), obj.getLength());
}
/**
* <p>
* 区間の位置と長さを、
* コピーした新たな区間を返します。
* </p>
*
* @return コピーされたオブジェクト
* @throws CloneNotSupportedException インスタンスを複製できない場合
*/
public Object clone()
throws CloneNotSupportedException {
SimpleRange obj = (SimpleRange)super.clone();
return obj;
}
/**
* <p>
* オブジェクトを指定されたオブジェクトと比較します。
* 結果が true になるのは、引数が null ではなく、
* このオブジェクトと同じ生成元、開始位置、
* 長さを持つオブジェクトである場合だけです。
* </p>
*
* @param obj 比較対象のオブジェクト
* @return オブジェクトが同じである場合は true、そうでない場合は false
*/
@Override
public boolean equals(Object obj) {
SimpleRange objp;
if (!(obj instanceof SimpleRange)) {
return false;
}
objp = (SimpleRange)obj;
if ((buffer != objp.buffer)
|| (start != objp.start)
|| (length != objp.length)) {
return false;
}
return true;
}
/**
* <p>
* オブジェクトのハッシュコードを返します。
* </p>
*
* @return オブジェクトが保持する buffer のハッシュコードと、
* start, length を変換式 (val ^ (val >> 32)) にて int に変換した値を
* 全て xor した値
*/
@Override
public int hashCode() {
int h;
if (buffer == null) {
h = 0;
} else {
h = buffer.hashCode();
}
return (int)(h
^ (start ^ (start >> 32))
^ (length ^ (length >> 32)));
}
@Override
public T getBuffer() {
return buffer;
}
@Override
public void setBuffer(T b) {
buffer = b;
}
@Override
public long getStart() {
return start;
}
@Override
public void setStart(long p) {
if (p < 0) {
throw new IllegalArgumentException("new start:" + p + " is negative.");
}
start = p;
}
@Override
public long getEnd() {
if (length == Range.LENGTH_UNKNOWN) {
return Range.LENGTH_UNKNOWN;
}
return start + length;
}
@Override
public void setEnd(long p) {
if (p < start) {
throw new NegativeArraySizeException("new end:" + p + " is less than start:" + start + ".");
}
length = p - start;
}
@Override
public long getLength() {
return length;
}
@Override
public void setLength(long l) {
if (l != Range.LENGTH_UNKNOWN && l < 0) {
throw new NegativeArraySizeException("new length:" + l + " is negative.");
}
length = l;
}
@Override
public boolean isHit(long i) {
if (getStart() <= i && i < getEnd()) {
return true;
} else {
return false;
}
}
@Override
public String toString() {
return String.format("addr:%d-%d(len:%d)",
getStart(), getEnd(), getLength());
}
}
| apache-2.0 |
harshal/sweble-wikitext | swc-parser-lazy/src/test/java/org/sweble/wikitext/lazy/XPathTest.java | 4065 | /**
* Copyright 2011 The Open Source Research Group,
* University of Erlangen-Nürnberg
*
* 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.sweble.wikitext.lazy;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl;
import org.junit.Test;
import org.sweble.wikitext.lazy.utils.FullParser;
import xtc.parser.ParseException;
import de.fau.cs.osr.ptk.common.AstPrinter;
import de.fau.cs.osr.ptk.common.ast.AstNode;
import de.fau.cs.osr.ptk.common.jxpath.AstNodePointerFactory;
import de.fau.cs.osr.utils.StringUtils;
public class XPathTest
{
private static final String PATH = "/xpath";
private static final boolean WARNINGS_ENABLED = false;
private static final boolean GATHER_RTD = true;
private static final boolean AUTO_CORRECT = false;
private final FullParser parser;
public XPathTest()
{
JXPathContextReferenceImpl.addNodePointerFactory(
new AstNodePointerFactory());
parser = new FullParser(WARNINGS_ENABLED, GATHER_RTD, AUTO_CORRECT);
}
@Test
public void testFrance() throws IOException, ParseException
{
String title = "raw-France";
AstNode ast = parse(title);
JXPathContext context = JXPathContext.newContext(ast);
StringBuilder b = new StringBuilder();
doQuery(context, b, "/*[1]/Paragraph[3]");
doQuery(context, b, "(//Section[@level=3])[1]");
doQuery(context, b, "//Template[contains(name//Text[@content],\"Infobox Country\")]//TemplateArgument[contains(name//Text[@content],\"capital\")]/value");
String actual = b.toString().replace("\r\n", "\n");
String expected = null;
try
{
expected = load(PATH + "/ast/" + title + ".ast");
}
catch (IOException e)
{
}
Assert.assertEquals(expected, actual);
}
@Test
public void testGermany() throws IOException, ParseException
{
String title = "raw-Germany";
AstNode ast = parse(title);
JXPathContext context = JXPathContext.newContext(ast);
StringBuilder b = new StringBuilder();
doQuery(context, b, "//Template[contains(name//Text[@content],\"Infobox country\")]//TemplateArgument[contains(name//Text[@content],\"capital\")]/value");
String actual = b.toString().replace("\r\n", "\n");
String expected = null;
try
{
expected = load(PATH + "/ast/" + title + ".ast");
}
catch (IOException e)
{
}
Assert.assertEquals(expected, actual);
}
private AstNode parse(String title) throws IOException, ParseException
{
AstNode ast = parser.parseArticle(
load(PATH + "/wikitext/" + title + ".wikitext"),
title);
return ast;
}
private String load(String path) throws IOException
{
InputStream in = getClass().getResourceAsStream(path);
if (in == null)
return null;
return IOUtils.toString(in, "UTF-8");
}
private void doQuery(JXPathContext context, StringBuilder b, final String query)
{
b.append(StringUtils.strrep('-', 80));
b.append("\n ");
b.append(query);
b.append('\n');
b.append(StringUtils.strrep('-', 80));
b.append('\n');
int j = 1;
for (Iterator<?> i = context.iterate(query); i.hasNext();)
{
if (j > 1)
{
b.append(StringUtils.strrep('-', 80));
b.append('\n');
}
b.append(AstPrinter.print((AstNode) i.next()));
b.append('\n');
++j;
}
b.append(StringUtils.strrep('=', 80));
b.append('\n');
}
}
| apache-2.0 |
agapsys/console-utils | src/main/java/com/agapsys/utils/console/args/ParsingException.java | 855 | /*
* Copyright 2015 Agapsys Tecnologia Ltda-ME.
*
* 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.agapsys.utils.console.args;
public class ParsingException extends Exception {
public ParsingException(String message, Object...msgArgs) {
super(msgArgs.length > 0 ? String.format(message, msgArgs) : message);
}
}
| apache-2.0 |
tempofeng/lambda-local | lambda-local/src/main/java/com/zaoo/lambda/rest/CrossOrigin.java | 475 | package com.zaoo.lambda.rest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CrossOrigin {
String value() default "*";
String allowedHeaders() default "*";
String allowMethods() default "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE";
}
| apache-2.0 |
plucena/lojamvn | src/test/java/net/mybluemix/parteg/lote/Dados.java | 3045 | package net.mybluemix.parteg.lote;
import java.util.Random;
public class Dados implements AdapterInterfaceDados{
@Override
public Integer dado_fornecedor(Integer fornecedor) {
String fornecedorOk = getFornecedorAleatoria (fornecedor);
Integer fornacedorNum = Integer.parseInt(fornecedorOk);
if (fornecedor > 0) return fornacedorNum;
else return null;
}
@Override
public Integer dado_materiaPrima(Integer materiaPrima) {
String materiaPrimaOk = getMateriaPrimaAleatoria (materiaPrima);
Integer materiaPrimaNum = Integer.parseInt(materiaPrimaOk);
if (materiaPrima > 0) return materiaPrimaNum;
else return null;
}
@Override
public Integer dado_quantidade(Integer quantidade) {
String quantidadeOk = getQuantidadeAleatoria (quantidade);
Integer quantidadeNum = Integer.parseInt(quantidadeOk);
if (quantidade > 0) return quantidadeNum;
else return null;
}
@Override
public Integer dado_unidade(Integer unidade) {
String unidadeOk = getUnidadeAleatoria (unidade);
Integer unidadeNum = Integer.parseInt(unidadeOk);
if (unidade > 0) return unidadeNum;
else return null;
}
@Override
public Integer dado_preco(Integer preco) {
String precoOk = getPrecoAleatoria (preco);
Integer precoNum = Integer.parseInt(precoOk);
if (preco > 0) return precoNum;
else return null;
}
String getFornecedorAleatoria (int fornecedor){
String cadenaAleatoria = "";
long seed = fornecedor;
Random r = new Random(seed);
int i = 0;
while (i < 2){
char c = (char)r.nextInt(255);
if ((c >= '0' && c <='9')){
cadenaAleatoria += c;
i ++;
}}
return cadenaAleatoria;
}
String getMateriaPrimaAleatoria (int materiaPrima){
String cadenaAleatoria = "";
long seed = materiaPrima;
Random r = new Random(seed);
int i = 0;
while (i < 2){
char c = (char)r.nextInt(255);
if ((c >= '0' && c <='9')){
cadenaAleatoria += c;
i ++;
}}
return cadenaAleatoria;
}
String getQuantidadeAleatoria (int quantidade){
String cadenaAleatoria = "";
long seed = quantidade;
Random r = new Random(seed);
int i = 0;
while (i < 3){
char c = (char)r.nextInt(255);
if ((c >= '0' && c <='9')){
cadenaAleatoria += c;
i ++;
}}
return cadenaAleatoria;
}
String getUnidadeAleatoria (int unidade){
String cadenaAleatoria = "";
long seed = unidade;
Random r = new Random(seed);
int i = 0;
while (i < 1){
char c = (char)r.nextInt(255);
if ((c >= '1' && c <='3')){
cadenaAleatoria += c;
i ++;
}}
return cadenaAleatoria;
}
String getPrecoAleatoria (int preco){
String cadenaAleatoria = "";
long seed = preco;
Random r = new Random(seed);
int i = 0;
while (i < 3){
char c = (char)r.nextInt(255);
if ((c >= '0' && c <='9')){
cadenaAleatoria += c;
i ++;
}}
return cadenaAleatoria;
}
}
| apache-2.0 |
palava/palava-core | src/test/java/de/cosmocode/palava/core/FailingListener.java | 865 | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.palava.core;
import java.io.IOException;
/**
* Hidden interface to easily mock listeners.
*
* @author Willi Schoenborn
*/
interface FailingListener {
/**
* Is doing anything.
*/
void doAnything() throws IOException;
}
| apache-2.0 |
markusgumbel/dshl7 | hl7-javasig/gencode/org/hl7/rim/CommunicationFunction.java | 2539 | /*
THIS FILE IS GENERATED AUTOMATICALLY - DO NOT MODIFY.
The contents of this file are subject to the Health Level-7 Public
License Version 1.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.hl7.org/HPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
The Original Code is all this file.
The Initial Developer of the Original Code is automatically generated
from HL7 copyrighted standards specification which may be subject to
different license. Portions created by Initial Developer are Copyright
(C) 2002-2004 Health Level Seven, Inc. All Rights Reserved.
THIS FILE IS GENERATED AUTOMATICALLY - DO NOT MODIFY.
*/
package org.hl7.rim;
import org.hl7.rim.InfrastructureRoot;
import org.hl7.types.CS;
import org.hl7.types.TEL;
import org.hl7.rim.Entity;
import org.hl7.rim.Transmission;
import /*org.hl7.rim.AssociationSet*/java.util.List;
/**<p>Relationship class binds the various entities which function in the transmission (sender, receiver, respond-to) to be linked
to the transmission.
</p>
*/
public interface CommunicationFunction extends org.hl7.rim.InfrastructureRoot {
/**<p>The type of communication function being served by the entity with respect to the transmission, such as sender, receiver,
respond-to party, etc.
</p>
*/
CS getTypeCode();
/** Sets the property typeCode.
@see #getTypeCode
*/
void setTypeCode(CS typeCode);
/**<p>The telecomm address that can be used to reach the entity that is serving this function.</p>
*/
TEL getTelecom();
/** Sets the property telecom.
@see #getTelecom
*/
void setTelecom(TEL telecom);
/**
*/
/*AssociationSet*/List<org.hl7.rim.Entity> getEntity();
/** Sets the property entity.
@see #getEntity
*/
void setEntity(/*AssociationSet*/List<org.hl7.rim.Entity> entity);
/** Adds an association entity.
@see #addEntity
*/
void addEntity(org.hl7.rim.Entity entity);
/**
*/
/*AssociationSet*/List<org.hl7.rim.Transmission> getTransmission();
/** Sets the property transmission.
@see #getTransmission
*/
void setTransmission(/*AssociationSet*/List<org.hl7.rim.Transmission> transmission);
/** Adds an association transmission.
@see #addTransmission
*/
void addTransmission(org.hl7.rim.Transmission transmission);
}
| apache-2.0 |
EixoX/Jetfuel-Java | com.eixox.jetfuel/src/main/java/com/eixox/data/DataTable.java | 2049 | package com.eixox.data;
import java.util.ArrayList;
public class DataTable {
private final ArrayList<DataColumn> columns = new ArrayList<DataColumn>();
private final ArrayList<DataRow> rows = new ArrayList<DataRow>();
private String caption;
private String name;
/**
* @return the caption
*/
public final String getCaption() {
return caption;
}
/**
* @param caption
* the caption to set
*/
public final void setCaption(String caption) {
this.caption = caption;
}
/**
* @return the name
*/
public final String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public final void setName(String name) {
this.name = name;
}
/**
* @return the columns
*/
public final ArrayList<DataColumn> getColumns() {
return columns;
}
/**
* @return the rows
*/
public final ArrayList<DataRow> getRows() {
return rows;
}
public final DataRow add(Object... values) {
DataRow row = new DataRow(this, this.columns.size());
if (values != null && values.length > 0)
for (int i = 0; i < values.length; i++)
row.setValue(i, values[i]);
this.rows.add(row);
return row;
}
public String toHtmlString(String tableClass, String tableStyle) {
StringBuilder builder = new StringBuilder(1024);
builder.append("<table");
builder.append(" class=\"");
builder.append(tableClass);
builder.append("\" style=\"");
builder.append(tableStyle);
builder.append("\">");
builder.append("<thead>");
builder.append("<tr>");
for (DataColumn col : columns) {
builder.append("<th>");
builder.append(col.getCaption());
builder.append("</th>");
}
builder.append("</tr>");
builder.append("</thead>");
builder.append("<tbody>");
for (DataRow row : rows) {
builder.append("<tr>");
for (Object td : row.getData()) {
builder.append("<td>");
builder.append(td);
builder.append("</td>");
}
builder.append("</tr>");
}
builder.append("</tbody>");
builder.append("</table>");
return builder.toString();
}
}
| apache-2.0 |
jaychang0917/SimpleRecyclerView | library/src/main/java/com/jaychang/srv/CellOperations.java | 1055 | package com.jaychang.srv;
import java.util.List;
interface CellOperations {
void addCell(SimpleCell cell);
void addCell(int atPosition, SimpleCell cell);
void addCells(List<? extends SimpleCell> cells);
void addCells(SimpleCell... cells);
void addCells(int fromPosition, List<? extends SimpleCell> cells);
void addCells(int fromPosition, SimpleCell... cells);
<T extends SimpleCell & Updatable> void addOrUpdateCell(T cell);
<T extends SimpleCell & Updatable> void addOrUpdateCells(List<T> cells);
<T extends SimpleCell & Updatable> void addOrUpdateCells(T... cells);
void removeCell(SimpleCell cell);
void removeCell(int atPosition);
void removeCells(int fromPosition, int toPosition);
void removeCells(int fromPosition);
void removeAllCells();
void updateCell(int atPosition, Object payload);
void updateCells(int fromPosition, int toPosition, Object payloads);
SimpleCell getCell(int atPosition);
List<SimpleCell> getCells(int fromPosition, int toPosition);
List<SimpleCell> getAllCells();
}
| apache-2.0 |
thymeleaf/thymeleaf-spring | thymeleaf-spring6/src/main/java/org/thymeleaf/spring6/context/Contexts.java | 2688 | /*
* =============================================================================
*
* Copyright (c) 2011-2022, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.spring6.context;
import org.thymeleaf.context.IContext;
import org.thymeleaf.context.IEngineContext;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.spring6.web.webflux.ISpringWebFluxWebExchange;
import org.thymeleaf.web.IWebExchange;
import org.thymeleaf.web.servlet.IServletWebExchange;
public final class Contexts {
private Contexts() {
super();
}
public static boolean isEngineContext(final IContext context) {
return org.thymeleaf.context.Contexts.isEngineContext(context);
}
public static IEngineContext asEngineContext(final IContext context) {
return org.thymeleaf.context.Contexts.asEngineContext(context);
}
public static boolean isWebContext(final IContext context) {
return org.thymeleaf.context.Contexts.isWebContext(context);
}
public static IWebContext asWebContext(final IContext context) {
return org.thymeleaf.context.Contexts.asWebContext(context);
}
public static IWebExchange getWebExchange(final IContext context) {
return org.thymeleaf.context.Contexts.getWebExchange(context);
}
public static boolean isServletWebContext(final IContext context) {
return org.thymeleaf.context.Contexts.isServletWebContext(context);
}
public static IServletWebExchange getServletWebExchange(final IContext context) {
return org.thymeleaf.context.Contexts.getServletWebExchange(context);
}
public static boolean isSpringWebFluxWebContext(final IContext context) {
return isWebContext(context) && (asWebContext(context).getExchange() instanceof ISpringWebFluxWebExchange);
}
public static ISpringWebFluxWebExchange getSpringWebFluxWebExchange(final IContext context) {
return (ISpringWebFluxWebExchange) asWebContext(context).getExchange();
}
}
| apache-2.0 |
gchq/stroom | stroom-legacy/stroom-legacy-model_6_1/src/main/java/stroom/legacy/model_6_1/EntityMarshaller.java | 2833 | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.legacy.model_6_1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import javax.xml.bind.JAXBContext;
@Deprecated
public abstract class EntityMarshaller<E extends BaseEntity, O> implements Marshaller<E, O> {
private static final Logger LOGGER = LoggerFactory.getLogger(EntityMarshaller.class);
private final JAXBContext jaxbContext;
public EntityMarshaller() {
try {
jaxbContext = JAXBContextCache.get(getObjectType());
} catch (final RuntimeException e) {
LOGGER.error(MarkerFactory.getMarker("FATAL"), "Unable to create new JAXBContext for object type!", e);
throw new RuntimeException(e.getMessage());
}
}
@Override
public E marshal(final E entity) {
try {
Object object = getObject(entity);
// Strip out references to empty collections.
try {
object = XMLMarshallerUtil.removeEmptyCollections(object);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
final String data = XMLMarshallerUtil.marshal(jaxbContext, object);
setData(entity, data);
} catch (final Exception e) {
LOGGER.debug("Problem marshaling {} {}", new Object[]{entity.getClass(), entity.getId()}, e);
LOGGER.warn("Problem marshaling {} {} - {} (enable debug for full trace)", new Object[]{entity.getClass(),
entity.getId(), String.valueOf(e)});
}
return entity;
}
@Override
public E unmarshal(final E entity) {
try {
final String data = getData(entity);
final O object = XMLMarshallerUtil.unmarshal(jaxbContext, getObjectType(), data);
setObject(entity, object);
} catch (final Exception e) {
LOGGER.debug("Unable to unmarshal entity!", e);
LOGGER.warn(e.getMessage());
}
return entity;
}
protected abstract String getData(E entity);
protected abstract void setData(E entity, String data);
protected abstract Class<O> getObjectType();
protected abstract String getEntityType();
}
| apache-2.0 |
PkayJava/fintech | src/main/java/com/angkorteam/fintech/pages/IndexPage.java | 1485 | package com.angkorteam.fintech.pages;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.PropertyModel;
import com.angkorteam.fintech.Page;
import com.angkorteam.fintech.dto.Function;
import com.angkorteam.framework.wicket.ajax.markup.html.AjaxLink;
import com.angkorteam.framework.wicket.markup.html.form.select2.Option;
@AuthorizeInstantiation(Function.ALL_FUNCTION)
public class IndexPage extends Page {
protected Option test;
protected Label pp;
protected AjaxLink<Void> ss;
@Override
protected void initData() {
}
@Override
protected void initComponent() {
this.pp = new Label("pp", new PropertyModel<>(this, "test.text"));
this.pp.setOutputMarkupId(true);
add(this.pp);
this.ss = new AjaxLink<>("ss");
this.ss.setOnClick(this::ssOnClick);
this.add(this.ss);
// ElasticsearchTemplate template = new ElasticsearchTemplate(client);
// ElasticsearchRepositoryFactory factory = new
// ElasticsearchRepositoryFactory(template);
}
@Override
protected void configureMetaData() {
}
protected boolean ssOnClick(AjaxLink<Void> link, AjaxRequestTarget target) {
this.test = new Option("ss", "vvvvvvvvvvv");
target.add(this.pp);
return false;
}
}
| apache-2.0 |
aehlig/bazel | src/test/java/com/google/devtools/build/lib/pkgcache/PackageCacheTest.java | 21589 | // Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.pkgcache;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static org.junit.Assert.fail;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ServerDirectories;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.util.AnalysisMock;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.BuildFileContainsErrorsException;
import com.google.devtools.build.lib.packages.NoSuchPackageException;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.PackageFactory;
import com.google.devtools.build.lib.packages.StarlarkSemanticsOptions;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction;
import com.google.devtools.build.lib.skyframe.BazelSkyframeExecutorConstants;
import com.google.devtools.build.lib.skyframe.PrecomputedValue;
import com.google.devtools.build.lib.skyframe.SkyframeExecutor;
import com.google.devtools.build.lib.syntax.StarlarkFile;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for package loading. */
@RunWith(JUnit4.class)
public class PackageCacheTest extends FoundationTestCase {
private AnalysisMock analysisMock;
private ConfiguredRuleClassProvider ruleClassProvider;
private SkyframeExecutor skyframeExecutor;
private final ActionKeyContext actionKeyContext = new ActionKeyContext();
@Before
public final void initializeSkyframeExecutor() throws Exception {
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ true);
}
/**
* @param doPackageLoadingChecks when true, a PackageLoader will be called after each package load
* this test performs, and the results compared to SkyFrame's result.
*/
private void initializeSkyframeExecutor(boolean doPackageLoadingChecks) throws Exception {
analysisMock = AnalysisMock.get();
ruleClassProvider = analysisMock.createRuleClassProvider();
BlazeDirectories directories =
new BlazeDirectories(
new ServerDirectories(outputBase, outputBase, outputBase),
rootDirectory,
/* defaultSystemJavabase= */ null,
analysisMock.getProductName());
PackageFactory.BuilderForTesting packageFactoryBuilder =
analysisMock.getPackageFactoryBuilderForTesting(directories);
if (!doPackageLoadingChecks) {
packageFactoryBuilder.disableChecks();
}
BuildOptions defaultBuildOptions;
try {
defaultBuildOptions = BuildOptions.of(ImmutableList.of());
} catch (OptionsParsingException e) {
throw new RuntimeException(e);
}
skyframeExecutor =
BazelSkyframeExecutorConstants.newBazelSkyframeExecutorBuilder()
.setPkgFactory(packageFactoryBuilder.build(ruleClassProvider, fileSystem))
.setFileSystem(fileSystem)
.setDirectories(directories)
.setActionKeyContext(actionKeyContext)
.setDefaultBuildOptions(defaultBuildOptions)
.setExtraSkyFunctions(analysisMock.getSkyFunctions(directories))
.build();
TestConstants.processSkyframeExecutorForTesting(skyframeExecutor);
setUpSkyframe(parsePackageCacheOptions(), parseSkylarkSemanticsOptions());
}
private void setUpSkyframe(
PackageCacheOptions packageCacheOptions, StarlarkSemanticsOptions starlarkSemanticsOptions) {
PathPackageLocator pkgLocator =
PathPackageLocator.create(
null,
packageCacheOptions.packagePath,
reporter,
rootDirectory,
rootDirectory,
BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY);
packageCacheOptions.showLoadingProgress = true;
packageCacheOptions.globbingThreads = 7;
skyframeExecutor.injectExtraPrecomputedValues(
ImmutableList.of(
PrecomputedValue.injected(
RepositoryDelegatorFunction.RESOLVED_FILE_INSTEAD_OF_WORKSPACE,
Optional.<RootedPath>absent())));
skyframeExecutor.preparePackageLoading(
pkgLocator,
packageCacheOptions,
starlarkSemanticsOptions,
UUID.randomUUID(),
ImmutableMap.<String, String>of(),
new TimestampGranularityMonitor(BlazeClock.instance()));
skyframeExecutor.setActionEnv(ImmutableMap.<String, String>of());
skyframeExecutor.setDeletedPackages(
ImmutableSet.copyOf(packageCacheOptions.getDeletedPackages()));
}
private OptionsParser parse(String... options) throws Exception {
OptionsParser parser =
OptionsParser.builder()
.optionsClasses(PackageCacheOptions.class, StarlarkSemanticsOptions.class)
.build();
parser.parse("--default_visibility=public");
parser.parse(options);
return parser;
}
private PackageCacheOptions parsePackageCacheOptions(String... options) throws Exception {
return parse(options).getOptions(PackageCacheOptions.class);
}
private StarlarkSemanticsOptions parseSkylarkSemanticsOptions(String... options)
throws Exception {
return parse(options).getOptions(StarlarkSemanticsOptions.class);
}
protected void setOptions(String... options) throws Exception {
setUpSkyframe(parsePackageCacheOptions(options), parseSkylarkSemanticsOptions(options));
}
private PackageManager getPackageManager() {
return skyframeExecutor.getPackageManager();
}
private void invalidatePackages() throws InterruptedException {
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
}
private Package getPackage(String packageName)
throws NoSuchPackageException, InterruptedException {
return getPackageManager()
.getPackage(reporter, PackageIdentifier.createInMainRepo(packageName));
}
private Target getTarget(Label label)
throws NoSuchPackageException, NoSuchTargetException, InterruptedException {
return getPackageManager().getTarget(reporter, label);
}
private Target getTarget(String label) throws Exception {
return getTarget(Label.parseAbsolute(label, ImmutableMap.of()));
}
private void createPkg1() throws IOException {
scratch.file("pkg1/BUILD", "cc_library(name = 'foo') # a BUILD file");
}
// Check that a substring is present in an error message.
private void checkGetPackageFails(String packageName, String expectedMessage) throws Exception {
NoSuchPackageException e =
assertThrows(NoSuchPackageException.class, () -> getPackage(packageName));
assertThat(e).hasMessageThat().contains(expectedMessage);
}
@Test
public void testGetPackage() throws Exception {
createPkg1();
Package pkg1 = getPackage("pkg1");
assertThat(pkg1.getName()).isEqualTo("pkg1");
assertThat(pkg1.getFilename().asPath().getPathString()).isEqualTo("/workspace/pkg1/BUILD");
assertThat(getPackageManager().getPackage(reporter, PackageIdentifier.createInMainRepo("pkg1")))
.isSameInstanceAs(pkg1);
}
@Test
public void testASTIsNotRetained() throws Exception {
createPkg1();
Package pkg1 = getPackage("pkg1");
MoreAsserts.assertInstanceOfNotReachable(pkg1, StarlarkFile.class);
}
@Test
public void testGetNonexistentPackage() throws Exception {
checkGetPackageFails("not-there", "no such package 'not-there': " + "BUILD file not found");
}
@Test
public void testGetPackageWithInvalidName() throws Exception {
scratch.file("invalidpackagename:42/BUILD", "cc_library(name = 'foo') # a BUILD file");
checkGetPackageFails(
"invalidpackagename:42",
"no such package 'invalidpackagename:42': Invalid package name 'invalidpackagename:42'");
}
@Test
public void testGetTarget() throws Exception {
createPkg1();
Label label = Label.parseAbsolute("//pkg1:foo", ImmutableMap.of());
Target target = getTarget(label);
assertThat(target.getLabel()).isEqualTo(label);
}
@Test
public void testGetNonexistentTarget() throws Exception {
createPkg1();
NoSuchTargetException e =
assertThrows(NoSuchTargetException.class, () -> getTarget("//pkg1:not-there"));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"no such target '//pkg1:not-there': target 'not-there' "
+ "not declared in package 'pkg1' defined by /workspace/pkg1/BUILD");
}
/**
* A missing package is one for which no BUILD file can be found. The PackageCache caches failures
* of this kind until the next sync.
*/
@Test
public void testRepeatedAttemptsToParseMissingPackage() throws Exception {
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
// Still missing:
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
// Update the BUILD file on disk so "missing" is no longer missing:
scratch.file("missing/BUILD", "# an ok build file");
// Still missing:
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
invalidatePackages();
// Found:
Package missing = getPackage("missing");
assertThat(missing.getName()).isEqualTo("missing");
}
/**
* A broken package is one that exists but contains lexer/parser/evaluator errors. The
* PackageCache only makes one attempt to parse each package once found.
*
* <p>Depending on the strictness of the PackageFactory, parsing a broken package may cause a
* Package object to be returned (possibly missing some rules) or an exception to be thrown. For
* this test we need that strict behavior.
*
* <p>Note: since the PackageCache.setStrictPackageCreation method was deleted (since it wasn't
* used by any significant clients) creating a "broken" build file got trickier--syntax errors are
* not enough. For now, we create an unreadable BUILD file, which will cause an IOException to be
* thrown. This test seems less valuable than it once did.
*/
@Test
public void testParseBrokenPackage() throws Exception {
reporter.removeHandler(failFastHandler);
Path brokenBuildFile = scratch.file("broken/BUILD");
brokenBuildFile.setReadable(false);
BuildFileContainsErrorsException e =
assertThrows(BuildFileContainsErrorsException.class, () -> getPackage("broken"));
assertThat(e).hasMessageThat().contains("/workspace/broken/BUILD (Permission denied)");
eventCollector.clear();
// Update the BUILD file on disk so "broken" is no longer broken:
scratch.overwriteFile("broken/BUILD", "# an ok build file");
invalidatePackages(); // resets cache of failures
Package broken = getPackage("broken");
assertThat(broken.getName()).isEqualTo("broken");
assertNoEvents();
}
@Test
public void testMovedBuildFileCausesReloadAfterSync() throws Exception {
// PackageLoader doesn't support --package_path.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
Path buildFile1 = scratch.file("pkg/BUILD", "cc_library(name = 'foo')");
Path buildFile2 = scratch.file("/otherroot/pkg/BUILD", "cc_library(name = 'bar')");
setOptions("--package_path=/workspace:/otherroot");
Package oldPkg = getPackage("pkg");
assertThat(getPackage("pkg")).isSameInstanceAs(oldPkg); // change not yet visible
assertThat(oldPkg.getFilename().asPath()).isEqualTo(buildFile1);
assertThat(oldPkg.getSourceRoot()).isEqualTo(Root.fromPath(rootDirectory));
buildFile1.delete();
invalidatePackages();
Package newPkg = getPackage("pkg");
assertThat(newPkg).isNotSameInstanceAs(oldPkg);
assertThat(newPkg.getFilename().asPath()).isEqualTo(buildFile2);
assertThat(newPkg.getSourceRoot()).isEqualTo(Root.fromPath(scratch.dir("/otherroot")));
// TODO(bazel-team): (2009) test BUILD file moves in the other direction too.
}
private Path rootDir1;
private Path rootDir2;
private void setUpCacheWithTwoRootLocator() throws Exception {
// Root 1:
// /a/BUILD
// /b/BUILD
// /c/d
// /c/e
//
// Root 2:
// /b/BUILD
// /c/BUILD
// /c/d/BUILD
// /f/BUILD
// /f/g
// /f/g/h/BUILD
rootDir1 = scratch.dir("/workspace");
rootDir2 = scratch.dir("/otherroot");
createBuildFile(rootDir1, "a", "foo.txt", "bar/foo.txt");
createBuildFile(rootDir1, "b", "foo.txt", "bar/foo.txt");
rootDir1.getRelative("c").createDirectory();
rootDir1.getRelative("c/d").createDirectory();
rootDir1.getRelative("c/e").createDirectory();
createBuildFile(rootDir2, "c", "d", "d/foo.txt", "foo.txt", "bar/foo.txt", "e", "e/foo.txt");
createBuildFile(rootDir2, "c/d", "foo.txt");
createBuildFile(rootDir2, "f", "g/foo.txt", "g/h", "g/h/foo.txt", "foo.txt");
createBuildFile(rootDir2, "f/g/h", "foo.txt");
setOptions("--package_path=/workspace:/otherroot");
}
protected Path createBuildFile(Path workspace, String packageName, String... targets)
throws IOException {
String[] lines = new String[targets.length];
for (int i = 0; i < targets.length; i++) {
lines[i] = "sh_library(name='" + targets[i] + "')";
}
return scratch.file(workspace + "/" + packageName + "/BUILD", lines);
}
private void assertLabelValidity(boolean expected, String labelString) throws Exception {
Label label = Label.parseAbsolute(labelString, ImmutableMap.of());
boolean actual = false;
String error = null;
try {
getTarget(label);
actual = true;
} catch (NoSuchPackageException | NoSuchTargetException e) {
error = e.getMessage();
}
if (actual != expected) {
fail(
"assertLabelValidity("
+ label
+ ") "
+ actual
+ ", not equal to expected value "
+ expected
+ " (error="
+ error
+ ")");
}
}
private void assertPackageLoadingFails(String pkgName, String expectedError) throws Exception {
Package pkg = getPackage(pkgName);
assertThat(pkg.containsErrors()).isTrue();
assertContainsEvent(expectedError);
}
@Test
public void testLocationForLabelCrossingSubpackage() throws Exception {
scratch.file("e/f/BUILD");
scratch.file("e/BUILD", "# Whatever", "filegroup(name='fg', srcs=['f/g'])");
reporter.removeHandler(failFastHandler);
List<Event> events = getPackage("e").getEvents();
assertThat(events).hasSize(1);
assertThat(events.get(0).getLocation().getStartLineAndColumn().getLine()).isEqualTo(2);
}
/** Static tests (i.e. no changes to filesystem, nor calls to sync). */
@Test
public void testLabelValidity() throws Exception {
// PackageLoader doesn't support --package_path.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
reporter.removeHandler(failFastHandler);
setUpCacheWithTwoRootLocator();
scratch.file(rootDir2 + "/c/d/foo.txt");
assertLabelValidity(true, "//a:foo.txt");
assertLabelValidity(true, "//a:bar/foo.txt");
assertLabelValidity(false, "//a/bar:foo.txt"); // no such package a/bar
assertLabelValidity(true, "//b:foo.txt");
assertLabelValidity(true, "//b:bar/foo.txt");
assertLabelValidity(false, "//b/bar:foo.txt"); // no such package b/bar
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(true, "//c:bar/foo.txt");
assertLabelValidity(false, "//c/bar:foo.txt"); // no such package c/bar
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(false, "//c:d/foo.txt"); // crosses boundary of c/d
assertLabelValidity(true, "//c/d:foo.txt");
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(true, "//c:e");
assertLabelValidity(true, "//c:e/foo.txt");
assertLabelValidity(false, "//c/e:foo.txt"); // no such package c/e
assertLabelValidity(true, "//f:foo.txt");
assertLabelValidity(true, "//f:g/foo.txt");
assertLabelValidity(false, "//f/g:foo.txt"); // no such package f/g
assertLabelValidity(false, "//f:g/h/foo.txt"); // crosses boundary of f/g/h
assertLabelValidity(false, "//f/g:h/foo.txt"); // no such package f/g
assertLabelValidity(true, "//f/g/h:foo.txt");
}
/** Dynamic tests of label validity. */
@Test
public void testAddedBuildFileCausesLabelToBecomeInvalid() throws Exception {
reporter.removeHandler(failFastHandler);
scratch.file("pkg/BUILD", "cc_library(name = 'foo', srcs = ['x/y.cc'])");
assertLabelValidity(true, "//pkg:x/y.cc");
// The existence of this file makes 'x/y.cc' an invalid reference.
scratch.file("pkg/x/BUILD");
// but not yet...
assertLabelValidity(true, "//pkg:x/y.cc");
invalidatePackages();
// now:
assertPackageLoadingFails(
"pkg", "Label '//pkg:x/y.cc' is invalid because 'pkg/x' is a subpackage");
}
@Test
public void testDeletedPackages() throws Exception {
// PackageLoader doesn't support --deleted_packages.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
reporter.removeHandler(failFastHandler);
setUpCacheWithTwoRootLocator();
createBuildFile(rootDir1, "c", "d/x");
// Now package c exists in both roots, and c/d exists in only in the second
// root. It's as if we've merged c and c/d in the first root.
// c/d is still a subpackage--found in the second root:
assertThat(getPackage("c/d").getFilename().asPath())
.isEqualTo(rootDir2.getRelative("c/d/BUILD"));
// Subpackage labels are still valid...
assertLabelValidity(true, "//c/d:foo.txt");
// ...and this crosses package boundaries:
assertLabelValidity(false, "//c:d/x");
assertPackageLoadingFails(
"c",
"Label '//c:d/x' is invalid because 'c/d' is a subpackage; have you deleted c/d/BUILD? "
+ "If so, use the --deleted_packages=c/d option");
assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d")))
.isTrue();
setOptions("--deleted_packages=c/d");
invalidatePackages();
assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d")))
.isFalse();
// c/d is no longer a subpackage--even though there's a BUILD file in the
// second root:
NoSuchPackageException e = assertThrows(NoSuchPackageException.class, () -> getPackage("c/d"));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"no such package 'c/d': Package is considered deleted due to --deleted_packages");
// Labels in the subpackage are no longer valid...
assertLabelValidity(false, "//c/d:x");
// ...and now d is just a subdirectory of c:
assertLabelValidity(true, "//c:d/x");
}
@Test
public void testPackageFeatures() throws Exception {
scratch.file(
"peach/BUILD",
"package(features = ['crosstool_default_false'])",
"cc_library(name = 'cc', srcs = ['cc.cc'])");
assertThat(getPackage("peach").getFeatures()).hasSize(1);
}
@Test
public void testBrokenPackageOnMultiplePackagePathEntries() throws Exception {
reporter.removeHandler(failFastHandler);
setOptions("--package_path=.:.");
scratch.file("x/y/BUILD");
scratch.file("x/BUILD", "genrule(name = 'x',", "srcs = [],", "outs = ['y/z.h'],", "cmd = '')");
Package p = getPackage("x");
assertThat(p.containsErrors()).isTrue();
}
}
| apache-2.0 |
lorislab/appky | appky-web/src/main/java/org/lorislab/appky/web/admin/user/action/UserResetPasswordAction.java | 1521 | /*
* Copyright 2014 lorislab.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.lorislab.appky.web.admin.user.action;
import org.lorislab.appky.web.admin.user.view.ResetPasswordViewController;
import org.lorislab.jel.jsf.view.AbstractViewControllerAction;
/**
* The user reset password action.
*
* @author Andrej Petras <andrej@ajka-andrej.com>
*/
public class UserResetPasswordAction extends AbstractViewControllerAction<ResetPasswordViewController> {
/**
* The UID for this class.
*/
private static final long serialVersionUID = 8170952895561648531L;
/**
* The default constructor.
*
* @param parent the reset password view controller.
*/
public UserResetPasswordAction(ResetPasswordViewController parent) {
super(parent);
}
/**
* {@inheritDoc}
*/
@Override
public Object execute() throws Exception {
Object result = null;
getParent().resetPassword();
return result;
}
}
| apache-2.0 |
java-config/tamaya-export | api/src/main/java/org/apache/tamaya/annot/DefaultAreas.java | 1378 | /*
* 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.tamaya.annot;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to control injection and resolution of a configured bean.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
public @interface DefaultAreas {
/**
* Allows to declare an operator that should be applied before injecting values into the bean.
* @return the operator class to be used.
*/
String[] value();
}
| apache-2.0 |
10045125/KJFrameForAndroid | KJFrame/src/org/kymjs/kjframe/plugin/I_CJService.java | 1769 | /*
* Copyright (c) 2014,KJFrameForAndroid 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.kymjs.kjframe.plugin;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
/**
* CJFrameService接口协议,插件Service必须实现此接口<br>
* Service实现此接口意味着将插件的Service生命周期交給CJFrame托管, 而不再是SDK托管<br>
*
* <b>创建时间</b> 2014-10-15 <br>
*
* @author kymjs(kymjs123@gmail.com)
* @version 1.0
*/
public interface I_CJService {
IBinder onBind(Intent intent);
void onCreate();
int onStartCommand(Intent intent, int flags, int startId);
void onDestroy();
void onConfigurationChanged(Configuration newConfig);
void onLowMemory();
void onTrimMemory(int level);
boolean onUnbind(Intent intent);
void onRebind(Intent intent);
void onTaskRemoved(Intent rootIntent);
/**
* 设置托管Service,并将that指针指向那个托管的Service
*
* @param proxyService
* @param dexPath
*/
void setProxy(Service proxyService, String dexPath);
}
| apache-2.0 |
smanvi-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/cache/ClientServerInvalidAndDestroyedEntryDUnitTest.java | 21581 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import static org.apache.geode.distributed.ConfigurationProperties.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.LogWriter;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.InterestResultPolicy;
import org.apache.geode.cache.Operation;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.tier.InterestType;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.SerializableCallable;
import org.apache.geode.test.dunit.SerializableCallableIF;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.junit.categories.ClientServerTest;
import org.apache.geode.test.junit.categories.DistributedTest;
/**
* This tests the fix for bug #43407 under a variety of configurations and also tests that
* tombstones are treated in a similar manner. The ticket complains that a client that does a get(K)
* does not end up with the entry in its cache if K is invalid on the server.
*/
@Category({DistributedTest.class, ClientServerTest.class})
public class ClientServerInvalidAndDestroyedEntryDUnitTest extends JUnit4CacheTestCase {
@Override
public final void postSetUp() throws Exception {
disconnectAllFromDS();
}
@Test
public void testClientGetsInvalidEntry() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsInvalidEntry(regionName, false, false);
}
@Test
public void testClientGetsInvalidEntryPR() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsInvalidEntry(regionName, true, false);
}
@Test
public void testClientGetsTombstone() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsTombstone(regionName, false, false);
}
@Test
public void testClientGetsTombstonePR() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsTombstone(regionName, true, false);
}
// same tests but with transactions...
@Test
public void testClientGetsInvalidEntryTX() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsInvalidEntry(regionName, false, true);
}
@Test
public void testClientGetsInvalidEntryPRTX() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsInvalidEntry(regionName, true, true);
}
@Test
public void testClientGetsTombstoneTX() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsTombstone(regionName, false, true);
}
@Test
public void testClientGetsTombstonePRTX() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestClientGetsTombstone(regionName, true, true);
}
// tests for bug #46780, tombstones left in client after RI
@Test
public void testRegisterInterestRemovesOldEntry() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestRegisterInterestRemovesOldEntry(regionName, false);
}
@Test
public void testRegisterInterestRemovesOldEntryPR() throws Exception {
final String regionName = getUniqueName() + "Region";
doTestRegisterInterestRemovesOldEntry(regionName, true);
}
/* this method creates a server cache and is used by all of the tests in this class */
private SerializableCallableIF getCreateServerCallable(final String regionName,
final boolean usePR) {
return new SerializableCallable("create server and entries") {
public Object call() {
Cache cache = getCache();
List<CacheServer> servers = cache.getCacheServers();
CacheServer server;
if (servers.size() > 0) {
server = servers.get(0);
} else {
server = cache.addCacheServer();
int port = AvailablePortHelper.getRandomAvailableTCPPort();
server.setPort(port);
server.setHostnameForClients("localhost");
try {
server.start();
} catch (IOException e) {
Assert.fail("Failed to start server ", e);
}
}
if (usePR) {
RegionFactory factory = cache.createRegionFactory(RegionShortcut.PARTITION);
PartitionAttributesFactory pf = new PartitionAttributesFactory();
pf.setTotalNumBuckets(2);
factory.setPartitionAttributes(pf.create());
factory.create(regionName);
} else {
cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
}
return server.getPort();
}
};
}
/**
* Bug #43407 - when a client does a get(k) and the entry is invalid in the server we want the
* client to end up with an entry that is invalid.
*/
private void doTestClientGetsInvalidEntry(final String regionName, final boolean usePR,
boolean useTX) throws Exception {
VM vm1 = Host.getHost(0).getVM(1);
VM vm2 = Host.getHost(0).getVM(2);
// here are the keys that will be used to validate behavior. Keys must be
// colocated if using both a partitioned region in the server and transactions
// in the client. All of these keys hash to bucket 0 in a two-bucket PR
// except Object11 and IDoNotExist1
final String notAffectedKey = "Object1";
final String nonexistantKey = (usePR && useTX) ? "IDoNotExist2" : "IDoNotExist1";
final String key1 = "Object10";
final String key2 = (usePR && useTX) ? "Object12" : "Object11";
SerializableCallableIF createServer = getCreateServerCallable(regionName, usePR);
int serverPort = (Integer) vm1.invoke(createServer);
vm2.invoke(createServer);
vm1.invoke(new SerializableRunnable("populate server and create invalid entry") {
public void run() {
Region myRegion = getCache().getRegion(regionName);
for (int i = 1; i <= 20; i++) {
myRegion.put("Object" + i, "Value" + i);
}
myRegion.invalidate(key1);
myRegion.invalidate(key2);
}
});
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("creating client cache");
ClientCache c = new ClientCacheFactory().addPoolServer("localhost", serverPort)
.set(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel()).create();
Region myRegion =
c.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);;
if (useTX) {
c.getCacheTransactionManager().begin();
}
// get of a valid entry should work
assertNotNull(myRegion.get(notAffectedKey));
// get of an invalid entry should return null and create the entry in an invalid state
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
.info("getting " + key1 + " - should reach this cache and be INVALID");
assertNull(myRegion.get(key1));
assertTrue(myRegion.containsKey(key1));
// since this might be a PR we also check the next key to force PR Get messaging
assertNull(myRegion.get(key2));
assertTrue(myRegion.containsKey(key2));
// now try a key that doesn't exist anywhere
assertNull(myRegion.get(nonexistantKey));
assertFalse(myRegion.containsKey(nonexistantKey));
if (useTX) {
c.getCacheTransactionManager().commit();
// test that the commit correctly created the entries in the region
assertNotNull(myRegion.get(notAffectedKey));
assertNull(myRegion.get(key1));
assertTrue(myRegion.containsKey(key1));
assertNull(myRegion.get(key2));
assertTrue(myRegion.containsKey(key2));
}
myRegion.localDestroy(notAffectedKey);
myRegion.localDestroy(key1);
myRegion.localDestroy(key2);
if (useTX) {
c.getCacheTransactionManager().begin();
}
// check that getAll returns invalidated entries
List keys = new LinkedList();
keys.add(notAffectedKey);
keys.add(key1);
keys.add(key2);
Map result = myRegion.getAll(keys);
assertNotNull(result.get(notAffectedKey));
assertNull(result.get(key1));
assertNull(result.get(key2));
assertTrue(result.containsKey(key1));
assertTrue(result.containsKey(key2));
assertTrue(myRegion.containsKey(key1));
assertTrue(myRegion.containsKey(key2));
if (useTX) {
c.getCacheTransactionManager().commit();
// test that the commit correctly created the entries in the region
assertNotNull(myRegion.get(notAffectedKey));
assertNull(myRegion.get(key1));
assertTrue(myRegion.containsKey(key1));
assertNull(myRegion.get(key2));
assertTrue(myRegion.containsKey(key2));
}
// test that a listener is not invoked when there is already an invalidated
// entry in the client cache
UpdateListener listener = new UpdateListener();
listener.log = org.apache.geode.test.dunit.LogWriterUtils.getLogWriter();
myRegion.getAttributesMutator().addCacheListener(listener);
myRegion.get(key1);
assertEquals("expected no cache listener invocations", 0, listener.updateCount,
listener.updateCount);
myRegion.localDestroy(notAffectedKey);
myRegion.getAll(keys);
assertTrue("expected to find " + notAffectedKey, myRegion.containsKey(notAffectedKey));
assertEquals("expected only one listener invocation for " + notAffectedKey, 1,
listener.updateCount);
}
/**
* Similar to bug #43407 but not reported in a ticket, we want a client that does a get() on a
* destroyed entry to end up with a tombstone for that entry. This was already the case but there
* were no unit tests covering this for different server configurations and with/without
* transactions.
*/
private void doTestClientGetsTombstone(final String regionName, final boolean usePR,
boolean useTX) throws Exception {
VM vm1 = Host.getHost(0).getVM(1);
VM vm2 = Host.getHost(0).getVM(2);
// here are the keys that will be used to validate behavior. Keys must be
// colocated if using both a partitioned region in the server and transactions
// in the client. All of these keys hash to bucket 0 in a two-bucket PR
// except Object11 and IDoNotExist1
final String notAffectedKey = "Object1";
final String nonexistantKey = (usePR && useTX) ? "IDoNotExist2" : "IDoNotExist1";
final String key1 = "Object10";
final String key2 = (usePR && useTX) ? "Object12" : "Object11";
SerializableCallableIF createServer = getCreateServerCallable(regionName, usePR);
int serverPort = (Integer) vm1.invoke(createServer);
vm2.invoke(createServer);
vm1.invoke(new SerializableRunnable("populate server and create invalid entry") {
public void run() {
Region myRegion = getCache().getRegion(regionName);
for (int i = 1; i <= 20; i++) {
myRegion.put("Object" + i, "Value" + i);
}
myRegion.destroy(key1);
myRegion.destroy(key2);
}
});
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("creating client cache");
ClientCache c = new ClientCacheFactory().addPoolServer("localhost", serverPort)
.set(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel()).create();
Region myRegion =
c.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);;
if (useTX) {
c.getCacheTransactionManager().begin();
}
// get of a valid entry should work
assertNotNull(myRegion.get(notAffectedKey));
// get of an invalid entry should return null and create the entry in an invalid state
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
.info("getting " + key1 + " - should reach this cache and be a TOMBSTONE");
assertNull(myRegion.get(key1));
assertFalse(myRegion.containsKey(key1));
RegionEntry entry;
if (!useTX) {
entry = ((LocalRegion) myRegion).getRegionEntry(key1);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
}
// since this might be a PR we also check the next key to force PR Get messaging
assertNull(myRegion.get(key2));
assertFalse(myRegion.containsKey(key2));
if (!useTX) {
entry = ((LocalRegion) myRegion).getRegionEntry(key2);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
}
// now try a key that doesn't exist anywhere
assertNull(myRegion.get(nonexistantKey));
assertFalse(myRegion.containsKey(nonexistantKey));
if (useTX) {
c.getCacheTransactionManager().commit();
// test that the commit correctly created the entries in the region
assertNotNull(myRegion.get(notAffectedKey));
assertNull(myRegion.get(key1));
assertFalse(myRegion.containsKey(key1));
entry = ((LocalRegion) myRegion).getRegionEntry(key1);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
assertNull(myRegion.get(key2));
assertFalse(myRegion.containsKey(key2));
entry = ((LocalRegion) myRegion).getRegionEntry(key2);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
}
myRegion.localDestroy(notAffectedKey);
if (useTX) {
c.getCacheTransactionManager().begin();
}
// check that getAll returns invalidated entries
List keys = new LinkedList();
keys.add(notAffectedKey);
keys.add(key1);
keys.add(key2);
Map result = myRegion.getAll(keys);
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("result of getAll = " + result);
assertNotNull(result.get(notAffectedKey));
assertNull(result.get(key1));
assertNull(result.get(key2));
assertFalse(myRegion.containsKey(key1));
assertFalse(myRegion.containsKey(key2));
if (!useTX) {
entry = ((LocalRegion) myRegion).getRegionEntry(key1);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
entry = ((LocalRegion) myRegion).getRegionEntry(key2);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
} else { // useTX
c.getCacheTransactionManager().commit();
// test that the commit correctly created the entries in the region
assertNotNull(myRegion.get(notAffectedKey));
assertNull(myRegion.get(key1));
assertFalse(myRegion.containsKey(key1));
entry = ((LocalRegion) myRegion).getRegionEntry(key1);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
assertNull(myRegion.get(key2));
assertFalse(myRegion.containsKey(key2));
entry = ((LocalRegion) myRegion).getRegionEntry(key2);
assertNotNull(entry); // it should be there
assertTrue(entry.isTombstone()); // it should be a destroyed entry with Token.TOMBSTONE
}
}
private void doTestRegisterInterestRemovesOldEntry(final String regionName, final boolean usePR)
throws Exception {
VM vm1 = Host.getHost(0).getVM(1);
VM vm2 = Host.getHost(0).getVM(2);
// here are the keys that will be used to validate behavior. Keys must be
// colocated if using both a partitioned region in the server and transactions
// in the client. All of these keys hash to bucket 0 in a two-bucket PR
// except Object11 and IDoNotExist1
final String key10 = "Object10";
final String interestPattern = "Object.*";
SerializableCallableIF createServer = getCreateServerCallable(regionName, usePR);
int serverPort = (Integer) vm1.invoke(createServer);
vm2.invoke(createServer);
vm1.invoke(new SerializableRunnable("populate server") {
public void run() {
Region myRegion = getCache().getRegion(regionName);
for (int i = 1; i <= 20; i++) {
myRegion.put("Object" + i, "Value" + i);
}
}
});
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("creating client cache");
ClientCache c = new ClientCacheFactory().addPoolServer("localhost", serverPort)
.set(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel()).setPoolSubscriptionEnabled(true)
.create();
Region myRegion =
c.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);;
myRegion.registerInterestRegex(interestPattern);
// make sure key1 is in the client because we're going to mess with it
assertNotNull(myRegion.get(key10));
// remove the entry for key1 on the servers and then simulate interest recovery
// to show that the entry for key1 is no longer there in the client when recovery
// finishes
SerializableRunnable destroyKey10 =
new SerializableRunnable("locally destroy " + key10 + " in the servers") {
public void run() {
Region myRegion = getCache().getRegion(regionName);
EntryEventImpl event = ((LocalRegion) myRegion).generateEvictDestroyEvent(key10);
event.setOperation(Operation.LOCAL_DESTROY);
if (usePR) {
BucketRegion bucket = ((PartitionedRegion) myRegion).getBucketRegion(key10);
if (bucket != null) {
event.setRegion(bucket);
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
.info("performing local destroy in " + bucket + " ccEnabled="
+ bucket.getConcurrencyChecksEnabled() + " rvv="
+ bucket.getVersionVector());
bucket.setConcurrencyChecksEnabled(false); // turn off cc so entry is removed
bucket.mapDestroy(event, false, false, null);
bucket.setConcurrencyChecksEnabled(true);
}
} else {
((LocalRegion) myRegion).setConcurrencyChecksEnabled(false); // turn off cc so entry
// is
// removed
((LocalRegion) myRegion).mapDestroy(event, false, false, null);
((LocalRegion) myRegion).setConcurrencyChecksEnabled(true);
}
}
};
vm1.invoke(destroyKey10);
vm2.invoke(destroyKey10);
myRegion.getCache().getLogger().info("clearing keys of interest");
((LocalRegion) myRegion).clearKeysOfInterest(interestPattern, InterestType.REGULAR_EXPRESSION,
InterestResultPolicy.KEYS_VALUES);
myRegion.getCache().getLogger().info("done clearing keys of interest");
assertTrue("expected region to be empty but it has " + myRegion.size() + " entries",
myRegion.size() == 0);
RegionEntry entry;
entry = ((LocalRegion) myRegion).getRegionEntry(key10);
assertNull(entry); // it should have been removed
// now register interest. At the end, finishRegisterInterest should clear
// out the entry for key1 because it was stored in image-state as a
// destroyed RI entry in clearKeysOfInterest
myRegion.registerInterestRegex(interestPattern);
entry = ((LocalRegion) myRegion).getRegionEntry(key10);
assertNull(entry); // it should not be there
}
static class UpdateListener extends CacheListenerAdapter {
int updateCount;
LogWriter log;
@Override
public void afterUpdate(EntryEvent event) {
// log.info("UpdateListener.afterUpdate invoked for " + event, new Exception("stack trace"));
this.updateCount++;
}
@Override
public void afterCreate(EntryEvent event) {
// log.info("UpdateListener.afterCreate invoked for " + event, new Exception("stack trace"));
this.updateCount++;
}
}
}
| apache-2.0 |
gottron/community-interaction | Reveal-interaction/src/de/unikoblenz/west/reveal/package-info.java | 122 | /**
*
*/
/**
* @author Thomas Gottron
*
* Base package for work in Reveal
*
*/
package de.unikoblenz.west.reveal; | apache-2.0 |
1551250249/Wei.Lib2A | Wei.Lib2A/src/com/wei/c/widget/DialogHelper.java | 10980 | /*
* Copyright (C) 2014 Wei Chou (weichou2010@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 com.wei.c.widget;
import android.app.Dialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wei.c.Debug;
import com.wei.c.lib.R;
import com.wei.c.utils.IdGetter;
import com.wei.c.widget.text.LinkSpan;
/**
* @author 周伟 Wei Chou(weichou2010@gmail.com)
*/
public class DialogHelper {
public static final String LOG_TAG = "DialogHelper";
public static final boolean LOG = Debug.LOG;
public static final String ID_LAYOUT = "lib_wei_c_dialog";
public static final String ID_STR_TITLE = "lib_wei_c_dialog_title";
public static final String ID_STR_CONTENT = "lib_wei_c_dialog_content";
public static final String ID_BTN_POSITIVE = "lib_wei_c_dialog_btn_positive";
public static final String ID_BTN_NEUTRAL = "lib_wei_c_dialog_btn_neutral";
public static final String ID_BTN_NEGATIVE = "lib_wei_c_dialog_btn_negative";
public static final String ID_BG_BTN_ONLY = "lib_wei_c_dialog_bg_selector_button_only";
public static void showAlertDialog(Context context, String title, int iconId, String msg, String positiveText, String neutralText,
String negativeText, final Runnable doPositive, final Runnable doNeutral, final Runnable doNegative) {
createDialogWithView(context, title, iconId, msg, positiveText, neutralText, negativeText, doPositive, doNeutral, doNegative).show();
}
public static void showSystemDialog(Context context, String title, int iconId, String msg, String positiveText, String neutralText,
String negativeText, final Runnable doPositive, final Runnable doNeutral, final Runnable doNegative) {
//getApplicationContext() 至关重要,如果没有这句,当在程序中弹出本对话框之后,再切换到主屏幕的时候将没法操作主屏幕(空白且被盖住)
context = context.getApplicationContext();
DialogViewCreator creator = new DialogViewCreator(context);
final WindowManager wManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
final View view = creator.get();
creator.setTitle(title);
creator.setIcon(iconId);
creator.setMessage(msg);
if(positiveText!=null || doNegative!=null) creator.setPositiveButton(positiveText, new Runnable() {
@Override
public void run() {
wManager.removeView(view);
if(doPositive != null) doPositive.run();
}
});
if(neutralText!=null || doNeutral!=null) creator.setNeutralButton(neutralText, new Runnable() {
@Override
public void run() {
wManager.removeView(view);
if(doNeutral != null) doNeutral.run();
}
});
if(negativeText!=null || doNegative!=null) creator.setNegativeButton(negativeText, new Runnable() {
@Override
public void run() {
wManager.removeView(view);
if(doNegative != null) doNegative.run();
}
});
LayoutParams p = new LayoutParams();
p.format = PixelFormat.TRANSLUCENT;
/* FLAG_NOT_FOCUSABLE默认会开启FLAG_NOT_TOUCH_MODAL,意味着后面的视图可以接收事件。FLAG_DIM_BEHIND使背景变暗
* 当不设置FLAG_NOT_FOCUSABLE或者FLAG_NOT_TOUCH_MODAL的时候,事件全都会被该View接收,即使该view布局不是全屏。
*/
p.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE;
//LayoutParams.FLAG_DIM_BEHIND;
//wmParams.dimAmount = 0.4f;
p.type = LayoutParams.TYPE_SYSTEM_ALERT;
computePosition(context, p, creator.getMargins());
wManager.addView(view, p);
}
private static Dialog createDialogWithView(Context context, String title, int iconId, String msg, String positiveText, String neutralText,
String negativeText, final Runnable doPositive, final Runnable doNeutral, final Runnable doNegative) {
final Dialog dialog = new Dialog(context, R.style.Theme_Wei_C_Dialog_Alert);
DialogViewCreator creator = new DialogViewCreator(context);
creator.setTitle(title);
creator.setIcon(iconId);
creator.setMessage(msg);
if(positiveText!=null || doNegative!=null) creator.setPositiveButton(positiveText, new Runnable() {
@Override
public void run() {
dialog.cancel();
if(doPositive != null) doPositive.run();
}
});
if(neutralText!=null || doNeutral!=null) creator.setNeutralButton(neutralText, new Runnable() {
@Override
public void run() {
dialog.cancel();
if(doNeutral != null) doNeutral.run();
}
});
if(negativeText!=null || doNegative!=null) creator.setNegativeButton(negativeText, new Runnable() {
@Override
public void run() {
dialog.cancel();
if(doNegative != null) doNegative.run();
}
});
dialog.setContentView(creator.get());
LayoutParams p = dialog.getWindow().getAttributes();
computePosition(context, p, creator.getMargins());
dialog.getWindow().setAttributes(p);
return dialog;
}
private static class DialogViewCreator {
Context mContext;
View mView;
TextView mTitle;
TextView mMsg;
Button mPositive;
Button mNeutral;
Button mNegative;
int mMargins;
public DialogViewCreator(Context context) {
mContext = context;
LayoutInflater factory = LayoutInflater.from(context);
mView = factory.inflate(IdGetter.getLayoutId(mContext, ID_LAYOUT), new LinearLayout(context), false);
mTitle = (TextView)mView.findViewById(IdGetter.getIdId(mContext, ID_STR_TITLE));
mMsg = (TextView)mView.findViewById(IdGetter.getIdId(mContext, ID_STR_CONTENT));
mPositive = (Button)mView.findViewById(IdGetter.getIdId(mContext, ID_BTN_POSITIVE));
mNeutral = (Button)mView.findViewById(IdGetter.getIdId(mContext, ID_BTN_NEUTRAL));
mNegative = (Button)mView.findViewById(IdGetter.getIdId(mContext, ID_BTN_NEGATIVE));
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mView.getLayoutParams();
mMargins = lp!=null ? lp.leftMargin : 30;
mPositive.setVisibility(View.GONE);
mNeutral.setVisibility(View.GONE);
mNegative.setVisibility(View.GONE);
/* 注意一定要使用:
TextView.setMovementMethod(LinkMovementMethod.getInstance());
并且一定要去掉:
android:autoLink="all"
并且只有当TextView的至少一个颜色或者drawable是selector时,才会刷新颜色,详见TextView.updateTextColors()
否则超链接点击不起作用。
在某些情况下,比如弹出窗口,如果没有指定文本的默认颜色,则setMovementMethod只后整个文本的颜色也会像超链接一样变。
*/
mMsg.setMovementMethod(LinkMovementMethod.getInstance());
}
public void setIcon(int iconId) {
if(iconId > 0x7f000000) mTitle.setCompoundDrawablesWithIntrinsicBounds(iconId, 0, 0, 0);
}
public void setTitle(CharSequence text) {
mTitle.setText(text);
}
public void setMessage(CharSequence text) {
if(text instanceof String) {
//把所有的超链接URLSpan替换成LinkSpan
text = ((String) text).replace("\n", "<br>").replace(" ", "  ").replace(" ", "\t");
SpannableStringBuilder spanText = new SpannableStringBuilder(Html.fromHtml((String)text));
URLSpan[] urlSpan = spanText.getSpans(0, spanText.length(), URLSpan.class);
for(URLSpan uSpan : urlSpan) {
final int start = spanText.getSpanStart(uSpan);
final int end = spanText.getSpanEnd(uSpan);
final String url = uSpan.getURL();
LinkSpan linkSpan = new LinkSpan(mMsg.getLinkTextColors(), url);
spanText.removeSpan(uSpan);
spanText.setSpan(linkSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
text = spanText;
}
mMsg.setText(text);
}
public void setPositiveButton(CharSequence positiveText, final Runnable doPositive) {
if(positiveText!=null || doPositive!=null) {
mPositive.setVisibility(View.VISIBLE);
mPositive.setText(positiveText);
mPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(doPositive != null) doPositive.run();
}
});
}else {
mPositive.setVisibility(View.GONE);
}
}
public void setNeutralButton(CharSequence neutralText, final Runnable doNeutral) {
if(neutralText!=null || doNeutral!=null) {
mNeutral.setVisibility(View.VISIBLE);
mNeutral.setText(neutralText);
mNeutral.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(doNeutral != null) doNeutral.run();
}
});
}else {
mNeutral.setVisibility(View.GONE);
}
}
public void setNegativeButton(CharSequence negativeText, final Runnable doNegative) {
if(negativeText!=null || doNegative!=null) {
mNegative.setVisibility(View.VISIBLE);
mNegative.setText(negativeText);
mNegative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(doNegative != null) doNegative.run();
}
});
}else {
mNegative.setVisibility(View.GONE);
}
updateButtonStytle();
}
private void updateButtonStytle() {
//只有一个按钮
if(mPositive.getVisibility()==View.GONE
&& mNeutral.getVisibility()==View.GONE
&& mNegative.getVisibility()!=View.GONE) {
mNegative.setBackgroundResource(IdGetter.getDrawableId(mContext, ID_BG_BTN_ONLY));
}
}
public int getMargins() {
return mMargins;
}
public View get() {
return mView;
}
}
private static void computePosition(Context context, LayoutParams p, int margins) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
if(dm.widthPixels > dm.heightPixels) { //横屏
p.width = (int)(dm.widthPixels*.75f);
}else {
p.width = dm.widthPixels - margins*2;
}
p.height = LayoutParams.WRAP_CONTENT;
p.gravity = Gravity.CENTER;
}
}
| apache-2.0 |
junkerm/specmate | tools/cause-effect-dsl/org.xtext.specmate/src-gen/org/xtext/specmate/SpecDSLStandaloneSetupGenerated.java | 1481 | /*
* generated by Xtext 2.17.1
*/
package org.xtext.specmate;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.ISetup;
import org.eclipse.xtext.common.TerminalsStandaloneSetup;
import org.eclipse.xtext.resource.IResourceFactory;
import org.eclipse.xtext.resource.IResourceServiceProvider;
import org.xtext.specmate.specDSL.SpecDSLPackage;
@SuppressWarnings("all")
public class SpecDSLStandaloneSetupGenerated implements ISetup {
@Override
public Injector createInjectorAndDoEMFRegistration() {
TerminalsStandaloneSetup.doSetup();
Injector injector = createInjector();
register(injector);
return injector;
}
public Injector createInjector() {
return Guice.createInjector(new SpecDSLRuntimeModule());
}
public void register(Injector injector) {
if (!EPackage.Registry.INSTANCE.containsKey("http://www.xtext.org/specmate/SpecDSL")) {
EPackage.Registry.INSTANCE.put("http://www.xtext.org/specmate/SpecDSL", SpecDSLPackage.eINSTANCE);
}
IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("spec", resourceFactory);
IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("spec", serviceProvider);
}
}
| apache-2.0 |
EvilGreenArmy/ams | src/main/java/com/ams/dao/admin/SourceMapper.java | 770 | package com.ams.dao.admin;
import com.ams.entities.admin.SourceInfo;
import com.ams.entities.admin.UserInfo;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* Created by Evan on 2016/3/27.
*/
@Repository
public interface SourceMapper {
List<SourceInfo> sourceQueryPage(Map map);
List<SourceInfo> getParentSource(UserInfo user);
List<SourceInfo> getChildrenSource(UserInfo user);
void insertSource(SourceInfo source);
List<SourceInfo> getSourceById(Integer id);
void updateSource(SourceInfo source);
void deleteSource(Integer[] ids);
List<SourceInfo> getAllParentSource();
List<SourceInfo> getAllChildrenSource();
List<SourceInfo> getRoleSource(Integer roleId);
}
| apache-2.0 |
ceefour/webdav-servlet | src/test/java/net/sf/webdav/methods/DoPropfindTest.java | 7405 | package net.sf.webdav.methods;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.webdav.IMimeTyper;
import net.sf.webdav.ITransaction;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.locking.ResourceLocks;
import net.sf.webdav.testutil.MockTest;
import org.jmock.Expectations;
import org.junit.BeforeClass;
import org.junit.Test;
public class DoPropfindTest extends MockTest {
static IWebdavStore mockStore;
static IMimeTyper mockMimeTyper;
static HttpServletRequest mockReq;
static HttpServletResponse mockRes;
static ITransaction mockTransaction;
static PrintWriter printWriter;
static byte[] resourceContent = new byte[] { '<', 'h', 'e', 'l', 'l', 'o',
'/', '>' };
@BeforeClass
public static void setUp() throws Exception {
mockStore = _mockery.mock(IWebdavStore.class);
mockMimeTyper = _mockery.mock(IMimeTyper.class);
mockReq = _mockery.mock(HttpServletRequest.class);
mockRes = _mockery.mock(HttpServletResponse.class);
mockTransaction = _mockery.mock(ITransaction.class);
}
@Test
public void doPropFindOnDirectory() throws Exception {
final String path = "/";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("infinity"));
StoredObject rootSo = initFolderStoredObject();
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(rootSo));
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getContentLength();
will(returnValue(0));
// no content, which means it is a allprop request
one(mockRes).setStatus(WebdavStatus.SC_MULTI_STATUS);
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockRes).getWriter();
will(returnValue(printWriter));
one(mockMimeTyper).getMimeType(path);
will(returnValue("text/xml; charset=UTF-8"));
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(rootSo));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore).getChildrenNames(mockTransaction, path);
will(returnValue(new String[] { "file1", "file2" }));
StoredObject file1So = initFileStoredObject(resourceContent);
one(mockStore).getStoredObject(mockTransaction, path + "file1");
will(returnValue(file1So));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore)
.getChildrenNames(mockTransaction, path + "file1");
will(returnValue(new String[] {}));
StoredObject file2So = initFileStoredObject(resourceContent);
one(mockStore).getStoredObject(mockTransaction, path + "file2");
will(returnValue(file2So));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore)
.getChildrenNames(mockTransaction, path + "file2");
will(returnValue(new String[] {}));
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
@Test
public void doPropFindOnFile() throws Exception {
final String path = "/testFile";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("0"));
StoredObject fileSo = initFolderStoredObject();
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(fileSo));
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getContentLength();
will(returnValue(0));
// no content, which means it is a allprop request
one(mockRes).setStatus(WebdavStatus.SC_MULTI_STATUS);
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockRes).getWriter();
will(returnValue(printWriter));
one(mockMimeTyper).getMimeType(path);
will(returnValue("text/xml; charset=UTF-8"));
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(fileSo));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue("/"));
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
@Test
public void doPropFindOnNonExistingResource() throws Exception {
final String path = "/notExists";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("0"));
StoredObject notExistingSo = null;
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(notExistingSo));
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockReq).getRequestURI();
will(returnValue(path));
one(mockRes).sendError(WebdavStatus.SC_NOT_FOUND, path);
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
}
| apache-2.0 |
kadirahq/flatbuffers | java/com/google/flatbuffers/FlatBufferBuilder.java | 29373 | /*
* Copyright 2014 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.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/// @file
/// @addtogroup flatbuffers_java_api
/// @{
/**
* Class that helps you build a FlatBuffer. See the section
* "Use in Java/C#" in the main FlatBuffers documentation.
*/
public class FlatBufferBuilder {
/// @cond FLATBUFFERS_INTERNAL
ByteBuffer bb; // Where we construct the FlatBuffer.
int space; // Remaining space in the ByteBuffer.
static final Charset utf8charset = Charset.forName("UTF-8"); // The UTF-8 character set used by FlatBuffers.
int minalign = 1; // Minimum alignment encountered so far.
int[] vtable = null; // The vtable for the current table.
int vtable_in_use = 0; // The amount of fields we're actually using.
boolean nested = false; // Whether we are currently serializing a table.
boolean finished = false; // Whether the buffer is finished.
int object_start; // Starting offset of the current struct/table.
int[] vtables = new int[16]; // List of offsets of all vtables.
int num_vtables = 0; // Number of entries in `vtables` in use.
int vector_num_elems = 0; // For the current vector being built.
boolean force_defaults = false; // False omits default values from the serialized data.
CharsetEncoder encoder = utf8charset.newEncoder();
ByteBuffer dst;
/// @endcond
/**
* Start with a buffer of size `initial_size`, then grow as required.
*
* @param initial_size The initial size of the internal buffer to use.
*/
public FlatBufferBuilder(int initial_size) {
if (initial_size <= 0) initial_size = 1;
space = initial_size;
bb = newByteBuffer(initial_size);
}
/**
* Start with a buffer of 1KiB, then grow as required.
*/
public FlatBufferBuilder() {
this(1024);
}
/**
* Alternative constructor allowing reuse of {@link ByteBuffer}s. The builder
* can still grow the buffer as necessary. User classes should make sure
* to call {@link #dataBuffer()} to obtain the resulting encoded message.
*
* @param existing_bb The byte buffer to reuse.
*/
public FlatBufferBuilder(ByteBuffer existing_bb) {
init(existing_bb);
}
/**
* Alternative initializer that allows reusing this object on an existing
* `ByteBuffer`. This method resets the builder's internal state, but keeps
* objects that have been allocated for temporary storage.
*
* @param existing_bb The byte buffer to reuse.
* @return Returns `this`.
*/
public FlatBufferBuilder init(ByteBuffer existing_bb){
bb = existing_bb;
bb.clear();
bb.order(ByteOrder.LITTLE_ENDIAN);
minalign = 1;
space = bb.capacity();
vtable_in_use = 0;
nested = false;
finished = false;
object_start = 0;
num_vtables = 0;
vector_num_elems = 0;
return this;
}
/// @cond FLATBUFFERS_INTERNAL
/**
* Create a `ByteBuffer` with a given capacity.
*
* @param capacity The size of the `ByteBuffer` to allocate.
* @return Returns the new `ByteBuffer` that was allocated.
*/
static ByteBuffer newByteBuffer(int capacity) {
ByteBuffer newbb = ByteBuffer.allocate(capacity);
newbb.order(ByteOrder.LITTLE_ENDIAN);
return newbb;
}
/**
* Doubles the size of the backing {@link ByteBuffer} and copies the old data towards the
* end of the new buffer (since we build the buffer backwards).
*
* @param bb The current buffer with the existing data.
* @return A new byte buffer with the old data copied copied to it. The data is
* located at the end of the buffer.
*/
static ByteBuffer growByteBuffer(ByteBuffer bb) {
int old_buf_size = bb.capacity();
if ((old_buf_size & 0xC0000000) != 0) // Ensure we don't grow beyond what fits in an int.
throw new AssertionError("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
int new_buf_size = old_buf_size << 1;
bb.position(0);
ByteBuffer nbb = newByteBuffer(new_buf_size);
nbb.position(new_buf_size - old_buf_size);
nbb.put(bb);
return nbb;
}
/**
* Offset relative to the end of the buffer.
*
* @return Offset relative to the end of the buffer.
*/
public int offset() {
return bb.capacity() - space;
}
/**
* Add zero valued bytes to prepare a new entry to be added.
*
* @param byte_size Number of bytes to add.
*/
public void pad(int byte_size) {
for (int i = 0; i < byte_size; i++) bb.put(--space, (byte)0);
}
/**
* Prepare to write an element of `size` after `additional_bytes`
* have been written, e.g. if you write a string, you need to align such
* the int length field is aligned to {@link com.google.flatbuffers.Constants#SIZEOF_INT}, and
* the string data follows it directly. If all you need to do is alignment, `additional_bytes`
* will be 0.
*
* @param size This is the of the new element to write.
* @param additional_bytes The padding size.
*/
public void prep(int size, int additional_bytes) {
// Track the biggest thing we've ever aligned to.
if (size > minalign) minalign = size;
// Find the amount of alignment needed such that `size` is properly
// aligned after `additional_bytes`
int align_size = ((~(bb.capacity() - space + additional_bytes)) + 1) & (size - 1);
// Reallocate the buffer if needed.
while (space < align_size + size + additional_bytes) {
int old_buf_size = bb.capacity();
bb = growByteBuffer(bb);
space += bb.capacity() - old_buf_size;
}
pad(align_size);
}
/**
* Add a `boolean` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `boolean` to put into the buffer.
*/
public void putBoolean(boolean x) { bb.put (space -= 1, (byte)(x ? 1 : 0)); }
/**
* Add a `byte` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `byte` to put into the buffer.
*/
public void putByte (byte x) { bb.put (space -= 1, x); }
/**
* Add a `short` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `short` to put into the buffer.
*/
public void putShort (short x) { bb.putShort (space -= 2, x); }
/**
* Add an `int` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x An `int` to put into the buffer.
*/
public void putInt (int x) { bb.putInt (space -= 4, x); }
/**
* Add a `long` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `long` to put into the buffer.
*/
public void putLong (long x) { bb.putLong (space -= 8, x); }
/**
* Add a `float` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `float` to put into the buffer.
*/
public void putFloat (float x) { bb.putFloat (space -= 4, x); }
/**
* Add a `double` to the buffer, backwards from the current location. Doesn't align nor
* check for space.
*
* @param x A `double` to put into the buffer.
*/
public void putDouble (double x) { bb.putDouble(space -= 8, x); }
/// @endcond
/**
* Add a `boolean` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `boolean` to put into the buffer.
*/
public void addBoolean(boolean x) { prep(1, 0); putBoolean(x); }
/**
* Add a `byte` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `byte` to put into the buffer.
*/
public void addByte (byte x) { prep(1, 0); putByte (x); }
/**
* Add a `short` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `short` to put into the buffer.
*/
public void addShort (short x) { prep(2, 0); putShort (x); }
/**
* Add an `int` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x An `int` to put into the buffer.
*/
public void addInt (int x) { prep(4, 0); putInt (x); }
/**
* Add a `long` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `long` to put into the buffer.
*/
public void addLong (long x) { prep(8, 0); putLong (x); }
/**
* Add a `float` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `float` to put into the buffer.
*/
public void addFloat (float x) { prep(4, 0); putFloat (x); }
/**
* Add a `double` to the buffer, properly aligned, and grows the buffer (if necessary).
*
* @param x A `double` to put into the buffer.
*/
public void addDouble (double x) { prep(8, 0); putDouble (x); }
/**
* Adds on offset, relative to where it will be written.
*
* @param off The offset to add.
*/
public void addOffset(int off) {
prep(SIZEOF_INT, 0); // Ensure alignment is already done.
assert off <= offset();
off = offset() - off + SIZEOF_INT;
putInt(off);
}
/// @cond FLATBUFFERS_INTERNAL
/**
* Start a new array/vector of objects. Users usually will not call
* this directly. The `FlatBuffers` compiler will create a start/end
* method for vector types in generated code.
* <p>
* The expected sequence of calls is:
* <ol>
* <li>Start the array using this method.</li>
* <li>Call {@link #addOffset(int)} `num_elems` number of times to set
* the offset of each element in the array.</li>
* <li>Call {@link #endVector()} to retrieve the offset of the array.</li>
* </ol>
* <p>
* For example, to create an array of strings, do:
* <pre>{@code
* // Need 10 strings
* FlatBufferBuilder builder = new FlatBufferBuilder(existingBuffer);
* int[] offsets = new int[10];
*
* for (int i = 0; i < 10; i++) {
* offsets[i] = fbb.createString(" " + i);
* }
*
* // Have the strings in the buffer, but don't have a vector.
* // Add a vector that references the newly created strings:
* builder.startVector(4, offsets.length, 4);
*
* // Add each string to the newly created vector
* // The strings are added in reverse order since the buffer
* // is filled in back to front
* for (int i = offsets.length - 1; i >= 0; i--) {
* builder.addOffset(offsets[i]);
* }
*
* // Finish off the vector
* int offsetOfTheVector = fbb.endVector();
* }</pre>
*
* @param elem_size The size of each element in the array.
* @param num_elems The number of elements in the array.
* @param alignment The alignment of the array.
*/
public void startVector(int elem_size, int num_elems, int alignment) {
notNested();
vector_num_elems = num_elems;
prep(SIZEOF_INT, elem_size * num_elems);
prep(alignment, elem_size * num_elems); // Just in case alignment > int.
nested = true;
}
/**
* Finish off the creation of an array and all its elements. The array
* must be created with {@link #startVector(int, int, int)}.
*
* @return The offset at which the newly created array starts.
* @see #startVector(int, int, int)
*/
public int endVector() {
if (!nested)
throw new AssertionError("FlatBuffers: endVector called without startVector");
nested = false;
putInt(vector_num_elems);
return offset();
}
/// @endcond
/**
* Encode the string `s` in the buffer using UTF-8. If {@code s} is
* already a {@link CharBuffer}, this method is allocation free.
*
* @param s The string to encode.
* @return The offset in the buffer where the encoded string starts.
*/
public int createString(CharSequence s) {
int length = s.length();
int estimatedDstCapacity = (int) (length * encoder.maxBytesPerChar());
if (dst == null || dst.capacity() < estimatedDstCapacity) {
dst = ByteBuffer.allocate(Math.max(128, estimatedDstCapacity));
}
dst.clear();
CharBuffer src = s instanceof CharBuffer ? (CharBuffer) s :
CharBuffer.wrap(s);
CoderResult result = encoder.encode(src, dst, true);
if (result.isError()) {
try {
result.throwException();
} catch (CharacterCodingException x) {
throw new Error(x);
}
}
dst.flip();
return createString(dst);
}
/**
* Create a string in the buffer from an already encoded UTF-8 string in a ByteBuffer.
*
* @param s An already encoded UTF-8 string as a `ByteBuffer`.
* @return The offset in the buffer where the encoded string starts.
*/
public int createString(ByteBuffer s) {
int length = s.remaining();
addByte((byte)0);
startVector(1, length, 1);
bb.position(space -= length);
bb.put(s);
return endVector();
}
/// @cond FLATBUFFERS_INTERNAL
/**
* Should not be accessing the final buffer before it is finished.
*/
public void finished() {
if (!finished)
throw new AssertionError(
"FlatBuffers: you can only access the serialized buffer after it has been" +
" finished by FlatBufferBuilder.finish().");
}
/**
* Should not be creating any other object, string or vector
* while an object is being constructed.
*/
public void notNested() {
if (nested)
throw new AssertionError("FlatBuffers: object serialization must not be nested.");
}
/**
* Structures are always stored inline, they need to be created right
* where they're used. You'll get this assertion failure if you
* created it elsewhere.
*
* @param obj The offset of the created object.
*/
public void Nested(int obj) {
if (obj != offset())
throw new AssertionError("FlatBuffers: struct must be serialized inline.");
}
/**
* Start encoding a new object in the buffer. Users will not usually need to
* call this directly. The `FlatBuffers` compiler will generate helper methods
* that call this method internally.
* <p>
* For example, using the "Monster" code found on the "landing page". An
* object of type `Monster` can be created using the following code:
*
* <pre>{@code
* int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
* fbb.createString("test1"),
* fbb.createString("test2")
* });
*
* Monster.startMonster(fbb);
* Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
* Color.Green, (short)5, (byte)6));
* Monster.addHp(fbb, (short)80);
* Monster.addName(fbb, str);
* Monster.addInventory(fbb, inv);
* Monster.addTestType(fbb, (byte)Any.Monster);
* Monster.addTest(fbb, mon2);
* Monster.addTest4(fbb, test4);
* Monster.addTestarrayofstring(fbb, testArrayOfString);
* int mon = Monster.endMonster(fbb);
* }</pre>
* <p>
* Here:
* <ul>
* <li>The call to `Monster#startMonster(FlatBufferBuilder)` will call this
* method with the right number of fields set.</li>
* <li>`Monster#endMonster(FlatBufferBuilder)` will ensure {@link #endObject()} is called.</li>
* </ul>
* <p>
* It's not recommended to call this method directly. If it's called manually, you must ensure
* to audit all calls to it whenever fields are added or removed from your schema. This is
* automatically done by the code generated by the `FlatBuffers` compiler.
*
* @param numfields The number of fields found in this object.
*/
public void startObject(int numfields) {
notNested();
if (vtable == null || vtable.length < numfields) vtable = new int[numfields];
vtable_in_use = numfields;
Arrays.fill(vtable, 0, vtable_in_use, 0);
nested = true;
object_start = offset();
}
/**
* Add a `boolean` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `boolean` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `boolean` default value to compare against when `force_defaults` is `false`.
*/
public void addBoolean(int o, boolean x, boolean d) { if(force_defaults || x != d) { addBoolean(x); slot(o); } }
/**
* Add a `byte` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `byte` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `byte` default value to compare against when `force_defaults` is `false`.
*/
public void addByte (int o, byte x, int d) { if(force_defaults || x != d) { addByte (x); slot(o); } }
/**
* Add a `short` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `short` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `short` default value to compare against when `force_defaults` is `false`.
*/
public void addShort (int o, short x, int d) { if(force_defaults || x != d) { addShort (x); slot(o); } }
/**
* Add an `int` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x An `int` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d An `int` default value to compare against when `force_defaults` is `false`.
*/
public void addInt (int o, int x, int d) { if(force_defaults || x != d) { addInt (x); slot(o); } }
/**
* Add a `long` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `long` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `long` default value to compare against when `force_defaults` is `false`.
*/
public void addLong (int o, long x, long d) { if(force_defaults || x != d) { addLong (x); slot(o); } }
/**
* Add a `float` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `float` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `float` default value to compare against when `force_defaults` is `false`.
*/
public void addFloat (int o, float x, double d) { if(force_defaults || x != d) { addFloat (x); slot(o); } }
/**
* Add a `double` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x A `double` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d A `double` default value to compare against when `force_defaults` is `false`.
*/
public void addDouble (int o, double x, double d) { if(force_defaults || x != d) { addDouble (x); slot(o); } }
/**
* Add an `offset` to a table at `o` into its vtable, with value `x` and default `d`.
*
* @param o The index into the vtable.
* @param x An `offset` to put into the buffer, depending on how defaults are handled. If
* `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the
* default value, it can be skipped.
* @param d An `offset` default value to compare against when `force_defaults` is `false`.
*/
public void addOffset (int o, int x, int d) { if(force_defaults || x != d) { addOffset (x); slot(o); } }
/**
* Add a struct to the table. Structs are stored inline, so nothing additional is being added.
*
* @param voffset The index into the vtable.
* @param x The offset of the created struct.
* @param d The default value is always `0`.
*/
public void addStruct(int voffset, int x, int d) {
if(x != d) {
Nested(x);
slot(voffset);
}
}
/**
* Set the current vtable at `voffset` to the current location in the buffer.
*
* @param voffset The index into the vtable to store the offset relative to the end of the
* buffer.
*/
public void slot(int voffset) {
vtable[voffset] = offset();
}
/**
* Finish off writing the object that is under construction.
*
* @return The offset to the object inside {@link #dataBuffer()}.
* @see #startObject(int)
*/
public int endObject() {
if (vtable == null || !nested)
throw new AssertionError("FlatBuffers: endObject called without startObject");
addInt(0);
int vtableloc = offset();
// Write out the current vtable.
for (int i = vtable_in_use - 1; i >= 0 ; i--) {
// Offset relative to the start of the table.
short off = (short)(vtable[i] != 0 ? vtableloc - vtable[i] : 0);
addShort(off);
}
final int standard_fields = 2; // The fields below:
addShort((short)(vtableloc - object_start));
addShort((short)((vtable_in_use + standard_fields) * SIZEOF_SHORT));
// Search for an existing vtable that matches the current one.
int existing_vtable = 0;
outer_loop:
for (int i = 0; i < num_vtables; i++) {
int vt1 = bb.capacity() - vtables[i];
int vt2 = space;
short len = bb.getShort(vt1);
if (len == bb.getShort(vt2)) {
for (int j = SIZEOF_SHORT; j < len; j += SIZEOF_SHORT) {
if (bb.getShort(vt1 + j) != bb.getShort(vt2 + j)) {
continue outer_loop;
}
}
existing_vtable = vtables[i];
break outer_loop;
}
}
if (existing_vtable != 0) {
// Found a match:
// Remove the current vtable.
space = bb.capacity() - vtableloc;
// Point table to existing vtable.
bb.putInt(space, existing_vtable - vtableloc);
} else {
// No match:
// Add the location of the current vtable to the list of vtables.
if (num_vtables == vtables.length) vtables = Arrays.copyOf(vtables, num_vtables * 2);
vtables[num_vtables++] = offset();
// Point table to current vtable.
bb.putInt(bb.capacity() - vtableloc, offset() - vtableloc);
}
nested = false;
return vtableloc;
}
/**
* Checks that a required field has been set in a given table that has
* just been constructed.
*
* @param table The offset to the start of the table from the `ByteBuffer` capacity.
* @param field The offset to the field in the vtable.
*/
public void required(int table, int field) {
int table_start = bb.capacity() - table;
int vtable_start = table_start - bb.getInt(table_start);
boolean ok = bb.getShort(vtable_start + field) != 0;
// If this fails, the caller will show what field needs to be set.
if (!ok)
throw new AssertionError("FlatBuffers: field " + field + " must be set");
}
/// @endcond
/**
* Finalize a buffer, pointing to the given `root_table`.
*
* @param root_table An offset to be added to the buffer.
*/
public void finish(int root_table) {
prep(minalign, SIZEOF_INT);
addOffset(root_table);
bb.position(space);
finished = true;
}
/**
* Finalize a buffer, pointing to the given `root_table`.
*
* @param root_table An offset to be added to the buffer.
* @param file_identifier A FlatBuffer file identifier to be added to the buffer before
* `root_table`.
*/
public void finish(int root_table, String file_identifier) {
prep(minalign, SIZEOF_INT + FILE_IDENTIFIER_LENGTH);
if (file_identifier.length() != FILE_IDENTIFIER_LENGTH)
throw new AssertionError("FlatBuffers: file identifier must be length " +
FILE_IDENTIFIER_LENGTH);
for (int i = FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
addByte((byte)file_identifier.charAt(i));
}
finish(root_table);
}
/**
* In order to save space, fields that are set to their default value
* don't get serialized into the buffer. Forcing defaults provides a
* way to manually disable this optimization.
*
* @param forceDefaults When set to `true`, always serializes default values.
* @return Returns `this`.
*/
public FlatBufferBuilder forceDefaults(boolean forceDefaults){
this.force_defaults = forceDefaults;
return this;
}
/**
* Get the ByteBuffer representing the FlatBuffer. Only call this after you've
* called `finish()`. The actual data starts at the ByteBuffer's current position,
* not necessarily at `0`.
*
* @return The {@link ByteBuffer} representing the FlatBuffer
*/
public ByteBuffer dataBuffer() {
finished();
return bb;
}
/**
* The FlatBuffer data doesn't start at offset 0 in the {@link ByteBuffer}, but
* now the {@code ByteBuffer}'s position is set to that location upon {@link #finish(int)}.
*
* @return The {@link ByteBuffer#position() position} the data starts in {@link #dataBuffer()}
* @deprecated This method should not be needed anymore, but is left
* here for the moment to document this API change. It will be removed in the future.
*/
@Deprecated
private int dataStart() {
finished();
return space;
}
/**
* A utility function to copy and return the ByteBuffer data from `start` to
* `start` + `length` as a `byte[]`.
*
* @param start Start copying at this offset.
* @param length How many bytes to copy.
* @return A range copy of the {@link #dataBuffer() data buffer}.
* @throws IndexOutOfBoundsException If the range of bytes is ouf of bound.
*/
public byte[] sizedByteArray(int start, int length){
finished();
byte[] array = new byte[length];
bb.position(start);
bb.get(array);
return array;
}
/**
* A utility function to copy and return the ByteBuffer data as a `byte[]`.
*
* @return A full copy of the {@link #dataBuffer() data buffer}.
*/
public byte[] sizedByteArray() {
return sizedByteArray(space, bb.capacity() - space);
}
}
/// @}
| apache-2.0 |
kul3r4/sms | apiclient/src/main/java/com/sms/meal/backend/MealProviderFromCache.java | 1962 | package com.sms.meal.backend;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.sms.meal.domainmeal.MyMeal;
import com.sms.transport.RequestCallback;
import java.util.List;
/**
* Created by cchiappini on 07/03/2015.
*/
public class MealProviderFromCache implements MealProvider {
private MealParser mealParser;
public MealProviderFromCache(MealParser mealParser){
this.mealParser = mealParser;
}
@Override
public void getMeals(final RequestCallback<List<MyMeal>> mealsCallback) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Meal");
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> list, com.parse.ParseException e) {
if (e == null && list.size() >0) {
List<MyMeal> mMealList = mealParser.extractUnbookedMealsFromListOfObject(list);
mealsCallback.onRetrieved(mMealList);
} else {
mealsCallback.onError("No meals found not found ");
}
}
});
}
@Override
public void getMeal(final RequestCallback<MyMeal> mealCallback, String id) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Meal");
query.fromLocalDatastore();
query.getInBackground(id, new GetCallback<ParseObject>() {
@Override
public void done(ParseObject meal, com.parse.ParseException e) {
if (e == null) {
mealCallback.onRetrieved(mealParser.parseMeal(meal));
}
else{
mealCallback.onError("Meal with id "+meal.getObjectId()+" not found ");
}
}
});
}
@Override
public void addMeal(MyMeal meal) {
//none
}
}
| apache-2.0 |
burakince/supply-manager | supply-manager-ui/src/main/java/net/burakince/supplymanager/SupplyManagerUI.java | 2360 | package net.burakince.supplymanager;
import javax.servlet.annotation.WebServlet;
import net.burakince.supplymanager.authentication.AccessControl;
import net.burakince.supplymanager.authentication.BasicAccessControl;
import net.burakince.supplymanager.authentication.LoginScreen;
import net.burakince.supplymanager.authentication.LoginScreen.LoginListener;
import net.burakince.supplymanager.view.MainScreen;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Viewport;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
/**
* Main UI class of the application that shows either the login screen or the
* main view of the application depending on whether a user is signed in.
*
* The @Viewport annotation configures the viewport meta tags appropriately on
* mobile devices. Instead of device based scaling (default), using responsive
* layouts.
*/
@SuppressWarnings("serial")
@Viewport("user-scalable=no,initial-scale=1.0")
@Theme("smtheme")
@Widgetset("net.burakince.supplymanager.SupplyManagerWidgetset")
public class SupplyManagerUI extends UI {
private AccessControl accessControl = new BasicAccessControl();
@Override
protected void init(VaadinRequest vaadinRequest) {
Responsive.makeResponsive(this);
setLocale(vaadinRequest.getLocale());
getPage().setTitle("SupplyManager");
if (!accessControl.isUserSignedIn()) {
setContent(new LoginScreen(accessControl, new LoginListener() {
@Override
public void loginSuccessful() {
showMainView();
}
}));
} else {
showMainView();
}
}
protected void showMainView() {
addStyleName(ValoTheme.UI_WITH_MENU);
setContent(new MainScreen(SupplyManagerUI.this));
getNavigator().navigateTo(getNavigator().getState());
}
public static SupplyManagerUI get() {
return (SupplyManagerUI) UI.getCurrent();
}
public AccessControl getAccessControl() {
return accessControl;
}
@WebServlet(urlPatterns = "/*", name = "SupplyManagerServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = SupplyManagerUI.class, productionMode = false)
public static class SupplyManagerServlet extends VaadinServlet {
}
}
| apache-2.0 |
Jayin/LightMeeting-Android | src/meizhuo/org/lightmeeting/camera/CameraManager.java | 10941 | package meizhuo.org.lightmeeting.camera;
import java.io.IOException;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
public final class CameraManager {
private static final String TAG = CameraManager.class.getSimpleName();
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 480;
private static final int MAX_FRAME_HEIGHT = 360;
private static CameraManager cameraManager;
static final int SDK_INT; // Later we can use Build.VERSION.SDK_INT
static {
int sdkInt;
try {
sdkInt = Integer.parseInt(Build.VERSION.SDK);
} catch (NumberFormatException nfe) {
// Just to be safe
sdkInt = 10000;
}
SDK_INT = sdkInt;
}
private final Context context;
private final CameraConfigurationManager configManager;
private Camera camera;
private Rect framingRect;
private Rect framingRectInPreview;
private boolean initialized;
private boolean previewing;
private final boolean useOneShotPreviewCallback;
/**
* Preview frames are delivered here, which we pass on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final PreviewCallback previewCallback;
/** Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. */
private final AutoFocusCallback autoFocusCallback;
/**
* Initializes this static object with the Context of the calling Activity.
*
* @param context The Activity which wants to use the camera.
*/
public static void init(Context context) {
if (cameraManager == null) {
cameraManager = new CameraManager(context);
}
}
/**
* Gets the CameraManager singleton instance.
*
* @return A reference to the CameraManager singleton.
*/
public static CameraManager get() {
return cameraManager;
}
private CameraManager(Context context) {
this.context = context;
this.configManager = new CameraConfigurationManager(context);
// Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
// Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
// the more efficient one shot callback, as the older one can swamp the system and cause it
// to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
//useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > 3; // 3 = Cupcake
previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
autoFocusCallback = new AutoFocusCallback();
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder The surface object which the camera will draw preview frames into.
* @throws IOException Indicates the camera driver failed to open.
*/
public void openDriver(SurfaceHolder holder) throws IOException {
if (camera == null) {
camera = Camera.open();
if (camera == null) {
throw new IOException();
}
camera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(camera);
}
configManager.setDesiredCameraParameters(camera);
//FIXME
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//是否使用前灯
// if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
// FlashlightManager.enableFlashlight();
// }
FlashlightManager.enableFlashlight();
}
}
/**
* Closes the camera driver if still in use.
*/
public void closeDriver() {
if (camera != null) {
FlashlightManager.disableFlashlight();
camera.release();
camera = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public void startPreview() {
if (camera != null && !previewing) {
camera.startPreview();
previewing = true;
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public void stopPreview() {
if (camera != null && previewing) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
camera.stopPreview();
previewCallback.setHandler(null, 0);
autoFocusCallback.setHandler(null, 0);
previewing = false;
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public void requestPreviewFrame(Handler handler, int message) {
if (camera != null && previewing) {
previewCallback.setHandler(handler, message);
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
} else {
camera.setPreviewCallback(previewCallback);
}
}
}
/**
* Asks the camera hardware to perform an autofocus.
*
* @param handler The Handler to notify when the autofocus completes.
* @param message The message to deliver.
*/
public void requestAutoFocus(Handler handler, int message) {
if (camera != null && previewing) {
autoFocusCallback.setHandler(handler, message);
//Log.d(TAG, "Requesting auto-focus callback");
camera.autoFocus(autoFocusCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user where to place the
* barcode. This target helps with alignment as well as forces the user to hold the device
* far enough away to ensure the image will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public Rect getFramingRect() {
Point screenResolution = configManager.getScreenResolution();
if (framingRect == null) {
if (camera == null) {
return null;
}
int width = screenResolution.x * 3 / 4;
if (width < MIN_FRAME_WIDTH) {
width = MIN_FRAME_WIDTH;
} else if (width > MAX_FRAME_WIDTH) {
width = MAX_FRAME_WIDTH;
}
int height = screenResolution.y * 3 / 4;
if (height < MIN_FRAME_HEIGHT) {
height = MIN_FRAME_HEIGHT;
} else if (height > MAX_FRAME_HEIGHT) {
height = MAX_FRAME_HEIGHT;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.d(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
* not UI / screen.
*/
public Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect rect = new Rect(getFramingRect());
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
//modify here
// rect.left = rect.left * cameraResolution.x / screenResolution.x;
// rect.right = rect.right * cameraResolution.x / screenResolution.x;
// rect.top = rect.top * cameraResolution.y / screenResolution.y;
// rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
framingRectInPreview = rect;
}
return framingRectInPreview;
}
/**
* Converts the result points from still resolution coordinates to screen coordinates.
*
* @param points The points returned by the Reader subclass through Result.getResultPoints().
* @return An array of Points scaled to the size of the framing rect and offset appropriately
* so they can be drawn in screen coordinates.
*/
/*
public Point[] convertResultPoints(ResultPoint[] points) {
Rect frame = getFramingRectInPreview();
int count = points.length;
Point[] output = new Point[count];
for (int x = 0; x < count; x++) {
output[x] = new Point();
output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
}
return output;
}
*/
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
int previewFormat = configManager.getPreviewFormat();
String previewFormatString = configManager.getPreviewFormatString();
switch (previewFormat) {
// This is the standard Android format which all devices are REQUIRED to support.
// In theory, it's the only one we should ever care about.
case PixelFormat.YCbCr_420_SP:
// This format has never been seen in the wild, but is compatible as we only care
// about the Y channel, so allow it.
case PixelFormat.YCbCr_422_SP:
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
default:
// The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
// Fortunately, it too has all the Y data up front, so we can read it.
if ("yuv420p".equals(previewFormatString)) {
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
}
}
throw new IllegalArgumentException("Unsupported picture format: " +
previewFormat + '/' + previewFormatString);
}
public Context getContext() {
return context;
}
}
| apache-2.0 |
debmalya/symmetrical-eureka | src/main/java/amazed/Anagram.java | 2802 | package amazed;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.BiConsumer;
public class Anagram {
static int count;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* Given a dictionary of English words, find sets of anagrams. For instance,
* “pots”, “stop”, and “tops” are all anagrams of one another because each
* can be found by permuting the letters of the others.
*
* @param wordList
* - list of words to be tested for anagram.
* @return true if they are anagram, false otherwise.
*/
public static boolean isAnagram(List<String> wordList) {
if (wordList != null && !wordList.isEmpty()) {
char[] sorted = wordList.get(0).toLowerCase().toCharArray();
Arrays.sort(sorted);
for (int i = 1; i < wordList.size(); i++) {
char[] check = wordList.get(i).toLowerCase().toCharArray();
Arrays.sort(check);
if (!Arrays.equals(sorted, check)) {
return false;
}
}
return true;
}
return false;
}
/**
* How many characters will be removed to make it an anagram.
*
* @param first
* string.
* @param second
* string.
* @return how many characters should be removed to make it anagram.
*/
public static int numberNeeded(String first, String second) {
int[] f = new int[26];
int[] s = new int[26];
for (int i = 0; i < first.length(); i++) {
f[first.charAt(i) - 'a']++;
}
for (int i = 0; i < second.length(); i++) {
s[second.charAt(i) - 'a']++;
}
int count = 0;
for (int i = 0; i < 26; i++) {
if (f[i] != s[i]) {
count += (Math.abs(f[i] - s[i]));
}
}
return count;
}
/**
*
* @param magazine
* word in the magazine (case sensitive)
* @param note
* word in the note (case sensitive)
* @return true if all the words in note are available in magazine, false
* otherwise.
*/
public static boolean isRansomNote(String magazine, String note) {
String[] magazineWords = magazine.split(" ");
String[] noteWords = note.split(" ");
LinkedHashMap<String, Integer> magazineMap = new LinkedHashMap<>();
LinkedHashMap<String, Integer> notemap = new LinkedHashMap<>();
for (String each : magazineWords) {
Integer count = magazineMap.get(each);
if (count == null) {
count = 0;
}
count++;
magazineMap.put(each, count);
}
for (String each : noteWords) {
Integer count = notemap.get(each);
if (count == null) {
count = 0;
}
count++;
notemap.put(each, count);
}
BiConsumer<String, Integer> biConsumer = (key, value) -> {
if (magazineMap.get(key) == value) {
count++;
}
};
notemap.forEach(biConsumer);
return count == notemap.size();
}
}
| apache-2.0 |
Soya93/Extract-Refactoring | platform/dvcs-impl/src/com/intellij/dvcs/DvcsUtil.java | 19978 | /*
* Copyright 2000-2014 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.dvcs;
import com.intellij.dvcs.push.PushSupport;
import com.intellij.dvcs.repo.AbstractRepositoryManager;
import com.intellij.dvcs.repo.RepoStateException;
import com.intellij.dvcs.repo.Repository;
import com.intellij.dvcs.repo.RepositoryManager;
import com.intellij.ide.file.BatchFileChangeListener;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.JdkOrderEntry;
import com.intellij.openapi.roots.LibraryOrderEntry;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.status.StatusBarUtil;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.vcs.log.TimedVcsCommit;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcsUtil.VcsImplUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.intellij.images.editor.ImageFileEditor;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
public class DvcsUtil {
private static final Logger LOG = Logger.getInstance(DvcsUtil.class);
private static final Logger LOGGER = Logger.getInstance(DvcsUtil.class);
private static final int IO_RETRIES = 3; // number of retries before fail if an IOException happens during file read.
private static final int SHORT_HASH_LENGTH = 8;
private static final int LONG_HASH_LENGTH = 40;
/**
* Comparator for virtual files by name
*/
public static final Comparator<VirtualFile> VIRTUAL_FILE_PRESENTATION_COMPARATOR = new Comparator<VirtualFile>() {
public int compare(final VirtualFile o1, final VirtualFile o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
return o1.getPresentableUrl().compareTo(o2.getPresentableUrl());
}
};
@NotNull
public static List<VirtualFile> sortVirtualFilesByPresentation(@NotNull Collection<VirtualFile> virtualFiles) {
return ContainerUtil.sorted(virtualFiles, VIRTUAL_FILE_PRESENTATION_COMPARATOR);
}
@NotNull
public static List<VirtualFile> findVirtualFilesWithRefresh(@NotNull List<File> files) {
RefreshVFsSynchronously.refreshFiles(files);
return ContainerUtil.mapNotNull(files, new Function<File, VirtualFile>() {
@Override
public VirtualFile fun(File file) {
return VfsUtil.findFileByIoFile(file, false);
}
});
}
/**
* @deprecated use {@link VcsImplUtil#getShortVcsRootName}
*/
@NotNull
@Deprecated
public static String getShortRepositoryName(@NotNull Project project, @NotNull VirtualFile root) {
return VcsImplUtil.getShortVcsRootName(project, root);
}
@NotNull
public static String getShortRepositoryName(@NotNull Repository repository) {
return getShortRepositoryName(repository.getProject(), repository.getRoot());
}
@NotNull
public static String getShortNames(@NotNull Collection<? extends Repository> repositories) {
return StringUtil.join(repositories, new Function<Repository, String>() {
@Override
public String fun(Repository repository) {
return getShortRepositoryName(repository);
}
}, ", ");
}
@NotNull
public static String fileOrFolder(@NotNull VirtualFile file) {
if (file.isDirectory()) {
return "folder";
}
else {
return "file";
}
}
public static boolean anyRepositoryIsFresh(Collection<? extends Repository> repositories) {
for (Repository repository : repositories) {
if (repository.isFresh()) {
return true;
}
}
return false;
}
@Nullable
public static String joinMessagesOrNull(@NotNull Collection<String> messages) {
String joined = StringUtil.join(messages, "\n");
return StringUtil.isEmptyOrSpaces(joined) ? null : joined;
}
/**
* Returns the currently selected file, based on which VcsBranch or StatusBar components will identify the current repository root.
*/
@Nullable
public static VirtualFile getSelectedFile(@NotNull Project project) {
StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
final FileEditor fileEditor = StatusBarUtil.getCurrentFileEditor(project, statusBar);
VirtualFile result = null;
if (fileEditor != null) {
if (fileEditor instanceof TextEditor) {
Document document = ((TextEditor)fileEditor).getEditor().getDocument();
result = FileDocumentManager.getInstance().getFile(document);
}
else if (fileEditor instanceof ImageFileEditor) {
result = ((ImageFileEditor)fileEditor).getImageEditor().getFile();
}
}
if (result == null) {
final FileEditorManager manager = FileEditorManager.getInstance(project);
if (manager != null) {
Editor editor = manager.getSelectedTextEditor();
if (editor != null) {
result = FileDocumentManager.getInstance().getFile(editor.getDocument());
}
}
}
return result;
}
@NotNull
public static String getShortHash(@NotNull String hash) {
if (hash.length() < SHORT_HASH_LENGTH) {
LOG.debug("Unexpectedly short hash: [" + hash + "]");
}
if (hash.length() > LONG_HASH_LENGTH) {
LOG.debug("Unexpectedly long hash: [" + hash + "]");
}
return hash.substring(0, Math.min(SHORT_HASH_LENGTH, hash.length()));
}
@NotNull
public static String getDateString(@NotNull TimedVcsCommit commit) {
return DateFormatUtil.formatPrettyDateTime(commit.getTimestamp()) + " ";
}
@NotNull
public static AccessToken workingTreeChangeStarted(@NotNull Project project) {
ApplicationManager.getApplication().getMessageBus().syncPublisher(BatchFileChangeListener.TOPIC).batchChangeStarted(project);
return HeavyProcessLatch.INSTANCE.processStarted("Changing DVCS working tree");
}
public static void workingTreeChangeFinished(@NotNull Project project, @NotNull AccessToken token) {
token.finish();
ApplicationManager.getApplication().getMessageBus().syncPublisher(BatchFileChangeListener.TOPIC).batchChangeCompleted(project);
}
public static final Comparator<Repository> REPOSITORY_COMPARATOR = new Comparator<Repository>() {
@Override
public int compare(Repository o1, Repository o2) {
return o1.getPresentableUrl().compareTo(o2.getPresentableUrl());
}
};
public static void assertFileExists(File file, String message) throws IllegalStateException {
if (!file.exists()) {
throw new IllegalStateException(message);
}
}
/**
* Loads the file content.
* Tries 3 times, then a {@link RepoStateException} is thrown.
* Content is then trimmed and line separators get converted.
*
* @param file File to read.
* @return file content.
*/
@NotNull
public static String tryLoadFile(@NotNull final File file) throws RepoStateException {
return tryOrThrow(new Callable<String>() {
@Override
public String call() throws Exception {
return StringUtil.convertLineSeparators(FileUtil.loadFile(file)).trim();
}
}, file);
}
@Nullable
@Contract("_ , !null -> !null")
public static String tryLoadFileOrReturn(@NotNull final File file, @Nullable String defaultValue) {
try {
return tryLoadFile(file);
}
catch (RepoStateException e) {
LOG.error(e);
return defaultValue;
}
}
/**
* Tries to execute the given action.
* If an IOException happens, tries again up to 3 times, and then throws a {@link RepoStateException}.
* If an other exception happens, rethrows it as a {@link RepoStateException}.
* In the case of success returns the result of the task execution.
*/
private static <T> T tryOrThrow(Callable<T> actionToTry, File fileToLoad) throws RepoStateException {
IOException cause = null;
for (int i = 0; i < IO_RETRIES; i++) {
try {
return actionToTry.call();
}
catch (IOException e) {
LOG.info("IOException while loading " + fileToLoad, e);
cause = e;
}
catch (Exception e) { // this shouldn't happen since only IOExceptions are thrown in clients.
throw new RepoStateException("Couldn't load file " + fileToLoad, e);
}
}
throw new RepoStateException("Couldn't load file " + fileToLoad, cause);
}
public static void visitVcsDirVfs(@NotNull VirtualFile vcsDir, @NotNull Collection<String> subDirs) {
vcsDir.getChildren();
for (String subdir : subDirs) {
VirtualFile dir = vcsDir.findFileByRelativePath(subdir);
// process recursively, because we need to visit all branches under refs/heads and refs/remotes
ensureAllChildrenInVfs(dir);
}
}
public static void ensureAllChildrenInVfs(@Nullable VirtualFile dir) {
if (dir != null) {
//noinspection unchecked
VfsUtilCore.processFilesRecursively(dir, Processor.TRUE);
}
}
public static void addMappingIfSubRoot(@NotNull Project project, @NotNull String newRepositoryPath, @NotNull String vcsName) {
if (project.getBasePath() != null && FileUtil.isAncestor(project.getBasePath(), newRepositoryPath, true)) {
ProjectLevelVcsManager manager = ProjectLevelVcsManager.getInstance(project);
manager.setDirectoryMappings(VcsUtil.addMapping(manager.getDirectoryMappings(), newRepositoryPath, vcsName));
}
}
@Nullable
public static <T extends Repository> T guessRepositoryForFile(@NotNull Project project,
@NotNull RepositoryManager<T> manager,
@Nullable VirtualFile file,
@Nullable String defaultRootPathValue) {
T repository = manager.getRepositoryForRoot(guessVcsRoot(project, file));
return repository != null ? repository : manager.getRepositoryForRoot(guessRootForVcs(project, manager.getVcs(), defaultRootPathValue));
}
@Nullable
public static <T extends Repository> T guessCurrentRepositoryQuick(@NotNull Project project,
@NotNull AbstractRepositoryManager<T> manager,
@Nullable String defaultRootPathValue) {
T repository = manager.getRepositoryForRootQuick(guessVcsRoot(project, getSelectedFile(project)));
return repository != null
? repository
: manager.getRepositoryForRootQuick(guessRootForVcs(project, manager.getVcs(), defaultRootPathValue));
}
@Nullable
private static VirtualFile guessRootForVcs(@NotNull Project project, @Nullable AbstractVcs vcs, @Nullable String defaultRootPathValue) {
if (project.isDisposed()) return null;
LOG.debug("Guessing vcs root...");
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
if (vcs == null) {
LOG.debug("Vcs not found.");
return null;
}
String vcsName = vcs.getDisplayName();
VirtualFile[] vcsRoots = vcsManager.getRootsUnderVcs(vcs);
if (vcsRoots.length == 0) {
LOG.debug("No " + vcsName + " roots in the project.");
return null;
}
if (vcsRoots.length == 1) {
VirtualFile onlyRoot = vcsRoots[0];
LOG.debug("Only one " + vcsName + " root in the project, returning: " + onlyRoot);
return onlyRoot;
}
// get remembered last visited repository root
if (defaultRootPathValue != null) {
VirtualFile recentRoot = VcsUtil.getVirtualFile(defaultRootPathValue);
if (recentRoot != null) {
LOG.debug("Returning the recent root: " + recentRoot);
return recentRoot;
}
}
// otherwise return the root of the project dir or the root containing the project dir, if there is such
VirtualFile projectBaseDir = project.getBaseDir();
if (projectBaseDir == null) {
VirtualFile firstRoot = vcsRoots[0];
LOG.debug("Project base dir is null, returning the first root: " + firstRoot);
return firstRoot;
}
VirtualFile rootCandidate;
for (VirtualFile root : vcsRoots) {
if (root.equals(projectBaseDir) || VfsUtilCore.isAncestor(root, projectBaseDir, true)) {
LOG.debug("The best candidate: " + root);
return root;
}
}
rootCandidate = vcsRoots[0];
LOG.debug("Returning the best candidate: " + rootCandidate);
return rootCandidate;
}
public static class Updater implements Consumer<Object> {
private final Repository myRepository;
public Updater(Repository repository) {
myRepository = repository;
}
@Override
public void consume(Object dummy) {
if (!Disposer.isDisposed(myRepository)) {
myRepository.update();
}
}
}
public static <T extends Repository> List<T> sortRepositories(@NotNull Collection<T> repositories) {
List<T> validRepositories = ContainerUtil.filter(repositories, new Condition<T>() {
@Override
public boolean value(T t) {
return t.getRoot().isValid();
}
});
Collections.sort(validRepositories, REPOSITORY_COMPARATOR);
return validRepositories;
}
@Nullable
private static VirtualFile getVcsRootForLibraryFile(@NotNull Project project, @NotNull VirtualFile file) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
// for a file inside .jar/.zip consider the .jar/.zip file itself
VirtualFile root = vcsManager.getVcsRootFor(VfsUtilCore.getVirtualFileForJar(file));
if (root != null) {
LOGGER.debug("Found root for zip/jar file: " + root);
return root;
}
// for other libs which don't have jars inside the project dir (such as JDK) take the owner module of the lib
List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(file);
Set<VirtualFile> libraryRoots = new HashSet<VirtualFile>();
for (OrderEntry entry : entries) {
if (entry instanceof LibraryOrderEntry || entry instanceof JdkOrderEntry) {
VirtualFile moduleRoot = vcsManager.getVcsRootFor(entry.getOwnerModule().getModuleFile());
if (moduleRoot != null) {
libraryRoots.add(moduleRoot);
}
}
}
if (libraryRoots.size() == 0) {
LOGGER.debug("No library roots");
return null;
}
// if the lib is used in several modules, take the top module
// (for modules of the same level we can't guess anything => take the first one)
Iterator<VirtualFile> libIterator = libraryRoots.iterator();
VirtualFile topLibraryRoot = libIterator.next();
while (libIterator.hasNext()) {
VirtualFile libRoot = libIterator.next();
if (VfsUtilCore.isAncestor(libRoot, topLibraryRoot, true)) {
topLibraryRoot = libRoot;
}
}
LOGGER.debug("Several library roots, returning " + topLibraryRoot);
return topLibraryRoot;
}
@Nullable
public static VirtualFile guessVcsRoot(@NotNull Project project, @Nullable VirtualFile file) {
VirtualFile root = null;
if (file != null) {
root = ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file);
if (root == null) {
LOGGER.debug("Cannot get root by file. Trying with get by library: " + file);
root = getVcsRootForLibraryFile(project, file);
}
}
return root;
}
@NotNull
public static <R extends Repository> Map<R, List<VcsFullCommitDetails>> groupCommitsByRoots(@NotNull RepositoryManager<R> repoManager,
@NotNull List<? extends VcsFullCommitDetails> commits) {
Map<R, List<VcsFullCommitDetails>> groupedCommits = ContainerUtil.newHashMap();
for (VcsFullCommitDetails commit : commits) {
R repository = repoManager.getRepositoryForRoot(commit.getRoot());
if (repository == null) {
LOGGER.info("No repository found for commit " + commit);
continue;
}
List<VcsFullCommitDetails> commitsInRoot = groupedCommits.get(repository);
if (commitsInRoot == null) {
commitsInRoot = ContainerUtil.newArrayList();
groupedCommits.put(repository, commitsInRoot);
}
commitsInRoot.add(commit);
}
return groupedCommits;
}
@Nullable
public static PushSupport getPushSupport(@NotNull final AbstractVcs vcs) {
return ContainerUtil.find(Extensions.getExtensions(PushSupport.PUSH_SUPPORT_EP, vcs.getProject()), new Condition<PushSupport>() {
@Override
public boolean value(final PushSupport support) {
return support.getVcs().equals(vcs);
}
});
}
@NotNull
public static String joinShortNames(@NotNull Collection<? extends Repository> repositories) {
return joinShortNames(repositories, -1);
}
@NotNull
public static String joinShortNames(@NotNull Collection<? extends Repository> repositories, int limit) {
return joinWithAnd(ContainerUtil.map(repositories, new Function<Repository, String>() {
@Override
public String fun(@NotNull Repository repository) {
return getShortRepositoryName(repository);
}
}), limit);
}
@NotNull
public static String joinWithAnd(@NotNull List<String> strings, int limit) {
int size = strings.size();
if (size == 0) return "";
if (size == 1) return strings.get(0);
if (size == 2) return strings.get(0) + " and " + strings.get(1);
boolean isLimited = limit >= 2 && limit < size;
int listCount = isLimited ? limit - 1 : size - 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < listCount; i++) {
if (i != 0) sb.append(", ");
sb.append(strings.get(i));
}
if (isLimited) {
sb.append(" and ").append(size - limit + 1).append(" others");
}
else {
sb.append(" and ").append(strings.get(size - 1));
}
return sb.toString();
}
}
| apache-2.0 |
haiquangtran/DesignPatterns | src/hqt/designpatterns/patterns/command/exampleone/RemoteControl.java | 1574 | package hqt.designpatterns.patterns.command.exampleone;
/**
* An API that is able to control various different devices
* and interact with the different device API's without being
* tightly coupled with them.
*
* The Command pattern allows you to decouple the requester of an action
* from the object that actually performs the action. So, here the requester
* would be the remote control and the object that performs the action
* would be an instance of one of your vendor classes (devices).
*
* @author Hai
*
*/
public class RemoteControl {
private Command[] onCommands;
private Command[] offCommands;
public RemoteControl() {
int size = 4;
this.onCommands = new Command[size];
this.offCommands = new Command[size];
// initialize
for (int i = 0; i < size; i++) {
onCommands[i] = new NoCommand();
offCommands[i] = new NoCommand();
}
}
public void setCommand(int slot, Command onCommand, Command offCommand) {
this.onCommands[slot] = onCommand;
this.offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot) {
this.onCommands[slot].execute();
}
public void offButtonWasPushed(int slot) {
this.offCommands[slot].execute();
}
public String toString() {
StringBuffer stringBuff = new StringBuffer();
stringBuff.append("\n------- Remote Control ---------\n");
for (int i = 0; i < onCommands.length; i++) {
stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName()
+ " " + offCommands[i].getClass().getName() + "\n");
}
return stringBuff.toString();
}
}
| apache-2.0 |
LionelOrange/androidstudioprojects | DatabaseTest/app/src/main/java/com/example/chen/databasetest/MainActivity.java | 4812 | package com.example.chen.databasetest;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private MydatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createDatabase=(Button) findViewById(R.id.create_database);
dbHelper=new MydatabaseHelper(this,"BookStore.db",null,2);
createDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase();
}
});
Button addData=(Button) findViewById(R.id.add_data);
addData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name","The Da Vinci Code");
values.put("author","Dan Brown");
values.put("pages",454);
values.put("price",16.96);
db.insert("Book",null,values);
values.clear();
values.put("name","The Lost Symbol");
values.put("author","Dan Brown");
values.put("pages",510);
values.put("price",19.95);
db.insert("Book",null,values);
}
});
Button updateData=(Button) findViewById(R.id.update_data);
updateData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("price",10.99);
db.update("Book",values,"name=?",new String[]{"The Da Vinci Code"});
}
});
Button deleteButton=(Button) findViewById(R.id.delete_data);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.delete("Book","pages>?",new String[]{"500"});
}
});
Button queryButton=(Button) findViewById(R.id.query_data);
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
Cursor cursor=db.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
String name=cursor.getString(cursor.getColumnIndex("name"));
String author=cursor.getString(cursor.getColumnIndex("author"));
int pages=cursor.getInt(cursor.getColumnIndex("pages"));
double price=cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("MainActivity","book name is"+name);
Log.d("MainActivity","book author is "+author);
Log.d("MainActivity","book pages is "+pages);
Log.d("MainActivity","book price is "+price);
}while (cursor.moveToNext());
}
cursor.close();
}
});
Button replaceData=(Button) findViewById(R.id.replace_data);
replaceData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.beginTransaction();
try{
db.delete("Book",null,null);
if(true){
throw new NullPointerException();
}
ContentValues values=new ContentValues();
values.put("name","Game of Thrones");
values.put("author","George Martin");
values.put("pages",720);
values.put("price",20.85);
db.insert("Book",null,values);
db.setTransactionSuccessful();
}catch (Exception e){
e.printStackTrace();
}finally {
db.endTransaction();
}
}
});
}
}
| apache-2.0 |
lingcreative/play-dbx | src/main/java/dbx/core/package-info.java | 176 | /**
* Provides basic classes for exception handling and version detection,
* and other core helpers that are not specific to any part of the framework.
*/
package dbx.core;
| apache-2.0 |
Kvest/tests | app/src/main/java/com/kvest/tests/ui/activity/SimpleRecyclerViewActivity.java | 4067 | package com.kvest.tests.ui.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.kvest.tests.R;
import android.support.v7.widget.RecyclerView;
import com.kvest.tests.ui.adapter.SimpleRecyclerViewAdapter;
import com.kvest.tests.ui.widget.CustomLayoutManager;
import java.util.Random;
/**
* User: roman
* Date: 12/26/14
* Time: 1:31 PM
*/
public class SimpleRecyclerViewActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
private static final int DATASET_SIZE = 1000;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
public static void startActivity(Context context) {
Intent intent = new Intent(context, SimpleRecyclerViewActivity.class);
context.startActivity(intent);
}
//TODO
// 3) Кастомный LayoutManager
// 4) Анимации
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_recycler_view_activity);
init();
}
private void init() {
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
RadioGroup layoutManagerType = (RadioGroup)findViewById(R.id.layout_manager_type);
layoutManagerType.setOnCheckedChangeListener(this);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
//set layout manager
onCheckedChanged(layoutManagerType, layoutManagerType.getCheckedRadioButtonId());
//create dataset
String[] dataset = new String[DATASET_SIZE];
Random r = new Random();
for (int i = 0; i < DATASET_SIZE; ++i) {
dataset[i] = "Test " + (i + r.nextInt(100));
}
// specify an adapter (see also next example)
mAdapter = new SimpleRecyclerViewAdapter(dataset);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.vertical_layout_manager :
// use vertical linear layout manager
RecyclerView.LayoutManager verticalLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(verticalLayoutManager);
break;
case R.id.horizontal_layout_manager :
// use vertical linear layout manager
RecyclerView.LayoutManager horizontallLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(horizontallLayoutManager);
break;
case R.id.grid_layout_manager :
RecyclerView.LayoutManager gridLayoutManager = new GridLayoutManager(this, 4 , GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(gridLayoutManager);
break;
case R.id.staggered_grid_layout_manager :
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);
staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
mRecyclerView.setLayoutManager(staggeredGridLayoutManager);
break;
case R.id.custom_layout_manager :
RecyclerView.LayoutManager customLayoutManager = new CustomLayoutManager();
mRecyclerView.setLayoutManager(customLayoutManager);
break;
}
}
}
| apache-2.0 |
ralscha/extdirectspring | src/test/java/ch/ralscha/extdirectspring_itest/ExceptionFormPostController.java | 1396 | /**
* Copyright 2010-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.ralscha.extdirectspring_itest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType;
@Controller
@RequestMapping("/exceptionTest")
public class ExceptionFormPostController {
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload")
@RequestMapping(value = "/throwIt", method = RequestMethod.POST)
public void throwAException(@SuppressWarnings("unused") HttpServletRequest request) {
throw new NullPointerException("a null pointer");
}
}
| apache-2.0 |
spring-projects/spring-framework | spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/Person.java | 1566 | /*
* 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 org.springframework.test.web.reactive.server.samples;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
class Person {
private String name;
// No-arg constructor for XML
public Person() {
}
@JsonCreator
public Person(@JsonProperty("name") String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Person person = (Person) other;
return getName().equals(person.getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
@Override
public String toString() {
return "Person[name='" + name + "']";
}
}
| apache-2.0 |
hoeghen/minlokaleScheduler | src/test/java/bitwork/dk/FireBaseRetrieverTest.java | 957 | package bitwork.dk;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* Kan jeg hente tilbud og emails fra firebase
* Created by cha on 04-10-2015.
*/
public class FireBaseRetrieverTest extends TestCase {
public void testRetrieveNotifications() throws Exception {
Map<String, User> notifications = new FireBaseRetriever().retrieveNotifications();
Assert.assertTrue(notifications.keySet().size() > 0);
}
public void testRetrieveAlleTilbud() throws Exception {
Map<String, Tilbud> stringTilbudMap = new FireBaseRetriever().retrieveAlleTilbud();
Assert.assertTrue(stringTilbudMap.keySet().size() > 0);
Collection<Tilbud> values = stringTilbudMap.values();
for (Tilbud value : values) {
System.out.println("acvtive="+value.active() + " slut="+value.getSlut());
}
}
} | apache-2.0 |
OneDecision/one-decision | one-decision-engine/src/main/java/io/onedecision/engine/decisions/model/dmn/DrgElement.java | 2106 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.10.30 at 01:30:38 PM GMT
//
package io.onedecision.engine.decisions.model.dmn;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for tDRGElement complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tDRGElement">
* <complexContent>
* <extension base="{http://www.omg.org/spec/DMN/20151101/dmn.xsd}tNamedElement">
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tDRGElement")
@XmlSeeAlso({
Decision.class,
BusinessKnowledgeModel.class,
InputData.class,
KnowledgeSource.class
})
public class DrgElement extends NamedElement implements Serializable {
private static final long serialVersionUID = -7746588678579419013L;
@Override
public DrgElement withName(String value) {
setName(value);
return this;
}
@Override
public DrgElement withDescription(String value) {
setDescription(value);
return this;
}
@Override
public DrgElement withExtensionElements(io.onedecision.engine.decisions.model.dmn.DmnElement.ExtensionElements value) {
setExtensionElements(value);
return this;
}
@Override
public DrgElement withId(String value) {
setId(value);
return this;
}
@Override
public DrgElement withLabel(String value) {
setLabel(value);
return this;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-fsx/src/main/java/com/amazonaws/services/fsx/model/IncompatibleRegionForMultiAZException.java | 1335 | /*
* 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.fsx.model;
import javax.annotation.Generated;
/**
* <p>
* Amazon FSx doesn't support Multi-AZ Windows File Server copy backup in the destination Region, so the copied backup
* can't be restored.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class IncompatibleRegionForMultiAZException extends com.amazonaws.services.fsx.model.AmazonFSxException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new IncompatibleRegionForMultiAZException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public IncompatibleRegionForMultiAZException(String message) {
super(message);
}
}
| apache-2.0 |
anilnamde/MafiaJava | test/src/test/DoctorTest.java | 504 | package test;
import com.company.domain.dto.Doctor;
import com.company.domain.dto.Role;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class DoctorTest {
@Test
public void test_Doctor() throws Exception {
Doctor doc = new Doctor("firstName", "lastName");
assertThat(doc.getRole(), is(Role.DOCTOR));
assertThat(doc.getFirstName(), is("firstName"));
assertThat(doc.getLastName(), is("lastName"));
}
} | apache-2.0 |
noties/Markwon | markwon-core/src/test/java/io/noties/markwon/SpannableBuilderTest.java | 10886 | package io.noties.markwon;
import androidx.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import java.util.List;
import ix.Ix;
import ix.IxFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static io.noties.markwon.SpannableBuilder.isPositionValid;
import static io.noties.markwon.SpannableBuilder.setSpans;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class SpannableBuilderTest {
private SpannableBuilder builder;
@Before
public void before() {
builder = new SpannableBuilder();
}
@Test
public void position_invalid() {
final Position[] positions = {
Position.of(0, 0, 0),
Position.of(-1, -1, -1),
Position.of(0, -1, 1),
Position.of(1, 1, 1),
Position.of(0, 0, 10),
Position.of(10, 10, 0),
Position.of(10, 5, 2),
Position.of(5, 1, 1)
};
for (Position position : positions) {
assertFalse(position.toString(), isPositionValid(position.length, position.start, position.end));
}
}
@Test
public void position_valid() {
final Position[] positions = {
Position.of(1, 0, 1),
Position.of(2, 0, 1),
Position.of(2, 1, 2),
Position.of(10, 0, 10),
Position.of(7, 6, 7)
};
for (Position position : positions) {
assertTrue(position.toString(), isPositionValid(position.length, position.start, position.end));
}
}
@Test
public void get_spans() {
// all spans that overlap with specified range or spans that include it fully -> should be returned
final int length = 10;
for (int i = 0; i < length; i++) {
builder.append(String.valueOf(i));
}
for (int start = 0, end = length - 1; start < end; start++, end--) {
builder.setSpan("" + start + "-" + end, start, end);
}
// all (simple check that spans that take range greater that supplied range are also returned)
final List<String> all = Arrays.asList("0-9", "1-8", "2-7", "3-6", "4-5");
for (int start = 0, end = length - 1; start < end; start++, end--) {
assertEquals(
"" + start + "-" + end,
all,
getSpans(start, end)
);
}
assertEquals(
"1-3",
Arrays.asList("0-9", "1-8", "2-7"),
getSpans(1, 3)
);
assertEquals(
"1-10",
all,
getSpans(1, 10)
);
assertEquals(
"5-10",
Arrays.asList("0-9", "1-8", "2-7", "3-6"),
getSpans(5, 10)
);
assertEquals(
"7-10",
Arrays.asList("0-9", "1-8"),
getSpans(7, 10)
);
}
@Test
public void get_spans_out_of_range() {
// let's test that if span.start >= range.start -> it will be less than range.end
// if span.end <= end -> it will be greater than range.start
for (int i = 0; i < 10; i++) {
builder.append(String.valueOf(i));
builder.setSpan("" + i + "-" + (i + 1), i, i + 1);
}
assertEquals(10, getSpans(0, 10).size());
// so
// 0-1
// 1-2
// 2-3
// etc
//noinspection ArraysAsListWithZeroOrOneArgument
assertEquals(
"0-1",
Arrays.asList("0-1"),
getSpans(0, 1)
);
assertEquals(
"1-5",
Arrays.asList("1-2", "2-3", "3-4", "4-5"),
getSpans(1, 5)
);
}
@NonNull
private List<String> getSpans(int start, int end) {
return Ix.from(builder.getSpans(start, end))
.map(new IxFunction<SpannableBuilder.Span, String>() {
@Override
public String apply(SpannableBuilder.Span span) {
return (String) span.what;
}
})
.toList();
}
@Test
public void set_spans_position_invalid() {
// if supplied position is invalid, no spans should be added
builder.append('0');
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
setSpans(builder, new Object(), -1, -1);
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
}
@Test
public void set_spans_single() {
// single span as `spans` argument correctly added
builder.append('0');
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
final Object span = new Object();
setSpans(builder, span, 0, 1);
final List<SpannableBuilder.Span> spans = builder.getSpans(0, builder.length());
assertEquals(1, spans.size());
assertEquals(span, spans.get(0).what);
}
@Test
public void set_spans_array_detected() {
// if supplied `spans` argument is an array -> it should be expanded
builder.append('0');
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
final Object[] spans = {
new Object(),
new Object(),
new Object()
};
setSpans(builder, spans, 0, 1);
final List<SpannableBuilder.Span> actual = builder.getSpans(0, builder.length());
assertEquals(spans.length, actual.size());
for (int i = 0, length = spans.length; i < length; i++) {
assertEquals(spans[i], actual.get(i).what);
}
}
@Test
public void set_spans_array_of_arrays() {
// if array of arrays is supplied -> it won't be expanded to single elements
builder.append('0');
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
final Object[] flatSpans = {
new Object(),
new Object(),
new Object(),
new Object(),
new Object()
};
final Object[] spans = {
new Object[]{
flatSpans[0], flatSpans[1]
},
new Object[]{
flatSpans[2], flatSpans[3], flatSpans[4]
}
};
setSpans(builder, spans, 0, 1);
final List<SpannableBuilder.Span> actual = builder.getSpans(0, builder.length());
assertEquals(flatSpans.length, actual.size());
for (int i = 0, length = spans.length; i < length; i++) {
assertEquals(flatSpans[i], actual.get(i).what);
}
}
@Test
public void set_spans_null() {
// if `spans` argument is null, then nothing will be added
builder.append('0');
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
setSpans(builder, null, 0, builder.length());
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
}
@Test
public void spans_reversed() {
// resulting SpannableStringBuilder should have spans reversed
final Object[] spans = {
0,
1,
2
};
for (Object span : spans) {
builder.append(span.toString(), span);
}
final SpannableStringBuilder spannableStringBuilder = builder.spannableStringBuilder();
final Object[] actual = spannableStringBuilder.getSpans(0, builder.length(), Object.class);
for (int start = 0, length = spans.length, end = length - 1; start < length; start++, end--) {
assertEquals(spans[start], actual[end]);
}
}
@Test
public void append_spanned_normal() {
// #append is called with regular Spanned content -> spans should be added in reverse
final SpannableStringBuilder ssb = new SpannableStringBuilder();
for (int i = 0; i < 3; i++) {
ssb.append(String.valueOf(i));
ssb.setSpan(i, i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
builder.append(ssb);
assertEquals("012", builder.toString());
// this one would return normal order as spans are reversed here
// final List<SpannableBuilder.Span> spans = builder.getSpans(0, builder.length());
final SpannableStringBuilder spannableStringBuilder = builder.spannableStringBuilder();
final Object[] spans = spannableStringBuilder.getSpans(0, builder.length(), Object.class);
assertEquals(3, spans.length);
for (int i = 0, length = spans.length; i < length; i++) {
assertEquals(length - 1 - i, spans[i]);
}
}
@Test
public void append_spanned_reversed() {
// #append is called with reversed spanned content -> spans should be added as-are
final SpannableBuilder spannableBuilder = new SpannableBuilder();
for (int i = 0; i < 3; i++) {
spannableBuilder.append(String.valueOf(i), i);
}
assertTrue(builder.getSpans(0, builder.length()).isEmpty());
builder.append(spannableBuilder.spannableStringBuilder());
final SpannableStringBuilder spannableStringBuilder = builder.spannableStringBuilder();
final Object[] spans = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), Object.class);
assertEquals(3, spans.length);
for (int i = 0, length = spans.length; i < length; i++) {
// in the end order should be as we expect in order to properly render it
// (no matter if reversed is used or not)
assertEquals(length - 1 - i, spans[i]);
}
}
private static class Position {
@NonNull
static Position of(int length, int start, int end) {
return new Position(length, start, end);
}
final int length;
final int start;
final int end;
private Position(int length, int start, int end) {
this.length = length;
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "Position{" +
"length=" + length +
", start=" + start +
", end=" + end +
'}';
}
}
} | apache-2.0 |
christophermoeketsi/multipoly | m-entity-restlet/src/main/generated-java-restlet/org/multipoly/Board/Board_board_block_lookUpForOne_ServerResourceImpl.java | 1586 | package org.multipoly.Board;
import org.multipoly.Board.Block.BlockRuntimePropertyEnum;
import org.multipoly.Board.Board.BoardRuntimePropertyEnum;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.umlg.runtime.adaptor.UMLG;
import org.umlg.runtime.restlet.UmlgRestletToJsonUtil;
import org.umlg.runtime.restlet.util.UmlgURLDecoder;
public class Board_board_block_lookUpForOne_ServerResourceImpl extends ServerResource {
private Object boardId;
/**
* default constructor for Board_board_block_lookUpForOne_ServerResourceImpl
*/
public Board_board_block_lookUpForOne_ServerResourceImpl() {
setNegotiated(false);
}
@Override
public Representation get() throws ResourceException {
try {
this.boardId = UmlgURLDecoder.decode((String)getRequestAttributes().get("boardId"));
Board resource = UMLG.get().getEntity(this.boardId);
StringBuilder json = new StringBuilder();
json.append("{\"data\": [");
json.append(UmlgRestletToJsonUtil.toJson(resource.lookupFor_board_block()));
json.append("],");
json.append(" \"meta\" : {");
json.append("\"qualifiedName\": \"RootElement::org::multipoly::Board::Board::block\"");
json.append(", \"to\": ");
json.append(BlockRuntimePropertyEnum.asJson());
json.append(", \"from\": ");
json.append(BoardRuntimePropertyEnum.asJson());
json.append("}}");
return new JsonRepresentation(json.toString());
} finally {
UMLG.get().rollback();
}
}
} | apache-2.0 |
michaelyin/wcrs | src/main/java/net/wyun/wcrs/wechat/message/resp/NewsMessage.java | 665 | package net.wyun.wcrs.wechat.message.resp;
import java.util.List;
/**
* 文本消息
*
* @author qikuo
* @date 2017-2-28
*/
public class NewsMessage extends RespBaseMessage {
// 图文消息个数,限制为10条以内
private int ArticleCount;
// 多条图文消息信息,默认第一个item为大图
private List<Article> Articles;
public int getArticleCount() {
return ArticleCount;
}
public void setArticleCount(int articleCount) {
ArticleCount = articleCount;
}
public List<Article> getArticles() {
return Articles;
}
public void setArticles(List<Article> articles) {
Articles = articles;
}
}
| apache-2.0 |
yukuai518/gobblin | gobblin-runtime/src/main/java/gobblin/runtime/util/TaskMetrics.java | 2735 | /*
* Copyright (C) 2014-2016 LinkedIn Corp. 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.
*/
package gobblin.runtime.util;
import java.util.List;
import java.util.concurrent.Callable;
import com.google.common.collect.Lists;
import gobblin.configuration.ConfigurationKeys;
import gobblin.metrics.GobblinMetrics;
import gobblin.metrics.MetricContext;
import gobblin.metrics.Tag;
import gobblin.metrics.event.TaskEvent;
import gobblin.runtime.TaskState;
/**
* An extension to {@link GobblinMetrics} specifically for tasks.
*
* @author Yinan Li
*/
public class TaskMetrics extends GobblinMetrics {
protected final String jobId;
protected TaskMetrics(TaskState taskState) {
super(name(taskState), parentContextForTask(taskState), tagsForTask(taskState));
this.jobId = taskState.getJobId();
}
/**
* Get a {@link TaskMetrics} instance for the task with the given {@link TaskState} instance.
*
* @param taskState the given {@link TaskState} instance
* @return a {@link TaskMetrics} instance
*/
public static TaskMetrics get(final TaskState taskState) {
return (TaskMetrics) GOBBLIN_METRICS_REGISTRY.getOrDefault(name(taskState), new Callable<GobblinMetrics>() {
@Override
public GobblinMetrics call()
throws Exception {
return new TaskMetrics(taskState);
}
});
}
/**
* Remove the {@link TaskMetrics} instance for the task with the given {@link TaskMetrics} instance.
*
* @param taskState the given {@link TaskState} instance
*/
public static void remove(TaskState taskState) {
remove(name(taskState));
}
private static String name(TaskState taskState) {
return "gobblin.metrics." + taskState.getJobId() + "." + taskState.getTaskId();
}
protected static List<Tag<?>> tagsForTask(TaskState taskState) {
List<Tag<?>> tags = Lists.newArrayList();
tags.add(new Tag<>(TaskEvent.METADATA_TASK_ID, taskState.getTaskId()));
tags.add(new Tag<>(TaskEvent.METADATA_TASK_ATTEMPT_ID, taskState.getTaskAttemptId().or("")));
tags.addAll(getCustomTagsFromState(taskState));
return tags;
}
private static MetricContext parentContextForTask(TaskState taskState) {
return JobMetrics.get(taskState.getProp(ConfigurationKeys.JOB_NAME_KEY), taskState.getJobId()).getMetricContext();
}
}
| apache-2.0 |
wimsymons/sling | bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/FactoryPreconditions.java | 6114 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.resourceresolver.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.resourceresolver.impl.legacy.LegacyResourceProviderWhiteboard;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderHandler;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderTracker;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class which checks whether all conditions for registering
* the resource resolver factory are fulfilled.
*/
public class FactoryPreconditions {
private static final class RequiredProvider {
public String name;
public String pid;
public Filter filter;
};
private volatile ResourceProviderTracker tracker;
private volatile List<RequiredProvider> requiredProviders;
public void activate(final BundleContext bc,
final String[] legycyConfiguration,
final String[] namesConfiguration,
final ResourceProviderTracker tracker) {
synchronized ( this ) {
this.tracker = tracker;
final List<RequiredProvider> rps = new ArrayList<RequiredProvider>();
if ( legycyConfiguration != null ) {
final Logger logger = LoggerFactory.getLogger(getClass());
for(final String r : legycyConfiguration) {
if ( r != null && r.trim().length() > 0 ) {
final String value = r.trim();
RequiredProvider rp = new RequiredProvider();
if ( value.startsWith("(") ) {
try {
rp.filter = bc.createFilter(value);
} catch (final InvalidSyntaxException e) {
logger.warn("Ignoring invalid filter syntax for required provider: " + value, e);
rp = null;
}
} else {
rp.pid = value;
}
if ( rp != null ) {
rps.add(rp);
}
}
}
}
if ( namesConfiguration != null ) {
for(final String r : namesConfiguration) {
final String value = r.trim();
if ( !value.isEmpty() ) {
final RequiredProvider rp = new RequiredProvider();
rp.name = value;
rps.add(rp);
}
}
}
this.requiredProviders = rps;
}
}
public void deactivate() {
synchronized ( this ) {
this.requiredProviders = null;
this.tracker = null;
}
}
public boolean checkPreconditions(final String unavailableName, final String unavailableServicePid) {
synchronized ( this ) {
final List<RequiredProvider> localRequiredProviders = this.requiredProviders;
final ResourceProviderTracker localTracker = this.tracker;
boolean canRegister = localTracker != null;
if (localRequiredProviders != null && localTracker != null ) {
for (final RequiredProvider rp : localRequiredProviders) {
canRegister = false;
for (final ResourceProviderHandler h : localTracker.getResourceProviderStorage().getAllHandlers()) {
final ServiceReference ref = h.getInfo().getServiceReference();
final Object servicePid = ref.getProperty(Constants.SERVICE_PID);
if ( unavailableServicePid != null && unavailableServicePid.equals(servicePid) ) {
// ignore this service
continue;
}
if ( unavailableName != null && unavailableName.equals(h.getInfo().getName()) ) {
// ignore this service
continue;
}
if ( rp.name != null && rp.name.equals(h.getInfo().getName()) ) {
canRegister = true;
break;
} else if (rp.filter != null && rp.filter.match(ref)) {
canRegister = true;
break;
} else if (rp.pid != null && rp.pid.equals(servicePid)){
canRegister = true;
break;
} else if (rp.pid != null && rp.pid.equals(ref.getProperty(LegacyResourceProviderWhiteboard.ORIGINAL_SERVICE_PID))) {
canRegister = true;
break;
}
}
if ( !canRegister ) {
break;
}
}
}
return canRegister;
}
}
}
| apache-2.0 |
kkhatua/drill | exec/vector/src/main/java/org/apache/drill/exec/vector/accessor/writer/OffsetVectorWriterImpl.java | 12001 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.vector.accessor.writer;
import org.apache.drill.exec.vector.BaseDataValueVector;
import org.apache.drill.exec.vector.UInt4Vector;
import org.apache.drill.exec.vector.accessor.InvalidConversionError;
import org.apache.drill.exec.vector.accessor.ValueType;
import org.apache.drill.exec.vector.accessor.impl.HierarchicalFormatter;
/**
* Specialized column writer for the (hidden) offset vector used
* with variable-length or repeated vectors. See comments in the
* <tt>ColumnAccessors.java</tt> template file for more details.
* <p>
* Note that the <tt>lastWriteIndex</tt> tracked here corresponds
* to the data values; it is one less than the actual offset vector
* last write index due to the nature of offset vector layouts. The selection
* of last write index basis makes roll-over processing easier as only this
* writer need know about the +1 translation required for writing.
* <p>
* The states illustrated in the base class apply here as well,
* remembering that the end offset for a row (or array position)
* is written one ahead of the vector index.
* <p>
* The vector index does create an interesting dynamic for the child
* writers. From the child writer's perspective, the states described in
* the super class are the only states of interest. Here we want to
* take the perspective of the parent.
* <p>
* The offset vector is an implementation of a repeat level. A repeat
* level can occur for a single array, or for a collection of columns
* within a repeated map. (A repeat level also occurs for variable-width
* fields, but this is a bit harder to see, so let's ignore that for
* now.)
* <p>
* The key point to realize is that each repeat level introduces an
* isolation level in terms of indexing. That is, empty values in the
* outer level have no affect on indexing in the inner level. In fact,
* the nature of a repeated outer level means that there are no empties
* in the inner level.
* <p>
* To illustrate:<pre><code>
* Offset Vector Data Vector Indexes
* lw, v > | 10 | - - - - - > | X | 10
* | 12 | - - + | X | < lw' 11
* | | + - - > | | < v' 12
* </code></pre>
* In the above, the client has just written an array of two elements
* at the current write position. The data starts at offset 10 in
* the data vector, and the next write will be at 12. The end offset
* is written one ahead of the vector index.
* <p>
* From the data vector's perspective, its last-write (lw') reflects
* the last element written. If this is an array of scalars, then the
* write index is automatically incremented, as illustrated by v'.
* (For map arrays, the index must be incremented by calling
* <tt>save()</tt> on the map array writer.)
* <p>
* Suppose the client now skips some arrays:<pre><code>
* Offset Vector Data Vector
* lw > | 10 | - - - - - > | X | 10
* | 12 | - - + | X | < lw' 11
* | | + - - > | | < v' 12
* | | | | 13
* v > | | | | 14
* </code></pre>
* The last write position does not move and there are gaps in the
* offset vector. The vector index points to the current row. Note
* that the data vector last write and vector indexes do not change,
* this reflects the fact that the the data vector's vector index
* (v') matches the tail offset
* <p>
* The
* client now writes a three-element vector:<pre><code>
* Offset Vector Data Vector
* | 10 | - - - - - > | X | 10
* | 12 | - - + | X | 11
* | 12 | - - + - - > | Y | 12
* | 12 | - - + | Y | 13
* lw, v > | 12 | - - + | Y | < lw' 14
* | 15 | - - - - - > | | < v' 15
* </code></pre>
* Quite a bit just happened. The empty offset slots were back-filled
* with the last write offset in the data vector. The client wrote
* three values, which advanced the last write and vector indexes
* in the data vector. And, the last write index in the offset
* vector also moved to reflect the update of the offset vector.
* Note that as a result, multiple positions in the offset vector
* point to the same location in the data vector. This is fine; we
* compute the number of entries as the difference between two successive
* offset vector positions, so the empty positions have become 0-length
* arrays.
* <p>
* Note that, for an array of scalars, when overflow occurs,
* we need only worry about two
* states in the data vector. Either data has been written for the
* row (as in the third example above), and so must be moved to the
* roll-over vector, or no data has been written and no move is
* needed. We never have to worry about missing values because the
* cannot occur in the data vector.
* <p>
* See {@link ObjectArrayWriter} for information about arrays of
* maps (arrays of multiple columns.)
*
* <h4>Empty Slots</h4>
*
* The offset vector writer handles empty slots in two distinct ways.
* First, the writer handles its own empties. Suppose that this is the offset
* vector for a VarChar column. Suppose we write "Foo" in the first slot. Now
* we have an offset vector with the values <tt>[ 0 3 ]</tt>. Suppose the client
* skips several rows and next writes at slot 5. We must copy the latest
* offset (3) into all the skipped slots: <tt>[ 0 3 3 3 3 3 ]</tt>. The result
* is a set of four empty VarChars in positions 1, 2, 3 and 4. (Here, remember
* that the offset vector always has one more value than the the number of rows.)
* <p>
* The second way to fill empties is in the data vector. The data vector may choose
* to fill the four "empty" slots with a value, say "X". In this case, it is up to
* the data vector to fill in the values, calling into this vector to set each
* offset. Note that when doing this, the calls are a bit different than for writing
* a regular value because we want to write at the "last write position", not the
* current row position. See {@link BaseVarWidthWriter} for an example.
*/
public class OffsetVectorWriterImpl extends AbstractFixedWidthWriter implements OffsetVectorWriter {
private static final int VALUE_WIDTH = UInt4Vector.VALUE_WIDTH;
private final UInt4Vector vector;
/**
* Offset of the first value for the current row. Used during
* overflow or if the row is restarted.
*/
private int rowStartOffset;
/**
* Cached value of the end offset for the current value. Used
* primarily for variable-width columns to allow the column to be
* rewritten multiple times within the same row. The start offset
* value is updated with the end offset only when the value is
* committed in {@link @endValue()}.
*/
protected int nextOffset;
public OffsetVectorWriterImpl(UInt4Vector vector) {
this.vector = vector;
}
@Override public BaseDataValueVector vector() { return vector; }
@Override public int width() { return VALUE_WIDTH; }
@Override
protected void realloc(int size) {
vector.reallocRaw(size);
setBuffer();
}
@Override
public ValueType valueType() { return ValueType.INTEGER; }
@Override
public void startWrite() {
super.startWrite();
nextOffset = 0;
rowStartOffset = 0;
// Special handling for first value. Alloc vector if needed.
// Offset vectors require a 0 at position 0. The (end) offset
// for row 0 starts at position 1, which is handled in
// writeOffset() below.
if (capacity * VALUE_WIDTH < MIN_BUFFER_SIZE) {
realloc(MIN_BUFFER_SIZE);
}
drillBuf.setInt(0, 0);
}
@Override
public int nextOffset() {return nextOffset; }
@Override
public int rowStartOffset() { return rowStartOffset; }
@Override
public void startRow() { rowStartOffset = nextOffset; }
/**
* Return the write offset, which is one greater than the index reported
* by the vector index.
*
* @return the offset in which to write the current offset of the end
* of the current data value
*/
protected final int prepareWrite() {
// This is performance critical code; every operation counts.
// Please be thoughtful when changing the code.
final int valueIndex = prepareFill();
final int fillCount = valueIndex - lastWriteIndex - 1;
if (fillCount > 0) {
fillEmpties(fillCount);
}
// Track the last write location for zero-fill use next time around.
lastWriteIndex = valueIndex;
return valueIndex + 1;
}
public final int prepareFill() {
final int valueIndex = vectorIndex.vectorIndex();
if (valueIndex + 1 < capacity) {
return valueIndex;
}
resize(valueIndex + 1);
// Call to resize may cause rollover, so get new write index afterwards.
return vectorIndex.vectorIndex();
}
@Override
protected final void fillEmpties(final int fillCount) {
for (int i = 0; i < fillCount; i++) {
fillOffset(nextOffset);
}
}
@Override
public final void setNextOffset(final int newOffset) {
final int writeIndex = prepareWrite();
drillBuf.setInt(writeIndex * VALUE_WIDTH, newOffset);
nextOffset = newOffset;
}
public final void reviseOffset(final int newOffset) {
final int writeIndex = vectorIndex.vectorIndex() + 1;
drillBuf.setInt(writeIndex * VALUE_WIDTH, newOffset);
nextOffset = newOffset;
}
public final void fillOffset(final int newOffset) {
drillBuf.setInt((++lastWriteIndex + 1) * VALUE_WIDTH, newOffset);
nextOffset = newOffset;
}
@Override
public final void setValue(final Object value) {
throw new InvalidConversionError(
"setValue() not supported for the offset vector writer: " + value);
}
@Override
public void skipNulls() {
// Nothing to do. Fill empties logic will fill in missing offsets.
}
@Override
public void restartRow() {
nextOffset = rowStartOffset;
super.restartRow();
}
@Override
public void preRollover() {
// Rollover is occurring. This means the current row is not complete.
// We want to keep 0..(row index - 1) which gives us (row index)
// rows. But, this being an offset vector, we add one to account
// for the extra 0 value at the start.
setValueCount(vectorIndex.rowStartIndex() + 1);
}
@Override
public void postRollover() {
final int newNext = nextOffset - rowStartOffset;
super.postRollover();
nextOffset = newNext;
}
@Override
public void setValueCount(int valueCount) {
mandatoryResize(valueCount);
// Value count is in row positions.
fillEmpties(valueCount - lastWriteIndex - 1);
vector().getBuffer().writerIndex((valueCount + 1) * VALUE_WIDTH);
}
@Override
public void dump(HierarchicalFormatter format) {
format.extend();
super.dump(format);
format
.attribute("lastWriteIndex", lastWriteIndex)
.attribute("nextOffset", nextOffset)
.endObject();
}
@Override
public void setDefaultValue(Object value) {
throw new UnsupportedOperationException("Encoding not supported for offset vectors");
}
}
| apache-2.0 |
facebook/litho | litho-processor/src/main/java/com/facebook/litho/specmodels/model/TreePropValidation.java | 2711 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.specmodels.model;
import com.facebook.litho.annotations.OnCreateTreeProp;
import com.squareup.javapoet.TypeName;
import java.util.ArrayList;
import java.util.List;
class TreePropValidation {
static List<SpecModelValidationError> validate(SpecModel specModel) {
List<SpecModelValidationError> validationErrors = new ArrayList<>();
final List<SpecMethodModel<DelegateMethod, Void>> onCreateTreePropMethods =
SpecModelUtils.getMethodModelsWithAnnotation(specModel, OnCreateTreeProp.class);
for (SpecMethodModel<DelegateMethod, Void> onCreateTreePropMethod : onCreateTreePropMethods) {
if (onCreateTreePropMethod.returnType.equals(TypeName.VOID)) {
validationErrors.add(
new SpecModelValidationError(
onCreateTreePropMethod.representedObject,
"@OnCreateTreeProp methods cannot return void."));
}
if (onCreateTreePropMethod.returnType.isPrimitive()
|| onCreateTreePropMethod.returnType.toString().startsWith("java.lang.")
|| onCreateTreePropMethod.returnType.toString().startsWith("java.util.")) {
validationErrors.add(
new SpecModelValidationError(
onCreateTreePropMethod.representedObject,
"Returning a common JAVA class or a primitive is against the design"
+ "of tree props, as they will be keyed on their specific types. Consider "
+ "creating your own wrapper classes instead."));
}
if (onCreateTreePropMethod.methodParams.isEmpty()
|| !onCreateTreePropMethod
.methodParams
.get(0)
.getTypeName()
.equals(specModel.getContextClass())) {
validationErrors.add(
new SpecModelValidationError(
onCreateTreePropMethod.representedObject,
"The first argument of an @OnCreateTreeProp method should be "
+ specModel.getContextClass()
+ "."));
}
}
return validationErrors;
}
}
| apache-2.0 |
Yggard/BrokkGUI | style/src/main/java/net/voxelindustry/brokkgui/style/shorthand/GenericShorthandProperty.java | 1965 | package net.voxelindustry.brokkgui.style.shorthand;
import net.voxelindustry.brokkgui.style.StyleProperty;
import net.voxelindustry.brokkgui.style.StyleSource;
import net.voxelindustry.brokkgui.style.adapter.StyleTranslator;
import java.util.ArrayList;
import java.util.List;
public class GenericShorthandProperty extends StyleProperty<String>
{
private final List<StyleProperty<?>> childProperties;
public GenericShorthandProperty(String defaultValue, String name)
{
super(defaultValue, name, String.class);
this.childProperties = new ArrayList<>();
}
public <C> void addChild(StyleProperty<C> childProperty)
{
childProperties.add(childProperty);
}
public void removeChild(StyleProperty<?> childProperty)
{
childProperties.remove(childProperty);
}
public void applyDefaultValue()
{
this.setStyleRaw(StyleSource.USER_AGENT, 0, this.getDefaultValue());
}
@Override
public boolean setStyleRaw(StyleSource source, int specificity, String rawValue)
{
String current = rawValue;
boolean anySet;
List<StyleProperty<?>> alreadySet = new ArrayList<>();
while (!current.isEmpty())
{
anySet = false;
for (StyleProperty<?> child : this.childProperties)
{
if (alreadySet.contains(child))
continue;
int validated = StyleTranslator.getInstance().validate(current, child.getValueClass());
if (validated != 0)
{
child.setStyleRaw(source, specificity, current.substring(0, validated));
current = current.substring(validated).trim();
alreadySet.add(child);
anySet = true;
break;
}
}
if (!anySet)
return false;
}
return true;
}
}
| apache-2.0 |
qq1588518/JRediClients | src/main/java/redis/clients/redisson/misc/RPromise.java | 2537 | /**
* Copyright 2016 Nikita Koksharov
*
* 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 redis.clients.redisson.misc;
import redis.clients.redisson.api.RFuture;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
/**
*
* @author Nikita Koksharov
*
* @param <T> type
*/
public interface RPromise<T> extends RFuture<T> {
/**
* Marks this future as a success and notifies all
* listeners.
*
* @param result object
* @return {@code true} if and only if successfully marked this future as
* a success. Otherwise {@code false} because this future is
* already marked as either a success or a failure.
*/
boolean trySuccess(T result);
/**
* Marks this future as a failure and notifies all
* listeners.
*
* @param cause object
* @return {@code true} if and only if successfully marked this future as
* a failure. Otherwise {@code false} because this future is
* already marked as either a success or a failure.
*/
boolean tryFailure(Throwable cause);
/**
* Make this future impossible to cancel.
*
* @return {@code true} if and only if successfully marked this future as uncancellable or it is already done
* without being cancelled. {@code false} if this future has been cancelled already.
*/
boolean setUncancellable();
@Override
RPromise<T> addListener(FutureListener<? super T> listener);
@Override
RPromise<T> addListeners(FutureListener<? super T>... listeners);
@Override
RPromise<T> removeListener(FutureListener<? super T> listener);
@Override
RPromise<T> removeListeners(FutureListener<? super T>... listeners);
@Override
RPromise<T> await() throws InterruptedException;
@Override
RPromise<T> awaitUninterruptibly();
@Override
RPromise<T> sync() throws InterruptedException;
@Override
RPromise<T> syncUninterruptibly();
}
| apache-2.0 |
palantir/http-remoting | conjure-java-retrofit2-client/src/test/java/com/palantir/conjure/java/client/retrofit2/Retrofit2ClientQueryParamHandlingTest.java | 2104 | /*
* (c) Copyright 2019 Palantir Technologies 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.palantir.conjure.java.client.retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import com.palantir.conjure.java.okhttp.HostMetricsRegistry;
import java.util.Arrays;
import java.util.List;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public final class Retrofit2ClientQueryParamHandlingTest extends TestBase {
@Rule
public final MockWebServer server = new MockWebServer();
private Service proxy;
@Before
public void before() {
HttpUrl url = server.url("/");
proxy = Retrofit2Client.create(
Service.class, AGENT, new HostMetricsRegistry(), createTestConfig(url.toString()));
MockResponse mockResponse = new MockResponse().setResponseCode(204);
server.enqueue(mockResponse);
}
public interface Service {
@GET("/queryList")
Call<Void> queryList(@Query("req") List<String> req);
}
@Test
public void testList() throws Exception {
proxy.queryList(Arrays.asList("str1", "str2")).execute();
RecordedRequest takeRequest = server.takeRequest();
assertThat(takeRequest.getRequestLine()).isEqualTo("GET /queryList?req=str1&req=str2 HTTP/1.1");
}
}
| apache-2.0 |
Sellegit/j2objc | runtime/src/main/java/apple/avfoundation/AVCaptureVideoPreviewLayer.java | 4787 | package apple.avfoundation;
import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.dispatch.*;
import apple.coreanimation.*;
import apple.coreaudio.*;
import apple.coremedia.*;
import apple.corevideo.*;
import apple.mediatoolbox.*;
/**
* @since Available in iOS 4.0 and later.
*/
@Library("AVFoundation/AVFoundation.h") @Mapping("AVCaptureVideoPreviewLayer")
public class AVCaptureVideoPreviewLayer
extends CALayer
{
@Mapping("initWithSession:")
public AVCaptureVideoPreviewLayer(AVCaptureSession session) { }
@Mapping("init")
public AVCaptureVideoPreviewLayer() { }
@Mapping("initWithLayer:")
public AVCaptureVideoPreviewLayer(Object layer) { }
@Mapping("session")
public native AVCaptureSession getSession();
@Mapping("setSession:")
public native void setSession(AVCaptureSession v);
/**
* @since Available in iOS 6.0 and later.
*/
@Mapping("connection")
public native AVCaptureConnection getConnection();
@Mapping("videoGravity")
public native AVLayerVideoGravity getVideoGravity();
@Mapping("setVideoGravity:")
public native void setVideoGravity(AVLayerVideoGravity v);
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("isOrientationSupported")
public native boolean isOrientationSupported();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("orientation")
public native @Representing("AVCaptureVideoOrientation") long getOrientation();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("setOrientation:")
public native void setOrientation(@Representing("AVCaptureVideoOrientation") long v);
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("isMirroringSupported")
public native boolean isMirroringSupported();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("automaticallyAdjustsMirroring")
public native boolean automaticallyAdjustsMirroring();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("setAutomaticallyAdjustsMirroring:")
public native void setAutomaticallyAdjustsMirroring(boolean v);
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("isMirrored")
public native boolean isMirrored();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("setMirrored:")
public native void setMirrored(boolean v);
/**
* @since Available in iOS 8.0 and later.
*/
@Mapping("setSessionWithNoConnection:")
public native void setSessionWithNoConnection(AVCaptureSession session);
/**
* @since Available in iOS 6.0 and later.
*/
@Mapping("captureDevicePointOfInterestForPoint:")
public native CGPoint captureDevicePointOfInterest(CGPoint pointInLayer);
/**
* @since Available in iOS 6.0 and later.
*/
@Mapping("pointForCaptureDevicePointOfInterest:")
public native CGPoint getDevicePointOfInterest(CGPoint captureDevicePointOfInterest);
/**
* @since Available in iOS 7.0 and later.
*/
@Mapping("metadataOutputRectOfInterestForRect:")
public native CGRect getRectOfInterestInLayerCoordinates(CGRect rectInLayerCoordinates);
/**
* @since Available in iOS 7.0 and later.
*/
@Mapping("rectForMetadataOutputRectOfInterest:")
public native CGRect getRectOfInterestInMetadataOutputCoordinates(CGRect rectInMetadataOutputCoordinates);
/**
* @since Available in iOS 6.0 and later.
*/
@Mapping("transformedMetadataObjectForMetadataObject:")
public native AVMetadataObject getTransformedMetadataObject(AVMetadataObject metadataObject);
@Mapping("layerWithSession:")
public static native AVCaptureVideoPreviewLayer create(AVCaptureSession session);
/**
* @since Available in iOS 8.0 and later.
*/
@Mapping("layerWithSessionWithNoConnection:")
public static native AVCaptureVideoPreviewLayer createWithNoConnection(AVCaptureSession session);
}
| apache-2.0 |
hellopsm/ansj_seg | src/org/ansj/training/crf/WordLocal.java | 550 | package org.ansj.training.crf;
import java.io.BufferedReader;
import org.ansj.library.InitDictionary;
import love.cq.util.IOUtil;
public class WordLocal {
public static void main(String[] args) throws Exception {
InitDictionary.initArrays() ;
BufferedReader reader = IOUtil.getReader("data/crf/prob_emit.txt", "UTF-8") ;
String temp = null ;
String[] strs = null ;
while((temp=reader.readLine())!=null){
strs = temp.split(":") ;
if(InitDictionary.words[strs[0].charAt(0)]==null){
System.out.println(strs[0]);
}
}
}
}
| apache-2.0 |
priyanka897/DEV_BPMABOT_2.2 | src/main/java/messageimpl/NBCaseSize.java | 7824 | package messageimpl;
public class NBCaseSize
{
public static String nbCaseSizeIntent(String channel, String period, String user_circle, String user_region, String userzone,
String real_tim_timstamp, String case_size_afyp_mtd, String case_size_afyp_ytd, String subchannel,
String user_clusters, String user_go)
{
String finalresponse="";
if("MLI".equalsIgnoreCase(channel))
{channel="";}
if("Monthly".equalsIgnoreCase(period))
{period="";}
else
{
if("FTD".equalsIgnoreCase(period))
{
period="MTD";
}
else
{
period=period.toUpperCase();
}
}
if(!"".equalsIgnoreCase(user_circle))
{
user_region="Circle "+user_circle;
}
if(!"".equalsIgnoreCase(user_go))
{
user_clusters="Office "+user_go;
}
if(!"".equalsIgnoreCase(subchannel))
{
channel = subchannel;
}
if("".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse= "As of " +real_tim_timstamp+ " Case Size MTD for MLI is Rs. "
+ case_size_afyp_mtd+ " Case Size YTD for MLI is Rs. " +case_size_afyp_ytd+
". If you want to see the channel wise business numbers, please specify.";
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse= "As of " +real_tim_timstamp+ " Case Size MTD for "+channel+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for "+channel+" is Rs. "+case_size_afyp_ytd+
". If you want to see the zone/region wise business numbers, please specify.";
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size MTD for "+userzone+ " zone is Rs. "+ case_size_afyp_mtd+" Case Size YTD for "+
userzone+" zone is Rs. "+case_size_afyp_ytd+". If you want to see the region wise business numbers, please specify.";
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size MTD for "+user_region+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for"+user_region+" is Rs. "+case_size_afyp_ytd;
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& !"".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size MTD for "+user_clusters+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for"+user_clusters+" is Rs. "+case_size_afyp_ytd;
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& !"".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size MTD for "+user_clusters+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for"+user_clusters+" is Rs. "+case_size_afyp_ytd;
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& !"".equalsIgnoreCase(user_clusters)
&& "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size MTD for "+user_clusters+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for"+user_clusters+" is Rs. "+case_size_afyp_ytd;
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size MTD for "+user_region+" is Rs. "+case_size_afyp_mtd+
" Case Size YTD for"+user_region+" is Rs. "+case_size_afyp_ytd;
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+ " Case Size " +period+" for "+channel+ " is Rs. "+ case_size_afyp_ytd+
". If you want to see the zone/region wise business numbers, please specify.";
}else
{
finalresponse="As of " +real_tim_timstamp+ " Case Size " +period+" for "+channel+ " is Rs. "+ case_size_afyp_mtd+
". If you want to see the zone/region wise business numbers, please specify.";
}
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+userzone+" zone is Rs. "+case_size_afyp_ytd+
". If you want to see the region wise business numbers, please specify.";
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+userzone+" zone is Rs. "+case_size_afyp_mtd+
". If you want to see the region wise business numbers, please specify.";
}
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_region+" is Rs. "+case_size_afyp_ytd;
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_region+" is Rs. "+case_size_afyp_mtd;
}
}
else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
&& !"".equalsIgnoreCase(user_clusters)&& !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_clusters+" is Rs. "+case_size_afyp_ytd;
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_clusters+" is Rs. "+case_size_afyp_mtd;
}
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& "".equalsIgnoreCase(user_clusters) && !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_region+" is Rs. "+case_size_afyp_ytd;
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_region+" is Rs. "+case_size_afyp_mtd;
}
}
else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
&& !"".equalsIgnoreCase(user_clusters) && !"".equalsIgnoreCase(period))
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_clusters+" is Rs. "+case_size_afyp_ytd;
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+" for "+user_clusters+" is Rs. "+case_size_afyp_mtd;
}
}
else
{
if("YTD".equalsIgnoreCase(period))
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+ " for MLI is Rs. "+case_size_afyp_ytd+
". If you want to see the channel wise business numbers, please specify.";
}else
{
finalresponse="As of " +real_tim_timstamp+" Case Size "+period+ " for MLI is Rs. "+case_size_afyp_mtd+
". If you want to see the channel wise business numbers, please specify.";
}
}
return finalresponse.toString();
}
}
| apache-2.0 |
davehunt/selenium | java/client/src/org/openqa/selenium/json/Json.java | 2478 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.json;
import com.google.common.reflect.TypeToken;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Json {
public static final Type LIST_OF_MAPS_TYPE = new TypeToken<List<Map<String, Object>>>() {}.getType();
public static final Type MAP_TYPE = new TypeToken<Map<String, Object>>() {}.getType();
public static final Type OBJECT_TYPE = new TypeToken<Object>() {}.getType();
private final JsonTypeCoercer fromJson = new JsonTypeCoercer();
public String toJson(Object toConvert) {
try (Writer writer = new StringWriter();
JsonOutput jsonOutput = newOutput(writer)) {
jsonOutput.write(toConvert);
return writer.toString();
} catch (IOException e) {
throw new JsonException(e);
}
}
public <T> T toType(String source, Type typeOfT) {
return toType(source, typeOfT, PropertySetting.BY_NAME);
}
public <T> T toType(String source, Type typeOfT, PropertySetting setter) {
if (setter == null) {
throw new JsonException("Mechanism for setting properties must be set");
}
try (StringReader reader = new StringReader(source);
JsonInput json = newInput(reader)) {
return fromJson.coerce(json, typeOfT, setter);
}
}
public JsonInput newInput(Reader from) throws UncheckedIOException {
return new JsonInput(from, fromJson);
}
public JsonOutput newOutput(Appendable to) throws UncheckedIOException {
return new JsonOutput(to);
}
}
| apache-2.0 |
emoranchel/DungeonsOnline | DungeonsOnline/src/main/java/net/dungeons/model/JsonIterator.java | 2557 | package net.dungeons.model;
import java.io.StringReader;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.json.Json;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
public interface JsonIterator<T> {
public T item(String name, String value);
public static void objectForEach(String json, JsonIterator<Void> iterator) {
try (JsonReader reader = Json.createReader(new StringReader(json))) {
JsonObject jsonBonus = reader.readObject();
jsonBonus.entrySet()
.stream()
.forEach((entry) -> {
iterator.item(entry.getKey(), ((JsonString) entry.getValue()).getString());
});
} catch (Exception e) {
System.err.println("Error in JsonIterator:" + json);
System.err.println(e.getClass().getName() + "::" + e.getMessage());
}
}
public static <T> List<T> objectToList(String json, JsonIterator<T> iterator) {
if (json != null && json.trim().length() > 0) {
try (JsonReader reader = Json.createReader(new StringReader(json))) {
JsonObject jsonBonus = reader.readObject();
return jsonBonus.entrySet()
.stream()
.map((entry) -> {
String key = entry.getKey();
String value = "";
switch (entry.getValue().getValueType()) {
case ARRAY:
case OBJECT:
String str = entry.getValue().toString();
value = str.substring(1, str.length() - 1);
break;
case STRING:
value = ((JsonString) entry.getValue()).getString();
break;
case NUMBER:
value = Integer.toString(((JsonNumber) entry.getValue()).intValue());
break;
case TRUE:
value = "true";
break;
case FALSE:
value = "false";
break;
case NULL:
default:
}
return iterator.item(key, value);
}).collect(Collectors.toList());
} catch (Exception e) {
System.err.println("Error in json:" + json);
System.err.println(e.getClass().getName() + "::" + e.getMessage());
}
}
return Collections.emptyList();
}
}
| apache-2.0 |
hstraub/droidparts-battery-widget | src/at/linuxhacker/battery/ScreenStatusEvent.java | 1044 | /*
* Copyright (C) 2012 Herbert Straub, herbert@linuxhacker.at
*
* 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 at.linuxhacker.battery;
public class ScreenStatusEvent {
private long timestamp; // Unix Timestamp in milliseconds
private boolean screenOnFlag;
public ScreenStatusEvent( boolean screenOnFlag) {
this.timestamp = System.currentTimeMillis( );
this.screenOnFlag = screenOnFlag;
}
public long getTimestamp( ) {
return timestamp;
}
public boolean isScreenOnFlag( ) {
return screenOnFlag;
}
}
| apache-2.0 |
dmfs/uri-toolkit | rfc3986-uri/src/main/java/org/dmfs/rfc3986/validation/CharSets.java | 4709 | /*
* Copyright 2017 dmfs GmbH
*
* 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.dmfs.rfc3986.validation;
/**
* @author Marten Gajda
*/
public final class CharSets
{
/**
* {@link BitMapCharSet} for alphabet characters.
*/
public final static CharSet ALPHA = new BitMapCharSet(0, 0, 0x07FFFFFE, 0x07FFFFFE);
/**
* {@link BitMapCharSet} for digits.
*/
public final static CharSet DIGIT = new BitMapCharSet(0, 0x03FF0000, 0, 0);
/**
* {@link BitMapCharSet} for unreserved characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* </pre>
*/
public final static CharSet UNRESERVED = new BitMapCharSet(0, 0x03FF6000, 0x87FFFFFE, 0x47FFFFFE);
/**
* {@link BitMapCharSet} for scheme characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
* </pre>
*/
public final static CharSet SCHEME_CHAR = new BitMapCharSet(0, 0x03FF6800, 0x07FFFFFE, 0x07FFFFFE);
/**
* {@link BitMapCharSet} for percent encoded characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* pct-encoded = "%" HEXDIG HEXDIG
* </pre>
*/
public final static CharSet PCT_ENCODED = new BitMapCharSet(0, 0x03FF0020, 0x0000007E, 0x0000007E);
/**
* {@link BitMapCharSet} for general delimiter characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
* </pre>
*/
public final static CharSet GEN_DELIMS = new BitMapCharSet(0, 0x84008008, 0x28000001, 0x00000000);
/**
* {@link BitMapCharSet} of characters that terminate the host part of an authority <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986,
* Appendix A</a>.
* <pre>
* gen-delims = ":" / "/" / "?" / "#"
* </pre>
*/
public final static CharSet HOST_TERMINATOR_CHARS = new BitMapCharSet(0, 0x84008008, 0x00000000, 0x00000000);
/**
* {@link BitMapCharSet} for sub-delimiter characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* </pre>
*/
public final static CharSet SUB_DELIMS = new BitMapCharSet(0, 0x28001FD2, 0x00000000, 0x00000000);
/**
* {@link BitMapCharSet} for characters of a registered name as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* reg-name = *( unreserved / pct-encoded / sub-delims )
* </pre>
*/
public final static CharSet REG_NAME_CHAR = new BitMapCharSet(0, 0x2BFF7FF2, 0x87FFFFFE, 0x47FFFFFE);
/**
* {@link BitMapCharSet} for pchar characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* </pre>
*/
public final static CharSet PCHAR = new BitMapCharSet(0, 0x2FFF7FF2, 0x87FFFFFF, 0x47FFFFFE);
// segments may contain any PCHAR
public final static CharSet SEGMENT_CHAR = PCHAR;
/**
* {@link BitMapCharSet} for query characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* query = *( pchar / "/" / "?" )
* </pre>
*/
public final static CharSet QUERY_CHAR = new BitMapCharSet(0, 0xAFFFFFF2, 0x87FFFFFF, 0x47FFFFFE);
/**
* {@link BitMapCharSet} for fragment characters as per <a href="https://tools.ietf.org/html/rfc3986#appendix-A">RFC 3986, Appendix A</a>.
* <pre>
* fragment = *( pchar / "/" / "?" )
* </pre>
*/
// this equals QUERY_CHAR
public final static CharSet FRAGMENT_CHAR = QUERY_CHAR;
private CharSets()
{
}
}
| apache-2.0 |
midikang/midi-petclinic-home | src/main/java/com/midi/samples/petclinic/config/DataSourceConfig.java | 1618 | package com.midi.samples.petclinic.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jndi.JndiObjectFactoryBean;
@Configuration
@PropertySource("classpath:spring/data-access.properties")
public class DataSourceConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
@Description("DataSource conifguration for the tomcat jdbc connnection pool")
@NotProfile("javaee")
public DataSource dataSource(){
org.apache.tomcat.jdbc.pool.DataSource dataSource=
new org.apache.tomcat.jdbc.pool.DataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean(name="dataSource")
@Description("JNDI DataSource for JEE environments")
@Profile("javaee")
public JndiObjectFactoryBean jndiDataSource()
throws IllegalArgumentException {
JndiObjectFactoryBean dataSource =
new JndiObjectFactoryBean();
dataSource.setExpectedType(DataSource.class);
dataSource.setJndiName(env.getProperty("java:com/env/jndi/petclinic"));
return dataSource;
}
}
| apache-2.0 |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/JDBCPlugin.java | 2263 | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins;
/*
* 修订记录:
* guqiu@yiji.com 2016-06-23 15:46 创建
*/
import com.yiji.falcon.agent.falcon.FalconReportObject;
import com.yiji.falcon.agent.vo.jdbc.JDBCConnectionInfo;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
/**
* JDBC 插件接口
* @author guqiu@yiji.com
*/
public interface JDBCPlugin extends Plugin{
/**
* 数据库的JDBC连接驱动名称
* @return
*/
String getJDBCDriveName();
/**
* 数据库的连接对象集合
* 系统将根据此对象建立数据库连接
* @return
*/
Collection<JDBCConnectionInfo> getConnectionInfos();
/**
* 数据库监控语句的配置文件
* 默认值 插件的简单类名第一个字母小写 加 MetricsConf.properties
* @return
* 若不需要语句配置文件,则设置其返回null
*/
default String metricsConfName(){
String className = this.getClass().getSimpleName();
return className.substring(0,1).toLowerCase() + className.substring(1) + "MetricsConf.properties";
}
/**
* 配置的数据库连接地址
*
* @return
* 返回与配置文件中配置的地址一样即可,用于启动判断
*/
String jdbcConfig();
/**
* 该插件监控的服务标记名称,目的是为能够在操作系统中准确定位该插件监控的是哪个具体服务
* 如该服务运行的端口号等
* 若不需要指定则可返回null
* @return
*/
String agentSignName();
/**
* 插件监控的服务正常运行时的內建监控报告
* 若有些特殊的监控值无法用配置文件进行配置监控,可利用此方法进行硬编码形式进行获取
* 注:此方法只有在监控对象可用时,才会调用,并加入到监控值报告中,一并上传
* @param connection
* 数据库连接 不需在方法内关闭连接
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
Collection<FalconReportObject> inbuiltReportObjectsForValid(Connection connection) throws SQLException, ClassNotFoundException;
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/CommitMarshaller.java | 3694 | /*
* 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.codecommit.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CommitMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CommitMarshaller {
private static final MarshallingInfo<String> COMMITID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("commitId").build();
private static final MarshallingInfo<String> TREEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("treeId").build();
private static final MarshallingInfo<List> PARENTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("parents").build();
private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("message").build();
private static final MarshallingInfo<StructuredPojo> AUTHOR_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("author").build();
private static final MarshallingInfo<StructuredPojo> COMMITTER_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("committer").build();
private static final MarshallingInfo<String> ADDITIONALDATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("additionalData").build();
private static final CommitMarshaller instance = new CommitMarshaller();
public static CommitMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Commit commit, ProtocolMarshaller protocolMarshaller) {
if (commit == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(commit.getCommitId(), COMMITID_BINDING);
protocolMarshaller.marshall(commit.getTreeId(), TREEID_BINDING);
protocolMarshaller.marshall(commit.getParents(), PARENTS_BINDING);
protocolMarshaller.marshall(commit.getMessage(), MESSAGE_BINDING);
protocolMarshaller.marshall(commit.getAuthor(), AUTHOR_BINDING);
protocolMarshaller.marshall(commit.getCommitter(), COMMITTER_BINDING);
protocolMarshaller.marshall(commit.getAdditionalData(), ADDITIONALDATA_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
googleapis/java-recommendations-ai | proto-google-cloud-recommendations-ai-v1beta1/src/main/java/com/google/cloud/recommendationengine/v1beta1/ListUserEventsResponseOrBuilder.java | 2921 | /*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/recommendationengine/v1beta1/user_event_service.proto
package com.google.cloud.recommendationengine.v1beta1;
public interface ListUserEventsResponseOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.recommendationengine.v1beta1.ListUserEventsResponse)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The user events.
* </pre>
*
* <code>repeated .google.cloud.recommendationengine.v1beta1.UserEvent user_events = 1;</code>
*/
java.util.List<com.google.cloud.recommendationengine.v1beta1.UserEvent> getUserEventsList();
/**
*
*
* <pre>
* The user events.
* </pre>
*
* <code>repeated .google.cloud.recommendationengine.v1beta1.UserEvent user_events = 1;</code>
*/
com.google.cloud.recommendationengine.v1beta1.UserEvent getUserEvents(int index);
/**
*
*
* <pre>
* The user events.
* </pre>
*
* <code>repeated .google.cloud.recommendationengine.v1beta1.UserEvent user_events = 1;</code>
*/
int getUserEventsCount();
/**
*
*
* <pre>
* The user events.
* </pre>
*
* <code>repeated .google.cloud.recommendationengine.v1beta1.UserEvent user_events = 1;</code>
*/
java.util.List<? extends com.google.cloud.recommendationengine.v1beta1.UserEventOrBuilder>
getUserEventsOrBuilderList();
/**
*
*
* <pre>
* The user events.
* </pre>
*
* <code>repeated .google.cloud.recommendationengine.v1beta1.UserEvent user_events = 1;</code>
*/
com.google.cloud.recommendationengine.v1beta1.UserEventOrBuilder getUserEventsOrBuilder(
int index);
/**
*
*
* <pre>
* If empty, the list is complete. If nonempty, the token to pass to the next
* request's ListUserEvents.page_token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
java.lang.String getNextPageToken();
/**
*
*
* <pre>
* If empty, the list is complete. If nonempty, the token to pass to the next
* request's ListUserEvents.page_token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
com.google.protobuf.ByteString getNextPageTokenBytes();
}
| apache-2.0 |
brockhaus-gruppe/mqtt-example | src/main/java/de/brockhaus/m2m/mqtt/util/ProductionOrderMessage.java | 1269 | package de.brockhaus.m2m.mqtt.util;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* Something which might come from a NFC Reader ...
*
* Project: mqtt-example
*
* Copyright (c) by Brockhaus Group
* www.brockhaus-gruppe.de
* @author mbohnen, Jun 23, 2015
*
*/
@XmlRootElement
public class ProductionOrderMessage implements Serializable {
private String senderId;
private String productionOrderId;
private Date date;
public ProductionOrderMessage() {
super();
}
public ProductionOrderMessage(String senderId, String productionOrderId,
Date date) {
super();
this.senderId = senderId;
this.productionOrderId = productionOrderId;
this.date = date;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getProductionOrderId() {
return productionOrderId;
}
public void setProductionOrderId(String productionOrderId) {
this.productionOrderId = productionOrderId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
//TODO implement hashCode, equals and toString
}
| apache-2.0 |
xbib/content | content-yaml/src/main/java/org/xbib/content/yaml/YamlXContent.java | 3163 | package org.xbib.content.yaml;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.xbib.content.XContent;
import org.xbib.content.XContentBuilder;
import org.xbib.content.XContentGenerator;
import org.xbib.content.XContentParser;
import org.xbib.content.io.BytesReference;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
/**
* A YAML based content implementation using Jackson.
*/
public class YamlXContent implements XContent {
private static final YamlXContent yamlXContent;
private static final YAMLFactory yamlFactory;
static {
yamlFactory = new YAMLFactory();
yamlXContent = new YamlXContent();
}
public static YamlXContent yamlContent() {
return yamlXContent;
}
public static YAMLFactory yamlFactory() {
return yamlFactory;
}
public static XContentBuilder contentBuilder() throws IOException {
return XContentBuilder.builder(yamlXContent);
}
public static XContentBuilder contentBuilder(OutputStream outputStream) throws IOException {
return XContentBuilder.builder(yamlXContent, outputStream);
}
@Override
public String name() {
return "yaml";
}
@Override
public XContentGenerator createGenerator(OutputStream os) throws IOException {
return new YamlXContentGenerator(yamlFactory.createGenerator(os, JsonEncoding.UTF8));
}
@Override
public XContentGenerator createGenerator(Writer writer) throws IOException {
return new YamlXContentGenerator(yamlFactory.createGenerator(writer));
}
@Override
public XContentParser createParser(String content) throws IOException {
return new YamlXContentParser(yamlFactory
.createParser(content.getBytes(StandardCharsets.UTF_8)));
}
@Override
public XContentParser createParser(InputStream is) throws IOException {
return new YamlXContentParser(yamlFactory.createParser(is));
}
@Override
public XContentParser createParser(byte[] data) throws IOException {
return new YamlXContentParser(yamlFactory.createParser(data));
}
@Override
public XContentParser createParser(byte[] data, int offset, int length) throws IOException {
return new YamlXContentParser(yamlFactory.createParser(data, offset, length));
}
@Override
public XContentParser createParser(BytesReference bytes) throws IOException {
return createParser(bytes.streamInput());
}
@Override
public XContentParser createParser(Reader reader) throws IOException {
return new YamlXContentParser(yamlFactory.createParser(reader));
}
@Override
public boolean isXContent(BytesReference bytes) {
int length = bytes.length() < 20 ? bytes.length() : 20;
if (length == 0) {
return false;
}
byte first = bytes.get(0);
return length > 2 && first == '-' && bytes.get(1) == '-' && bytes.get(2) == '-';
}
}
| apache-2.0 |
jaadds/product-apim | modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/utils/base/APIMIntegrationBaseTest.java | 32443 | /*
*Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.am.integration.test.utils.base;
import org.apache.axiom.om.OMElement;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.wso2.am.admin.clients.user.RemoteUserStoreManagerServiceClient;
import org.wso2.am.integration.clients.publisher.api.ApiResponse;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIInfoDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIListDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductInfoDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductListDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationInfoDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationListDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionListDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.SubscriptionDTO;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.bean.APIMURLBean;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.am.integration.test.utils.generic.APIMTestCaseUtils;
import org.wso2.am.integration.test.utils.http.HttpRequestUtil;
import org.wso2.am.integration.test.impl.RestAPIPublisherImpl;
import org.wso2.am.integration.test.impl.RestAPIStoreImpl;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.ContextXpathConstants;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.context.beans.User;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;
import org.wso2.carbon.tenant.mgt.stub.beans.xsd.TenantInfoBean;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
/**
* Base class for all API Manager integration tests
* Users need to extend this class to write integration tests.
*/
public class APIMIntegrationBaseTest {
private static final Log log = LogFactory.getLog(APIMIntegrationBaseTest.class);
protected AutomationContext storeContext, publisherContext, keyManagerContext, gatewayContextMgt,
gatewayContextWrk, backEndServer, superTenantKeyManagerContext;
protected OMElement synapseConfiguration;
protected APIMTestCaseUtils apimTestCaseUtils;
protected TestUserMode userMode;
protected String executionMode;
protected APIMURLBean storeUrls, publisherUrls, gatewayUrlsMgt, gatewayUrlsWrk, keyMangerUrl, backEndServerUrl;
protected User user;
private static final long WAIT_TIME = 45 * 1000;
protected APIPublisherRestClient apiPublisher;
protected APIStoreRestClient apiStore;
protected RestAPIPublisherImpl restAPIPublisher;
protected RestAPIStoreImpl restAPIStore;
protected UserManagementClient userManagementClient;
protected RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient;
protected TenantManagementServiceClient tenantManagementServiceClient;
protected String publisherURLHttp;
protected String publisherURLHttps;
protected String keyManagerHTTPSURL;
protected String gatewayHTTPSURL;
protected String storeURLHttp;
protected String storeURLHttps;
protected String keymanagerSessionCookie;
protected String keymanagerSuperTenantSessionCookie;
protected final int inboundWebSocketPort = 9099;
protected final int portOffset = 500; //This need to be properly fixed rather than hard coding
/**
* This method will initialize test environment
* based on user mode and configuration given at automation.xml
*
* @throws APIManagerIntegrationTestException - if test configuration init fails
*/
protected void init() throws APIManagerIntegrationTestException {
userMode = TestUserMode.SUPER_TENANT_ADMIN;
init(userMode);
}
/**
* init the object with user mode , create context objects and get session cookies
*
* @param userMode - user mode to run the tests
* @throws APIManagerIntegrationTestException - if test configuration init fails
*/
protected void init(TestUserMode userMode) throws APIManagerIntegrationTestException {
apimTestCaseUtils = new APIMTestCaseUtils();
try {
//create store server instance based on configuration given at automation.xml
storeContext =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_STORE_INSTANCE, userMode);
storeUrls = new APIMURLBean(storeContext.getContextUrls());
//create publisher server instance based on configuration given at automation.xml
publisherContext =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_PUBLISHER_INSTANCE, userMode);
publisherUrls = new APIMURLBean(publisherContext.getContextUrls());
//create gateway server instance based on configuration given at automation.xml
gatewayContextMgt =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_GATEWAY_MGT_INSTANCE, userMode);
gatewayUrlsMgt = new APIMURLBean(gatewayContextMgt.getContextUrls());
gatewayContextWrk =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_GATEWAY_WRK_INSTANCE, userMode);
gatewayUrlsWrk = new APIMURLBean(gatewayContextWrk.getContextUrls());
keyManagerContext = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_KEY_MANAGER_INSTANCE, userMode);
keyMangerUrl = new APIMURLBean(keyManagerContext.getContextUrls());
backEndServer = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.BACKEND_SERVER_INSTANCE, userMode);
backEndServerUrl = new APIMURLBean(backEndServer.getContextUrls());
executionMode = gatewayContextMgt.getConfigurationValue(ContextXpathConstants.EXECUTION_ENVIRONMENT);
user = storeContext.getContextTenant().getContextUser();
superTenantKeyManagerContext = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_KEY_MANAGER_INSTANCE,
TestUserMode.SUPER_TENANT_ADMIN);
keymanagerSessionCookie = createSession(keyManagerContext);
publisherURLHttp = publisherUrls.getWebAppURLHttp();
publisherURLHttps = publisherUrls.getWebAppURLHttps();
keyManagerHTTPSURL = keyMangerUrl.getWebAppURLHttps();
gatewayHTTPSURL = gatewayUrlsWrk.getWebAppURLNhttps();
storeURLHttp = storeUrls.getWebAppURLHttp();
storeURLHttps = storeUrls.getWebAppURLHttps();
apiPublisher = new APIPublisherRestClient(publisherURLHttp);
apiStore = new APIStoreRestClient(storeURLHttp);
restAPIPublisher = new RestAPIPublisherImpl(
publisherContext.getContextTenant().getContextUser().getUserNameWithoutDomain(),
publisherContext.getContextTenant().getContextUser().getPassword(),
publisherContext.getContextTenant().getDomain(), publisherURLHttps);
restAPIStore =
new RestAPIStoreImpl(storeContext.getContextTenant().getContextUser().getUserNameWithoutDomain(),
storeContext.getContextTenant().getContextUser().getPassword(),
storeContext.getContextTenant().getDomain(), storeURLHttps);
try {
keymanagerSuperTenantSessionCookie = new LoginLogoutClient(superTenantKeyManagerContext).login();
userManagementClient = new UserManagementClient(
keyManagerContext.getContextUrls().getBackEndUrl(), keymanagerSessionCookie);
remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient(
keyManagerContext.getContextUrls().getBackEndUrl(), keymanagerSessionCookie);
tenantManagementServiceClient = new TenantManagementServiceClient(
superTenantKeyManagerContext.getContextUrls().getBackEndUrl(),
keymanagerSuperTenantSessionCookie);
} catch (Exception e) {
throw new APIManagerIntegrationTestException(e.getMessage(), e);
}
} catch (XPathExpressionException e) {
log.error("APIM test environment initialization failed", e);
throw new APIManagerIntegrationTestException("APIM test environment initialization failed", e);
}
}
/**
* init the object with tenant domain, user key and instance of store,publisher and gateway
* create context objects and construct URL bean
*
* @param domainKey - tenant domain key
* @param userKey - tenant user key
* @throws APIManagerIntegrationTestException - if test configuration init fails
*/
protected void init(String domainKey, String userKey)
throws APIManagerIntegrationTestException {
try {
//create store server instance based configuration given at automation.xml
storeContext =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_STORE_INSTANCE, domainKey, userKey);
storeUrls = new APIMURLBean(storeContext.getContextUrls());
//create publisher server instance
publisherContext =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_PUBLISHER_INSTANCE, domainKey, userKey);
publisherUrls = new APIMURLBean(publisherContext.getContextUrls());
//create gateway server instance
gatewayContextMgt =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_GATEWAY_MGT_INSTANCE, domainKey, userKey);
gatewayUrlsMgt = new APIMURLBean(gatewayContextMgt.getContextUrls());
gatewayContextWrk =
new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_GATEWAY_WRK_INSTANCE, domainKey, userKey);
gatewayUrlsWrk = new APIMURLBean(gatewayContextWrk.getContextUrls());
keyManagerContext = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.AM_KEY_MANAGER_INSTANCE, domainKey, userKey);
keyMangerUrl = new APIMURLBean(keyManagerContext.getContextUrls());
backEndServer = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,
APIMIntegrationConstants.BACKEND_SERVER_INSTANCE, domainKey, userKey);
backEndServerUrl = new APIMURLBean(backEndServer.getContextUrls());
user = storeContext.getContextTenant().getContextUser();
} catch (XPathExpressionException e) {
log.error("Init failed", e);
throw new APIManagerIntegrationTestException("APIM test environment initialization failed", e);
}
}
/**
* @param relativeFilePath - file path to load config
* @throws APIManagerIntegrationTestException - Throws if load synapse configuration from file path
* fails
*/
protected void loadSynapseConfigurationFromClasspath(String relativeFilePath,
AutomationContext automationContext,
String sessionCookie)
throws APIManagerIntegrationTestException {
relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));
OMElement synapseConfig;
try {
synapseConfig = APIMTestCaseUtils.loadResource(relativeFilePath);
updateSynapseConfiguration(synapseConfig, automationContext, sessionCookie);
} catch (FileNotFoundException e) {
log.error("synapse config loading issue", e);
throw new APIManagerIntegrationTestException("synapse config loading issue", e);
} catch (XMLStreamException e) {
log.error("synapse config loading issue", e);
throw new APIManagerIntegrationTestException("synapse config loading issue", e);
}
}
/**
* @param automationContext - automation context instance of given server
* @return - created session cookie variable
* @throws APIManagerIntegrationTestException - Throws if creating session cookie fails
*/
protected String createSession(AutomationContext automationContext)
throws APIManagerIntegrationTestException {
LoginLogoutClient loginLogoutClient;
try {
loginLogoutClient = new LoginLogoutClient(automationContext);
return loginLogoutClient.login();
} catch (Exception e) {
log.error("session creation error", e);
throw new APIManagerIntegrationTestException("session creation error", e);
}
}
/**
* Get test artifact resources location
*
* @return - absolute patch of test artifact directory
*/
protected String getAMResourceLocation() {
return FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AM";
}
/**
* update synapse config to server
*
* @param synapseConfig - config to upload
* @param automationContext - automation context of the server instance
* @param sessionCookie - logged in session cookie
* @throws APIManagerIntegrationTestException - If synapse config update fails
*/
protected void updateSynapseConfiguration(OMElement synapseConfig,
AutomationContext automationContext,
String sessionCookie)
throws APIManagerIntegrationTestException {
if (synapseConfiguration == null) {
synapseConfiguration = synapseConfig;
} else {
Iterator<OMElement> itr = synapseConfig.cloneOMElement().getChildElements(); //ToDo
while (itr.hasNext()) {
synapseConfiguration.addChild(itr.next());
}
}
try {
APIMTestCaseUtils.updateSynapseConfiguration(synapseConfig,
automationContext.getContextUrls().getBackEndUrl(),
sessionCookie);
} catch (Exception e) {
log.error("synapse config upload error", e);
throw new APIManagerIntegrationTestException("synapse config upload error", e);
}
}
protected String getStoreURLHttp() {
return storeUrls.getWebAppURLHttp();
}
protected String getStoreURLHttps() {
return storeUrls.getWebAppURLHttps();
}
protected String getPublisherURLHttp() {
return publisherUrls.getWebAppURLHttp();
}
protected String getPublisherURLHttps() {
return publisherUrls.getWebAppURLHttps();
}
protected String getGatewayMgtURLHttp() {
return gatewayUrlsMgt.getWebAppURLHttp();
}
protected String getGatewayMgtBackendURLHttps() {
return gatewayUrlsMgt.getWebAppURLHttp();
}
protected String getGatewayMgtURLHttps() {
return gatewayUrlsMgt.getWebAppURLHttps();
}
protected String getGatewayURLHttp() {
return gatewayUrlsWrk.getWebAppURLHttp();
}
protected String getGatewayURLNhttp() {
return gatewayUrlsWrk.getWebAppURLNhttp();
}
protected String getGatewayURLHttps() {
return gatewayUrlsWrk.getWebAppURLHttps();
}
protected String getGatewayURLNhttps() {
return gatewayUrlsWrk.getWebAppURLNhttps();
}
protected String getKeyManagerURLHttp() {
return keyMangerUrl.getWebAppURLHttp();
}
protected String getKeyManagerURLHttps() throws XPathExpressionException {
return keyManagerContext.getContextUrls().getBackEndUrl().replace("/services", "");
}
protected String getAPIInvocationURLHttp(String apiContext) throws XPathExpressionException {
return gatewayContextWrk.getContextUrls().getServiceUrl().replace("/services", "") + "/" + apiContext;
}
protected String getAPIInvocationURLHttp(String apiContext, String version)
throws XPathExpressionException {
return gatewayContextWrk.getContextUrls().getServiceUrl().replace("/services", "") + "/" + apiContext + "/" + version;
}
/**
* To get the API invocation in https with context and version.
*
* @param apiContext Relevant context of the API.
* @param version Version of the API.
* @return Https url related with api context and version.
* @throws XPathExpressionException XPath Express Exception.
*/
protected String getAPIInvocationURLHttps(String apiContext, String version) throws XPathExpressionException {
return gatewayContextWrk.getContextUrls().getSecureServiceUrl().replace("/services", "") + "/" + apiContext
+ "/" + version;
}
protected String getWebSocketAPIInvocationURL(String apiContext, String version)
throws XPathExpressionException {
String url = gatewayContextWrk.getContextUrls().getServiceUrl().replace("/services", "").
replace("http", "ws");
url = url.substring(0, url.lastIndexOf(":") + 1) + (inboundWebSocketPort + portOffset) + "/" + apiContext + "/" + version;
return url;
}
protected String getWebSocketTenantAPIInvocationURL(String apiContext, String version, String tenantDomain)
throws XPathExpressionException {
String url = gatewayContextWrk.getContextUrls().getServiceUrl().replace("/services", "").
replace("http", "ws");
url = url.substring(0, url.lastIndexOf(":") + 1) + (inboundWebSocketPort + portOffset)
+ "/t/" + tenantDomain + "/" + apiContext + "/" + version;
return url;
}
protected String getAPIInvocationURLHttps(String apiContext) throws XPathExpressionException {
return gatewayContextWrk.getContextUrls().getSecureServiceUrl().replace("/services", "") + "/" + apiContext;
}
protected String getBackendEndServiceEndPointHttp(String serviceName) {
return backEndServerUrl.getWebAppURLHttp() + serviceName;
}
protected String getBackendEndServiceEndPointHttps(String serviceName) {
return backEndServerUrl.getWebAppURLHttps() + serviceName;
}
protected String getSuperTenantAPIInvocationURLHttp(String apiContext, String version)
throws XPathExpressionException {
return gatewayContextWrk.getContextUrls().getServiceUrl().replace("/services", "")
.replace("/t/" + user.getUserDomain(), "") + "/" + apiContext + "/" + version;
}
/**
* Cleaning up the API manager by removing all APIs and applications other than default application
*
* @throws APIManagerIntegrationTestException - occurred when calling the apis
*/
protected void cleanUp() throws Exception {
ApplicationListDTO applicationListDTO = restAPIStore.getAllApps();
for (ApplicationInfoDTO applicationInfoDTO: applicationListDTO.getList()) {
SubscriptionListDTO subsDTO = restAPIStore
.getAllSubscriptionsOfApplication(applicationInfoDTO.getApplicationId());
if (subsDTO != null) {
for (SubscriptionDTO subscriptionDTO : subsDTO.getList()) {
restAPIStore.removeSubscription(subscriptionDTO.getSubscriptionId());
}
}
if (!APIMIntegrationConstants.OAUTH_DEFAULT_APPLICATION_NAME.equals(applicationInfoDTO.getName())) {
restAPIStore.deleteApplication(applicationInfoDTO.getApplicationId());
}
}
APIProductListDTO allApiProducts = restAPIPublisher.getAllApiProducts();
List<APIProductInfoDTO> apiProductListDTO = allApiProducts.getList();
if (apiProductListDTO != null) {
for(APIProductInfoDTO apiProductInfoDTO : apiProductListDTO) {
restAPIPublisher.deleteApiProduct(apiProductInfoDTO.getId());
}
}
APIListDTO apiListDTO = restAPIPublisher.getAllAPIs();
if (apiListDTO != null) {
for (APIInfoDTO apiInfoDTO: apiListDTO.getList()) {
restAPIPublisher.deleteAPI(apiInfoDTO.getId());
}
}
}
protected void verifyResponse(HttpResponse httpResponse) throws JSONException {
Assert.assertNotNull(httpResponse, "Response object is null");
log.info("Response Code : " + httpResponse.getResponseCode());
log.info("Response Message : " + httpResponse.getData());
Assert.assertEquals(httpResponse.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
JSONObject responseData = new JSONObject(httpResponse.getData());
Assert.assertFalse(responseData.getBoolean(APIMIntegrationConstants.API_RESPONSE_ELEMENT_NAME_ERROR), "Error message received " + httpResponse.getData());
}
/**
* This method can be used to wait for API deployment sync in distributed and clustered environment
* APIStatusMonitor will be invoked to get API related data and then verify that data matches with
* expected response provided.
*/
protected void waitForAPIDeployment() {
try {
if (executionMode.equalsIgnoreCase(String.valueOf(ExecutionEnvironment.PLATFORM))) {
Thread.sleep(WAIT_TIME);
} else {
Thread.sleep(15000);
}
} catch (InterruptedException ignored) {
}
}
/**
* This method can be used to wait for API deployment sync in distributed and clustered environment
* APIStatusMonitor will be invoked to get API related data and then verify that data matches with
* expected response provided.
*
* @param apiProvider - Provider of the API
* @param apiName - API name
* @param apiVersion - API version
* @param expectedResponse - Expected response
* @throws APIManagerIntegrationTestException - Throws if something goes wrong
*/
protected void waitForAPIDeploymentSync(String apiProvider, String apiName, String apiVersion,
String expectedResponse)
throws APIManagerIntegrationTestException, XPathExpressionException {
long currentTime = System.currentTimeMillis();
long waitTime = currentTime + WAIT_TIME;
String colonSeparatedHeader =
keyManagerContext.getContextTenant().getTenantAdmin().getUserName() + ":" + keyManagerContext
.getContextTenant().getTenantAdmin().getPassword();
String authorizationHeader = "Basic "+new String(Base64.encodeBase64(colonSeparatedHeader.getBytes()));
Map headerMap = new HashMap();
headerMap.put("Authorization",authorizationHeader);
String tenantIdentifier = getTenantIdentifier(apiProvider);
while (waitTime > System.currentTimeMillis()) {
HttpResponse response = null;
try {
response = HttpRequestUtil.doGet(getGatewayURLHttp() +
"APIStatusMonitor/apiInformation/api/" +
tenantIdentifier +
apiName + "/" + apiVersion, headerMap);
} catch (IOException ignored) {
log.warn("WebAPP:" + " APIStatusMonitor not yet deployed or" + " API :" + apiName + " not yet " +
"deployed " + " with provider: " + apiProvider);
}
log.info("WAIT for availability of API: " + apiName + " with version: " + apiVersion
+ " with provider: " + apiProvider + " with Tenant Identifier: " + tenantIdentifier
+ " with expected response : " + expectedResponse);
if (response != null) {
log.info("Data: " + response.getData());
if (response.getData().contains(expectedResponse)) {
log.info("API :" + apiName + " with version: " + apiVersion +
" with expected response " + expectedResponse + " found");
break;
} else {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
}
}
/**
* This method can be used to wait for API Un-deployment sync in distributed and clustered environment
* APIStatusMonitor will be invoked to get API related data and then verify that data matches with
* expected response provided.
*
* @param apiProvider - Provider of the API
* @param apiName - API name
* @param apiVersion - API version
* @param expectedResponse - Expected response
* @throws APIManagerIntegrationTestException - Throws if something goes wrong
*/
protected void waitForAPIUnDeploymentSync(String apiProvider, String apiName, String apiVersion,
String expectedResponse)
throws APIManagerIntegrationTestException {
long currentTime = System.currentTimeMillis();
long waitTime = currentTime + WAIT_TIME;
String tenantIdentifier = getTenantIdentifier(apiProvider);
String colonSeparatedHeader = user.getUserName()+":"+user.getPassword();
String authorizationHeader = "Basic "+Base64.encodeBase64(colonSeparatedHeader.getBytes()).toString();
Map headerMap = new HashMap();
headerMap.put("Authorization",authorizationHeader);
while (waitTime > System.currentTimeMillis()) {
HttpResponse response = null;
try{
response = HttpRequestUtil.doGet(getGatewayURLHttp() +
"APIStatusMonitor/apiInformation/api/" +
tenantIdentifier +
apiName + "/" + apiVersion, headerMap);
} catch (IOException ignored) {
log.warn("WebAPP:" + " APIStatusMonitor not yet deployed or" + " API :" + apiName + " not yet deployed " + " with provider: " + apiProvider);
}
log.info("WAIT for meta data sync of API :" + apiName + " with version: " + apiVersion + " with provider: " + apiProvider +
" without entry : " + expectedResponse);
if (response != null) {
if (!response.getData().contains(expectedResponse)) {
log.info("API :" + apiName + " with version: " + apiVersion +
" with expected response " + expectedResponse + " not found");
break;
} else {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
}
}
/**
* This returns "tenatDomain/tenantId/" string
* @param apiProvider
*/
private String getTenantIdentifier(String apiProvider) throws APIManagerIntegrationTestException {
int tenantId = -1234;
String providerTenantDomain = MultitenantUtils.getTenantDomain(apiProvider);
try{
if(!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(providerTenantDomain)){
keymanagerSuperTenantSessionCookie = new LoginLogoutClient(superTenantKeyManagerContext).login();
tenantManagementServiceClient = new TenantManagementServiceClient(
superTenantKeyManagerContext.getContextUrls().getBackEndUrl(),
keymanagerSuperTenantSessionCookie);
TenantInfoBean tenant = tenantManagementServiceClient.getTenant(providerTenantDomain);
if(tenant == null){
log.info("tenant is null: " + providerTenantDomain);
} else {
tenantId = tenant.getTenantId();
}
//forced tenant loading
new LoginLogoutClient(gatewayContextWrk).login();
}
} catch (Exception e) {
throw new APIManagerIntegrationTestException(e.getMessage(), e);
}
return providerTenantDomain + "/" + tenantId + "/";
}
protected Header pickHeader(Header[] headers, String requiredHeader){
if (requiredHeader == null){
return null;
}
for (Header header : headers) {
if(requiredHeader.equals(header.getName())){
return header;
}
}
return null;
}
protected RestAPIPublisherImpl getRestAPIPublisherForUser(String user, String pass, String tenantDomain) {
return new RestAPIPublisherImpl(user, pass, tenantDomain, publisherURLHttps);
}
protected RestAPIStoreImpl getRestAPIStoreForUser(String user, String pass, String tenantDomain) {
return new RestAPIStoreImpl(user, pass, tenantDomain, storeURLHttps);
}
protected RestAPIStoreImpl getRestAPIStoreForAnonymousUser(String tenantDomain) {
return new RestAPIStoreImpl(tenantDomain, storeURLHttps);
}
}
| apache-2.0 |
neowu/cmn-project | cmn/src/main/java/core/aws/resource/elb/ELB.java | 5682 | package core.aws.resource.elb;
import com.amazonaws.services.elasticloadbalancing.model.ListenerDescription;
import com.amazonaws.services.elasticloadbalancing.model.LoadBalancerDescription;
import core.aws.resource.Resource;
import core.aws.resource.ResourceStatus;
import core.aws.resource.Resources;
import core.aws.resource.ec2.SecurityGroup;
import core.aws.resource.s3.Bucket;
import core.aws.resource.vpc.Subnet;
import core.aws.resource.vpc.SubnetType;
import core.aws.task.elb.CreateELBListenerTask;
import core.aws.task.elb.CreateELBTask;
import core.aws.task.elb.DeleteELBListenerTask;
import core.aws.task.elb.DeleteELBTask;
import core.aws.task.elb.DescribeELBTask;
import core.aws.task.elb.UpdateELBSGTask;
import core.aws.util.Asserts;
import core.aws.util.Lists;
import core.aws.workflow.Tasks;
import java.util.List;
import java.util.Optional;
/**
* @author neo
*/
public class ELB extends Resource {
public LoadBalancerDescription remoteELB;
public String name;
public boolean listenHTTP;
public boolean listenHTTPS;
public ServerCert cert;
public String healthCheckURL;
public SecurityGroup securityGroup;
public Subnet subnet;
public Bucket accessLogBucket;
public Optional<String> scheme = Optional.empty(); // currently only allowed value is "internal"
public String amazonCertARN;
public ELB(String id) {
super(id);
}
@Override
public void validate(Resources resources) {
if (status == ResourceStatus.LOCAL_ONLY && subnet.type == SubnetType.PRIVATE) {
Asserts.isFalse(scheme.isPresent(), "ELB in private subnet doesn't need scheme, it will be internal by default");
}
if (status == ResourceStatus.LOCAL_ONLY) {
Asserts.isTrue(name.length() <= 32, "max length of elb name is 32");
Asserts.isTrue(name.matches("[a-zA-Z0-9\\-]+"), "elb name can only contain alphanumeric, and '-'");
}
if (listenHTTPS && (status == ResourceStatus.LOCAL_ONLY || status == ResourceStatus.LOCAL_REMOTE)) {
Asserts.isTrue(amazonCertARN != null || cert != null, "https listener requires cert");
}
}
@Override
protected void createTasks(Tasks tasks) {
tasks.add(new CreateELBTask(this));
}
@Override
protected void updateTasks(Tasks tasks) {
if (sgChanged()) {
tasks.add(new UpdateELBSGTask(this));
}
CreateELBListenerTask createELBListenerTask = null;
List<String> addedProtocols = Lists.newArrayList();
if (httpListenerAdded()) addedProtocols.add("HTTP");
if (httpsListenerAdded() || httpsCertChanged()) addedProtocols.add("HTTPS");
if (!addedProtocols.isEmpty()) {
createELBListenerTask = new CreateELBListenerTask(this, addedProtocols);
tasks.add(createELBListenerTask);
}
List<String> deletedProtocols = Lists.newArrayList();
if (httpListenerRemoved()) deletedProtocols.add("HTTP");
if (httpsListenerRemoved() || httpsCertChanged()) deletedProtocols.add("HTTPS");
if (!deletedProtocols.isEmpty()) {
DeleteELBListenerTask deleteELBListenerTask = new DeleteELBListenerTask(this, deletedProtocols);
if (createELBListenerTask != null) createELBListenerTask.dependsOn(deleteELBListenerTask);
tasks.add(deleteELBListenerTask);
}
}
@Override
protected void describeTasks(Tasks tasks) {
tasks.add(new DescribeELBTask(this));
}
private boolean sgChanged() {
if (securityGroup == null) return false; // no vpc
if (securityGroup.remoteSecurityGroup == null) return true;
if (remoteELB.getSecurityGroups().isEmpty()) return true;
return !remoteELB.getSecurityGroups().get(0).equals(securityGroup.remoteSecurityGroup.getGroupId());
}
@Override
protected void deleteTasks(Tasks tasks) {
tasks.add(new DeleteELBTask(this));
}
private boolean httpListenerAdded() {
return listenHTTP && !hasRemoteHTTPListener();
}
private boolean httpListenerRemoved() {
return !listenHTTP && hasRemoteHTTPListener();
}
private boolean httpsListenerAdded() {
Optional<ListenerDescription> remoteHTTPSListener = findRemoteHTTPSListener();
return listenHTTPS && !remoteHTTPSListener.isPresent();
}
private boolean httpsListenerRemoved() {
Optional<ListenerDescription> remoteHTTPSListener = findRemoteHTTPSListener();
return !listenHTTPS && remoteHTTPSListener.isPresent();
}
boolean httpsCertChanged() {
Optional<ListenerDescription> remoteHTTPSListener = findRemoteHTTPSListener();
if (!listenHTTPS || !remoteHTTPSListener.isPresent()) return false;
String remoteCertARN = remoteHTTPSListener.get().getListener().getSSLCertificateId();
if (cert != null) { // cert files
if (cert.status == ResourceStatus.LOCAL_ONLY
|| !cert.remoteCert.getServerCertificateMetadata().getArn().equals(remoteCertARN))
return true;
return cert.changed();
} else {
return !remoteCertARN.equals(amazonCertARN);
}
}
private boolean hasRemoteHTTPListener() {
return remoteELB.getListenerDescriptions().stream().anyMatch(listener -> "HTTP".equalsIgnoreCase(listener.getListener().getProtocol()));
}
private Optional<ListenerDescription> findRemoteHTTPSListener() {
return remoteELB.getListenerDescriptions().stream().filter(listener -> "HTTPS".equalsIgnoreCase(listener.getListener().getProtocol())).findAny();
}
}
| apache-2.0 |
mobgen/halo-android | sdk-libs/halo-translations/src/main/java/com/mobgen/halo/android/translations/callbacks/DefaultTextHandler.java | 830 | package com.mobgen.halo.android.translations.callbacks;
import android.support.annotation.Keep;
import android.support.annotation.Nullable;
import com.mobgen.halo.android.framework.common.annotations.Api;
import com.mobgen.halo.android.translations.HaloTranslationsApi;
/**
* Allows the user to define a default text based on the key or return null to use the default
* text provided in the configuration.
*/
@Keep
public interface DefaultTextHandler {
/**
* Provides the default text for a given key.
*
* @param key The key requested to {@link HaloTranslationsApi#getText(String)}.
* @param isLoading Tells if the texts are being loaded.
* @return The text provided.
*/
@Keep
@Api(2.0)
@Nullable
String provideDefaultText(@Nullable String key, boolean isLoading);
}
| apache-2.0 |
xsolla/xsolla-sdk-android | xsollasdk/src/main/java/com/xsolla/android/sdk/data/model/utils/XUser.java | 2147 | package com.xsolla.android.sdk.data.model.utils;
class XUser {
private int saved_payment_method_count;// "saved_payment_method_count":0,
private int saved_charge_payment_method_count;// "saved_charge_payment_method_count":0,
private boolean vat_required;// "vat_required":false,
private String local;// "local":"en",
private String accept_language;// "accept_language":"ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,cs;q=0.2",
private String accept_encoding;// "accept_encoding":"gzip, deflate, br",
private String phone;// "phone":null,
private String tracking_id;// "tracking_id":null
private XRequisites requisites;// "requisites":{},
private XCountry country;// "country":{},
private XGeoIP geoip;// "geoip":{},
private XBalance virtual_currency_balance;// "virtual_currency_balance":{},
private XBalance user_balance;// "user_balance":{},
private XEmail email;// "email":{},
//private Object[] attributes;// "attributes":[],
boolean isVcBalance() {
return virtual_currency_balance != null;
}
boolean isAccounts() {
return !requisites.isIdAllowModify();
}
public XCountry getCountry() {
return country;
}
@Override
public String toString() {
return "XUser{" +
"saved_payment_method_count=" + saved_payment_method_count +
", saved_charge_payment_method_count=" + saved_charge_payment_method_count +
", vat_required=" + vat_required +
", local='" + local + '\'' +
", accept_language='" + accept_language + '\'' +
", accept_encoding='" + accept_encoding + '\'' +
", phone='" + phone + '\'' +
", tracking_id='" + tracking_id + '\'' +
", requisites=" + requisites +
", country=" + country +
", geoip=" + geoip +
", virtual_currency_balance=" + virtual_currency_balance +
", user_balance=" + user_balance +
", email=" + email +
'}';
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-opensearch/src/main/java/com/amazonaws/services/opensearch/model/transform/ReservedInstanceMarshaller.java | 6294 | /*
* 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.opensearch.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.opensearch.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ReservedInstanceMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ReservedInstanceMarshaller {
private static final MarshallingInfo<String> RESERVATIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReservationName").build();
private static final MarshallingInfo<String> RESERVEDINSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReservedInstanceId").build();
private static final MarshallingInfo<Long> BILLINGSUBSCRIPTIONID_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("BillingSubscriptionId").build();
private static final MarshallingInfo<String> RESERVEDINSTANCEOFFERINGID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReservedInstanceOfferingId").build();
private static final MarshallingInfo<String> INSTANCETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstanceType").build();
private static final MarshallingInfo<java.util.Date> STARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StartTime").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<Integer> DURATION_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Duration").build();
private static final MarshallingInfo<Double> FIXEDPRICE_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FixedPrice").build();
private static final MarshallingInfo<Double> USAGEPRICE_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UsagePrice").build();
private static final MarshallingInfo<String> CURRENCYCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CurrencyCode").build();
private static final MarshallingInfo<Integer> INSTANCECOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstanceCount").build();
private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("State").build();
private static final MarshallingInfo<String> PAYMENTOPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PaymentOption").build();
private static final MarshallingInfo<List> RECURRINGCHARGES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RecurringCharges").build();
private static final ReservedInstanceMarshaller instance = new ReservedInstanceMarshaller();
public static ReservedInstanceMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ReservedInstance reservedInstance, ProtocolMarshaller protocolMarshaller) {
if (reservedInstance == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(reservedInstance.getReservationName(), RESERVATIONNAME_BINDING);
protocolMarshaller.marshall(reservedInstance.getReservedInstanceId(), RESERVEDINSTANCEID_BINDING);
protocolMarshaller.marshall(reservedInstance.getBillingSubscriptionId(), BILLINGSUBSCRIPTIONID_BINDING);
protocolMarshaller.marshall(reservedInstance.getReservedInstanceOfferingId(), RESERVEDINSTANCEOFFERINGID_BINDING);
protocolMarshaller.marshall(reservedInstance.getInstanceType(), INSTANCETYPE_BINDING);
protocolMarshaller.marshall(reservedInstance.getStartTime(), STARTTIME_BINDING);
protocolMarshaller.marshall(reservedInstance.getDuration(), DURATION_BINDING);
protocolMarshaller.marshall(reservedInstance.getFixedPrice(), FIXEDPRICE_BINDING);
protocolMarshaller.marshall(reservedInstance.getUsagePrice(), USAGEPRICE_BINDING);
protocolMarshaller.marshall(reservedInstance.getCurrencyCode(), CURRENCYCODE_BINDING);
protocolMarshaller.marshall(reservedInstance.getInstanceCount(), INSTANCECOUNT_BINDING);
protocolMarshaller.marshall(reservedInstance.getState(), STATE_BINDING);
protocolMarshaller.marshall(reservedInstance.getPaymentOption(), PAYMENTOPTION_BINDING);
protocolMarshaller.marshall(reservedInstance.getRecurringCharges(), RECURRINGCHARGES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
imspa/NFC-Lottery | libraries/CardmeAndroid/src/main/java/net/sourceforge/cardme/util/Base64Wrapper.java | 4331 | package net.sourceforge.cardme.util;
/*
* Copyright 2011 George El-Haddad. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of George El-Haddad.
*/
/**
*
* @author George El-Haddad
* <br/>
* Aug 23, 2006
*
*/
public final class Base64Wrapper {
/**
* @author George El-Haddad
* <br/>
* Feb 10, 2010
*
* <p>Base64 options.</p>
*/
public enum OPTIONS {
/**
* <p>Compress the bytes to GZIP compression before encoding them
* to base64. This significantly reduces the size of the base64.
* Other applications that will decode must be aware that the encoding
* is compressed.</p>
*/
GZIP_COMPRESSION,
/**
* <p>Do not compress the bytes before encoding to base64. This is
* the default unless compression option is explicitly stated.</p>
*/
NO_COMPRESSION;
}
private Base64Wrapper() {
}
/**
* <p>Encodes the specified bytes into a base64 String
* without using GZIP compression as the default.</p>
*
* @see Base64
* @see OPTIONS
*
* @param bytes
* @return {@link String}
*/
public static String encode(byte[] bytes)
{
return encode(bytes, OPTIONS.NO_COMPRESSION);
}
/**
* <p>Encodes the specified bytes into a base64 String with the given
* options to use GZIP compression or not.</p>
*
* @see Base64
* @see OPTIONS
*
* @param bytes
* @param options
* @return {@link String}
*/
public static String encode(byte[] bytes, OPTIONS options)
{
switch(options)
{
case GZIP_COMPRESSION:
{
return Base64.encodeBytes(bytes, Base64.GZIP);
}
case NO_COMPRESSION:
{
return Base64.encodeBytes(bytes, Base64.NO_OPTIONS);
}
default:
{
return Base64.encodeBytes(bytes,Base64.NO_OPTIONS);
}
}
}
/**
* <p>Decodes a base64 String into an array of bytes. GZIP compression
* is automatically detected and decompressed.</p>
*
* @see Base64
*
* @param base64String
* @return byte[]
*/
public static byte[] decode(String base64String)
{
return Base64.decode(base64String, Base64.NO_OPTIONS);
}
// /**
// *
// * @param base64string
// * @return String
// */
// private static String unfoldBase64String(String base64string)
// {
// base64string = base64string.replaceAll(VCardUtils.LF, "");
// base64string = base64string.replaceAll(VCardUtils.CR, "");
// return base64string;
// }
//
// public static void main(String ...args) {
//
// try {
// File file = new File(Base64Wrapper.class.getResource("tux.png").toURI());
// BufferedReader br = new BufferedReader(new FileReader(file));
// int b = -1;
// int i = 0;
// byte[] bytes = new byte[(int)file.length()];
// while((b = br.read()) != -1) {
// bytes[i] = (byte)b;
// i++;
// }
//
// System.out.println(Base64Wrapper.encode(bytes));
// }
// catch(Exception ex) {
// ex.printStackTrace();
// }
// }
}
| apache-2.0 |
zapr-oss/druidry | src/main/java/in/zapr/druid/druidry/aggregator/StringLastAggregator.java | 1427 | /*
* Copyright 2018-present Red Brick Lane Marketing Solutions Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package in.zapr.druid.druidry.aggregator;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
@Getter
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class StringLastAggregator extends DruidAggregator {
private static final String STRING_LAST_TYPE = "stringLast";
private String fieldName;
private Integer maxStringBytes;
@Builder
private StringLastAggregator(@NonNull String name, @NonNull String fieldName,
Integer maxStringBytes) {
this.type = STRING_LAST_TYPE;
this.name = name;
this.fieldName = fieldName;
this.maxStringBytes = maxStringBytes;
}
}
| apache-2.0 |
plexiti/camunda-bpm-platform | qa/test-db-rolling-update/test-old-engine/src/test/java/org/camunda/bpm/qa/rolling/update/task/CompleteProcessWithParallelGatewayAndServiceTaskTest.java | 4500 | /*
* Copyright 2016 camunda services GmbH.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.qa.rolling.update.task;
import java.util.List;
import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery;
import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.qa.rolling.update.RollingUpdateConstants;
import org.camunda.bpm.qa.rolling.upgrade.EngineVersions;
import org.camunda.bpm.qa.rolling.upgrade.RollingUpdateRule;
import org.camunda.bpm.qa.upgrade.ScenarioUnderTest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
/**
* This test ensures that the old engine can complete an
* existing process with parallel gateway and service task on the new schema.
*
* @author Christopher Zell <christopher.zell@camunda.com>
*/
@ScenarioUnderTest("ProcessWithParallelGatewayAndServiceTaskScenario")
@EngineVersions({ RollingUpdateConstants.OLD_ENGINE_TAG, RollingUpdateConstants.NEW_ENGINE_TAG})
public class CompleteProcessWithParallelGatewayAndServiceTaskTest {
@Rule
public RollingUpdateRule rule = new RollingUpdateRule();
@Test
@ScenarioUnderTest("init.none.1")
public void testCompleteProcessWithParallelGateway() {
//given an already started process instance with one user task
ProcessInstance oldInstance = rule.processInstance();
Assert.assertNotNull(oldInstance);
Task task = rule.taskQuery().singleResult();
Assert.assertNotNull(task);
//and completed service task
HistoricActivityInstanceQuery historicActQuery = rule.getHistoryService()
.createHistoricActivityInstanceQuery()
.activityType("serviceTask")
.processInstanceId(oldInstance.getId())
.finished();
Assert.assertEquals(1, historicActQuery.count());
//when completing the user task
rule.getTaskService().complete(task.getId());
//then there exists no more tasks
//and the process instance is also completed
Assert.assertEquals(0, rule.taskQuery().count());
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.async.1")
public void testCompleteProcessWithParallelGatewayAndSingleUserTask() {
//given an already started process instance
ProcessInstance oldInstance = rule.processInstance();
Assert.assertNotNull(oldInstance);
//with one user task
List<Task> tasks = rule.taskQuery().list();
Assert.assertEquals(1, tasks.size());
//and async service task
Job job = rule.jobQuery().singleResult();
Assert.assertNotNull(job);
//when job is executed
rule.getManagementService().executeJob(job.getId());
//and user task completed
rule.getTaskService().complete(rule.taskQuery().singleResult().getId());
//then there exists no more tasks
//and the process instance is also completed
Assert.assertEquals(0, rule.taskQuery().count());
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.async.complete.1")
public void testQueryHistoricProcessWithParallelGateway() {
//given an already started process instance
ProcessInstance oldInstance = rule.processInstance();
Assert.assertNotNull(oldInstance);
//with one completed user task
HistoricTaskInstanceQuery historicTaskQuery = rule.getHistoryService()
.createHistoricTaskInstanceQuery()
.processInstanceId(oldInstance.getId())
.finished();
Assert.assertEquals(1, historicTaskQuery.count());
//and one async service task
Job job = rule.jobQuery().singleResult();
Assert.assertNotNull(job);
//when job is executed
rule.getManagementService().executeJob(job.getId());
//then there exists no more tasks
//and the process instance is also completed
Assert.assertEquals(0, rule.taskQuery().count());
rule.assertScenarioEnded();
}
}
| apache-2.0 |
shisoft/LinkedIn-J | core/src/main/java/com/google/code/linkedinapi/schema/xpp/UpdateActionImpl.java | 2875 | /*
* Copyright 2010-2011 Nabeel Mukhtar
*
* 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.linkedinapi.schema.xpp;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import com.google.code.linkedinapi.schema.Action;
import com.google.code.linkedinapi.schema.OriginalUpdate;
import com.google.code.linkedinapi.schema.UpdateAction;
public class UpdateActionImpl
extends BaseSchemaEntity
implements UpdateAction
{
private final static long serialVersionUID = 2461660169443089969L;
protected ActionImpl action;
protected OriginalUpdateImpl originalUpdate;
public Action getAction() {
return action;
}
public void setAction(Action value) {
this.action = ((ActionImpl) value);
}
public OriginalUpdate getOriginalUpdate() {
return originalUpdate;
}
public void setOriginalUpdate(OriginalUpdate value) {
this.originalUpdate = ((OriginalUpdateImpl) value);
}
@Override
public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, null, null);
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("action")) {
ActionImpl actionImpl = new ActionImpl();
actionImpl.init(parser);
setAction(actionImpl);
} else if (name.equals("original-update")) {
OriginalUpdateImpl updateImpl = new OriginalUpdateImpl();
updateImpl.init(parser);
setOriginalUpdate(updateImpl);
} else {
// Consume something we don't understand.
LOG.warning("Found tag that we don't recognize: " + name);
XppUtils.skipSubTree(parser);
}
}
}
@Override
public void toXml(XmlSerializer serializer) throws IOException {
serializer.startTag(null, "update-action");
if (getAction() != null) {
((ActionImpl) getAction()).toXml(serializer);
}
if (getOriginalUpdate() != null) {
((OriginalUpdateImpl) getOriginalUpdate()).toXml(serializer);
}
serializer.endTag(null, "update-action");
}
}
| apache-2.0 |
lettuce-io/lettuce-core | src/test/java/io/lettuce/core/LimitUnitTests.java | 1268 | /*
* Copyright 2011-2022 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 io.lettuce.core;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* @author Mark Paluch
*/
class LimitUnitTests {
@Test
void create() {
Limit limit = Limit.create(1, 2);
assertThat(limit.getOffset()).isEqualTo(1);
assertThat(limit.getCount()).isEqualTo(2);
assertThat(limit.isLimited()).isTrue();
}
@Test
void unlimited() {
Limit limit = Limit.unlimited();
assertThat(limit.getOffset()).isEqualTo(-1);
assertThat(limit.getCount()).isEqualTo(-1);
assertThat(limit.isLimited()).isFalse();
}
}
| apache-2.0 |
Ensembl/ensj-healthcheck | src/org/ensembl/healthcheck/eg_gui/dragAndDrop/ListOfTestsToBeRunDropListener.java | 5874 | /*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2019] EMBL-European Bioinformatics Institute
*
* 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.ensembl.healthcheck.eg_gui.dragAndDrop;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.dnd.InvalidDnDOperationException;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.swing.JList;
import org.ensembl.healthcheck.GroupOfTests;
import org.ensembl.healthcheck.TestInstantiator;
import org.ensembl.healthcheck.eg_gui.TestClassListModel;
import org.ensembl.healthcheck.eg_gui.TestInstantiatorDynamic;
import org.ensembl.healthcheck.testcase.EnsTestCase;
/**
* <p>
* Class that handles drop events to the list of tests to be run.
* </p>
*
* @author michael
*
*/
public class ListOfTestsToBeRunDropListener implements DropTargetListener {
final protected JList DragAndDropDestination;
final protected TestInstantiatorDynamic testInstantiator;
public ListOfTestsToBeRunDropListener(
JList DragAndDropDestination,
TestInstantiatorDynamic testInstantiator
) {
super();
this.DragAndDropDestination = DragAndDropDestination;
this.testInstantiator = testInstantiator;
}
public void dragEnter (DropTargetDragEvent dtde) {}
public void dragOver (DropTargetDragEvent dtde) {}
public void dropActionChanged (DropTargetDragEvent dtde) {}
public void dragExit (DropTargetEvent dte) {}
/**
* <p>
* Adds a test to the list. The itemToAdd can be a String with the name
* of the GroupOfTests or a String with the SimpleName of the testclass or
* the testclass or the class of the GroupOfTests.
* </p>
* <p>
* If itemToAdd has a different type than the ones mentioned above, a
* RuntimeException is thrown.
* </p>
*
* @param itemsToAdd
*
*/
protected void addTestToList(Object... itemsToAdd) {
TestClassListModel currentListModel = (TestClassListModel) DragAndDropDestination.getModel();
boolean testWasAdded = false;
for (Object itemToAdd : itemsToAdd) {
if (itemToAdd instanceof String) {
String currentItem = (String) itemToAdd;
if (testInstantiator.isDynamic(currentItem)) {
System.out.print(currentItem);
currentListModel.addTest(
testInstantiator.instanceByName(
currentItem, GroupOfTests.class
)
);
testWasAdded = true;
} else {
Class<?> itemToAddClass = testInstantiator.forName((String) itemToAdd);
currentListModel.addTest(itemToAddClass);
testWasAdded = true;
}
}
if (
// Make sure it is a Class object, before casting it in one of
// the next two tests
//
(itemToAdd instanceof Class)
&& (
// Test, if itemToAdd is a class which is a testcase or a
// GroupOfTests.
//
(EnsTestCase.class.isAssignableFrom((Class) itemToAdd))
||
(GroupOfTests.class.isAssignableFrom((Class) itemToAdd))
)
) {
currentListModel.addTest((Class) itemToAdd);
testWasAdded = true;
//DragAndDropDestination.revalidate();
}
}
if (testWasAdded) {
// If something was added, repaint the list.
// The next two lines should not be done like this. It should be
// possible to just run this to make the changes in the JList take
// effect. Unfortunately this does not happen.
//
//DragAndDropDestination.repaint();
TestClassListModel newListModel = new TestClassListModel(currentListModel.getGroupOfTests());
DragAndDropDestination.setModel(newListModel);
} else {
// If nothing was added, an exception is thrown.
//
throw new RuntimeException("Couldn't add any of the objects "+ itemsToAdd.toString() +" to the list of tests to be run!");
}
}
public void drop(DropTargetDropEvent dtde) {
try {
// Get the dropped object and try to figure out what it is.
Transferable tr = dtde.getTransferable( );
DataFlavor[] flavors = tr.getTransferDataFlavors( );
for (int i = 0; i < flavors.length; i++) {
// Check that the type is correct.
//
if (flavors[i].isFlavorTextType()) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
String name = (String) tr.getTransferData(flavors[i]);
addTestToList(name);
dtde.dropComplete(true);
return;
}
}
dtde.rejectDrop( );
}
catch ( UnsupportedFlavorException e) { dtde.rejectDrop(); }
catch (InvalidDnDOperationException e) { dtde.rejectDrop(); }
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
rodrigobusata/bhammer-android | src/main/java/com/busata/bhammer/listeners/BRecyclerItemClickListener.java | 1793 | package com.busata.bhammer.listeners;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class BRecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public static interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public BRecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
} | apache-2.0 |
Uni-Sol/batik | sources/org/apache/batik/bridge/AbstractGraphicsNodeBridge.java | 19429 | /*
Copyright 2001-2006 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.batik.bridge;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.batik.css.engine.CSSEngineEvent;
import org.apache.batik.css.engine.SVGCSSEngine;
import org.apache.batik.dom.events.AbstractEvent;
import org.apache.batik.dom.svg.AnimatedLiveAttributeValue;
import org.apache.batik.dom.svg.LiveAttributeException;
import org.apache.batik.dom.svg.SVGContext;
import org.apache.batik.dom.svg.SVGMotionAnimatableElement;
import org.apache.batik.dom.svg.SVGOMElement;
import org.apache.batik.ext.awt.geom.SegmentList;
import org.apache.batik.gvt.CanvasGraphicsNode;
import org.apache.batik.gvt.CompositeGraphicsNode;
import org.apache.batik.gvt.GraphicsNode;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.events.MutationEvent;
import org.w3c.dom.svg.SVGFitToViewBox;
import org.w3c.dom.svg.SVGLength;
import org.w3c.dom.svg.SVGMatrix;
import org.w3c.dom.svg.SVGTransformList;
import org.w3c.dom.svg.SVGTransformable;
/**
* The base bridge class for SVG graphics node. By default, the namespace URI is
* the SVG namespace. Override the <tt>getNamespaceURI</tt> if you want to add
* custom <tt>GraphicsNode</tt> with a custom namespace.
*
* <p>This class handles various attributes that are defined on most
* of the SVG graphic elements as described in the SVG
* specification.</p>
*
* <ul>
* <li>clip-path</li>
* <li>filter</li>
* <li>mask</li>
* <li>opacity</li>
* <li>transform</li>
* <li>visibility</li>
* </ul>
*
* @author <a href="mailto:tkormann@apache.org">Thierry Kormann</a>
* @version $Id$
*/
public abstract class AbstractGraphicsNodeBridge extends AnimatableSVGBridge
implements SVGContext,
BridgeUpdateHandler,
GraphicsNodeBridge,
ErrorConstants {
/**
* The graphics node constructed by this bridge.
*/
protected GraphicsNode node;
/**
* Whether the document is an SVG 1.2 document.
*/
protected boolean isSVG12;
/**
* The unit context for length conversions.
*/
protected UnitProcessor.Context unitContext;
/**
* Constructs a new abstract bridge.
*/
protected AbstractGraphicsNodeBridge() {}
/**
* Creates a <tt>GraphicsNode</tt> according to the specified parameters.
*
* @param ctx the bridge context to use
* @param e the element that describes the graphics node to build
* @return a graphics node that represents the specified element
*/
public GraphicsNode createGraphicsNode(BridgeContext ctx, Element e) {
// 'requiredFeatures', 'requiredExtensions' and 'systemLanguage'
if (!SVGUtilities.matchUserAgent(e, ctx.getUserAgent())) {
return null;
}
GraphicsNode node = instantiateGraphicsNode();
// 'transform'
setTransform(node, e);
// 'visibility'
node.setVisible(CSSUtilities.convertVisibility(e));
associateSVGContext(ctx, e, node);
return node;
}
/**
* Creates the GraphicsNode depending on the GraphicsNodeBridge
* implementation.
*/
protected abstract GraphicsNode instantiateGraphicsNode();
/**
* Builds using the specified BridgeContext and element, the
* specified graphics node.
*
* @param ctx the bridge context to use
* @param e the element that describes the graphics node to build
* @param node the graphics node to build
*/
public void buildGraphicsNode(BridgeContext ctx,
Element e,
GraphicsNode node) {
// 'opacity'
node.setComposite(CSSUtilities.convertOpacity(e));
// 'filter'
node.setFilter(CSSUtilities.convertFilter(e, node, ctx));
// 'mask'
node.setMask(CSSUtilities.convertMask(e, node, ctx));
// 'clip-path'
node.setClip(CSSUtilities.convertClipPath(e, node, ctx));
// 'pointer-events'
node.setPointerEventType(CSSUtilities.convertPointerEvents(e));
initializeDynamicSupport(ctx, e, node);
}
/**
* Returns true if the graphics node has to be displayed, false
* otherwise.
*/
public boolean getDisplay(Element e) {
return CSSUtilities.convertDisplay(e);
}
/**
* Sets the graphics node's transform to the current animated transform
* value.
*/
protected void setTransform(GraphicsNode n, Element e) {
SVGTransformable te = (SVGTransformable) e;
try {
// 'transform'
AffineTransform at = new AffineTransform();
SVGTransformList tl = te.getTransform().getAnimVal();
int count = tl.getNumberOfItems();
for (int i = 0; i < count; i++) {
SVGMatrix m = tl.getItem(i).getMatrix();
at.concatenate(new AffineTransform(m.getA(), m.getB(),
m.getC(), m.getD(),
m.getE(), m.getF()));
}
if (e instanceof SVGMotionAnimatableElement) {
SVGMotionAnimatableElement mae = (SVGMotionAnimatableElement) e;
AffineTransform motion = mae.getMotionTransform();
if (motion != null) {
at.concatenate(motion);
}
}
n.setTransform(at);
} catch (LiveAttributeException ex) {
throw new BridgeException(ctx, ex);
}
}
/**
* Associates the {@link SVGContext} with the element. This method should
* be called even for static documents, since some bridges will need to
* access animated attribute values even during the first build.
*/
protected void associateSVGContext(BridgeContext ctx,
Element e,
GraphicsNode node) {
this.e = e;
this.node = node;
this.ctx = ctx;
this.unitContext = UnitProcessor.createContext(ctx, e);
this.isSVG12 = ctx.isSVG12();
((SVGOMElement)e).setSVGContext(this);
}
/**
* This method is invoked during the build phase if the document
* is dynamic. The responsibility of this method is to ensure that
* any dynamic modifications of the element this bridge is
* dedicated to, happen on its associated GVT product.
*/
protected void initializeDynamicSupport(BridgeContext ctx,
Element e,
GraphicsNode node) {
if (ctx.isInteractive()) {
// Bind the nodes for interactive and dynamic.
ctx.bind(e, node);
}
}
// BridgeUpdateHandler implementation //////////////////////////////////
/**
* Invoked when an MutationEvent of type 'DOMAttrModified' is fired.
*/
public void handleDOMAttrModifiedEvent(MutationEvent evt) {
}
/**
* Invoked when the geometry of a graphical element has changed.
*/
protected void handleGeometryChanged() {
node.setFilter(CSSUtilities.convertFilter(e, node, ctx));
node.setMask(CSSUtilities.convertMask(e, node, ctx));
node.setClip(CSSUtilities.convertClipPath(e, node, ctx));
if (isSVG12) {
if (!SVG_USE_TAG.equals(e.getLocalName())) {
// ShapeChange events get fired only for basic shapes and paths.
fireShapeChangeEvent();
}
fireBBoxChangeEvent();
}
}
/**
* Fires a ShapeChange event on the element this bridge is managing.
*/
protected void fireShapeChangeEvent() {
DocumentEvent d = (DocumentEvent) e.getOwnerDocument();
AbstractEvent evt = (AbstractEvent) d.createEvent("SVGEvents");
evt.initEventNS(SVG_NAMESPACE_URI,
"shapechange",
true,
false);
try {
((EventTarget) e).dispatchEvent(evt);
} catch (RuntimeException ex) {
ctx.getUserAgent().displayError(ex);
}
}
/**
* Invoked when an MutationEvent of type 'DOMNodeInserted' is fired.
*/
public void handleDOMNodeInsertedEvent(MutationEvent evt) {
if (evt.getTarget() instanceof Element) {
// Handle "generic" bridges.
Element e2 = (Element)evt.getTarget();
Bridge b = ctx.getBridge(e2);
if (b instanceof GenericBridge) {
((GenericBridge) b).handleElement(ctx, e2);
}
}
}
/**
* Invoked when an MutationEvent of type 'DOMNodeRemoved' is fired.
*/
public void handleDOMNodeRemovedEvent(MutationEvent evt) {
CompositeGraphicsNode gn = node.getParent();
gn.remove(node);
disposeTree(e);
}
/**
* Invoked when an MutationEvent of type 'DOMCharacterDataModified'
* is fired.
*/
public void handleDOMCharacterDataModified(MutationEvent evt) {
}
/**
* Disposes this BridgeUpdateHandler and releases all resources.
*/
public void dispose() {
SVGOMElement elt = (SVGOMElement)e;
elt.setSVGContext(null);
ctx.unbind(e);
}
/**
* Disposes all resources related to the specified node and its subtree.
*/
protected void disposeTree(Node node) {
disposeTree(node, true);
}
/**
* Disposes all resources related to the specified node and its subtree,
* and optionally removes the nodes' {@link SVGContext}.
*/
protected void disposeTree(Node node, boolean removeContext) {
if (node instanceof SVGOMElement) {
SVGOMElement elt = (SVGOMElement)node;
SVGContext ctx = elt.getSVGContext();
if (ctx instanceof BridgeUpdateHandler) {
BridgeUpdateHandler h = (BridgeUpdateHandler) ctx;
if (removeContext) {
elt.setSVGContext(null);
}
h.dispose();
}
}
for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
disposeTree(n, removeContext);
}
}
/**
* Invoked when an CSSEngineEvent is fired.
*/
public void handleCSSEngineEvent(CSSEngineEvent evt) {
try {
SVGCSSEngine eng = (SVGCSSEngine) evt.getSource();
int[] properties = evt.getProperties();
for (int i = 0; i < properties.length; i++) {
int idx = properties[i];
handleCSSPropertyChanged(idx);
String pn = eng.getPropertyName(idx);
fireBaseAttributeListeners(pn);
}
} catch (Exception ex) {
ctx.getUserAgent().displayError(ex);
}
}
/**
* Invoked for each CSS property that has changed.
*/
protected void handleCSSPropertyChanged(int property) {
switch(property) {
case SVGCSSEngine.VISIBILITY_INDEX:
node.setVisible(CSSUtilities.convertVisibility(e));
break;
case SVGCSSEngine.OPACITY_INDEX:
node.setComposite(CSSUtilities.convertOpacity(e));
break;
case SVGCSSEngine.FILTER_INDEX:
node.setFilter(CSSUtilities.convertFilter(e, node, ctx));
break;
case SVGCSSEngine.MASK_INDEX:
node.setMask(CSSUtilities.convertMask(e, node, ctx));
break;
case SVGCSSEngine.CLIP_PATH_INDEX:
node.setClip(CSSUtilities.convertClipPath(e, node, ctx));
break;
case SVGCSSEngine.POINTER_EVENTS_INDEX:
node.setPointerEventType(CSSUtilities.convertPointerEvents(e));
break;
case SVGCSSEngine.DISPLAY_INDEX:
if (!getDisplay(e)) {
// Remove the subtree.
CompositeGraphicsNode parent = node.getParent();
parent.remove(node);
disposeTree(e, false);
}
break;
}
}
/**
* Invoked when the animated value of an animatable attribute has changed.
*/
public void handleAnimatedAttributeChanged
(AnimatedLiveAttributeValue alav) {
if (alav.getNamespaceURI() == null
&& alav.getLocalName().equals(SVG_TRANSFORM_ATTRIBUTE)) {
setTransform(node, e);
handleGeometryChanged();
}
}
/**
* Invoked when an 'other' animation value has changed.
*/
public void handleOtherAnimationChanged(String type) {
if (type.equals("motion")) {
setTransform(node, e);
handleGeometryChanged();
}
}
/**
* Checks if the bounding box of the node has changed, and if so,
* fires a bboxchange event on the element.
*/
protected void checkBBoxChange() {
if (e != null) {
/*Rectangle2D oldBBox = bbox;
Rectangle2D newBBox = getBBox();
if (oldBBox != newBBox && newBBox != null) {
if (oldBBox == null ||
oldBBox.getX() != bbox.getX()
|| oldBBox.getY() != bbox.getY()
|| oldBBox.getWidth() != bbox.getWidth()
|| oldBBox.getHeight() != bbox.getHeight()) {*/
fireBBoxChangeEvent();
/*}
}*/
}
}
/**
* Fires an svg:bboxchange event on the element.
*/
protected void fireBBoxChangeEvent() {
DocumentEvent d = (DocumentEvent) e.getOwnerDocument();
AbstractEvent evt = (AbstractEvent) d.createEvent("SVGEvents");
evt.initEventNS(SVG_NAMESPACE_URI,
"RenderedBBoxChange",
true,
false);
try {
((EventTarget) e).dispatchEvent(evt);
} catch (RuntimeException ex) {
ctx.getUserAgent().displayError(ex);
}
}
// SVGContext implementation ///////////////////////////////////////////
/**
* Returns the size of a px CSS unit in millimeters.
*/
public float getPixelUnitToMillimeter() {
return ctx.getUserAgent().getPixelUnitToMillimeter();
}
/**
* Returns the size of a px CSS unit in millimeters.
* This will be removed after next release.
* @see #getPixelUnitToMillimeter()
*/
public float getPixelToMM() {
return getPixelUnitToMillimeter();
}
protected SoftReference bboxShape = null;
protected Rectangle2D bbox = null;
/**
* Returns the tight bounding box in current user space (i.e.,
* after application of the transform attribute, if any) on the
* geometry of all contained graphics elements, exclusive of
* stroke-width and filter effects).
*/
public Rectangle2D getBBox() {
if (node == null) {
return null;
}
Shape s = node.getOutline();
if ((bboxShape != null) && (s == bboxShape.get())) return bbox;
bboxShape = new SoftReference(s); // don't keep this live.
bbox = null;
if (s == null) return bbox;
// SegmentList.getBounds2D gives tight BBox.
SegmentList sl = new SegmentList(s);
bbox = sl.getBounds2D();
return bbox;
}
/**
* Returns the transformation matrix from current user units
* (i.e., after application of the transform attribute, if any) to
* the viewport coordinate system for the nearestViewportElement.
*/
public AffineTransform getCTM() {
GraphicsNode gn = node;
AffineTransform ctm = new AffineTransform();
Element elt = e;
while (elt != null) {
if (elt instanceof SVGFitToViewBox) {
AffineTransform at;
if (gn instanceof CanvasGraphicsNode) {
at = ((CanvasGraphicsNode)gn).getViewingTransform();
} else {
at = gn.getTransform();
}
if (at != null) {
ctm.preConcatenate(at);
}
break;
}
AffineTransform at = gn.getTransform();
if (at != null)
ctm.preConcatenate(at);
elt = SVGCSSEngine.getParentCSSStylableElement(elt);
gn = gn.getParent();
}
return ctm;
}
/**
* Returns the display transform.
*/
public AffineTransform getScreenTransform() {
return ctx.getUserAgent().getTransform();
}
/**
* Sets the display transform.
*/
public void setScreenTransform(AffineTransform at) {
ctx.getUserAgent().setTransform(at);
}
/**
* Returns the global transformation matrix from the current
* element to the root.
*/
public AffineTransform getGlobalTransform() {
return node.getGlobalTransform();
}
/**
* Returns the width of the viewport which directly contains the
* given element.
*/
public float getViewportWidth() {
return ctx.getBlockWidth(e);
}
/**
* Returns the height of the viewport which directly contains the
* given element.
*/
public float getViewportHeight() {
return ctx.getBlockHeight(e);
}
/**
* Returns the font-size on the associated element.
*/
public float getFontSize() {
return CSSUtilities.getComputedStyle
(e, SVGCSSEngine.FONT_SIZE_INDEX).getFloatValue();
}
/**
* Converts the given SVG length into user units.
* @param v the SVG length value
* @param type the SVG length units (one of the
* {@link SVGLength}.SVG_LENGTH_* constants)
* @param pcInterp how to interpretet percentage values (one of the
* {@link SVGContext}.PERCENTAGE_* constants)
* @return the SVG value in user units
*/
public float svgToUserSpace(float v, int type, int pcInterp) {
if (pcInterp == PERCENTAGE_FONT_SIZE
&& type == SVGLength.SVG_LENGTHTYPE_PERCENTAGE) {
// XXX
return 0f;
} else {
return UnitProcessor.svgToUserSpace(v, (short) type,
(short) (3 - pcInterp),
unitContext);
}
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/concurrent/atomiclong/operations/GetAndAlterOperation.java | 1597 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.concurrent.atomiclong.operations;
import com.hazelcast.concurrent.atomiclong.AtomicLongContainer;
import com.hazelcast.concurrent.atomiclong.AtomicLongDataSerializerHook;
import com.hazelcast.core.IFunction;
public class GetAndAlterOperation extends AbstractAlterOperation {
public GetAndAlterOperation() {
}
public GetAndAlterOperation(String name, IFunction<Long, Long> function) {
super(name, function);
}
@Override
public void run() throws Exception {
AtomicLongContainer atomicLongContainer = getLongContainer();
long input = atomicLongContainer.get();
response = input;
long output = function.apply(input);
shouldBackup = input != output;
if (shouldBackup) {
backup = output;
atomicLongContainer.set(output);
}
}
@Override
public int getId() {
return AtomicLongDataSerializerHook.GET_AND_ALTER;
}
}
| apache-2.0 |
lawtech0902/coolweather | app/src/main/java/com/example/lawtech/coolweather/db/CoolWeatherDB.java | 4715 | package com.example.lawtech.coolweather.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.lawtech.coolweather.model.City;
import com.example.lawtech.coolweather.model.District;
import com.example.lawtech.coolweather.model.Province;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lawtech on 16/8/26.
*/
public class CoolWeatherDB {
/**
* 数据库名
*/
private static final String DB_NAME = "cool_weather";
/**
* 数据库版本
*/
private static final int VERSION = 1;
private static CoolWeatherDB coolWeatherDB;
private SQLiteDatabase db;
/**
* 将构造方法私有化
*/
private CoolWeatherDB(Context context) {
CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
}
/**
* 获取CoolWeatherDB的实例
*/
public synchronized static CoolWeatherDB getInstance(Context context) {
if (coolWeatherDB == null) {
coolWeatherDB = new CoolWeatherDB(context);
}
return coolWeatherDB;
}
/**
* 将Province实例存储到数据库
*/
public void saveProvince(Province province) {
if (province != null) {
ContentValues values = new ContentValues();
values.put("province_name", province.getProvinceName());
db.insert("Province", null, values);
}
}
/**
* 从数据库读取全国所有的省份信息
*/
public List<Province> loadProvinces() {
List<Province> list = new ArrayList<Province>();
Cursor cursor = db.query("Province", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getInt(cursor.getColumnIndex("id")));
province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
list.add(province);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return list;
}
/**
* 将City实例存储到数据库
*/
public void saveCity(City city) {
if (city != null) {
ContentValues values = new ContentValues();
values.put("city_name", city.getCityName());
values.put("province_id", city.getProvinceId());
db.insert("City", null, values);
}
}
/**
* 从数据库读取某省下所有的城市信息
*/
public List<City> loadCities(int provinceId) {
List<City> list = new ArrayList<City>();
Cursor cursor = db.query("City", null, "province_id = ?",
new String[]{String.valueOf(provinceId)}, null, null, null);
if (cursor.moveToFirst()) {
do {
City city = new City();
city.setId(cursor.getInt(cursor.getColumnIndex("id")));
city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
city.setProvinceId(provinceId);
list.add(city);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return list;
}
/**
* 将District实例存储到数据库
*/
public void saveDistrict(District district) {
if (district != null) {
ContentValues values = new ContentValues();
values.put("district_name", district.getDistrictName());
values.put("city_id", district.getCityId());
db.insert("District", null, values);
}
}
/**
* 从数据库读取某城市下所有的县信息
*/
public List<District> loadDistricts(int cityId) {
List<District> lists = new ArrayList<>();
Cursor cursor = db.query("District", null, "city_id = ?", new String[]{String.valueOf(cityId)},
null, null, null);
if (cursor.moveToFirst()) {
do {
District district = new District();
district.setId(cursor.getInt(cursor.getColumnIndex("id")));
district.setDistrictName(cursor.getString(cursor.getColumnIndex("district_name")));
district.setCityId(cursor.getInt(cursor.getColumnIndex("city_id")));
lists.add(district);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return lists;
}
} | apache-2.0 |
sonatype/maven-demo | maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactMetadata.java | 4200 | package org.apache.maven.project.artifact;
/*
* 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 java.io.File;
import java.io.IOException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.AbstractArtifactMetadata;
import org.apache.maven.artifact.metadata.ArtifactMetadata;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreException;
import org.codehaus.plexus.util.FileUtils;
/**
* Attach a POM to an artifact.
*
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
* @version $Id: ProjectArtifactMetadata.java 988749 2010-08-24 22:46:07Z bentmann $
*/
public class ProjectArtifactMetadata
extends AbstractArtifactMetadata
{
private final File file;
public ProjectArtifactMetadata( Artifact artifact )
{
this( artifact, null );
}
public ProjectArtifactMetadata( Artifact artifact, File file )
{
super( artifact );
this.file = file;
}
public File getFile()
{
return file;
}
public String getRemoteFilename()
{
return getFilename();
}
public String getLocalFilename( ArtifactRepository repository )
{
return getFilename();
}
private String getFilename()
{
return getArtifactId() + "-" + artifact.getVersion() + ".pom";
}
public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository )
throws RepositoryMetadataStoreException
{
File destination =
new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( this,
remoteRepository ) );
// ----------------------------------------------------------------------------
// I'm fully aware that the file could just be moved using File.rename but
// there are bugs in various JVM that have problems doing this across
// different filesystem. So we'll incur the small hit to actually copy
// here and be safe. jvz.
// ----------------------------------------------------------------------------
try
{
FileUtils.copyFile( file, destination );
}
catch ( IOException e )
{
throw new RepositoryMetadataStoreException( "Error copying POM to the local repository.", e );
}
}
public String toString()
{
return "project information for " + artifact.getArtifactId() + " " + artifact.getVersion();
}
public boolean storedInArtifactVersionDirectory()
{
return true;
}
public String getBaseVersion()
{
return artifact.getBaseVersion();
}
public Object getKey()
{
return "project " + artifact.getGroupId() + ":" + artifact.getArtifactId();
}
public void merge( ArtifactMetadata metadata )
{
ProjectArtifactMetadata m = (ProjectArtifactMetadata) metadata;
if ( !m.file.equals( file ) )
{
throw new IllegalStateException( "Cannot add two different pieces of metadata for: " + getKey() );
}
}
public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata )
{
this.merge( (ArtifactMetadata) metadata );
}
}
| apache-2.0 |
pyj0918/study | mybatis/mybatis-05-ssm/src/main/java/com/test/dao/impl/DaoBase.java | 857 | package com.test.dao.impl;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
public class DaoBase {
//@Autowired
//protected SqlSessionFactoryBean sqlsessionFactory;
//protected SqlSession session = null;
@Resource
protected SqlSessionTemplate sessionTemplate;
protected static String userStatement = "com.test.mapper.UserMapper.{sqlId}";
protected static String teacherStatement = "com.test.mapper.TeacherMapper.{sqlId}";
// protected SqlSession getSession(boolean autoCommit) {
// try {
// return sqlsessionFactory.getObject().openSession(autoCommit);
// } catch (Exception e) {
// throw new RuntimeException("»ñÈ¡sqlsessionÒì³£", e);
// }
// }
}
| apache-2.0 |
dasomel/egovframework | common-component/v2.3.2/src/main/java/egovframework/com/uss/olh/faq/service/impl/EgovFaqManageServiceImpl.java | 3285 | package egovframework.com.uss.olh.faq.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import egovframework.com.uss.olh.faq.service.EgovFaqManageService;
import egovframework.com.uss.olh.faq.service.FaqManageDefaultVO;
import egovframework.com.uss.olh.faq.service.FaqManageVO;
import egovframework.rte.fdl.cmmn.AbstractServiceImpl;
import egovframework.rte.fdl.idgnr.EgovIdGnrService;
/**
*
* FAQ를 처리하는 비즈니스 구현 클래스
* @author 공통서비스 개발팀 박정규
* @since 2009.04.01
* @version 1.0
* @see
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.04.01 박정규 최초 생성
*
* </pre>
*/
@Service("FaqManageService")
public class EgovFaqManageServiceImpl extends AbstractServiceImpl implements
EgovFaqManageService {
@Resource(name="FaqManageDAO")
private FaqManageDAO faqManageDAO;
/** ID Generation */
@Resource(name="egovFaqManageIdGnrService")
private EgovIdGnrService idgenService;
/**
* FAQ 글을 조회한다.
* @param vo - 조회할 정보가 담긴 FaqManageVO
* @return 조회한 글
* @exception Exception
*/
public FaqManageVO selectFaqListDetail(FaqManageVO vo) throws Exception {
FaqManageVO resultVO = faqManageDAO.selectFaqListDetail(vo);
if (resultVO == null)
throw processException("info.nodata.msg");
return resultVO;
}
/**
* FAQ 조회수를 수정한다.
* @param vo
* @exception Exception
*/
public void updateFaqInqireCo(FaqManageVO vo) throws Exception {
log.debug(vo.toString());
faqManageDAO.updateFaqInqireCo(vo);
}
/**
* FAQ 글 목록을 조회한다.
* @param searchVO
* @return 글 목록
* @exception Exception
*/
public List selectFaqList(FaqManageDefaultVO searchVO) throws Exception {
return faqManageDAO.selectFaqList(searchVO);
}
/**
* FAQ 글 총 갯수를 조회한다.
* @param searchVO
* @return 글 총 갯수
* @exception
*/
public int selectFaqListTotCnt(FaqManageDefaultVO searchVO) {
return faqManageDAO.selectFaqListTotCnt(searchVO);
}
/**
* FAQ 글을 등록한다.
* @param vo
* @exception Exception
*/
public void insertFaqCn(FaqManageVO vo) throws Exception {
log.debug(vo.toString());
String newsId = idgenService.getNextStringId();
vo.setFaqId(newsId);
faqManageDAO.insertFaqCn(vo);
}
/**
* FAQ 글을 수정한다.
* @param vo
* @exception Exception
*/
public void updateFaqCn(FaqManageVO vo) throws Exception {
log.debug(vo.toString());
faqManageDAO.updateFaqCn(vo);
}
/**
* FAQ 글을 삭제한다.
* @param vo
* @exception Exception
*/
public void deleteFaqCn(FaqManageVO vo) throws Exception {
log.debug(vo.toString());
faqManageDAO.deleteFaqCn(vo);
}
}
| apache-2.0 |
kucera-jan-cz/esBench | core/src/main/java/org/esbench/workload/json/databind/InstantSerializer.java | 735 | package org.esbench.workload.json.databind;
import java.io.IOException;
import java.time.Instant;
import org.esbench.generator.field.meta.MetadataConstants;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class InstantSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
String valueAsString = MetadataConstants.DEFAULT_DATE_FORMATTER.format(value);
gen.writeString(valueAsString);
}
}
| apache-2.0 |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/util/annotations/PackageNonnull.java | 1166 | package io.petros.posts.util.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
/**
* This annotation can be applied to a package, class or method to indicate that the class fields, method return types and
* parameters in that element are not null by default unless:
* - The method overrides a method in a superclass (in which case the annotation of the corresponding parameter in the
* superclass applies).
* - There is a default parameter annotation applied to a more tightly nested element.
*/
@Documented
@Nonnull
@TypeQualifierDefault(
{
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.PARAMETER,
ElementType.TYPE
})
@Retention(RetentionPolicy.RUNTIME)
public @interface PackageNonnull {
}
| apache-2.0 |
bguerout/keemto | src/test/java/fr/keemto/web/TestConnectionFactory.java | 63 | package fr.keemto.web;
public class TestConnectionFactory {
}
| apache-2.0 |
smileonroad/WMSRFClient | quartz-labor/src/java/com/labor/job/worker/JobBlockWorker.java | 794 | package com.labor.job.worker;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import com.labor.job.JobFlow;
import com.labor.job.config.WorkerContext;
import com.labor.job.exception.WorkerException;
@SuppressWarnings("deprecation")
public abstract class JobBlockWorker extends JobWorker implements StatefulJob, JobFlow{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
execute(this, context);
}
@Override
public void beforeWorker(WorkerContext context) throws WorkerException {
// TODO Auto-generated method stub
}
@Override
public void afterWorker(WorkerContext context) throws WorkerException {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/ne/ResourceName.java | 1653 | /* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.app.util.bin.format.ne;
import ghidra.app.util.bin.format.*;
import java.io.IOException;
/**
* A class for storing new-executable resource names.
*
*
*/
public class ResourceName {
private LengthStringSet lns;
private long index;
/**
* Constructs a resource name.
* @param reader the binary reader
*/
ResourceName(FactoryBundledWithBinaryReader reader) throws IOException {
index = reader.getPointerIndex();
lns = new LengthStringSet(reader);
}
/**
* Returns the length of the resource name.
* @return the length of the resource name
*/
public byte getLength() {
return lns.getLength();
}
/**
* Returns the name of the resource name.
* @return the name of the resource name
*/
public String getName() {
return lns.getString();
}
/**
* Returns the byte index of this resource name, relative to the beginning of the file.
* @return the byte index of this resource name
*/
public long getIndex() {
return index;
}
}
| apache-2.0 |
wazzi/anni_deca | app/src/main/java/wazza/ke/servista/utilities/Assignment.java | 2889 | package wazza.ke.servista.utilities;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
/**
* Created by kelli on 11/17/14.
*/
public class Assignment implements Parcelable{
//Tags
private static final String EXP_TAG = "UNIT_EXCEPTION";
private static final String ERR_TAG = "UNIT_ERROR";
private static final String INFO_TAG = "UNIT_INFO";
//
private String title;
private String description;
private String dueDate;
private String grade;
private String submissionsAllowDate;
public Assignment(){
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getSubmissionsAllowDate() {
return submissionsAllowDate;
}
public void setSubmissionsAllowDate(String submissionsAllowDate) {
this.submissionsAllowDate = submissionsAllowDate;
}
// //unserialization happens here (retrieving the unit data from the parcel object)...this will be invoked by the method createFromParcel(Parcel p) of the
//object CREATOR
public Assignment(Parcel in) {
Log.i(INFO_TAG, "creating object from parcel");
this.title = in.readString();
this.description = in.readString();
this.grade = in.readString();
this.submissionsAllowDate = in.readString();
this.dueDate=in.readString();
}
@Override
public int describeContents() {
return 0;
}
//serializing the object here...
@Override
public void writeToParcel(Parcel parcel, int i) {
Log.i(INFO_TAG, "Writting object to parcel..." + i);
parcel.writeString(title);
parcel.writeString(description);
parcel.writeString(grade);
parcel.writeString(submissionsAllowDate);
parcel.writeString(dueDate);
}
public static final Parcelable.Creator<Assignment> CREATOR = new Parcelable.Creator<Assignment>() {
public Assignment createFromParcel(Parcel in) {
Assignment assignment = new Assignment(in);
// u.fullName=in.readString();
// u.code=in.readString();
String s = assignment.getTitle();
Log.i(INFO_TAG, "Current unit: " + s);
return assignment;
}
public Assignment[] newArray(int size) {
return new Assignment[size];
}
};
}
| apache-2.0 |