repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
altsoft/PlatypusJS | platypus-js-forms/src/main/java/com/eas/client/forms/components/model/ModelSpin.java | 6288 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.client.forms.components.model;
import com.eas.client.forms.components.rt.HasEmptyText;
import com.eas.client.forms.components.rt.VSpinner;
import com.eas.design.Undesignable;
import com.eas.script.HasPublished;
import com.eas.script.NoPublisherException;
import com.eas.script.ScriptFunction;
import com.eas.script.Scripts;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JSpinner.NumberEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.internal.runtime.JSType;
/**
*
* @author mg
*/
public class ModelSpin extends ModelComponentDecorator<VSpinner, Double> implements HasPublished, HasEmptyText {
private static final String CONSTRUCTOR_JSDOC = ""
+ "/**\n"
+ " * A model component that represents a combination of a numeric text box and arrow buttons to change the value incrementally. \n"
+ " */";
@ScriptFunction(jsDoc = CONSTRUCTOR_JSDOC)
public ModelSpin() {
super();
setDecorated(new VSpinner());
setBackground((new JTextField()).getBackground());
}
@ScriptFunction(name = "value", jsDoc = JS_VALUE_JSDOC)
@Undesignable
@Override
public Object getJsValue() {
return super.getJsValue();
}
@ScriptFunction
@Override
public void setJsValue(Object aValue) {
if (aValue == null || "".equals(aValue)) {
setValue(null);
} else {
setValue(JSType.toNumber(aValue));
}
}
@Override
public JSObject getPublished() {
if (published == null) {
JSObject publisher = Scripts.getSpace().getPublisher(this.getClass().getName());
if (publisher == null || !publisher.isFunction()) {
throw new NoPublisherException();
}
published = (JSObject) publisher.call(null, new Object[]{this});
}
return published;
}
private static final String EDITABLE_JSDOC = ""
+ "/**\n"
+ " * Determines if component is editable.\n"
+ " */";
@ScriptFunction(jsDoc = EDITABLE_JSDOC)
public boolean getEditable() {
return decorated.getEditable();
}
@ScriptFunction
public void setEditable(boolean aValue) {
decorated.setEditable(aValue);
}
private static final String MIN_JSDOC = ""
+ "/**\n"
+ "* Determines the lower bound of spinner's value. If it's null, valus is unlimited at lower bound.\n"
+ "*/";
@ScriptFunction(jsDoc = MIN_JSDOC)
public Double getMin() {
return decorated.getMin();
}
@ScriptFunction
public void setMin(Double aValue) throws Exception {
decorated.setMin(aValue);
}
private static final String MAX_JSDOC = ""
+ "/**\n"
+ "* Determines the upper bound of spinner's value. If it's null, valus is unlimited at upper bound.\n"
+ "*/";
@ScriptFunction(jsDoc = MAX_JSDOC)
public Double getMax() {
return decorated.getMax();
}
@ScriptFunction
public void setMax(Double aValue) throws Exception {
decorated.setMax(aValue);
}
private static final String STEP_JSDOC = ""
+ "/**\n"
+ "* Determines the spinner's value change step. Can't be null.\n"
+ "*/";
@ScriptFunction(jsDoc = STEP_JSDOC)
public double getStep() {
return decorated.getStep();
}
@ScriptFunction
public void setStep(double aValue) throws Exception {
decorated.setStep(aValue);
}
@ScriptFunction
@Override
public String getEmptyText() {
return decorated.getEmptyText();
}
@ScriptFunction
@Override
public void setEmptyText(String aValue) {
decorated.setEmptyText(aValue);
}
@ScriptFunction
public String getText() {
return decorated.getText();
}
@ScriptFunction
public void setText(String aValue) throws Exception {
decorated.setText(aValue);
}
@Override
protected void setupCellRenderer(JTable table, int row, int column, boolean isSelected) {
removeAll();
JLabel rendererLine = new JLabel(decorated.getText());
rendererLine.setOpaque(false);
add(rendererLine, BorderLayout.CENTER);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (decorated.getEditor() instanceof NumberEditor) {
JFormattedTextField ftf = ((NumberEditor) decorated.getEditor()).getTextField();
ftf.getActionMap().remove(TextFieldsCommitAction.COMMIT_ACTION_NAME);
ftf.getActionMap().put(TextFieldsCommitAction.COMMIT_ACTION_NAME, new TextFieldsCommitAction(ftf));
}
EventQueue.invokeLater(() -> {
decorated.requestFocus();
});
return super.getTableCellEditorComponent(table, value, isSelected, row, column); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean stopCellEditing() {
if (decorated.getEditor() instanceof NumberEditor) {
JFormattedTextField ftf = ((NumberEditor) decorated.getEditor()).getTextField();
try {
ftf.commitEdit();
} catch (ParseException ex) {
Logger.getLogger(ModelDate.class.getName()).log(Level.WARNING, null, ex);
}
}
return super.stopCellEditing();
}
@Override
public boolean isFieldContentModified() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| apache-2.0 |
shun634501730/java_source_cn | src_en/java/rmi/server/RemoteObject.java | 17722 | /*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.rmi.server;
import java.rmi.Remote;
import java.rmi.NoSuchObjectException;
import java.lang.reflect.Proxy;
import sun.rmi.server.Util;
/**
* The <code>RemoteObject</code> class implements the
* <code>java.lang.Object</code> behavior for remote objects.
* <code>RemoteObject</code> provides the remote semantics of Object by
* implementing methods for hashCode, equals, and toString.
*
* @author Ann Wollrath
* @author Laird Dornin
* @author Peter Jones
* @since JDK1.1
*/
public abstract class RemoteObject implements Remote, java.io.Serializable {
/** The object's remote reference. */
transient protected RemoteRef ref;
/** indicate compatibility with JDK 1.1.x version of class */
private static final long serialVersionUID = -3215090123894869218L;
/**
* Creates a remote object.
*/
protected RemoteObject() {
ref = null;
}
/**
* Creates a remote object, initialized with the specified remote
* reference.
* @param newref remote reference
*/
protected RemoteObject(RemoteRef newref) {
ref = newref;
}
/**
* Returns the remote reference for the remote object.
*
* <p>Note: The object returned from this method may be an instance of
* an implementation-specific class. The <code>RemoteObject</code>
* class ensures serialization portability of its instances' remote
* references through the behavior of its custom
* <code>writeObject</code> and <code>readObject</code> methods. An
* instance of <code>RemoteRef</code> should not be serialized outside
* of its <code>RemoteObject</code> wrapper instance or the result may
* be unportable.
*
* @return remote reference for the remote object
* @since 1.2
*/
public RemoteRef getRef() {
return ref;
}
/**
* Returns the stub for the remote object <code>obj</code> passed
* as a parameter. This operation is only valid <i>after</i>
* the object has been exported.
* @param obj the remote object whose stub is needed
* @return the stub for the remote object, <code>obj</code>.
* @exception NoSuchObjectException if the stub for the
* remote object could not be found.
* @since 1.2
*/
public static Remote toStub(Remote obj) throws NoSuchObjectException {
if (obj instanceof RemoteStub ||
(obj != null &&
Proxy.isProxyClass(obj.getClass()) &&
Proxy.getInvocationHandler(obj) instanceof
RemoteObjectInvocationHandler))
{
return obj;
} else {
return sun.rmi.transport.ObjectTable.getStub(obj);
}
}
/**
* Returns a hashcode for a remote object. Two remote object stubs
* that refer to the same remote object will have the same hash code
* (in order to support remote objects as keys in hash tables).
*
* @see java.util.Hashtable
*/
public int hashCode() {
return (ref == null) ? super.hashCode() : ref.remoteHashCode();
}
/**
* Compares two remote objects for equality.
* Returns a boolean that indicates whether this remote object is
* equivalent to the specified Object. This method is used when a
* remote object is stored in a hashtable.
* If the specified Object is not itself an instance of RemoteObject,
* then this method delegates by returning the result of invoking the
* <code>equals</code> method of its parameter with this remote object
* as the argument.
* @param obj the Object to compare with
* @return true if these Objects are equal; false otherwise.
* @see java.util.Hashtable
*/
public boolean equals(Object obj) {
if (obj instanceof RemoteObject) {
if (ref == null) {
return obj == this;
} else {
return ref.remoteEquals(((RemoteObject)obj).ref);
}
} else if (obj != null) {
/*
* Fix for 4099660: if object is not an instance of RemoteObject,
* use the result of its equals method, to support symmetry is a
* remote object implementation class that does not extend
* RemoteObject wishes to support equality with its stub objects.
*/
return obj.equals(this);
} else {
return false;
}
}
/**
* Returns a String that represents the value of this remote object.
*/
public String toString() {
String classname = Util.getUnqualifiedName(getClass());
return (ref == null) ? classname :
classname + "[" + ref.remoteToString() + "]";
}
/**
* <code>writeObject</code> for custom serialization.
*
* <p>This method writes this object's serialized form for this class
* as follows:
*
* <p>The {@link RemoteRef#getRefClass(java.io.ObjectOutput) getRefClass}
* method is invoked on this object's <code>ref</code> field
* to obtain its external ref type name.
* If the value returned by <code>getRefClass</code> was
* a non-<code>null</code> string of length greater than zero,
* the <code>writeUTF</code> method is invoked on <code>out</code>
* with the value returned by <code>getRefClass</code>, and then
* the <code>writeExternal</code> method is invoked on
* this object's <code>ref</code> field passing <code>out</code>
* as the argument; otherwise,
* the <code>writeUTF</code> method is invoked on <code>out</code>
* with a zero-length string (<code>""</code>), and then
* the <code>writeObject</code> method is invoked on <code>out</code>
* passing this object's <code>ref</code> field as the argument.
*
* @serialData
*
* The serialized data for this class comprises a string (written with
* <code>ObjectOutput.writeUTF</code>) that is either the external
* ref type name of the contained <code>RemoteRef</code> instance
* (the <code>ref</code> field) or a zero-length string, followed by
* either the external form of the <code>ref</code> field as written by
* its <code>writeExternal</code> method if the string was of non-zero
* length, or the serialized form of the <code>ref</code> field as
* written by passing it to the serialization stream's
* <code>writeObject</code> if the string was of zero length.
*
* <p>If this object is an instance of
* {@link RemoteStub} or {@link RemoteObjectInvocationHandler}
* that was returned from any of
* the <code>UnicastRemoteObject.exportObject</code> methods
* and custom socket factories are not used,
* the external ref type name is <code>"UnicastRef"</code>.
*
* If this object is an instance of
* <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code>
* that was returned from any of
* the <code>UnicastRemoteObject.exportObject</code> methods
* and custom socket factories are used,
* the external ref type name is <code>"UnicastRef2"</code>.
*
* If this object is an instance of
* <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code>
* that was returned from any of
* the <code>java.rmi.activation.Activatable.exportObject</code> methods,
* the external ref type name is <code>"ActivatableRef"</code>.
*
* If this object is an instance of
* <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code>
* that was returned from
* the <code>RemoteObject.toStub</code> method (and the argument passed
* to <code>toStub</code> was not itself a <code>RemoteStub</code>),
* the external ref type name is a function of how the remote object
* passed to <code>toStub</code> was exported, as described above.
*
* If this object is an instance of
* <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code>
* that was originally created via deserialization,
* the external ref type name is the same as that which was read
* when this object was deserialized.
*
* <p>If this object is an instance of
* <code>java.rmi.server.UnicastRemoteObject</code> that does not
* use custom socket factories,
* the external ref type name is <code>"UnicastServerRef"</code>.
*
* If this object is an instance of
* <code>UnicastRemoteObject</code> that does
* use custom socket factories,
* the external ref type name is <code>"UnicastServerRef2"</code>.
*
* <p>Following is the data that must be written by the
* <code>writeExternal</code> method and read by the
* <code>readExternal</code> method of <code>RemoteRef</code>
* implementation classes that correspond to the each of the
* defined external ref type names:
*
* <p>For <code>"UnicastRef"</code>:
*
* <ul>
*
* <li>the hostname of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeUTF(String)}
*
* <li>the port of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeInt(int)}
*
* <li>the data written as a result of calling
* {link java.rmi.server.ObjID#write(java.io.ObjectOutput)}
* on the <code>ObjID</code> instance contained in the reference
*
* <li>the boolean value <code>false</code>,
* written by {@link java.io.ObjectOutput#writeBoolean(boolean)}
*
* </ul>
*
* <p>For <code>"UnicastRef2"</code> with a
* <code>null</code> client socket factory:
*
* <ul>
*
* <li>the byte value <code>0x00</code>
* (indicating <code>null</code> client socket factory),
* written by {@link java.io.ObjectOutput#writeByte(int)}
*
* <li>the hostname of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeUTF(String)}
*
* <li>the port of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeInt(int)}
*
* <li>the data written as a result of calling
* {link java.rmi.server.ObjID#write(java.io.ObjectOutput)}
* on the <code>ObjID</code> instance contained in the reference
*
* <li>the boolean value <code>false</code>,
* written by {@link java.io.ObjectOutput#writeBoolean(boolean)}
*
* </ul>
*
* <p>For <code>"UnicastRef2"</code> with a
* non-<code>null</code> client socket factory:
*
* <ul>
*
* <li>the byte value <code>0x01</code>
* (indicating non-<code>null</code> client socket factory),
* written by {@link java.io.ObjectOutput#writeByte(int)}
*
* <li>the hostname of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeUTF(String)}
*
* <li>the port of the referenced remote object,
* written by {@link java.io.ObjectOutput#writeInt(int)}
*
* <li>a client socket factory (object of type
* <code>java.rmi.server.RMIClientSocketFactory</code>),
* written by passing it to an invocation of
* <code>writeObject</code> on the stream instance
*
* <li>the data written as a result of calling
* {link java.rmi.server.ObjID#write(java.io.ObjectOutput)}
* on the <code>ObjID</code> instance contained in the reference
*
* <li>the boolean value <code>false</code>,
* written by {@link java.io.ObjectOutput#writeBoolean(boolean)}
*
* </ul>
*
* <p>For <code>"ActivatableRef"</code> with a
* <code>null</code> nested remote reference:
*
* <ul>
*
* <li>an instance of
* <code>java.rmi.activation.ActivationID</code>,
* written by passing it to an invocation of
* <code>writeObject</code> on the stream instance
*
* <li>a zero-length string (<code>""</code>),
* written by {@link java.io.ObjectOutput#writeUTF(String)}
*
* </ul>
*
* <p>For <code>"ActivatableRef"</code> with a
* non-<code>null</code> nested remote reference:
*
* <ul>
*
* <li>an instance of
* <code>java.rmi.activation.ActivationID</code>,
* written by passing it to an invocation of
* <code>writeObject</code> on the stream instance
*
* <li>the external ref type name of the nested remote reference,
* which must be <code>"UnicastRef2"</code>,
* written by {@link java.io.ObjectOutput#writeUTF(String)}
*
* <li>the external form of the nested remote reference,
* written by invoking its <code>writeExternal</code> method
* with the stream instance
* (see the description of the external form for
* <code>"UnicastRef2"</code> above)
*
* </ul>
*
* <p>For <code>"UnicastServerRef"</code> and
* <code>"UnicastServerRef2"</code>, no data is written by the
* <code>writeExternal</code> method or read by the
* <code>readExternal</code> method.
*/
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException, java.lang.ClassNotFoundException
{
if (ref == null) {
throw new java.rmi.MarshalException("Invalid remote object");
} else {
String refClassName = ref.getRefClass(out);
if (refClassName == null || refClassName.length() == 0) {
/*
* No reference class name specified, so serialize
* remote reference.
*/
out.writeUTF("");
out.writeObject(ref);
} else {
/*
* Built-in reference class specified, so delegate
* to reference to write out its external form.
*/
out.writeUTF(refClassName);
ref.writeExternal(out);
}
}
}
/**
* <code>readObject</code> for custom serialization.
*
* <p>This method reads this object's serialized form for this class
* as follows:
*
* <p>The <code>readUTF</code> method is invoked on <code>in</code>
* to read the external ref type name for the <code>RemoteRef</code>
* instance to be filled in to this object's <code>ref</code> field.
* If the string returned by <code>readUTF</code> has length zero,
* the <code>readObject</code> method is invoked on <code>in</code>,
* and than the value returned by <code>readObject</code> is cast to
* <code>RemoteRef</code> and this object's <code>ref</code> field is
* set to that value.
* Otherwise, this object's <code>ref</code> field is set to a
* <code>RemoteRef</code> instance that is created of an
* implementation-specific class corresponding to the external ref
* type name returned by <code>readUTF</code>, and then
* the <code>readExternal</code> method is invoked on
* this object's <code>ref</code> field.
*
* <p>If the external ref type name is
* <code>"UnicastRef"</code>, <code>"UnicastServerRef"</code>,
* <code>"UnicastRef2"</code>, <code>"UnicastServerRef2"</code>,
* or <code>"ActivatableRef"</code>, a corresponding
* implementation-specific class must be found, and its
* <code>readExternal</code> method must read the serial data
* for that external ref type name as specified to be written
* in the <b>serialData</b> documentation for this class.
* If the external ref type name is any other string (of non-zero
* length), a <code>ClassNotFoundException</code> will be thrown,
* unless the implementation provides an implementation-specific
* class corresponding to that external ref type name, in which
* case this object's <code>ref</code> field will be set to an
* instance of that implementation-specific class.
*/
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, java.lang.ClassNotFoundException
{
String refClassName = in.readUTF();
if (refClassName == null || refClassName.length() == 0) {
/*
* No reference class name specified, so construct
* remote reference from its serialized form.
*/
ref = (RemoteRef) in.readObject();
} else {
/*
* Built-in reference class specified, so delegate to
* internal reference class to initialize its fields from
* its external form.
*/
String internalRefClassName =
RemoteRef.packagePrefix + "." + refClassName;
Class<?> refClass = Class.forName(internalRefClassName);
try {
ref = (RemoteRef) refClass.newInstance();
/*
* If this step fails, assume we found an internal
* class that is not meant to be a serializable ref
* type.
*/
} catch (InstantiationException e) {
throw new ClassNotFoundException(internalRefClassName, e);
} catch (IllegalAccessException e) {
throw new ClassNotFoundException(internalRefClassName, e);
} catch (ClassCastException e) {
throw new ClassNotFoundException(internalRefClassName, e);
}
ref.readExternal(in);
}
}
}
| apache-2.0 |
netroby/gerrit | gerrit-gwtui/src/main/java/com/google/gerrit/client/account/GpgKeyInfo.java | 1121 | // Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.account;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
public class GpgKeyInfo extends JavaScriptObject {
public final native String id() /*-{ return this.id; }-*/;
public final native String fingerprint() /*-{ return this.fingerprint; }-*/;
public final native JsArrayString userIds() /*-{ return this.user_ids; }-*/;
public final native String key() /*-{ return this.key; }-*/;
protected GpgKeyInfo() {
}
}
| apache-2.0 |
lcs777/simple-binary-encoding | perf/java/uk/co/real_logic/protobuf/CarBenchmark.java | 6866 | /*
* Copyright 2013 Real Logic 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 uk.co.real_logic.protobuf;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import uk.co.real_logic.protobuf.examples.Examples;
import uk.co.real_logic.protobuf.examples.Examples.Car.Model;
import uk.co.real_logic.protobuf.examples.Examples.PerformanceFigures;
public class CarBenchmark
{
private static final String VEHICLE_CODE = "abcdef";
private static final String ENG_MAN_CODE = "abc";
private static final String MAKE = "AUDI";
private static final String MODEL = "R8";
@State(Scope.Benchmark)
public static class MyState
{
final byte[] decodeBuffer;
{
try
{
decodeBuffer = encode();
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
}
@Benchmark
public byte[] testEncode(final MyState state) throws Exception
{
return encode();
}
@Benchmark
public Examples.Car testDecode(final MyState state) throws Exception
{
final byte[] buffer = state.decodeBuffer;
return decode(buffer);
}
private static byte[] encode() throws Exception
{
final Examples.Car.Builder car = Examples.Car.newBuilder();
car.setCode(Model.A)
.setModelYear(2005)
.setSerialNumber(12345)
.setAvailable(true)
.setVehicleCode(VEHICLE_CODE);
for (int i = 0, size = 5; i < size; i++)
{
car.addSomeNumbers(i);
}
car.addOptionalExtras(Examples.Car.Extras.SPORTS_PACK)
.addOptionalExtras(Examples.Car.Extras.SUN_ROOF);
car.getEngineBuilder().setCapacity(4200)
.setNumCylinders(8)
.setManufacturerCode(ENG_MAN_CODE);
car.addFuelFigures(Examples.FuelFigures.newBuilder().setSpeed(30).setMpg(35.9f));
car.addFuelFigures(Examples.FuelFigures.newBuilder().setSpeed(50).setMpg(35.9f));
car.addFuelFigures(Examples.FuelFigures.newBuilder().setSpeed(70).setMpg(35.9f));
final PerformanceFigures.Builder perf1 = car.addPerformanceBuilder().setOctaneRating(95);
perf1.addAcceleration(Examples.Acceleration.newBuilder().setMph(30).setSeconds(4.0f));
perf1.addAcceleration(Examples.Acceleration.newBuilder().setMph(60).setSeconds(7.5f));
perf1.addAcceleration(Examples.Acceleration.newBuilder().setMph(100).setSeconds(12.2f));
final PerformanceFigures.Builder perf2 = car.addPerformanceBuilder().setOctaneRating(99);
perf2.addAcceleration(Examples.Acceleration.newBuilder().setMph(30).setSeconds(3.8f));
perf2.addAcceleration(Examples.Acceleration.newBuilder().setMph(60).setSeconds(7.1f));
perf2.addAcceleration(Examples.Acceleration.newBuilder().setMph(100).setSeconds(11.8f));
car.setMake(MAKE);
car.setModel(MODEL);
return car.build().toByteArray();
}
private static Examples.Car decode(final byte[] buffer) throws Exception
{
final Examples.Car car = Examples.Car.parseFrom(buffer);
car.getSerialNumber();
car.getModelYear();
car.hasAvailable();
car.getCode();
for (int i = 0, size = car.getSomeNumbersCount(); i < size; i++)
{
car.getSomeNumbers(i);
}
car.getVehicleCode();
for (int i = 0, size = car.getOptionalExtrasCount(); i < size; i++)
{
car.getOptionalExtras(i);
}
final Examples.Engine engine = car.getEngine();
engine.getCapacity();
engine.getNumCylinders();
engine.getMaxRpm();
engine.getManufacturerCode();
engine.getFuel();
for (final Examples.FuelFigures fuelFigures : car.getFuelFiguresList())
{
fuelFigures.getSpeed();
fuelFigures.getMpg();
}
for (final PerformanceFigures performanceFigures : car.getPerformanceList())
{
performanceFigures.getOctaneRating();
for (final Examples.Acceleration acceleration : performanceFigures.getAccelerationList())
{
acceleration.getMph();
acceleration.getSeconds();
}
}
car.getMake();
car.getModel();
return car;
}
/*
* Benchmarks to allow execution outside of JMH.
*/
public static void main(final String[] args) throws Exception
{
for (int i = 0; i < 10; i++)
{
perfTestEncode(i);
perfTestDecode(i);
}
}
private static void perfTestEncode(final int runNumber) throws Exception
{
final int reps = 1 * 1000 * 1000;
final MyState state = new MyState();
final CarBenchmark benchmark = new CarBenchmark();
byte[] encodedBuffer = null;
final long start = System.nanoTime();
for (int i = 0; i < reps; i++)
{
encodedBuffer = benchmark.testEncode(state);
}
final long totalDuration = System.nanoTime() - start;
System.out.printf(
"%d - %d(ns) average duration for %s.testEncode() - message encodedLength %d\n",
Integer.valueOf(runNumber),
Long.valueOf(totalDuration / reps),
benchmark.getClass().getName(),
Integer.valueOf(encodedBuffer.length));
}
private static void perfTestDecode(final int runNumber) throws Exception
{
final int reps = 1 * 1000 * 1000;
final MyState state = new MyState();
final CarBenchmark benchmark = new CarBenchmark();
Examples.Car car = null;
final long start = System.nanoTime();
for (int i = 0; i < reps; i++)
{
car = benchmark.testDecode(state);
}
final long totalDuration = System.nanoTime() - start;
System.out.printf(
"%d - %d(ns) average duration for %s.testDecode() - message encodedLength %d\n",
Integer.valueOf(runNumber),
Long.valueOf(totalDuration / reps),
benchmark.getClass().getName(),
Integer.valueOf(car.getSomeNumbersCount()));
}
}
| apache-2.0 |
peterl1084/framework | client/src/main/java/com/vaadin/client/ui/layout/LayoutDependencyTree.java | 30129 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.ui.layout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
import com.google.gwt.core.client.JsArrayString;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorMap;
import com.vaadin.client.FastStringMap;
import com.vaadin.client.FastStringSet;
import com.vaadin.client.HasComponentsConnector;
import com.vaadin.client.JsArrayObject;
import com.vaadin.client.Profiler;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.Util;
import com.vaadin.client.VConsole;
import com.vaadin.client.ui.ManagedLayout;
import com.vaadin.shared.AbstractComponentState;
/**
* Internal class used to keep track of layout dependencies during one layout
* run. This class is not intended to be used directly by applications.
*
* @author Vaadin Ltd
* @since 7.0.0
*/
public class LayoutDependencyTree {
private class LayoutDependency {
private final ComponentConnector connector;
private final int direction;
private boolean needsLayout = false;
private boolean needsMeasure = false;
private boolean scrollingParentCached = false;
private ComponentConnector scrollingBoundary = null;
private FastStringSet measureBlockers = FastStringSet.create();
private FastStringSet layoutBlockers = FastStringSet.create();
public LayoutDependency(ComponentConnector connector, int direction) {
this.connector = connector;
this.direction = direction;
}
private void addLayoutBlocker(ComponentConnector blocker) {
String blockerId = blocker.getConnectorId();
if (!layoutBlockers.contains(blockerId)) {
boolean wasEmpty = layoutBlockers.isEmpty();
layoutBlockers.add(blockerId);
if (wasEmpty) {
if (needsLayout) {
getLayoutQueue(direction)
.remove(connector.getConnectorId());
} else {
// Propagation already done if needsLayout is set
propagatePotentialLayout();
}
}
}
}
private void removeLayoutBlocker(ComponentConnector blocker) {
String blockerId = blocker.getConnectorId();
if (layoutBlockers.contains(blockerId)) {
layoutBlockers.remove(blockerId);
if (layoutBlockers.isEmpty()) {
if (needsLayout) {
getLayoutQueue(direction)
.add(connector.getConnectorId());
} else {
propagateNoUpcomingLayout();
}
}
}
}
private void addMeasureBlocker(ComponentConnector blocker) {
String blockerId = blocker.getConnectorId();
boolean alreadyAdded = measureBlockers.contains(blockerId);
if (alreadyAdded) {
return;
}
boolean wasEmpty = measureBlockers.isEmpty();
measureBlockers.add(blockerId);
if (wasEmpty) {
if (needsMeasure) {
getMeasureQueue(direction)
.remove(connector.getConnectorId());
} else {
propagatePotentialResize();
}
}
}
private void removeMeasureBlocker(ComponentConnector blocker) {
String blockerId = blocker.getConnectorId();
boolean alreadyRemoved = !measureBlockers.contains(blockerId);
if (alreadyRemoved) {
return;
}
measureBlockers.remove(blockerId);
if (measureBlockers.isEmpty()) {
if (needsMeasure) {
getMeasureQueue(direction).add(connector.getConnectorId());
} else {
propagateNoUpcomingResize();
}
}
}
public void setNeedsMeasure(boolean needsMeasure) {
if (needsMeasure && !this.needsMeasure) {
// If enabling needsMeasure
this.needsMeasure = needsMeasure;
if (measureBlockers.isEmpty()) {
// Add to queue if there are no blockers
getMeasureQueue(direction).add(connector.getConnectorId());
// Only need to propagate if not already propagated when
// setting blockers
propagatePotentialResize();
}
} else if (!needsMeasure && this.needsMeasure
&& measureBlockers.isEmpty()) {
// Only disable if there are no blockers (elements gets measured
// in both directions even if there is a blocker in one
// direction)
this.needsMeasure = needsMeasure;
getMeasureQueue(direction).remove(connector.getConnectorId());
propagateNoUpcomingResize();
}
}
public void setNeedsLayout(boolean needsLayout) {
if (!(connector instanceof ManagedLayout)) {
throw new IllegalStateException(
"Only managed layouts can need layout, layout attempted for "
+ Util.getConnectorString(connector));
}
if (needsLayout && !this.needsLayout) {
// If enabling needsLayout
this.needsLayout = needsLayout;
if (layoutBlockers.isEmpty()) {
// Add to queue if there are no blockers
getLayoutQueue(direction).add(connector.getConnectorId());
// Only need to propagate if not already propagated when
// setting blockers
propagatePotentialLayout();
}
} else if (!needsLayout && this.needsLayout
&& layoutBlockers.isEmpty()) {
// Only disable if there are no layout blockers
// (SimpleManagedLayout gets layouted in both directions
// even if there is a blocker in one direction)
this.needsLayout = needsLayout;
getLayoutQueue(direction).remove(connector.getConnectorId());
propagateNoUpcomingLayout();
}
}
private void propagatePotentialResize() {
JsArrayString needsSizeForLayout = getNeedsSizeForLayout();
int length = needsSizeForLayout.length();
for (int i = 0; i < length; i++) {
String needsSizeId = needsSizeForLayout.get(i);
LayoutDependency layoutDependency = getDependency(needsSizeId,
direction);
layoutDependency.addLayoutBlocker(connector);
}
}
private JsArrayString getNeedsSizeForLayout() {
// Find all connectors that need the size of this connector for
// layouting
// Parent needs size if it isn't relative?
// Connector itself needs size if it isn't undefined?
// Children doesn't care?
JsArrayString needsSize = JsArrayObject.createArray().cast();
if (!isUndefinedInDirection(connector, direction)) {
needsSize.push(connector.getConnectorId());
}
if (!isRelativeInDirection(connector, direction)) {
ServerConnector parent = connector.getParent();
if (parent instanceof ComponentConnector) {
needsSize.push(parent.getConnectorId());
}
}
return needsSize;
}
private void propagateNoUpcomingResize() {
JsArrayString needsSizeForLayout = getNeedsSizeForLayout();
int length = needsSizeForLayout.length();
for (int i = 0; i < length; i++) {
String mightNeedLayoutId = needsSizeForLayout.get(i);
LayoutDependency layoutDependency = getDependency(
mightNeedLayoutId, direction);
layoutDependency.removeLayoutBlocker(connector);
}
}
private void propagatePotentialLayout() {
JsArrayString resizedByLayout = getResizedByLayout();
int length = resizedByLayout.length();
for (int i = 0; i < length; i++) {
String sizeMightChangeId = resizedByLayout.get(i);
LayoutDependency layoutDependency = getDependency(
sizeMightChangeId, direction);
layoutDependency.addMeasureBlocker(connector);
}
}
private JsArrayString getResizedByLayout() {
// Components that might get resized by a layout of this component
// Parent never resized
// Connector itself resized if undefined
// Children resized if relative
JsArrayString resized = JsArrayObject.createArray().cast();
if (isUndefinedInDirection(connector, direction)) {
resized.push(connector.getConnectorId());
}
if (connector instanceof HasComponentsConnector) {
HasComponentsConnector container = (HasComponentsConnector) connector;
for (ComponentConnector child : container
.getChildComponents()) {
if (!Util.shouldSkipMeasurementOfConnector(child, connector)
&& isRelativeInDirection(child, direction)) {
resized.push(child.getConnectorId());
}
}
}
return resized;
}
private void propagateNoUpcomingLayout() {
JsArrayString resizedByLayout = getResizedByLayout();
int length = resizedByLayout.length();
for (int i = 0; i < length; i++) {
String sizeMightChangeId = resizedByLayout.get(i);
LayoutDependency layoutDependency = getDependency(
sizeMightChangeId, direction);
layoutDependency.removeMeasureBlocker(connector);
}
}
public void markSizeAsChanged() {
Profiler.enter("LayoutDependency.markSizeAsChanged phase 1");
// When the size has changed, all that use that size should be
// layouted
JsArrayString needsSizeForLayout = getNeedsSizeForLayout();
int length = needsSizeForLayout.length();
for (int i = 0; i < length; i++) {
String connectorId = needsSizeForLayout.get(i);
LayoutDependency layoutDependency = getDependency(connectorId,
direction);
if (layoutDependency.connector instanceof ManagedLayout) {
Profiler.enter(
"LayoutDependency.markSizeAsChanged setNeedsLayout");
layoutDependency.setNeedsLayout(true);
Profiler.leave(
"LayoutDependency.markSizeAsChanged setNeedsLayout");
} else {
Profiler.enter(
"LayoutDependency.markSizeAsChanged propagatePostLayoutMeasure");
// Should simulate setNeedsLayout(true) + markAsLayouted ->
// propagate needs measure
layoutDependency.propagatePostLayoutMeasure();
Profiler.leave(
"LayoutDependency.markSizeAsChanged propagatePostLayoutMeasure");
}
}
Profiler.leave("LayoutDependency.markSizeAsChanged phase 1");
Profiler.enter("LayoutDependency.markSizeAsChanged scrollbars");
// Should also go through the hierarchy to discover appeared or
// disappeared scrollbars
ComponentConnector scrollingBoundary = getScrollingBoundary(
connector);
if (scrollingBoundary != null) {
getDependency(scrollingBoundary.getConnectorId(),
getOppositeDirection()).setNeedsMeasure(true);
}
Profiler.leave("LayoutDependency.markSizeAsChanged scrollbars");
}
/**
* Go up the hierarchy to find a component whose size might have changed
* in the other direction because changes to this component causes
* scrollbars to appear or disappear.
*
* @return
*/
private LayoutDependency findPotentiallyChangedScrollbar() {
ComponentConnector currentConnector = connector;
while (true) {
ServerConnector parent = currentConnector.getParent();
if (!(parent instanceof ComponentConnector)) {
return null;
}
if (parent instanceof MayScrollChildren) {
return getDependency(currentConnector.getConnectorId(),
getOppositeDirection());
}
currentConnector = (ComponentConnector) parent;
}
}
private int getOppositeDirection() {
return direction == HORIZONTAL ? VERTICAL : HORIZONTAL;
}
public void markAsLayouted() {
if (!layoutBlockers.isEmpty()) {
// Don't do anything if there are layout blockers (SimpleLayout
// gets layouted in both directions even if one direction is
// blocked)
return;
}
setNeedsLayout(false);
propagatePostLayoutMeasure();
}
private void propagatePostLayoutMeasure() {
Profiler.enter(
"LayoutDependency.propagatePostLayoutMeasure getResizedByLayout");
JsArrayString resizedByLayout = getResizedByLayout();
Profiler.leave(
"LayoutDependency.propagatePostLayoutMeasure getResizedByLayout");
int length = resizedByLayout.length();
for (int i = 0; i < length; i++) {
Profiler.enter(
"LayoutDependency.propagatePostLayoutMeasure setNeedsMeasure");
String resizedId = resizedByLayout.get(i);
LayoutDependency layoutDependency = getDependency(resizedId,
direction);
layoutDependency.setNeedsMeasure(true);
Profiler.leave(
"LayoutDependency.propagatePostLayoutMeasure setNeedsMeasure");
}
// Special case for e.g. wrapping texts
Profiler.enter(
"LayoutDependency.propagatePostLayoutMeasure horizontal case");
if (direction == HORIZONTAL && !connector.isUndefinedWidth()
&& connector.isUndefinedHeight()) {
LayoutDependency dependency = getDependency(
connector.getConnectorId(), VERTICAL);
dependency.setNeedsMeasure(true);
}
Profiler.leave(
"LayoutDependency.propagatePostLayoutMeasure horizontal case");
}
@Override
public String toString() {
String s = getCompactConnectorString(connector) + "\n";
if (direction == VERTICAL) {
s += "Vertical";
} else {
s += "Horizontal";
}
AbstractComponentState state = connector.getState();
s += " sizing: "
+ getSizeDefinition(
direction == VERTICAL ? state.height : state.width)
+ "\n";
if (needsLayout) {
s += "Needs layout\n";
}
if (getLayoutQueue(direction)
.contains(connector.getConnectorId())) {
s += "In layout queue\n";
}
s += "Layout blockers: " + blockersToString(layoutBlockers) + "\n";
if (needsMeasure) {
s += "Needs measure\n";
}
if (getMeasureQueue(direction)
.contains(connector.getConnectorId())) {
s += "In measure queue\n";
}
s += "Measure blockers: " + blockersToString(measureBlockers);
return s;
}
public boolean noMoreChangesExpected() {
return !needsLayout && !needsMeasure && layoutBlockers.isEmpty()
&& measureBlockers.isEmpty();
}
}
private static final int HORIZONTAL = 0;
private static final int VERTICAL = 1;
@SuppressWarnings("unchecked")
private final FastStringMap<LayoutDependency>[] dependenciesInDirection = new FastStringMap[] {
FastStringMap.create(), FastStringMap.create() };
private final FastStringSet[] measureQueueInDirection = new FastStringSet[] {
FastStringSet.create(), FastStringSet.create() };
private final FastStringSet[] layoutQueueInDirection = new FastStringSet[] {
FastStringSet.create(), FastStringSet.create() };
private final ApplicationConnection connection;
public LayoutDependencyTree(ApplicationConnection connection) {
this.connection = connection;
}
public void setNeedsMeasure(ComponentConnector connector,
boolean needsMeasure) {
setNeedsHorizontalMeasure(connector, needsMeasure);
setNeedsVerticalMeasure(connector, needsMeasure);
}
/**
* @param connectorId
* @param needsMeasure
*
* @deprecated As of 7.4.2, use
* {@link #setNeedsMeasure(ComponentConnector, boolean)} for
* improved performance.
*/
@Deprecated
public void setNeedsMeasure(String connectorId, boolean needsMeasure) {
ComponentConnector connector = (ComponentConnector) ConnectorMap
.get(connection).getConnector(connectorId);
if (connector == null) {
return;
}
setNeedsMeasure(connector, needsMeasure);
}
public void setNeedsHorizontalMeasure(ComponentConnector connector,
boolean needsMeasure) {
LayoutDependency dependency = getDependency(connector, HORIZONTAL);
dependency.setNeedsMeasure(needsMeasure);
}
public void setNeedsHorizontalMeasure(String connectorId,
boolean needsMeasure) {
// Ensure connector exists
ComponentConnector connector = (ComponentConnector) ConnectorMap
.get(connection).getConnector(connectorId);
if (connector == null) {
return;
}
setNeedsHorizontalMeasure(connector, needsMeasure);
}
public void setNeedsVerticalMeasure(ComponentConnector connector,
boolean needsMeasure) {
LayoutDependency dependency = getDependency(connector, VERTICAL);
dependency.setNeedsMeasure(needsMeasure);
}
public void setNeedsVerticalMeasure(String connectorId,
boolean needsMeasure) {
// Ensure connector exists
ComponentConnector connector = (ComponentConnector) ConnectorMap
.get(connection).getConnector(connectorId);
if (connector == null) {
return;
}
setNeedsVerticalMeasure(connector, needsMeasure);
}
private LayoutDependency getDependency(ComponentConnector connector,
int direction) {
return getDependency(connector.getConnectorId(), connector, direction);
}
private LayoutDependency getDependency(String connectorId, int direction) {
return getDependency(connectorId, null, direction);
}
private LayoutDependency getDependency(String connectorId,
ComponentConnector connector, int direction) {
FastStringMap<LayoutDependency> dependencies = dependenciesInDirection[direction];
LayoutDependency dependency = dependencies.get(connectorId);
if (dependency == null) {
if (connector == null) {
connector = (ComponentConnector) ConnectorMap.get(connection)
.getConnector(connectorId);
if (connector == null) {
getLogger().warning("No connector found for id "
+ connectorId + " while creating LayoutDependency");
return null;
}
}
dependency = new LayoutDependency(connector, direction);
dependencies.put(connectorId, dependency);
}
return dependency;
}
private FastStringSet getLayoutQueue(int direction) {
return layoutQueueInDirection[direction];
}
private FastStringSet getMeasureQueue(int direction) {
return measureQueueInDirection[direction];
}
/**
* @param layout
* @param needsLayout
*
* @deprecated As of 7.0.1, use
* {@link #setNeedsHorizontalLayout(String, boolean)} for
* improved performance.
*/
@Deprecated
public void setNeedsHorizontalLayout(ManagedLayout layout,
boolean needsLayout) {
setNeedsHorizontalLayout(layout.getConnectorId(), needsLayout);
}
public void setNeedsHorizontalLayout(String connectorId,
boolean needsLayout) {
LayoutDependency dependency = getDependency(connectorId, HORIZONTAL);
if (dependency != null) {
dependency.setNeedsLayout(needsLayout);
} else {
getLogger()
.warning("No dependency found in setNeedsHorizontalLayout");
}
}
/**
* @param layout
* @param needsLayout
*
* @deprecated As of 7.0.1, use
* {@link #setNeedsVerticalLayout(String, boolean)} for improved
* performance.
*/
@Deprecated
public void setNeedsVerticalLayout(ManagedLayout layout,
boolean needsLayout) {
setNeedsVerticalLayout(layout.getConnectorId(), needsLayout);
}
public void setNeedsVerticalLayout(String connectorId,
boolean needsLayout) {
LayoutDependency dependency = getDependency(connectorId, VERTICAL);
if (dependency != null) {
dependency.setNeedsLayout(needsLayout);
} else {
getLogger()
.warning("No dependency found in setNeedsVerticalLayout");
}
}
public void markAsHorizontallyLayouted(ManagedLayout layout) {
LayoutDependency dependency = getDependency(layout.getConnectorId(),
HORIZONTAL);
dependency.markAsLayouted();
}
public void markAsVerticallyLayouted(ManagedLayout layout) {
LayoutDependency dependency = getDependency(layout.getConnectorId(),
VERTICAL);
dependency.markAsLayouted();
}
public void markHeightAsChanged(ComponentConnector connector) {
LayoutDependency dependency = getDependency(connector.getConnectorId(),
VERTICAL);
dependency.markSizeAsChanged();
}
public void markWidthAsChanged(ComponentConnector connector) {
LayoutDependency dependency = getDependency(connector.getConnectorId(),
HORIZONTAL);
dependency.markSizeAsChanged();
}
private static boolean isRelativeInDirection(ComponentConnector connector,
int direction) {
if (direction == HORIZONTAL) {
return connector.isRelativeWidth();
} else {
return connector.isRelativeHeight();
}
}
private static boolean isUndefinedInDirection(ComponentConnector connector,
int direction) {
if (direction == VERTICAL) {
return connector.isUndefinedHeight();
} else {
return connector.isUndefinedWidth();
}
}
private static String getCompactConnectorString(ServerConnector connector) {
return connector.getClass().getSimpleName() + " ("
+ connector.getConnectorId() + ")";
}
private static String getSizeDefinition(String size) {
if (size == null || size.length() == 0) {
return "undefined";
} else if (size.endsWith("%")) {
return "relative";
} else {
return "fixed";
}
}
private String blockersToString(FastStringSet blockers) {
StringBuilder b = new StringBuilder("[");
ConnectorMap connectorMap = ConnectorMap.get(connection);
JsArrayString blockersDump = blockers.dump();
for (int i = 0; i < blockersDump.length(); i++) {
ServerConnector blocker = connectorMap
.getConnector(blockersDump.get(i));
if (b.length() != 1) {
b.append(", ");
}
b.append(getCompactConnectorString(blocker));
}
b.append(']');
return b.toString();
}
public boolean hasConnectorsToMeasure() {
return !measureQueueInDirection[HORIZONTAL].isEmpty()
|| !measureQueueInDirection[VERTICAL].isEmpty();
}
public boolean hasHorizontalConnectorToLayout() {
return !getLayoutQueue(HORIZONTAL).isEmpty();
}
public boolean hasVerticaConnectorToLayout() {
return !getLayoutQueue(VERTICAL).isEmpty();
}
/**
* @return
* @deprecated As of 7.0.1, use {@link #getHorizontalLayoutTargetsJsArray()}
* for improved performance.
*/
@Deprecated
public ManagedLayout[] getHorizontalLayoutTargets() {
return asManagedLayoutArray(getHorizontalLayoutTargetsJsArray());
}
/**
* @return
* @deprecated As of 7.0.1, use {@link #getVerticalLayoutTargetsJsArray()}
* for improved performance.
*/
@Deprecated
public ManagedLayout[] getVerticalLayoutTargets() {
return asManagedLayoutArray(getVerticalLayoutTargetsJsArray());
}
private ManagedLayout[] asManagedLayoutArray(
JsArrayString connectorIdArray) {
int length = connectorIdArray.length();
ConnectorMap connectorMap = ConnectorMap.get(connection);
ManagedLayout[] result = new ManagedLayout[length];
for (int i = 0; i < length; i++) {
result[i] = (ManagedLayout) connectorMap
.getConnector(connectorIdArray.get(i));
}
return result;
}
public JsArrayString getHorizontalLayoutTargetsJsArray() {
return getLayoutQueue(HORIZONTAL).dump();
}
public JsArrayString getVerticalLayoutTargetsJsArray() {
return getLayoutQueue(VERTICAL).dump();
}
/**
* @return
* @deprecated As of 7.0.1, use {@link #getMeasureTargetsJsArray()} for
* improved performance.
*/
@Deprecated
public Collection<ComponentConnector> getMeasureTargets() {
JsArrayString targetIds = getMeasureTargetsJsArray();
int length = targetIds.length();
ArrayList<ComponentConnector> targets = new ArrayList<>(length);
ConnectorMap connectorMap = ConnectorMap.get(connection);
for (int i = 0; i < length; i++) {
targets.add((ComponentConnector) connectorMap
.getConnector(targetIds.get(i)));
}
return targets;
}
public JsArrayString getMeasureTargetsJsArray() {
FastStringSet allMeasuredTargets = FastStringSet.create();
allMeasuredTargets.addAll(getMeasureQueue(HORIZONTAL));
allMeasuredTargets.addAll(getMeasureQueue(VERTICAL));
return allMeasuredTargets.dump();
}
public void logDependencyStatus(ComponentConnector connector) {
VConsole.log("====");
String connectorId = connector.getConnectorId();
VConsole.log(getDependency(connectorId, HORIZONTAL).toString());
VConsole.log(getDependency(connectorId, VERTICAL).toString());
}
public boolean noMoreChangesExpected(ComponentConnector connector) {
return getDependency(connector.getConnectorId(), HORIZONTAL)
.noMoreChangesExpected()
&& getDependency(connector.getConnectorId(), VERTICAL)
.noMoreChangesExpected();
}
public ComponentConnector getScrollingBoundary(
ComponentConnector connector) {
LayoutDependency dependency = getDependency(connector.getConnectorId(),
HORIZONTAL);
if (!dependency.scrollingParentCached) {
ServerConnector parent = dependency.connector.getParent();
if (parent instanceof MayScrollChildren) {
dependency.scrollingBoundary = connector;
} else if (parent instanceof ComponentConnector) {
dependency.scrollingBoundary = getScrollingBoundary(
(ComponentConnector) parent);
} else {
// No scrolling parent
}
dependency.scrollingParentCached = true;
}
return dependency.scrollingBoundary;
}
private static Logger getLogger() {
return Logger.getLogger(LayoutDependencyTree.class.getName());
}
}
| apache-2.0 |
hd5970/ONOS | core/store/dist/src/main/java/org/onosproject/store/hz/StoreManager.java | 2006 | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.hz;
import com.hazelcast.config.Config;
import com.hazelcast.config.FileSystemXmlConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
/**
* Auxiliary bootstrap of distributed store.
*/
@Component(immediate = true)
@Service
public class StoreManager implements StoreService {
protected static final String HAZELCAST_XML_FILE = "etc/hazelcast.xml";
private final Logger log = LoggerFactory.getLogger(getClass());
protected HazelcastInstance instance;
@Activate
public void activate() {
try {
Config config = new FileSystemXmlConfig(HAZELCAST_XML_FILE);
instance = Hazelcast.newHazelcastInstance(config);
log.info("Started");
} catch (FileNotFoundException e) {
log.error("Unable to configure Hazelcast", e);
}
}
@Deactivate
public void deactivate() {
instance.shutdown();
log.info("Stopped");
}
@Override
public HazelcastInstance getHazelcastInstance() {
return instance;
}
}
| apache-2.0 |
TheSoftwareFactory/lokki-android | App/src/main/java/cc/softwarefactory/lokki/android/utilities/map/PersonRenderer.java | 3826 | package cc.softwarefactory.lokki.android.utilities.map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterManager;
import com.google.maps.android.clustering.view.DefaultClusterRenderer;
import com.google.maps.android.ui.IconGenerator;
import java.util.ArrayList;
import java.util.List;
import cc.softwarefactory.lokki.android.R;
import cc.softwarefactory.lokki.android.models.Person;
import cc.softwarefactory.lokki.android.utilities.MultiDrawable;
import cc.softwarefactory.lokki.android.utilities.Utils;
/**
* Created by haider
*/
public class PersonRenderer extends DefaultClusterRenderer<Person> {
private final IconGenerator mIconGenerator;
private final IconGenerator mClusterIconGenerator;
private final ImageView mImageView;
private final ImageView mClusterImageView;
private final int mDimension;
private final Context mContext;
public PersonRenderer(Context context, GoogleMap map, ClusterManager clusterManager) {
super(context, map, clusterManager);
mContext = context;
mIconGenerator = new IconGenerator(mContext);
mClusterIconGenerator = new IconGenerator(mContext);
View multiProfile = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
mClusterIconGenerator.setContentView(multiProfile);
mClusterImageView = (ImageView) multiProfile.findViewById(R.id.image);
mImageView = new ImageView(context);
mDimension = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
mImageView.setLayoutParams(new ViewGroup.LayoutParams(mDimension, mDimension));
mIconGenerator.setContentView(mImageView);
}
@Override
protected void onBeforeClusterItemRendered(Person person, MarkerOptions markerOptions) {
mImageView.setImageBitmap(person.getMarkerPhoto());
Bitmap icon = mIconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(person.toString());
long time = 0;
if (person.getLocation() != null && person.getLocation().getTime() != null) time = person.getLocation().getTime().getTime();
markerOptions.snippet(Utils.timestampText(String.valueOf(time)));
}
@Override
protected void onBeforeClusterRendered(Cluster<Person> cluster, MarkerOptions markerOptions) {
List<Drawable> profilePhotos = new ArrayList<Drawable>(Math.min(4, cluster.getSize()));
int width = mDimension;
int height = mDimension;
for (Person p : cluster.getItems()) {
// Draw 4 at most.
if (profilePhotos.size() == 4) break;
Drawable drawable = new BitmapDrawable(mContext.getResources(), p.getPhoto());
drawable.setBounds(0, 0, width, height);
profilePhotos.add(drawable);
}
MultiDrawable multiDrawable = new MultiDrawable(profilePhotos);
multiDrawable.setBounds(0, 0, width, height);
mClusterImageView.setImageDrawable(multiDrawable);
Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
@Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
// Always render clusters.
return cluster.getSize() > 1;
}
}
| apache-2.0 |
ingokegel/intellij-community | plugins/ui-designer/src/com/intellij/uiDesigner/actions/MorphAction.java | 7311 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.uiDesigner.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.designSurface.GuiEditor;
import com.intellij.uiDesigner.designSurface.InsertComponentProcessor;
import com.intellij.uiDesigner.inspections.FormInspectionUtil;
import com.intellij.uiDesigner.lw.IComponent;
import com.intellij.uiDesigner.lw.IProperty;
import com.intellij.uiDesigner.palette.ComponentItem;
import com.intellij.uiDesigner.palette.Palette;
import com.intellij.uiDesigner.propertyInspector.IntrospectedProperty;
import com.intellij.uiDesigner.propertyInspector.properties.BindingProperty;
import com.intellij.uiDesigner.propertyInspector.properties.IntroComponentProperty;
import com.intellij.uiDesigner.quickFixes.ChangeFieldTypeFix;
import com.intellij.uiDesigner.radComponents.RadAtomicComponent;
import com.intellij.uiDesigner.radComponents.RadComponent;
import com.intellij.uiDesigner.radComponents.RadContainer;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class MorphAction extends AbstractGuiEditorAction {
private static final Logger LOG = Logger.getInstance(MorphAction.class);
public MorphAction() {
super(true);
}
@Override
protected void actionPerformed(final GuiEditor editor, final List<? extends RadComponent> selection, final AnActionEvent e) {
Processor<ComponentItem> processor = selectedValue -> {
Runnable runnable = () -> {
for(RadComponent c: selection) {
if (!morphComponent(editor, c, selectedValue)) break;
}
editor.refreshAndSave(true);
};
CommandProcessor.getInstance().executeCommand(editor.getProject(), runnable, UIDesignerBundle.message("morph.component.command"), null);
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(editor.getGlassLayer(), true));
return true;
};
PaletteListPopupStep step = new PaletteListPopupStep(editor, null, processor,
UIDesignerBundle.message("morph.component.title"));
step.hideNonAtomic();
if (selection.size() == 1) {
step.hideComponentClass(selection.get(0).getComponentClassName());
}
final ListPopup listPopup = JBPopupFactory.getInstance().createListPopup(step);
FormEditingUtil.showPopupUnderComponent(listPopup, selection.get(0));
}
private static boolean morphComponent(final GuiEditor editor, final RadComponent oldComponent, ComponentItem targetItem) {
targetItem =
InsertComponentProcessor.replaceAnyComponentItem(editor, targetItem, UIDesignerBundle.message("morph.non.palette.component"));
if (targetItem == null) {
return false;
}
final RadComponent newComponent = InsertComponentProcessor.createInsertedComponent(editor, targetItem);
if (newComponent == null) return false;
newComponent.setBinding(oldComponent.getBinding());
newComponent.setCustomLayoutConstraints(oldComponent.getCustomLayoutConstraints());
newComponent.getConstraints().restore(oldComponent.getConstraints());
updateBoundFieldType(editor, oldComponent, targetItem);
final IProperty[] oldProperties = oldComponent.getModifiedProperties();
final Palette palette = Palette.getInstance(editor.getProject());
for(IProperty prop: oldProperties) {
IntrospectedProperty newProp = palette.getIntrospectedProperty(newComponent, prop.getName());
if (newProp == null || !prop.getClass().equals(newProp.getClass())) continue;
Object oldValue = prop.getPropertyValue(oldComponent);
try {
//noinspection unchecked
newProp.setValue(newComponent, oldValue);
}
catch (Exception e) {
// ignore
}
}
retargetComponentProperties(editor, oldComponent, newComponent);
final RadContainer parent = oldComponent.getParent();
int index = parent.indexOfComponent(oldComponent);
parent.removeComponent(oldComponent);
parent.addComponent(newComponent, index);
newComponent.setSelected(true);
if (oldComponent.isDefaultBinding()) {
final String text = FormInspectionUtil.getText(newComponent.getModule(), newComponent);
if (text != null) {
String binding = BindingProperty.suggestBindingFromText(newComponent, text);
if (binding != null) {
new BindingProperty(newComponent.getProject()).setValueEx(newComponent, binding);
}
}
newComponent.setDefaultBinding(true);
}
return true;
}
private static void updateBoundFieldType(final GuiEditor editor, final RadComponent oldComponent, final ComponentItem targetItem) {
PsiField oldBoundField = BindingProperty.findBoundField(editor.getRootContainer(), oldComponent.getBinding());
if (oldBoundField != null) {
final PsiElementFactory factory = JavaPsiFacade.getInstance(editor.getProject()).getElementFactory();
try {
PsiType componentType = factory.createTypeFromText(targetItem.getClassName().replace('$', '.'), null);
new ChangeFieldTypeFix(editor, oldBoundField, componentType).run();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
private static void retargetComponentProperties(final GuiEditor editor, final RadComponent c, final RadComponent newComponent) {
FormEditingUtil.iterate(editor.getRootContainer(), new FormEditingUtil.ComponentVisitor() {
@Override
public boolean visit(final IComponent component) {
RadComponent rc = (RadComponent) component;
for(IProperty p: component.getModifiedProperties()) {
if (p instanceof IntroComponentProperty) {
IntroComponentProperty icp = (IntroComponentProperty) p;
final String value = icp.getValue(rc);
if (value.equals(c.getId())) {
try {
icp.setValue((RadComponent)component, newComponent.getId());
}
catch (Exception e) {
// ignore
}
}
}
}
return true;
}
});
}
@Override
protected void update(@NotNull GuiEditor editor, final ArrayList<? extends RadComponent> selection, final AnActionEvent e) {
if (selection.size() == 0) {
e.getPresentation().setEnabled(false);
return;
}
for(RadComponent c: selection) {
if (!(c instanceof RadAtomicComponent)) {
e.getPresentation().setEnabled(false);
return;
}
}
}
}
| apache-2.0 |
AndroidX/androidx | samples/SupportLeanbackDemos/src/main/java/com/example/android/leanback/OnboardingActivity.java | 920 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.example.android.leanback;
import android.app.Activity;
import android.os.Bundle;
public class OnboardingActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.onboarding);
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-container/v1beta1/1.29.2/com/google/api/services/container/v1beta1/model/CloudRunConfig.java | 2176 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.container.v1beta1.model;
/**
* Configuration options for the Cloud Run feature.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Kubernetes Engine API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class CloudRunConfig extends com.google.api.client.json.GenericJson {
/**
* Whether Cloud Run addon is enabled for this cluster.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean disabled;
/**
* Whether Cloud Run addon is enabled for this cluster.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDisabled() {
return disabled;
}
/**
* Whether Cloud Run addon is enabled for this cluster.
* @param disabled disabled or {@code null} for none
*/
public CloudRunConfig setDisabled(java.lang.Boolean disabled) {
this.disabled = disabled;
return this;
}
@Override
public CloudRunConfig set(String fieldName, Object value) {
return (CloudRunConfig) super.set(fieldName, value);
}
@Override
public CloudRunConfig clone() {
return (CloudRunConfig) super.clone();
}
}
| apache-2.0 |
vlsi/calcite | core/src/main/java/org/apache/calcite/util/NameSet.java | 2796 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.util;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
/** Set of names that can be accessed with and without case sensitivity. */
public class NameSet {
public static final Comparator<String> COMPARATOR = CaseInsensitiveComparator.COMPARATOR;
private static final Object DUMMY = new Object();
private final NameMap<Object> names;
/** Creates a NameSet based on an existing set. */
private NameSet(NameMap<Object> names) {
this.names = names;
}
/** Creates a NameSet, initially empty. */
public NameSet() {
this(new NameMap<>());
}
/** Creates a NameSet that is an immutable copy of a given collection. */
public static NameSet immutableCopyOf(Set<String> names) {
return new NameSet(NameMap.immutableCopyOf(Maps.asMap(names, k -> DUMMY)));
}
@Override public String toString() {
return names.map().keySet().toString();
}
@Override public int hashCode() {
return names.hashCode();
}
@Override public boolean equals(Object obj) {
return this == obj
|| obj instanceof NameSet
&& names.equals(((NameSet) obj).names);
}
public void add(String name) {
names.put(name, DUMMY);
}
/** Returns an iterable over all the entries in the set that match the given
* name. If case-sensitive, that iterable will have 0 or 1 elements; if
* case-insensitive, it may have 0 or more. */
public Collection<String> range(String name, boolean caseSensitive) {
return names.range(name, caseSensitive).keySet();
}
/** Returns whether this set contains the given name, with a given
* case-sensitivity. */
public boolean contains(String name, boolean caseSensitive) {
return names.containsKey(name, caseSensitive);
}
/** Returns the contents as an iterable. */
public Iterable<String> iterable() {
return Collections.unmodifiableSet(names.map().keySet());
}
}
| apache-2.0 |
ravisund/Kundera | src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSOTOLazyTest.java | 5090 | /*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * 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.impetus.client.crud;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.impetus.client.crud.entities.AddressRDBMSOTO;
import com.impetus.client.crud.entities.PersonLazyRDBMSOTO;
public class RDBMSOTOLazyTest
{
private EntityManagerFactory emf;
private EntityManager em;
private RDBMSCli cli;
private static final String SCHEMA = "testdb";
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
emf = Persistence.createEntityManagerFactory("testHibernate");
em = getNewEM();
createSchema();
}
@Test
public void testCRUD()
{
AddressRDBMSOTO address = new AddressRDBMSOTO();
address.setAddressId("a");
address.setStreet("sector 11");
PersonLazyRDBMSOTO person = new PersonLazyRDBMSOTO();
person.setPersonId("1");
person.setPersonName("Kuldeep");
person.setAddress(address);
em.persist(person);
em = getNewEM();
PersonLazyRDBMSOTO foundPerson = em.find(PersonLazyRDBMSOTO.class, "1");
Assert.assertNotNull(foundPerson);
Assert.assertNotNull(foundPerson.getAddress());
Assert.assertEquals("1", foundPerson.getPersonId());
Assert.assertEquals("Kuldeep", foundPerson.getPersonName());
Assert.assertEquals("a", foundPerson.getAddress().getAddressId());
Assert.assertEquals("sector 11", foundPerson.getAddress().getStreet());
foundPerson.setPersonName("KK");
foundPerson.getAddress().setStreet("sector 12");
em.merge(foundPerson);
em = getNewEM();
foundPerson = em.find(PersonLazyRDBMSOTO.class, "1");
Assert.assertNotNull(foundPerson);
Assert.assertNotNull(foundPerson.getAddress());
Assert.assertEquals("1", foundPerson.getPersonId());
Assert.assertEquals("KK", foundPerson.getPersonName());
Assert.assertEquals("a", foundPerson.getAddress().getAddressId());
Assert.assertEquals("sector 12", foundPerson.getAddress().getStreet());
em.remove(foundPerson);
foundPerson = em.find(PersonLazyRDBMSOTO.class, "1");
Assert.assertNull(foundPerson);
}
private EntityManager getNewEM()
{
if (em != null && em.isOpen())
{
em.close();
}
return em = emf.createEntityManager();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
em.close();
emf.close();
dropSchema();
}
private void createSchema() throws SQLException
{
try
{
cli = new RDBMSCli(SCHEMA);
cli.createSchema(SCHEMA);
cli.update("CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))");
cli.update("CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))");
}
catch (Exception e)
{
cli.update("DELETE FROM TESTDB.PERSONNEL");
cli.update("DELETE FROM TESTDB.ADDRESS");
cli.update("DROP TABLE TESTDB.PERSONNEL");
cli.update("DROP TABLE TESTDB.ADDRESS");
cli.update("DROP SCHEMA TESTDB");
cli.update("CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))");
cli.update("CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))");
// nothing
// do
}
}
private void dropSchema()
{
try
{
cli.update("DELETE FROM TESTDB.PERSONNEL");
cli.update("DELETE FROM TESTDB.ADDRESS");
cli.update("DROP TABLE TESTDB.PERSONNEL");
cli.update("DROP TABLE TESTDB.ADDRESS");
cli.update("DROP SCHEMA TESTDB");
cli.closeConnection();
}
catch (Exception e)
{
// Nothing to do
}
}
} | apache-2.0 |
ern/elasticsearch | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/rest/action/compat/RestPutTransformActionDeprecated.java | 2120 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.transform.rest.action.compat;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xpack.core.transform.TransformField;
import org.elasticsearch.xpack.core.transform.TransformMessages;
import org.elasticsearch.xpack.core.transform.action.PutTransformAction;
import org.elasticsearch.xpack.core.transform.action.compat.PutTransformActionDeprecated;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.rest.RestRequest.Method.PUT;
public class RestPutTransformActionDeprecated extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(
Route.builder(PUT, TransformField.REST_BASE_PATH_TRANSFORMS_BY_ID_DEPRECATED)
.deprecated(TransformMessages.REST_DEPRECATED_ENDPOINT, RestApiVersion.V_8).build()
);
}
@Override
public String getName() {
return "data_frame_put_transform_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
String id = restRequest.param(TransformField.ID.getPreferredName());
XContentParser parser = restRequest.contentParser();
boolean deferValidation = restRequest.paramAsBoolean(TransformField.DEFER_VALIDATION.getPreferredName(), false);
PutTransformAction.Request request = PutTransformAction.Request.fromXContent(parser, id, deferValidation);
return channel -> client.execute(PutTransformActionDeprecated.INSTANCE, request, new RestToXContentListener<>(channel));
}
}
| apache-2.0 |
SourceStudyNotes/log4j2 | src/main/java/org/apache/logging/log4j/core/config/builder/impl/DefaultLayoutComponentBuilder.java | 1333 | /*
* 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.logging.log4j.core.config.builder.impl;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
/**
*
*/
class DefaultLayoutComponentBuilder extends DefaultComponentAndConfigurationBuilder<LayoutComponentBuilder>
implements LayoutComponentBuilder {
public DefaultLayoutComponentBuilder(final DefaultConfigurationBuilder<? extends Configuration> builder, final String type) {
super(builder, type);
}
}
| apache-2.0 |
miniway/presto | presto-main/src/main/java/io/prestosql/sql/planner/RelationPlan.java | 3217 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner;
import com.google.common.collect.ImmutableList;
import io.prestosql.sql.analyzer.RelationType;
import io.prestosql.sql.analyzer.Scope;
import io.prestosql.sql.planner.plan.PlanNode;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
/**
* The purpose of this class is to hold the current plan built so far
* for a relation (query, table, values, etc.), and the mapping to
* indicate how the fields (by position) in the relation map to
* the outputs of the plan.
* <p>
* Fields are resolved by {@link TranslationMap} within local scopes hierarchy.
* Indexes of resolved parent scope fields start from "total number of child scope fields".
* For instance if a child scope has n fields, then first parent scope field
* will have index n.
*/
class RelationPlan
{
private final PlanNode root;
private final List<Symbol> fieldMappings; // for each field in the relation, the corresponding symbol from "root"
private final Scope scope;
public RelationPlan(PlanNode root, Scope scope, List<Symbol> fieldMappings)
{
requireNonNull(root, "root is null");
requireNonNull(fieldMappings, "outputSymbols is null");
requireNonNull(scope, "scope is null");
int allFieldCount = getAllFieldCount(scope);
checkArgument(allFieldCount == fieldMappings.size(),
"Number of outputs (%s) doesn't match number of fields in scopes tree (%s)",
fieldMappings.size(),
allFieldCount);
this.root = root;
this.scope = scope;
this.fieldMappings = ImmutableList.copyOf(fieldMappings);
}
public Symbol getSymbol(int fieldIndex)
{
checkArgument(fieldIndex >= 0 && fieldIndex < fieldMappings.size(), "No field->symbol mapping for field %s", fieldIndex);
return fieldMappings.get(fieldIndex);
}
public PlanNode getRoot()
{
return root;
}
public List<Symbol> getFieldMappings()
{
return fieldMappings;
}
public RelationType getDescriptor()
{
return scope.getRelationType();
}
public Scope getScope()
{
return scope;
}
private static int getAllFieldCount(Scope root)
{
int allFieldCount = 0;
Optional<Scope> current = Optional.of(root);
while (current.isPresent()) {
allFieldCount += current.get().getRelationType().getAllFieldCount();
current = current.get().getLocalParent();
}
return allFieldCount;
}
}
| apache-2.0 |
rareddy/olingo-odata4 | lib/server-core/src/main/java/org/apache/olingo/server/core/etag/ETagInformation.java | 2346 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.server.core.etag;
import java.util.Collection;
/**
* Information about the values of an ETag-relevant HTTP header.
*/
public class ETagInformation {
private final boolean all;
private final Collection<String> eTags;
public ETagInformation(final boolean all, final Collection<String> eTags) {
this.all = all;
this.eTags = eTags;
}
/**
* Gets the information whether the values contain "*".
*/
public boolean isAll() {
return all;
}
/**
* Gets the collection of ETag values found.
* It is empty if {@link #isAll()} returns <code>true</code>.
*/
public Collection<String> getETags() {
return eTags;
}
/**
* <p>Checks whether a given ETag value is matched by this ETag information,
* using weak comparison as described in
* <a href="https://www.ietf.org/rfc/rfc7232.txt">RFC 7232</a>, section 2.3.2.</p>
* <p>If the given value is <code>null</code>, or if this ETag information
* does not contain anything, the result is <code>false</code>.</p>
* @param eTag the ETag value to match
* @return a boolean match result
*/
public boolean isMatchedBy(final String eTag) {
if (eTag == null) {
return false;
} else if (all) {
return true;
} else {
for (final String candidate : eTags) {
if ((eTag.startsWith("W/") ? eTag.substring(2) : eTag)
.equals(candidate.startsWith("W/") ? candidate.substring(2) : candidate)) {
return true;
}
}
return false;
}
}
} | apache-2.0 |
opennetworkinglab/onos | apps/faultmanagement/fmmgr/src/test/java/org/onosproject/faultmanagement/impl/AlarmManagerTest.java | 13241 | /*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.faultmanagement.impl;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onlab.junit.TestTools;
import org.onlab.junit.TestUtils;
import org.onlab.util.ItemNotFoundException;
import org.onosproject.common.event.impl.TestEventDispatcher;
import org.onosproject.event.Event;
import org.onosproject.alarm.Alarm;
import org.onosproject.alarm.AlarmEntityId;
import org.onosproject.alarm.AlarmEvent;
import org.onosproject.alarm.AlarmId;
import org.onosproject.alarm.AlarmListener;
import org.onosproject.alarm.AlarmProvider;
import org.onosproject.alarm.AlarmProviderRegistry;
import org.onosproject.alarm.AlarmProviderService;
import org.onosproject.alarm.DefaultAlarm;
import org.onosproject.mastership.MastershipService;
import org.onosproject.mastership.MastershipServiceAdapter;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.NetTestTools;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.store.service.TestStorageService;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.onosproject.alarm.Alarm.SeverityLevel.CLEARED;
import static org.onosproject.alarm.Alarm.SeverityLevel.CRITICAL;
import static org.onosproject.net.NetTestTools.PID;
/**
* Alarm manager test suite.
*/
public class AlarmManagerTest {
private static final DeviceId DEVICE_ID = DeviceId.deviceId("foo:bar");
private static final String UNIQUE_ID_1 = "unique_id_1";
private static final String UNIQUE_ID_2 = "unique_id_2";
private static final AlarmId A_ID = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_1);
private static final AlarmId B_ID = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_2);
private static final DefaultAlarm ALARM_A = new DefaultAlarm.Builder(A_ID,
DEVICE_ID, "aaa", Alarm.SeverityLevel.CRITICAL, 0).build();
private static final DefaultAlarm ALARM_A_CLEARED = new DefaultAlarm.Builder(ALARM_A)
.clear().build();
private static final DefaultAlarm ALARM_A_WITHSRC = new DefaultAlarm.Builder(
ALARM_A).forSource(AlarmEntityId.alarmEntityId("port:foo")).build();
private static final DefaultAlarm ALARM_B = new DefaultAlarm.Builder(B_ID,
DEVICE_ID, "bbb", Alarm.SeverityLevel.CRITICAL, 0).build();
private AlarmManager manager;
private DistributedAlarmStore alarmStore;
private AlarmProviderService providerService;
private TestProvider provider;
protected AlarmProviderRegistry registry;
protected TestListener listener = new TestListener();
private final MastershipService mastershipService = new MockMastershipService();
protected final MockDeviceService deviceService = new MockDeviceService();
private final Device device = new MockDevice(DEVICE_ID);
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws Exception {
alarmStore = new DistributedAlarmStore();
TestUtils.setField(alarmStore, "storageService", new TestStorageService());
alarmStore.activate();
manager = new AlarmManager();
registry = manager;
manager.addListener(listener);
NetTestTools.injectEventDispatcher(manager, new TestEventDispatcher());
manager.deviceService = deviceService;
manager.mastershipService = mastershipService;
manager.store = alarmStore;
manager.activate();
provider = new TestProvider();
providerService = registry.register(provider);
}
@Test
public void deactivate() throws Exception {
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(ALARM_B, ALARM_A));
verifyGettingSetsOfAlarms(manager, 2, 2);
alarmStore.deactivate();
manager.removeListener(listener);
manager.deactivate();
NetTestTools.injectEventDispatcher(manager, null);
assertFalse("Store should not have delegate", alarmStore.hasDelegate());
}
@Test
public void testGettersWhenNoAlarms() {
assertTrue("No alarms should be present", manager.getAlarms().isEmpty());
assertTrue("No active alarms should be present", manager.getActiveAlarms().isEmpty());
assertTrue("The map should be empty per unknown device",
manager.getAlarmCounts(DeviceId.NONE).keySet().isEmpty());
assertTrue("The counts should be empty", manager.getAlarmCounts().keySet().isEmpty());
assertEquals("Incorrect number of alarms for unknown device",
0, manager.getAlarms(DeviceId.NONE).size());
assertEquals("Incorrect number of major alarms for unknown device",
0, manager.getAlarms(Alarm.SeverityLevel.MAJOR).size());
exception.expect(NullPointerException.class);
manager.getAlarm(null);
exception.expect(ItemNotFoundException.class);
manager.getAlarm(AlarmId.alarmId(DEVICE_ID, "unique_3"));
}
@Test
public void testAlarmUpdates() throws InterruptedException {
assertTrue("No alarms should be present", manager.getAlarms().isEmpty());
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of());
assertTrue("No alarms should be present", manager.getAlarms().isEmpty());
Map<Alarm.SeverityLevel, Long> zeroAlarms = new CountsMapBuilder().create();
assertEquals("No alarms count should be present", zeroAlarms, manager.getAlarmCounts());
assertEquals("No alarms count should be present", zeroAlarms, manager.getAlarmCounts(DEVICE_ID));
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(ALARM_B, ALARM_A));
verifyGettingSetsOfAlarms(manager, 2, 2);
validateEvents(AlarmEvent.Type.CREATED, AlarmEvent.Type.CREATED);
Map<Alarm.SeverityLevel, Long> critical2 = new CountsMapBuilder().with(CRITICAL, 2L).create();
assertEquals("A critical should be present", critical2, manager.getAlarmCounts());
assertEquals("A critical should be present", critical2, manager.getAlarmCounts(DEVICE_ID));
Alarm updated = manager.updateBookkeepingFields(ALARM_A.id(), true, false, null);
// providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(ALARM_A));
verifyGettingSetsOfAlarms(manager, 2, 1);
validateEvents(AlarmEvent.Type.UPDATED);
Map<Alarm.SeverityLevel, Long> critical1cleared1 =
new CountsMapBuilder().with(CRITICAL, 1L).with(CLEARED, 1L).create();
assertEquals("A critical should be present and cleared", critical1cleared1,
manager.getAlarmCounts());
assertEquals("A critical should be present and cleared", critical1cleared1,
manager.getAlarmCounts(DEVICE_ID));
// No change map when same alarms sent
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(updated));
verifyGettingSetsOfAlarms(manager, 2, 1);
validateEvents();
assertEquals("Map should not be changed for same alarm", critical1cleared1,
manager.getAlarmCounts());
assertEquals("Map should not be changed for same alarm", critical1cleared1,
manager.getAlarmCounts(DEVICE_ID));
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(updated, ALARM_A_WITHSRC));
verifyGettingSetsOfAlarms(manager, 2, 2);
validateEvents(AlarmEvent.Type.UPDATED);
Map<Alarm.SeverityLevel, Long> critical2cleared1 =
new CountsMapBuilder().with(CRITICAL, 2L).create();
assertEquals("A critical should be present", critical2cleared1, manager.getAlarmCounts());
assertEquals("A critical should be present", critical2cleared1, manager.getAlarmCounts(DEVICE_ID));
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of());
verifyGettingSetsOfAlarms(manager, 2, 2);
validateEvents();
assertEquals(new CountsMapBuilder().with(CRITICAL, 2L).create(),
manager.getAlarmCounts(DEVICE_ID));
assertEquals("The counts should be empty for unknown devices", zeroAlarms,
manager.getAlarmCounts(DeviceId.NONE));
assertEquals("The counts should be empty for unknown devices", zeroAlarms,
manager.getAlarmCounts(DeviceId.deviceId("junk:junk")));
}
@Test
public void testRemoveWhenDeviceRemoved() {
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(ALARM_B, ALARM_A));
verifyGettingSetsOfAlarms(manager, 2, 2);
validateEvents(AlarmEvent.Type.CREATED, AlarmEvent.Type.CREATED);
Map<Alarm.SeverityLevel, Long> critical2 = new CountsMapBuilder().with(CRITICAL, 2L).create();
assertEquals("A critical should be present", critical2, manager.getAlarmCounts());
assertEquals("A critical should be present", critical2, manager.getAlarmCounts(DEVICE_ID));
deviceService.deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device));
Map<Alarm.SeverityLevel, Long> zeroAlarms = new CountsMapBuilder().create();
assertEquals("The counts should be empty for removed device", zeroAlarms,
manager.getAlarmCounts(DEVICE_ID));
}
private void verifyGettingSetsOfAlarms(AlarmManager am, int expectedTotal, int expectedActive) {
assertEquals("Incorrect total alarms", expectedTotal, am.getAlarms().size());
assertEquals("Incorrect active alarms count", expectedActive, am.getActiveAlarms().size());
}
/**
* Method to validate that actual versus expected device key events were
* received correctly.
*
* @param types expected device key events.
*/
private void validateEvents(Enum... types) {
TestTools.assertAfter(100, () -> {
int i = 0;
assertEquals("wrong events received", types.length, listener.events.size());
for (Event event : listener.events) {
assertEquals("incorrect event type", types[i], event.type());
i++;
}
listener.events.clear();
});
}
private static class CountsMapBuilder {
private final Map<Alarm.SeverityLevel, Long> map = new HashMap<>();
public CountsMapBuilder with(Alarm.SeverityLevel sev, Long count) {
map.put(sev, count);
return this;
}
public Map<Alarm.SeverityLevel, Long> create() {
return Collections.unmodifiableMap(map);
}
}
private class MockDeviceService extends DeviceServiceAdapter {
DeviceListener deviceListener = null;
@Override
public void addListener(DeviceListener listener) {
this.deviceListener = listener;
}
@Override
public void removeListener(DeviceListener listener) {
this.deviceListener = null;
}
}
private class TestProvider extends AbstractProvider implements AlarmProvider {
private DeviceId deviceReceived;
private MastershipRole roleReceived;
public TestProvider() {
super(PID);
}
@Override
public void triggerProbe(DeviceId deviceId) {
}
}
private class MockMastershipService extends MastershipServiceAdapter {
int test = 0;
@Override
public boolean isLocalMaster(DeviceId deviceId) {
return true;
}
}
/**
* Test listener class to receive alarm events.
*/
private static class TestListener implements AlarmListener {
protected List<AlarmEvent> events = Lists.newArrayList();
@Override
public void event(AlarmEvent event) {
events.add(event);
}
}
private class MockDevice extends DefaultDevice {
MockDevice(DeviceId id) {
super(null, id, null, null, null, null, null,
null, DefaultAnnotations.EMPTY);
}
}
}
| apache-2.0 |
wildfly/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java | 4421 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Assert;
import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
/**
* Checks to see if "slow consumer advisory messages" are generated when
* small number of messages (2) are published to a topic which has a subscriber
* with a prefetch of one set.
*/
public class TopicSubscriptionSlowConsumerTest extends TestCase {
private static final String TOPIC_NAME = "slow.consumer";
Connection connection;
private Session session;
private ActiveMQTopic destination;
private MessageProducer producer;
private MessageConsumer consumer;
private BrokerService brokerService;
public void setUp() throws Exception {
brokerService = createBroker();
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost");
activeMQConnectionFactory.setWatchTopicAdvisories(true);
connection = activeMQConnectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = new ActiveMQTopic(TOPIC_NAME);
producer = session.createProducer(destination);
connection.start();
}
public void testPrefetchValueOne() throws Exception {
ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=1");
consumer = session.createConsumer(consumerDestination);
//add a consumer to the slow consumer advisory topic.
ActiveMQTopic slowConsumerAdvisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination);
MessageConsumer slowConsumerAdvisory = session.createConsumer(slowConsumerAdvisoryTopic);
//publish 2 messages
Message txtMessage = session.createTextMessage("Sample Text Message");
for (int i = 0; i < 2; i++) {
producer.send(txtMessage);
}
//consume 2 messages
for (int i = 0; i < 2; i++) {
Message receivedMsg = consumer.receive(100);
Assert.assertNotNull("received msg " + i + " should not be null", receivedMsg);
}
//check for "slow consumer" advisory message
Message slowAdvisoryMessage = slowConsumerAdvisory.receive(100);
Assert.assertNull("should not have received a slow consumer advisory message", slowAdvisoryMessage);
}
public void tearDown() throws Exception {
consumer.close();
producer.close();
session.close();
connection.close();
brokerService.stop();
}
//helper method to create a broker with slow consumer advisory turned on
private BrokerService createBroker() throws Exception {
BrokerService broker = new BrokerService();
broker.setBrokerName("localhost");
broker.setUseJmx(true);
broker.setDeleteAllMessagesOnStartup(true);
broker.addConnector("vm://localhost");
PolicyMap policyMap = new PolicyMap();
PolicyEntry defaultEntry = new PolicyEntry();
defaultEntry.setAdvisoryForSlowConsumers(true);
policyMap.setDefaultEntry(defaultEntry);
broker.setDestinationPolicy(policyMap);
broker.start();
broker.waitUntilStarted();
return broker;
}
}
| apache-2.0 |
plutext/sling | contrib/extensions/distribution/core/src/main/java/org/apache/sling/distribution/transport/impl/MultipleEndpointDistributionTransport.java | 5460 | /*
* 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.distribution.transport.impl;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.distribution.DistributionRequest;
import org.apache.sling.distribution.component.impl.SettingsUtils;
import org.apache.sling.distribution.packaging.DistributionPackage;
import org.apache.sling.distribution.packaging.DistributionPackageInfo;
import org.apache.sling.distribution.transport.DistributionTransportSecretProvider;
import org.apache.sling.distribution.transport.core.DistributionTransport;
import org.apache.sling.distribution.transport.core.DistributionTransportException;
import org.apache.sling.distribution.transport.DistributionTransportSecret;
/**
* {@link org.apache.sling.distribution.transport.core.DistributionTransport} supporting delivery / retrieval from multiple
* endpoints.
*/
public class MultipleEndpointDistributionTransport implements DistributionTransport {
private final Map<String, DistributionTransport> transportHelpers;
private final TransportEndpointStrategyType endpointStrategyType;
public MultipleEndpointDistributionTransport(Map<String, DistributionTransport> transportHelpers,
TransportEndpointStrategyType endpointStrategyType) {
this.transportHelpers = new TreeMap<String, DistributionTransport>();
this.transportHelpers.putAll(transportHelpers);
this.endpointStrategyType = endpointStrategyType;
}
public MultipleEndpointDistributionTransport(List<DistributionTransport> transportHelpers,
TransportEndpointStrategyType endpointStrategyType) {
this(SettingsUtils.toMap(transportHelpers, "endpoint"), endpointStrategyType);
}
public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage) throws DistributionTransportException {
if (endpointStrategyType.equals(TransportEndpointStrategyType.One)) {
DistributionPackageInfo info = distributionPackage.getInfo();
String queueName = info == null ? null : info.getQueue();
DistributionTransport distributionTransport = getDefaultTransport();
if (queueName != null) {
distributionTransport = transportHelpers.get(queueName);
}
if (distributionTransport != null) {
distributionTransport.deliverPackage(resourceResolver, distributionPackage);
}
} else if (endpointStrategyType.equals(TransportEndpointStrategyType.All)) {
for (DistributionTransport distributionTransport: transportHelpers.values()) {
distributionTransport.deliverPackage(resourceResolver, distributionPackage);
}
}
}
@Nonnull
public List<DistributionPackage> retrievePackages(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionRequest distributionRequest) throws DistributionTransportException {
List<DistributionPackage> result = new ArrayList<DistributionPackage>();
if (endpointStrategyType.equals(TransportEndpointStrategyType.One)) {
DistributionTransport distributionTransport = getDefaultTransport();
if (distributionTransport != null) {
Iterable<DistributionPackage> retrievedPackages = distributionTransport.retrievePackages(resourceResolver, distributionRequest);
for (DistributionPackage retrievedPackage : retrievedPackages) {
result.add(retrievedPackage);
}
}
} else if (endpointStrategyType.equals(TransportEndpointStrategyType.All)) {
for (DistributionTransport distributionTransport: transportHelpers.values()) {
Iterable<DistributionPackage> retrievedPackages = distributionTransport.retrievePackages(resourceResolver, distributionRequest);
for (DistributionPackage retrievedPackage : retrievedPackages) {
result.add(retrievedPackage);
}
}
}
return result;
}
DistributionTransport getDefaultTransport() {
java.util.Collection<DistributionTransport> var = transportHelpers.values();
DistributionTransport[] handlers = var.toArray(new DistributionTransport[var.size()]);
if (handlers != null && handlers.length > 0) {
return handlers[0];
}
return null;
}
}
| apache-2.0 |
shuyouliu/zycloud | edge-service/src/main/java/demo/EdgeApplication.java | 1160 | package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableResourceServer
@EnableHystrix
public class EdgeApplication {
public static void main(String[] args) {
SpringApplication.run(EdgeApplication.class, args);
}
@Configuration
public static class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
}
| apache-2.0 |
emag/wildfly-swarm | core/container/src/main/java/org/wildfly/swarm/container/internal/ServerBootstrap.java | 1778 | /**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.swarm.container.internal;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.wildfly.swarm.internal.OutboundSocketBindingRequest;
import org.wildfly.swarm.internal.SocketBindingRequest;
import org.wildfly.swarm.spi.api.Fraction;
import org.wildfly.swarm.spi.api.config.ConfigView;
/**
* @author Bob McWhirter
* @author Ken Finnigan
*/
public interface ServerBootstrap {
String WELD_INSTANCE_ID = "internal";
ServerBootstrap withArguments(String[] args);
ServerBootstrap withXmlConfig(Optional<URL> url);
ServerBootstrap withBootstrapDebug(boolean debugBootstrap);
ServerBootstrap withExplicitlyInstalledFractions(Collection<Fraction> explicitlyInstalledFractions);
ServerBootstrap withUserComponents(Set<Class<?>> userComponentClasses);
ServerBootstrap withSocketBindings(List<SocketBindingRequest> bindings);
ServerBootstrap withOutboundSocketBindings(List<OutboundSocketBindingRequest> bindings);
ServerBootstrap withConfigView(ConfigView configView);
Server bootstrap() throws Exception;
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201405/AuthenticationErrorReason.java | 5952 | /**
* AuthenticationErrorReason.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201405;
public class AuthenticationErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected AuthenticationErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _AMBIGUOUS_SOAP_REQUEST_HEADER = "AMBIGUOUS_SOAP_REQUEST_HEADER";
public static final java.lang.String _INVALID_EMAIL = "INVALID_EMAIL";
public static final java.lang.String _AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED";
public static final java.lang.String _INVALID_OAUTH_SIGNATURE = "INVALID_OAUTH_SIGNATURE";
public static final java.lang.String _INVALID_SERVICE = "INVALID_SERVICE";
public static final java.lang.String _MISSING_SOAP_REQUEST_HEADER = "MISSING_SOAP_REQUEST_HEADER";
public static final java.lang.String _MISSING_AUTHENTICATION_HTTP_HEADER = "MISSING_AUTHENTICATION_HTTP_HEADER";
public static final java.lang.String _MISSING_AUTHENTICATION = "MISSING_AUTHENTICATION";
public static final java.lang.String _NOT_WHITELISTED_FOR_API_ACCESS = "NOT_WHITELISTED_FOR_API_ACCESS";
public static final java.lang.String _NO_NETWORKS_TO_ACCESS = "NO_NETWORKS_TO_ACCESS";
public static final java.lang.String _NETWORK_NOT_FOUND = "NETWORK_NOT_FOUND";
public static final java.lang.String _NETWORK_CODE_REQUIRED = "NETWORK_CODE_REQUIRED";
public static final java.lang.String _CONNECTION_ERROR = "CONNECTION_ERROR";
public static final java.lang.String _GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORK = "GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORK";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final AuthenticationErrorReason AMBIGUOUS_SOAP_REQUEST_HEADER = new AuthenticationErrorReason(_AMBIGUOUS_SOAP_REQUEST_HEADER);
public static final AuthenticationErrorReason INVALID_EMAIL = new AuthenticationErrorReason(_INVALID_EMAIL);
public static final AuthenticationErrorReason AUTHENTICATION_FAILED = new AuthenticationErrorReason(_AUTHENTICATION_FAILED);
public static final AuthenticationErrorReason INVALID_OAUTH_SIGNATURE = new AuthenticationErrorReason(_INVALID_OAUTH_SIGNATURE);
public static final AuthenticationErrorReason INVALID_SERVICE = new AuthenticationErrorReason(_INVALID_SERVICE);
public static final AuthenticationErrorReason MISSING_SOAP_REQUEST_HEADER = new AuthenticationErrorReason(_MISSING_SOAP_REQUEST_HEADER);
public static final AuthenticationErrorReason MISSING_AUTHENTICATION_HTTP_HEADER = new AuthenticationErrorReason(_MISSING_AUTHENTICATION_HTTP_HEADER);
public static final AuthenticationErrorReason MISSING_AUTHENTICATION = new AuthenticationErrorReason(_MISSING_AUTHENTICATION);
public static final AuthenticationErrorReason NOT_WHITELISTED_FOR_API_ACCESS = new AuthenticationErrorReason(_NOT_WHITELISTED_FOR_API_ACCESS);
public static final AuthenticationErrorReason NO_NETWORKS_TO_ACCESS = new AuthenticationErrorReason(_NO_NETWORKS_TO_ACCESS);
public static final AuthenticationErrorReason NETWORK_NOT_FOUND = new AuthenticationErrorReason(_NETWORK_NOT_FOUND);
public static final AuthenticationErrorReason NETWORK_CODE_REQUIRED = new AuthenticationErrorReason(_NETWORK_CODE_REQUIRED);
public static final AuthenticationErrorReason CONNECTION_ERROR = new AuthenticationErrorReason(_CONNECTION_ERROR);
public static final AuthenticationErrorReason GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORK = new AuthenticationErrorReason(_GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORK);
public static final AuthenticationErrorReason UNKNOWN = new AuthenticationErrorReason(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static AuthenticationErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
AuthenticationErrorReason enumeration = (AuthenticationErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static AuthenticationErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AuthenticationErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "AuthenticationError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
paplorinc/intellij-community | plugins/InspectionGadgets/src/com/siyeh/ig/visibility/MethodOverloadsParentMethodInspection.java | 5901 | /*
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.visibility;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.RenameFix;
import com.siyeh.ig.psiutils.MethodUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class MethodOverloadsParentMethodInspection extends BaseInspection {
@SuppressWarnings("PublicField")
public boolean reportIncompatibleParameters = false;
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
return new RenameFix();
}
@Override
@NotNull
public String getID() {
return "MethodOverloadsMethodOfSuperclass";
}
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("method.overloads.display.name");
}
@Override
protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
return true;
}
@Override
@NotNull
public String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message("method.overloads.problem.descriptor");
}
@Nullable
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("method.overloads.report.incompatible.option"),
this, "reportIncompatibleParameters");
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new MethodOverloadsParentMethodVisitor();
}
private class MethodOverloadsParentMethodVisitor extends BaseInspectionVisitor {
@Override
public void visitMethod(@NotNull PsiMethod method) {
if (method.hasModifierProperty(PsiModifier.PRIVATE) || method.hasModifierProperty(PsiModifier.STATIC)) {
return;
}
if (method.getNameIdentifier() == null || method.isConstructor()) {
return;
}
final PsiClass aClass = method.getContainingClass();
if (aClass == null) {
return;
}
if (MethodUtils.hasSuper(method)) {
return;
}
final Set<PsiClass> visitedClasses = new HashSet<>();
processSupers(method, aClass, aClass, visitedClasses);
}
private boolean processSupers(final PsiMethod method,
final PsiClass psiClass,
final PsiClass initialClass,
final Set<? super PsiClass> visitedClasses) {
if (!visitedClasses.add(psiClass)) {
return false;
}
if (initialClass != psiClass && methodOverloads(method, psiClass)) {
registerMethodError(method);
return true;
}
else {
if (PsiUtil.isLanguageLevel8OrHigher(method)) {
for (PsiClass superClass : psiClass.getSupers()) {
if (processSupers(method, superClass, initialClass, visitedClasses)) {
return true;
}
}
} else {
final PsiClass superClass = psiClass.getSuperClass();
if (superClass != null) {
return processSupers(method, superClass, initialClass, visitedClasses);
}
}
}
return false;
}
private boolean methodOverloads(PsiMethod method, PsiClass ancestorClass) {
final String methodName = method.getName();
final PsiParameterList parameterList = method.getParameterList();
final PsiParameter[] parameters = parameterList.getParameters();
final PsiMethod[] methods = ancestorClass.findMethodsByName(methodName, false);
for (final PsiMethod testMethod : methods) {
if (!testMethod.hasModifierProperty(PsiModifier.PRIVATE) &&
!testMethod.hasModifierProperty(PsiModifier.STATIC) &&
!testMethod.hasModifierProperty(PsiModifier.ABSTRACT) &&
!isOverriddenInClass(testMethod, method.getContainingClass())) {
final PsiParameterList testParameterList = testMethod.getParameterList();
final PsiParameter[] testParameters = testParameterList.getParameters();
if (testParameters.length == parameters.length) {
if (reportIncompatibleParameters || parametersAreCompatible(parameters, testParameters)) {
return true;
}
}
}
}
return false;
}
private boolean isOverriddenInClass(PsiMethod method, PsiClass aClass) {
return aClass.findMethodsBySignature(method, false).length > 0;
}
private boolean parametersAreCompatible(PsiParameter[] parameters, PsiParameter[] testParameters) {
for (int i = 0; i < parameters.length; i++) {
final PsiParameter parameter = parameters[i];
final PsiType parameterType = parameter.getType();
final PsiParameter testParameter = testParameters[i];
final PsiType testParameterType = testParameter.getType();
if (!parameterType.isAssignableFrom(testParameterType) && !testParameterType.isAssignableFrom(parameterType)) {
return false;
}
}
return true;
}
}
}
| apache-2.0 |
ern/elasticsearch | server/src/main/java/org/elasticsearch/search/internal/FilterStoredFieldVisitor.java | 1774 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search.internal;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.StoredFieldVisitor;
import java.io.IOException;
public class FilterStoredFieldVisitor extends StoredFieldVisitor {
private final StoredFieldVisitor visitor;
public FilterStoredFieldVisitor(StoredFieldVisitor visitor) {
this.visitor = visitor;
}
@Override
public void binaryField(FieldInfo fieldInfo, byte[] value) throws IOException {
visitor.binaryField(fieldInfo, value);
}
@Override
public void stringField(FieldInfo fieldInfo, byte[] value) throws IOException {
visitor.stringField(fieldInfo, value);
}
@Override
public void intField(FieldInfo fieldInfo, int value) throws IOException {
visitor.intField(fieldInfo, value);
}
@Override
public void longField(FieldInfo fieldInfo, long value) throws IOException {
visitor.longField(fieldInfo, value);
}
@Override
public void floatField(FieldInfo fieldInfo, float value) throws IOException {
visitor.floatField(fieldInfo, value);
}
@Override
public void doubleField(FieldInfo fieldInfo, double value) throws IOException {
visitor.doubleField(fieldInfo, value);
}
@Override
public Status needsField(FieldInfo fieldInfo) throws IOException {
return visitor.needsField(fieldInfo);
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/SimpleDataContext.java | 3127 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.actionSystem.impl;
import com.intellij.ide.DataManager;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.ide.impl.dataRules.GetDataRule;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.IdeFocusManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
public class SimpleDataContext implements DataContext {
private final Map<String, Object> myDataId2Data;
private final DataContext myParent;
private final boolean myWithRules;
private final DataProvider myDataProvider;
private SimpleDataContext(String dataId, Object data, DataContext parent) {
this(new HashMap<>(1), parent, false);
myDataId2Data.put(dataId, data);
}
private SimpleDataContext(@NotNull Map<String, Object> dataId2data, DataContext parent, boolean withRules) {
myDataId2Data = dataId2data;
myParent = parent;
myWithRules = withRules;
myDataProvider = withRules ? dataId -> getDataFromSelfOrParent(dataId) : __ -> null;
}
@Override
public Object getData(@NotNull String dataId) {
Object result = getDataFromSelfOrParent(dataId);
if (result == null && PlatformDataKeys.CONTEXT_COMPONENT.getName().equals(dataId)) {
result = IdeFocusManager.getGlobalInstance().getFocusOwner();
}
if (result == null && myWithRules) {
GetDataRule rule = ((DataManagerImpl)DataManager.getInstance()).getDataRule(dataId);
if (rule != null) {
return rule.getData(myDataProvider);
}
}
return result;
}
@Nullable
private Object getDataFromSelfOrParent(String dataId) {
return myDataId2Data.containsKey(dataId) ? myDataId2Data.get(dataId) :
myParent == null ? null : myParent.getData(dataId);
}
@NotNull
public static DataContext getSimpleContext(String dataId, Object data, DataContext parent) {
return new SimpleDataContext(dataId, data, parent);
}
@NotNull
public static DataContext getSimpleContext(@NotNull Map<String,Object> dataId2data, DataContext parent) {
return getSimpleContext(dataId2data, parent, false);
}
/**
* Creates a simple data context which can apply data rules.
*/
@NotNull
public static DataContext getSimpleContext(@NotNull Map<String, Object> dataId2data, DataContext parent, boolean withRules) {
return new SimpleDataContext(dataId2data, parent, withRules);
}
@NotNull
public static DataContext getSimpleContext(String dataId, Object data) {
return getSimpleContext(dataId, data, null);
}
@NotNull
public static DataContext getProjectContext(Project project) {
return getSimpleContext(CommonDataKeys.PROJECT.getName(), project);
}
}
| apache-2.0 |
kakada/dhis2 | dhis-web/dhis-web-maintenance/dhis-web-maintenance-user/src/main/java/org/hisp/dhis/user/action/usergroup/AddUserGroupAction.java | 4647 | package org.hisp.dhis.user.action.usergroup;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.attribute.AttributeService;
import org.hisp.dhis.system.util.AttributeUtils;
import org.hisp.dhis.user.UserGroup;
import org.hisp.dhis.user.UserGroupService;
import org.hisp.dhis.user.UserService;
import com.opensymphony.xwork2.Action;
public class AddUserGroupAction
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private UserService userService;
public void setUserService( UserService userService )
{
this.userService = userService;
}
private UserGroupService userGroupService;
public void setUserGroupService( UserGroupService userGroupService )
{
this.userGroupService = userGroupService;
}
private AttributeService attributeService;
public void setAttributeService( AttributeService attributeService )
{
this.attributeService = attributeService;
}
// -------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------
private Set<String> usersSelected = new HashSet<>();
public void setUsersSelected( Set<String> usersSelected )
{
this.usersSelected = usersSelected;
}
private String name;
public void setName( String name )
{
this.name = name;
}
private List<String> jsonAttributeValues;
public void setJsonAttributeValues( List<String> jsonAttributeValues )
{
this.jsonAttributeValues = jsonAttributeValues;
}
private Set<String> userGroupsSelected = new HashSet<>();
public void setUserGroupsSelected( Set<String> userGroupsSelected )
{
this.userGroupsSelected = userGroupsSelected;
}
// -------------------------------------------------------------------------
// Action Implementation
// -------------------------------------------------------------------------
@Override
public String execute()
throws Exception
{
UserGroup userGroup = new UserGroup( StringUtils.trimToNull( name ) );
for ( String uid : usersSelected )
{
userGroup.addUser( userService.getUser( uid ) );
}
if ( jsonAttributeValues != null )
{
AttributeUtils.updateAttributeValuesFromJson( userGroup.getAttributeValues(), jsonAttributeValues,
attributeService );
}
for ( String uid : userGroupsSelected )
{
userGroup.addManagedGroup( userGroupService.getUserGroup( uid ) );
}
userGroupService.addUserGroup( userGroup );
return SUCCESS;
}
}
| bsd-3-clause |
leighpauls/k2cro4 | content/public/android/java/src/org/chromium/content/browser/ResourceExtractor.java | 11706 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import org.chromium.base.PathUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Locale;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
/**
* Handles extracting the necessary resources bundled in an APK and moving them to a location on
* the file system accessible from the native code.
*/
public class ResourceExtractor {
private static final String LOGTAG = "ResourceExtractor";
private static final String LAST_LANGUAGE = "Last language";
private static final String PAK_FILENAMES = "Pak filenames";
private static String[] sMandatoryPaks = null;
private class ExtractTask extends AsyncTask<Void, Void, Void> {
private static final int BUFFER_SIZE = 16 * 1024;
public ExtractTask() {
}
@Override
protected Void doInBackground(Void... unused) {
if (sMandatoryPaks == null) {
assert false : "No pak files specified. Call setMandatoryPaksToExtract before "
+ "beginning the resource extractions";
return null;
}
if (!mOutputDir.exists() && !mOutputDir.mkdirs()) {
Log.e(LOGTAG, "Unable to create pak resources directory!");
return null;
}
String timestampFile = checkPakTimestamp();
if (timestampFile != null) {
deleteFiles(mContext);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
HashSet<String> filenames = (HashSet<String>) prefs.getStringSet(
PAK_FILENAMES, new HashSet<String>());
String currentLanguage = Locale.getDefault().getLanguage();
if (prefs.getString(LAST_LANGUAGE, "").equals(currentLanguage)
&& filenames.size() >= sMandatoryPaks.length) {
boolean filesPresent = true;
for (String file : filenames) {
if (!new File(mOutputDir, file).exists()) {
filesPresent = false;
break;
}
}
if (filesPresent) return null;
} else {
prefs.edit().putString(LAST_LANGUAGE, currentLanguage).apply();
}
StringBuilder p = new StringBuilder();
for (String mandatoryPak : sMandatoryPaks) {
p.append("\\Q" + mandatoryPak + "\\E|");
}
// As well as the minimum required set of .paks above, we'll also add all .paks that
// we have for the users currently selected language.
// Android uses non-standard language codes for Indonesian, Hebrew, and Yiddish:
// http://developer.android.com/reference/java/util/Locale.html. Correct these codes
// so that we unpack the correct .pak file (see crbug.com/136933).
if (currentLanguage.equals("in")) {
currentLanguage = "id";
} else if (currentLanguage.equals("iw")) {
currentLanguage = "he";
} else if (currentLanguage.equals("ji")) {
currentLanguage = "yi";
}
p.append(currentLanguage);
p.append("(-\\w+)?\\.pak");
Pattern paksToInstall = Pattern.compile(p.toString());
AssetManager manager = mContext.getResources().getAssets();
try {
// Loop through every asset file that we have in the APK, and look for the
// ones that we need to extract by trying to match the Patterns that we
// created above.
byte[] buffer = null;
String[] files = manager.list("");
for (String file : files) {
if (!paksToInstall.matcher(file).matches()) {
continue;
}
File output = new File(mOutputDir, file);
if (output.exists()) {
continue;
}
InputStream is = null;
OutputStream os = null;
try {
is = manager.open(file);
os = new FileOutputStream(output);
Log.i(LOGTAG, "Extracting resource " + file);
if (buffer == null) {
buffer = new byte[BUFFER_SIZE];
}
int count = 0;
while ((count = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
os.write(buffer, 0, count);
}
os.flush();
// Ensure something reasonable was written.
if (output.length() == 0) {
throw new IOException(file + " extracted with 0 length!");
}
filenames.add(file);
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (os != null) {
os.close();
}
}
}
}
} catch (IOException e) {
// TODO(benm): See crbug/152413.
// Try to recover here, can we try again after deleting files instead of
// returning null? It might be useful to gather UMA here too to track if
// this happens with regularity.
Log.w(LOGTAG, "Exception unpacking required pak resources: " + e.getMessage());
deleteFiles(mContext);
return null;
}
// Finished, write out a timestamp file if we need to.
if (timestampFile != null) {
try {
new File(mOutputDir, timestampFile).createNewFile();
} catch (IOException e) {
// Worst case we don't write a timestamp, so we'll re-extract the resource
// paks next start up.
Log.w(LOGTAG, "Failed to write resource pak timestamp!");
}
}
// TODO(yusufo): Figure out why remove is required here.
prefs.edit().remove(PAK_FILENAMES).apply();
prefs.edit().putStringSet(PAK_FILENAMES, filenames).apply();
return null;
}
// Looks for a timestamp file on disk that indicates the version of the APK that
// the resource paks were extracted from. Returns null if a timestamp was found
// and it indicates that the resources match the current APK. Otherwise returns
// a String that represents the filename of a timestamp to create.
// Note that we do this to avoid adding a BroadcastReceiver on
// android.content.Intent#ACTION_PACKAGE_CHANGED as that causes process churn
// on (re)installation of *all* APK files.
private String checkPakTimestamp() {
final String TIMESTAMP_PREFIX = "pak_timestamp-";
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = null;
try {
pi = pm.getPackageInfo(mContext.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
return TIMESTAMP_PREFIX;
}
if (pi == null) {
return TIMESTAMP_PREFIX;
}
String expectedTimestamp = TIMESTAMP_PREFIX + pi.versionCode + "-" + pi.lastUpdateTime;
String[] timestamps = mOutputDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(TIMESTAMP_PREFIX);
}
});
if (timestamps.length != 1) {
// If there's no timestamp, nuke to be safe as we can't tell the age of the files.
// If there's multiple timestamps, something's gone wrong so nuke.
return expectedTimestamp;
}
if (!expectedTimestamp.equals(timestamps[0])) {
return expectedTimestamp;
}
// timestamp file is already up-to date.
return null;
}
}
private Context mContext;
private ExtractTask mExtractTask;
private File mOutputDir;
private static ResourceExtractor sInstance;
public static ResourceExtractor get(Context context) {
if (sInstance == null) {
sInstance = new ResourceExtractor(context);
}
return sInstance;
}
/**
* Specifies the .pak files that should be extracted from the APK's asset resources directory
* and moved to {@link #getOutputDirFromContext(Context)}.
* @param mandatoryPaks The list of pak files to be loaded.
*/
public static void setMandatoryPaksToExtract(String... mandatoryPaks) {
assert (sInstance == null || sInstance.mExtractTask == null)
: "Must be called before startExtractingResources is called";
sMandatoryPaks = mandatoryPaks;
}
private ResourceExtractor(Context context) {
mContext = context;
mOutputDir = getOutputDirFromContext(mContext);
}
public void waitForCompletion() {
assert mExtractTask != null;
try {
mExtractTask.get();
}
catch (CancellationException e) {
// Don't leave the files in an inconsistent state.
deleteFiles(mContext);
}
catch (ExecutionException e2) {
deleteFiles(mContext);
}
catch (InterruptedException e3) {
deleteFiles(mContext);
}
}
// This will extract the application pak resources in an
// AsyncTask. Call waitForCompletion() at the point resources
// are needed to block until the task completes.
public void startExtractingResources() {
if (mExtractTask != null) {
return;
}
mExtractTask = new ExtractTask();
mExtractTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static File getOutputDirFromContext(Context context) {
return new File(PathUtils.getDataDirectory(context.getApplicationContext()), "paks");
}
public static void deleteFiles(Context context) {
File dir = getOutputDirFromContext(context);
if (dir.exists()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.delete()) {
Log.w(LOGTAG, "Unable to remove existing resource " + file.getName());
}
}
}
}
}
| bsd-3-clause |
strahanjen/strahanjen.github.io | elasticsearch-master/core/src/main/java/org/elasticsearch/index/mapper/DocumentMapperParser.java | 8406 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper;
import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.indices.mapper.MapperRegistry;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Supplier;
import static java.util.Collections.unmodifiableMap;
public class DocumentMapperParser {
final MapperService mapperService;
final AnalysisService analysisService;
private final SimilarityService similarityService;
private final Supplier<QueryShardContext> queryShardContextSupplier;
private final RootObjectMapper.TypeParser rootObjectTypeParser = new RootObjectMapper.TypeParser();
private final Version indexVersionCreated;
private final ParseFieldMatcher parseFieldMatcher;
private final Map<String, Mapper.TypeParser> typeParsers;
private final Map<String, MetadataFieldMapper.TypeParser> rootTypeParsers;
public DocumentMapperParser(IndexSettings indexSettings, MapperService mapperService, AnalysisService analysisService,
SimilarityService similarityService, MapperRegistry mapperRegistry,
Supplier<QueryShardContext> queryShardContextSupplier) {
this.parseFieldMatcher = new ParseFieldMatcher(indexSettings.getSettings());
this.mapperService = mapperService;
this.analysisService = analysisService;
this.similarityService = similarityService;
this.queryShardContextSupplier = queryShardContextSupplier;
this.typeParsers = mapperRegistry.getMapperParsers();
this.rootTypeParsers = mapperRegistry.getMetadataMapperParsers();
indexVersionCreated = indexSettings.getIndexVersionCreated();
}
public Mapper.TypeParser.ParserContext parserContext(String type) {
return new Mapper.TypeParser.ParserContext(type, analysisService, similarityService::getSimilarity, mapperService, typeParsers::get, indexVersionCreated, parseFieldMatcher, queryShardContextSupplier.get());
}
public DocumentMapper parse(@Nullable String type, CompressedXContent source) throws MapperParsingException {
return parse(type, source, null);
}
public DocumentMapper parse(@Nullable String type, CompressedXContent source, String defaultSource) throws MapperParsingException {
Map<String, Object> mapping = null;
if (source != null) {
Map<String, Object> root = XContentHelper.convertToMap(source.compressedReference(), true).v2();
Tuple<String, Map<String, Object>> t = extractMapping(type, root);
type = t.v1();
mapping = t.v2();
}
if (mapping == null) {
mapping = new HashMap<>();
}
return parse(type, mapping, defaultSource);
}
@SuppressWarnings({"unchecked"})
private DocumentMapper parse(String type, Map<String, Object> mapping, String defaultSource) throws MapperParsingException {
if (type == null) {
throw new MapperParsingException("Failed to derive type");
}
if (defaultSource != null) {
Tuple<String, Map<String, Object>> t = extractMapping(MapperService.DEFAULT_MAPPING, defaultSource);
if (t.v2() != null) {
XContentHelper.mergeDefaults(mapping, t.v2());
}
}
Mapper.TypeParser.ParserContext parserContext = parserContext(type);
// parse RootObjectMapper
DocumentMapper.Builder docBuilder = new DocumentMapper.Builder((RootObjectMapper.Builder) rootObjectTypeParser.parse(type, mapping, parserContext), mapperService);
Iterator<Map.Entry<String, Object>> iterator = mapping.entrySet().iterator();
// parse DocumentMapper
while(iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String fieldName = entry.getKey();
Object fieldNode = entry.getValue();
MetadataFieldMapper.TypeParser typeParser = rootTypeParsers.get(fieldName);
if (typeParser != null) {
iterator.remove();
Map<String, Object> fieldNodeMap = (Map<String, Object>) fieldNode;
docBuilder.put(typeParser.parse(fieldName, fieldNodeMap, parserContext));
fieldNodeMap.remove("type");
checkNoRemainingFields(fieldName, fieldNodeMap, parserContext.indexVersionCreated());
}
}
Map<String, Object> meta = (Map<String, Object>) mapping.remove("_meta");
if (meta != null) {
// It may not be required to copy meta here to maintain immutability
// but the cost is pretty low here.
docBuilder.meta(unmodifiableMap(new HashMap<>(meta)));
}
checkNoRemainingFields(mapping, parserContext.indexVersionCreated(), "Root mapping definition has unsupported parameters: ");
return docBuilder.build(mapperService);
}
public static void checkNoRemainingFields(String fieldName, Map<?, ?> fieldNodeMap, Version indexVersionCreated) {
checkNoRemainingFields(fieldNodeMap, indexVersionCreated, "Mapping definition for [" + fieldName + "] has unsupported parameters: ");
}
public static void checkNoRemainingFields(Map<?, ?> fieldNodeMap, Version indexVersionCreated, String message) {
if (!fieldNodeMap.isEmpty()) {
throw new MapperParsingException(message + getRemainingFields(fieldNodeMap));
}
}
private static String getRemainingFields(Map<?, ?> map) {
StringBuilder remainingFields = new StringBuilder();
for (Object key : map.keySet()) {
remainingFields.append(" [").append(key).append(" : ").append(map.get(key)).append("]");
}
return remainingFields.toString();
}
private Tuple<String, Map<String, Object>> extractMapping(String type, String source) throws MapperParsingException {
Map<String, Object> root;
try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) {
root = parser.mapOrdered();
} catch (Exception e) {
throw new MapperParsingException("failed to parse mapping definition", e);
}
return extractMapping(type, root);
}
@SuppressWarnings({"unchecked"})
private Tuple<String, Map<String, Object>> extractMapping(String type, Map<String, Object> root) throws MapperParsingException {
if (root.size() == 0) {
// if we don't have any keys throw an exception
throw new MapperParsingException("malformed mapping no root object found");
}
String rootName = root.keySet().iterator().next();
Tuple<String, Map<String, Object>> mapping;
if (type == null || type.equals(rootName)) {
mapping = new Tuple<>(rootName, (Map<String, Object>) root.get(rootName));
} else {
mapping = new Tuple<>(type, root);
}
return mapping;
}
}
| bsd-3-clause |
stachon/XChange | xchange-bitfinex/src/test/java/org/knowm/xchange/bitfinex/v2/dto/marketdata/BitfinexTickerJSONTest.java | 3373 | package org.knowm.xchange.bitfinex.v2.dto.marketdata;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import org.knowm.xchange.bitfinex.service.BitfinexAdapters;
public class BitfinexTickerJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is =
BitfinexTickerJSONTest.class.getResourceAsStream(
"/org/knowm/xchange/bitfinex/v2/dto/marketdata/example-ticker-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
CollectionType constructCollectionType =
mapper.getTypeFactory().constructCollectionType(List.class, ArrayNode.class);
List<ArrayNode> tickers0 = mapper.readValue(is, constructCollectionType);
BitfinexTicker[] tickers = BitfinexAdapters.adoptBitfinexTickers(tickers0);
// Verify that the example data was unmarshalled correctly
// funding currency:
BitfinexTickerFundingCurrency bitfinexTicker = (BitfinexTickerFundingCurrency) tickers[0];
assertThat(bitfinexTicker.getSymbol()).isEqualTo("fLEO");
assertThat(bitfinexTicker.getFrr()).isEqualTo("1.0958904109589042e-08");
assertThat(bitfinexTicker.getBid()).isEqualTo("0");
assertThat(bitfinexTicker.getBidPeriod()).isEqualTo("0");
assertThat(bitfinexTicker.getBidSize()).isEqualTo("0");
assertThat(bitfinexTicker.getAsk()).isEqualByComparingTo("1e-08");
assertThat(bitfinexTicker.getAskPeriod()).isEqualTo("2");
assertThat(bitfinexTicker.getAskSize()).isEqualTo("2663861.8810786298");
assertThat(bitfinexTicker.getDailyChange()).isEqualTo("0");
assertThat(bitfinexTicker.getDailyChangePerc()).isEqualTo("0");
assertThat(bitfinexTicker.getLastPrice()).isEqualByComparingTo("1e-08");
assertThat(bitfinexTicker.getVolume()).isEqualTo("664.1085");
assertThat(bitfinexTicker.getHigh()).isEqualByComparingTo("1e-08");
assertThat(bitfinexTicker.getLow()).isEqualByComparingTo("1e-08");
assertThat(bitfinexTicker.getPlaceHolder0()).isNull();
assertThat(bitfinexTicker.getPlaceHolder1()).isNull();
assertThat(bitfinexTicker.getFrrAmountAvailable()).isEqualTo("2594257.74114297");
// traiding pair:
BitfinexTickerTraidingPair bitfinexTicker2 = (BitfinexTickerTraidingPair) tickers[1];
assertThat(bitfinexTicker2.getSymbol()).isEqualTo("tBTCUSD");
assertThat(bitfinexTicker2.getBid()).isEqualTo("7381.6");
assertThat(bitfinexTicker2.getBidSize()).isEqualTo("38.644979070000005");
assertThat(bitfinexTicker2.getAsk()).isEqualTo("7381.7");
assertThat(bitfinexTicker2.getAskSize()).isEqualByComparingTo("32.145906579999995");
assertThat(bitfinexTicker2.getDailyChange()).isEqualTo("126.6");
assertThat(bitfinexTicker2.getDailyChangePerc()).isEqualTo("0.0175");
assertThat(bitfinexTicker2.getLastPrice()).isEqualByComparingTo("7381.2");
assertThat(bitfinexTicker2.getVolume()).isEqualTo("1982.88275223");
assertThat(bitfinexTicker2.getHigh()).isEqualByComparingTo("7390");
assertThat(bitfinexTicker2.getLow()).isEqualByComparingTo("7228.1");
}
}
| mit |
adolphenom/MARS_Assembler | mars/mips/instructions/syscalls/SyscallPrintString.java | 2621 | package mars.mips.instructions.syscalls;
import mars.util.*;
import mars.mips.hardware.*;
import mars.*;
/*
Copyright (c) 2003-2006, Pete Sanderson and Kenneth Vollmar
Developed by Pete Sanderson (psanderson@otterbein.edu)
and Kenneth Vollmar (kenvollmar@missouristate.edu)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(MIT license, http://www.opensource.org/licenses/mit-license.html)
*/
/**
* Service to display string stored starting at address in $a0 onto the console.
*/
public class SyscallPrintString extends AbstractSyscall {
/**
* Build an instance of the Print String syscall. Default service number
* is 4 and name is "PrintString".
*/
public SyscallPrintString() {
super(4, "PrintString");
}
/**
* Performs syscall function to print string stored starting at address in $a0.
*/
public void simulate(ProgramStatement statement) throws ProcessingException {
int byteAddress = RegisterFile.getValue(4);
char ch = 0;
try
{
ch = (char) Globals.memory.getByte(byteAddress);
// won't stop until NULL byte reached!
while (ch != 0)
{
SystemIO.printString(new Character(ch).toString());
byteAddress++;
ch = (char) Globals.memory.getByte(byteAddress);
}
}
catch (AddressErrorException e)
{
throw new ProcessingException(statement, e);
}
}
} | mit |
sk89q/CommandHelper | src/main/java/com/laytonsmith/core/exceptions/CRE/CRECausedByWrapper.java | 1149 | package com.laytonsmith.core.exceptions.CRE;
import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CClassType;
import com.laytonsmith.core.constructs.Target;
/**
* Wraps a CArray that represents a causedBy exception.
*/
public class CRECausedByWrapper extends CREThrowable {
private final CArray exception;
public CRECausedByWrapper(String msg, Target t) {
super(msg, t);
throw new UnsupportedOperationException();
}
public CRECausedByWrapper(String msg, Target t, Throwable ex) {
super(msg, t, ex);
throw new UnsupportedOperationException();
}
public CRECausedByWrapper(CArray exception) {
super(null, Target.UNKNOWN);
this.exception = exception.clone();
}
public CArray getException() {
return exception;
}
@Override
public Version since() {
return super.since();
}
@Override
public String docs() {
return super.docs();
}
@Override
public CClassType[] getInterfaces() {
throw new UnsupportedOperationException();
}
@Override
public CClassType[] getSuperclasses() {
throw new UnsupportedOperationException();
}
}
| mit |
plumer/codana | tomcat_files/7.0.61/RpcChannel.java | 11797 | /*
* 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.catalina.tribes.group;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.catalina.tribes.Channel;
import org.apache.catalina.tribes.ChannelException;
import org.apache.catalina.tribes.ChannelListener;
import org.apache.catalina.tribes.ErrorHandler;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.UniqueId;
import org.apache.catalina.tribes.util.UUIDGenerator;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* A channel to handle RPC messaging
* @author Filip Hanik
*/
public class RpcChannel implements ChannelListener{
private static final Log log = LogFactory.getLog(RpcChannel.class);
public static final int FIRST_REPLY = 1;
public static final int MAJORITY_REPLY = 2;
public static final int ALL_REPLY = 3;
public static final int NO_REPLY = 4;
private Channel channel;
private RpcCallback callback;
private byte[] rpcId;
private int replyMessageOptions = 0;
private HashMap<RpcCollectorKey, RpcCollector> responseMap = new HashMap<RpcCollectorKey, RpcCollector>();
/**
* Create an RPC channel. You can have several RPC channels attached to a group
* all separated out by the uniqueness
* @param rpcId - the unique Id for this RPC group
* @param channel Channel
* @param callback RpcCallback
*/
public RpcChannel(byte[] rpcId, Channel channel, RpcCallback callback) {
this.channel = channel;
this.callback = callback;
this.rpcId = rpcId;
channel.addChannelListener(this);
}
/**
* Send a message and wait for the response.
* @param destination Member[] - the destination for the message, and the members you request a reply from
* @param message Serializable - the message you are sending out
* @param rpcOptions int - FIRST_REPLY, MAJORITY_REPLY or ALL_REPLY
* @param channelOptions channel sender options
* @param timeout long - timeout in milliseconds, if no reply is received within this time null is returned
* @return Response[] - an array of response objects.
* @throws ChannelException
*/
public Response[] send(Member[] destination,
Serializable message,
int rpcOptions,
int channelOptions,
long timeout) throws ChannelException {
if ( destination==null || destination.length == 0 ) return new Response[0];
//avoid dead lock
int sendOptions =
channelOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK;
RpcCollectorKey key = new RpcCollectorKey(UUIDGenerator.randomUUID(false));
RpcCollector collector = new RpcCollector(key,rpcOptions,destination.length);
try {
synchronized (collector) {
if ( rpcOptions != NO_REPLY ) responseMap.put(key, collector);
RpcMessage rmsg = new RpcMessage(rpcId, key.id, message);
channel.send(destination, rmsg, sendOptions);
if ( rpcOptions != NO_REPLY ) collector.wait(timeout);
}
} catch ( InterruptedException ix ) {
Thread.currentThread().interrupt();
}finally {
responseMap.remove(key);
}
return collector.getResponses();
}
@Override
public void messageReceived(Serializable msg, Member sender) {
RpcMessage rmsg = (RpcMessage)msg;
RpcCollectorKey key = new RpcCollectorKey(rmsg.uuid);
if ( rmsg.reply ) {
RpcCollector collector = responseMap.get(key);
if (collector == null) {
callback.leftOver(rmsg.message, sender);
} else {
synchronized (collector) {
//make sure it hasn't been removed
if ( responseMap.containsKey(key) ) {
if ( (rmsg instanceof RpcMessage.NoRpcChannelReply) )
collector.destcnt--;
else
collector.addResponse(rmsg.message, sender);
if (collector.isComplete()) collector.notifyAll();
} else {
if (! (rmsg instanceof RpcMessage.NoRpcChannelReply) )
callback.leftOver(rmsg.message, sender);
}
}//synchronized
}//end if
} else{
boolean finished = false;
final ExtendedRpcCallback excallback = (callback instanceof ExtendedRpcCallback)?((ExtendedRpcCallback)callback) : null;
boolean asyncReply = ((replyMessageOptions & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS);
Serializable reply = callback.replyRequest(rmsg.message,sender);
ErrorHandler handler = null;
final Serializable request = msg;
final Serializable response = reply;
final Member fsender = sender;
if (excallback!=null && asyncReply) {
handler = new ErrorHandler() {
@Override
public void handleError(ChannelException x, UniqueId id) {
excallback.replyFailed(request, response, fsender, x);
}
@Override
public void handleCompletion(UniqueId id) {
excallback.replySucceeded(request, response, fsender);
}
};
}
rmsg.reply = true;
rmsg.message = reply;
try {
if (handler!=null) {
channel.send(new Member[] {sender}, rmsg,replyMessageOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK, handler);
} else {
channel.send(new Member[] {sender}, rmsg,replyMessageOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK);
}
finished = true;
}catch ( Exception x ) {
if (excallback != null && !asyncReply) {
excallback.replyFailed(rmsg.message, reply, sender, x);
} else {
log.error("Unable to send back reply in RpcChannel.",x);
}
}
if (finished && excallback != null && !asyncReply) {
excallback.replySucceeded(rmsg.message, reply, sender);
}
}//end if
}
public void breakdown() {
channel.removeChannelListener(this);
}
@Override
public void finalize() throws Throwable {
breakdown();
super.finalize();
}
@Override
public boolean accept(Serializable msg, Member sender) {
if ( msg instanceof RpcMessage ) {
RpcMessage rmsg = (RpcMessage)msg;
return Arrays.equals(rmsg.rpcId,rpcId);
}else return false;
}
public Channel getChannel() {
return channel;
}
public RpcCallback getCallback() {
return callback;
}
public byte[] getRpcId() {
return rpcId;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public void setCallback(RpcCallback callback) {
this.callback = callback;
}
public void setRpcId(byte[] rpcId) {
this.rpcId = rpcId;
}
public int getReplyMessageOptions() {
return replyMessageOptions;
}
public void setReplyMessageOptions(int replyMessageOptions) {
this.replyMessageOptions = replyMessageOptions;
}
/**
*
* Class that holds all response.
* @author not attributable
* @version 1.0
*/
public static class RpcCollector {
public ArrayList<Response> responses = new ArrayList<Response>();
public RpcCollectorKey key;
public int options;
public int destcnt;
/**
* @deprecated Unused - will be removed in Tomcat 8.0.x
*/
@Deprecated
public long timeout;
/**
* @deprecated Use {@link
* RpcChannel.RpcCollector#RpcChannel.RpcCollector(
* RpcChannel.RpcCollectorKey, int, int)}
*/
@Deprecated
public RpcCollector(RpcCollectorKey key, int options, int destcnt,
long timeout) {
this.key = key;
this.options = options;
this.destcnt = destcnt;
this.timeout = timeout;
}
public RpcCollector(RpcCollectorKey key, int options, int destcnt) {
this(key, options, destcnt, 0);
}
public void addResponse(Serializable message, Member sender){
Response resp = new Response(sender,message);
responses.add(resp);
}
public boolean isComplete() {
if ( destcnt <= 0 ) return true;
switch (options) {
case ALL_REPLY:
return destcnt == responses.size();
case MAJORITY_REPLY:
{
float perc = ((float)responses.size()) / ((float)destcnt);
return perc >= 0.50f;
}
case FIRST_REPLY:
return responses.size()>0;
default:
return false;
}
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public boolean equals(Object o) {
if ( o instanceof RpcCollector ) {
RpcCollector r = (RpcCollector)o;
return r.key.equals(this.key);
} else return false;
}
public Response[] getResponses() {
return responses.toArray(new Response[responses.size()]);
}
}
public static class RpcCollectorKey {
byte[] id;
public RpcCollectorKey(byte[] id) {
this.id = id;
}
@Override
public int hashCode() {
return id[0]+id[1]+id[2]+id[3];
}
@Override
public boolean equals(Object o) {
if ( o instanceof RpcCollectorKey ) {
RpcCollectorKey r = (RpcCollectorKey)o;
return Arrays.equals(id,r.id);
} else return false;
}
}
/**
* @deprecated Unused - will be removed in Tomcat 8.0.x
*/
@Deprecated
protected static String bToS(byte[] data) {
StringBuilder buf = new StringBuilder(4*16);
buf.append("{");
for (int i=0; data!=null && i<data.length; i++ ) buf.append(String.valueOf(data[i])).append(" ");
buf.append("}");
return buf.toString();
}
}
| mit |
sk89q/CommandHelper | src/main/java/com/laytonsmith/PureUtilities/HeapDumper.java | 1726 | package com.laytonsmith.PureUtilities;
import com.sun.management.HotSpotDiagnosticMXBean;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
public class HeapDumper {
// This is the name of the HotSpot Diagnostic MBean
private static final String HOTSPOT_BEAN_NAME
= "com.sun.management:type=HotSpotDiagnostic";
// field to store the hotspot diagnostic MBean
private static volatile HotSpotDiagnosticMXBean hotspotMBean;
/**
* Call this method from your application whenever you want to dump the heap snapshot into a file.
*
* @param fileName name of the heap dump file
* @param live flag that tells whether to dump only the live objects
*/
public static void dumpHeap(String fileName, boolean live) {
// initialize hotspot diagnostic MBean
initHotspotMBean();
try {
hotspotMBean.dumpHeap(fileName, live);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
// initialize the hotspot diagnostic MBean field
private static void initHotspotMBean() {
if(hotspotMBean == null) {
synchronized(HeapDumper.class) {
if(hotspotMBean == null) {
hotspotMBean = getHotspotMBean();
}
}
}
}
// get the hotspot diagnostic MBean from the
// platform MBean server
private static HotSpotDiagnosticMXBean getHotspotMBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean bean
= ManagementFactory.newPlatformMXBeanProxy(server,
HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
return bean;
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
| mit |
bartlomiej-laczkowski/che | plugins/plugin-nodejs-debugger/che-plugin-nodejs-debugger-server/src/test/java/org/eclipse/che/plugin/nodejsdbg/server/NodeJsDebuggerTest.java | 6545 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.nodejsdbg.server;
import org.eclipse.che.api.debug.shared.model.Breakpoint;
import org.eclipse.che.api.debug.shared.model.DebuggerInfo;
import org.eclipse.che.api.debug.shared.model.event.BreakpointActivatedEvent;
import org.eclipse.che.api.debug.shared.model.event.DebuggerEvent;
import org.eclipse.che.api.debug.shared.model.event.DisconnectEvent;
import org.eclipse.che.api.debug.shared.model.event.SuspendEvent;
import org.eclipse.che.api.debug.shared.model.impl.BreakpointImpl;
import org.eclipse.che.api.debug.shared.model.impl.LocationImpl;
import org.eclipse.che.api.debug.shared.model.impl.action.ResumeActionImpl;
import org.eclipse.che.api.debug.shared.model.impl.action.StepIntoActionImpl;
import org.eclipse.che.api.debug.shared.model.impl.action.StepOutActionImpl;
import org.eclipse.che.api.debug.shared.model.impl.action.StepOverActionImpl;
import org.eclipse.che.api.debugger.server.Debugger;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* @author Anatolii Bazko
*/
public class NodeJsDebuggerTest {
private NodeJsDebugger debugger;
private Debugger.DebuggerCallback callback;
@BeforeMethod
public void setUp() throws Exception {
String file = NodeJsDebuggerTest.class.getResource("/app.js").getFile();
callback = mock(Debugger.DebuggerCallback.class);
debugger = NodeJsDebugger.newInstance(null, null, file, callback);
}
@AfterMethod
public void tearDown() throws Exception {
debugger.disconnect();
}
@Test
public void testGetInfo() throws Exception {
DebuggerInfo info = debugger.getInfo();
assertTrue(info.getFile().endsWith("app.js"));
assertTrue(!isNullOrEmpty(info.getVersion()));
assertTrue(info.getName().equals("'node'") || info.getName().equals("'nodejs'"));
}
@Test
public void testManageBreakpoints() throws Exception {
List<Breakpoint> breakpoints = debugger.getAllBreakpoints();
assertEquals(breakpoints.size(), 1);
debugger.addBreakpoint(new BreakpointImpl(new LocationImpl("app.js", 2)));
ArgumentCaptor<BreakpointActivatedEvent> breakpointActivated = ArgumentCaptor.forClass(BreakpointActivatedEvent.class);
verify(callback).onEvent(breakpointActivated.capture());
BreakpointActivatedEvent event = breakpointActivated.getValue();
Breakpoint breakpoint = event.getBreakpoint();
assertEquals(breakpoint.getLocation().getTarget(), "app.js");
assertEquals(breakpoint.getLocation().getLineNumber(), 2);
debugger.addBreakpoint(new BreakpointImpl(new LocationImpl("app.js", 5)));
breakpoints = debugger.getAllBreakpoints();
assertEquals(breakpoints.size(), 3);
debugger.deleteBreakpoint(new LocationImpl("app.js", 2));
breakpoints = debugger.getAllBreakpoints();
assertEquals(breakpoints.size(), 2);
debugger.deleteAllBreakpoints();
breakpoints = debugger.getAllBreakpoints();
assertEquals(breakpoints.size(), 1);
}
@Test
public void testEvaluation() throws Exception {
String result = debugger.evaluate("2+2");
assertEquals(result, "4");
result = debugger.evaluate("console.log('hello')");
assertEquals(result, "< hello");
result = debugger.evaluate("var y=1");
assertEquals(result, "undefined");
}
@Test
public void testOver() throws Exception {
debugger.stepOver(new StepOverActionImpl());
ArgumentCaptor<SuspendEvent> suspendEventCaptor = ArgumentCaptor.forClass(SuspendEvent.class);
verify(callback, timeout(1000)).onEvent(suspendEventCaptor.capture());
SuspendEvent suspendEvent = suspendEventCaptor.getValue();
assertEquals(suspendEvent.getLocation().getLineNumber(), 2);
assertTrue(suspendEvent.getLocation().getTarget().endsWith("app.js"));
}
@Test
public void testIntoAndOut() throws Exception {
ArgumentCaptor<SuspendEvent> suspendEventCaptor = ArgumentCaptor.forClass(SuspendEvent.class);
debugger.stepInto(new StepIntoActionImpl());
verify(callback).onEvent(suspendEventCaptor.capture());
SuspendEvent suspendEvent = suspendEventCaptor.getValue();
assertEquals(suspendEvent.getLocation().getLineNumber(), 2);
assertTrue(suspendEvent.getLocation().getTarget().endsWith("app.js"));
Mockito.reset(callback);
debugger.stepInto(new StepIntoActionImpl());
verify(callback, timeout(1000)).onEvent(suspendEventCaptor.capture());
suspendEvent = suspendEventCaptor.getValue();
assertEquals(suspendEvent.getLocation().getLineNumber(), 5);
assertTrue(suspendEvent.getLocation().getTarget().endsWith("app.js"));
Mockito.reset(callback);
debugger.stepOut(new StepOutActionImpl());
verify(callback, timeout(1000)).onEvent(suspendEventCaptor.capture());
suspendEvent = suspendEventCaptor.getValue();
assertEquals(suspendEvent.getLocation().getLineNumber(), 9);
assertTrue(suspendEvent.getLocation().getTarget().endsWith("app.js"));
}
@Test
public void testResume() throws Exception {
debugger.resume(new ResumeActionImpl());
ArgumentCaptor<DebuggerEvent> eventCaptor = ArgumentCaptor.forClass(DebuggerEvent.class);
verify(callback, timeout(5000)).onEvent(eventCaptor.capture());
assertTrue(eventCaptor.getValue() != null);
assertTrue(eventCaptor.getValue() instanceof DisconnectEvent);
}
}
| epl-1.0 |
TheNetStriker/openhab | bundles/binding/org.openhab.binding.rfxcom.test/src/test/java/org/openhab/binding/rfxcom/internal/messages/RFXComTemperatureMessageTest.java | 2240 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.rfxcom.internal.messages;
import static org.junit.Assert.assertEquals;
import static org.openhab.binding.rfxcom.internal.messages.RFXComTemperatureMessage.SubType.*;
import javax.xml.bind.DatatypeConverter;
import org.junit.Test;
import org.openhab.binding.rfxcom.internal.RFXComException;
/**
* Test for RFXCom-binding
*
* @author Martin van Wingerden
* @since 1.9.0
*/
public class RFXComTemperatureMessageTest {
private void testMessage(String hexMsg, RFXComTemperatureMessage.SubType subType, int seqNbr, String deviceId,
double temperature, int signalLevel, int bateryLevel) throws RFXComException {
final RFXComTemperatureMessage msg = (RFXComTemperatureMessage) RFXComMessageFactory
.getMessageInterface(DatatypeConverter.parseHexBinary(hexMsg));
assertEquals("SubType", subType, msg.subType);
assertEquals("Seq Number", seqNbr, (short) (msg.seqNbr & 0xFF));
assertEquals("Sensor Id", deviceId, msg.generateDeviceId());
assertEquals("Temperature", temperature, msg.temperature, 0.001);
assertEquals("Signal Level", signalLevel, msg.signalLevel);
assertEquals("Battery", bateryLevel, msg.batteryLevel);
byte[] decoded = msg.decodeMessage();
assertEquals("Message converted back", hexMsg, DatatypeConverter.printHexBinary(decoded));
}
@Test
public void testSomeMessages() throws RFXComException {
testMessage("08500110000180BC69", THR128_138_THC138, 16, "1", -18.8d, 6, 9);
testMessage("0850021DFB0100D770", THC238_268_THN122_132_THWR288_THRN122_AW129_131, 29, "64257", 21.5d, 7, 0);
testMessage("08500502770000D389", LACROSSE_TX2_TX3_TX4_TX17, 2, "30464", 21.1d, 8, 9);
testMessage("0850091A00C3800689", RUBICSON, 26, "195", -0.6d, 8, 9);
testMessage("0850097200C300E089", RUBICSON, 114, "195", 22.4d, 8, 9);
}
}
| epl-1.0 |
akervern/che | selenium/che-selenium-test/src/test/resources/projects/defaultSpringProjectWithDifferentTypeOfFiles/src/test/java.org.eclipse.qa.examples/AppControlleTest.java | 484 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.qa.examples
public class AppControlleTest
{
public String helloWorld()
{
return "Hello World";
}
}
| epl-1.0 |
Ori-Libhaber/che-core | ide/che-core-ide-jseditor/src/main/java/org/eclipse/che/ide/jseditor/client/texteditor/EditorHandle.java | 660 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.jseditor.client.texteditor;
/**
* Handle on an editor view instance.
*/
public interface EditorHandle {
}
| epl-1.0 |
idserda/openhab | bundles/binding/org.openhab.binding.weather/src/main/java/org/openhab/binding/weather/internal/utils/UnitUtils.java | 5375 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.weather.internal.utils;
import org.openhab.binding.weather.internal.common.Unit;
/**
* Utility class for different unit conversions.
*
* @author Gerhard Riegler
* @since 1.6.0
*/
public class UnitUtils {
/**
* Converts celsius to fahrenheit.
*/
public static Double celsiusToFahrenheit(Double celsius) {
if (celsius == null) {
return null;
}
return celsius * 1.8 + 32.0;
}
/**
* Converts millimeters to inches.
*/
public static Double millimetersToInches(Double millimeters) {
if (millimeters == null) {
return null;
}
return millimeters * 0.0393700787;
}
/**
* Converts kilometers per hour to miles per hour.
*/
public static Double kmhToMph(Double kmh) {
if (kmh == null) {
return null;
}
return kmh * 0.621371192;
}
/**
* Converts kilometers per hour to knots.
*/
public static Double kmhToKnots(Double kmh) {
if (kmh == null) {
return null;
}
return kmh * 0.539956803;
}
/**
* Converts kilometers per hour to meter per seconds.
*/
public static Double kmhToMps(Double kmh) {
if (kmh == null) {
return null;
}
return kmh * 0.277777778;
}
/**
* Converts meter per seconds to kilometers per hour.
*/
public static Double mpsToKmh(Double mps) {
if (mps == null) {
return null;
}
return mps / 0.277777778;
}
/**
* Converts kilometers per hour to beaufort.
*/
public static Double kmhToBeaufort(Double kmh) {
if (kmh == null) {
return null;
}
return new Double(Math.round(Math.pow(kmh / 3.01, 0.666666666)));
}
/**
* Converts millibar to inches.
*/
public static Double millibarToInches(Double millibar) {
if (millibar == null) {
return null;
}
return millibar * 0.0295299830714;
}
/**
* Converts meter to feet.
*/
public static Double meterToFeet(Double meter) {
if (meter == null) {
return null;
}
return meter * 3.2808399;
}
/**
* Converts feet to meter.
*/
public static Double feetToMeter(Double feet) {
if (feet == null) {
return null;
}
return feet / 3.2808399;
}
/**
* Converts centimeter to millimeter.
*/
public static Double centimeterToMillimeter(Double centimeter) {
if (centimeter == null) {
return null;
}
return centimeter * 100;
}
/**
* Calculates the humidex (feels like temperature) from temperature and
* humidity.
*/
public static double getHumidex(double temp, int humidity) {
Double x = 7.5 * temp / (237.7 + temp);
Double e = 6.112 * Math.pow(10, x) * humidity / 100;
return temp + (5d / 9d) * (e - 10);
}
/**
* Returns the wind direction based on degree.
*/
public static String getWindDirection(Integer degree) {
if (degree < 0 || degree > 360) {
return null;
}
String[] directions = new String[] { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW",
"W", "WNW", "NW", "NNW" };
double step = 360.0 / directions.length;
double b = Math.floor((degree + (step / 2.0)) / step);
return directions[(int) (b % directions.length)];
}
/**
* Converts a value to the unit configured in the item binding.
*/
public static Double convertUnit(Double value, Unit unit, String property) {
if (unit != null) {
switch (unit) {
case FAHRENHEIT:
return celsiusToFahrenheit(value);
case MPH:
return kmhToMph(value);
case INCHES:
if ("atmosphere.pressure".equals(property)) {
return millibarToInches(value);
} else if ("precipitation.snow".equals(property)) {
return millimetersToInches(centimeterToMillimeter(value));
} else {
return millimetersToInches(value);
}
case BEAUFORT:
return kmhToBeaufort(value);
case KNOTS:
return kmhToKnots(value);
case MPS:
return kmhToMps(value);
}
}
return value;
}
/**
* Computes the sea level pressure depending of observed pressure,
* temperature and altitude of the observed point
*/
public static double getSeaLevelPressure(double pressure, double temp, double altitude) {
double x = 0.0065 * altitude;
x = (1 - x / (temp + x + 273.15));
return pressure * Math.pow(x, -5.257);
}
}
| epl-1.0 |
agoncal/core | javaee/impl/src/main/java/org/jboss/forge/addon/javaee/servlet/ui/ServletMethod.java | 614 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.servlet.ui;
/**
* @author <a href="mailto:antonio.goncalves@gmail.com">Antonio Goncalves</a>
*/
public enum ServletMethod
{
GET("doGet"),
POST("doPost"),
PUT("doPut"),
DELETE("doDelete");
private String methodName;
private ServletMethod(String methodName)
{
this.methodName = methodName;
}
public String getMethodName()
{
return methodName;
}
}
| epl-1.0 |
royleexhFake/mayloon-portingtool | net.sourceforge.jseditor/src-jseditor/net/sourceforge/jseditor/utility/JSConstant.java | 1156 | package net.sourceforge.jseditor.utility;
public class JSConstant {
public static boolean isFirstTime=true;
public static boolean isDoubleClicked=false;
//ÿ´Îµ÷ÓÃJSDoubleClickStrategyµÄº¯ÊýµÄʱºò£¬½«doubleClickTagÉèÖóÉ0;
public static int doubleClickTag=1;
public static final int stringOffsetLength =600;
public static String load_pattern_tag="default";
//default innerClassLevel=0,when meet push,innerClassLevel++,when pop,innerClassLevel--
public static int innerClassLevel =0;
//when scan the document from the beginning,judge whether it is the first class of the document
public static boolean isFirstClass=true;
public static final String Keyword_declarePackage="Clazz.declarePackage";
public static final String Keyword_load="Clazz.load";
public static final String Keyword_declareType="Clazz.declareType";
public static final String Keyword_makeConstructor="Clazz.makeConstructor";
public static final String Keyword_defineMethod="Clazz.defineMethod";
public static final String Keyword_overrideMethod="Clazz.overrideMethod";
public static final String Keyword_decorateasclass="Clazz.instantialize";
}
| epl-1.0 |
idserda/openhab | bundles/action/org.openhab.action.mios/src/main/java/org/openhab/action/mios/internal/MiosActionService.java | 2690 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.action.mios.internal;
import java.util.Dictionary;
import org.openhab.binding.mios.MiosActionProvider;
import org.openhab.core.scriptengine.action.ActionService;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class registers an OSGi service for the MiOS Action.
*
* @author Mark Clark
* @since 1.7.0
*/
public class MiosActionService implements ActionService, ManagedService {
private static final Logger logger = LoggerFactory.getLogger(MiosActionService.class);
private MiosActionProvider actionProvider;
private static MiosActionService service;
public static MiosActionService getMiosActionService() {
return service;
}
public void activate() {
logger.debug("MiOS action service activated");
service = this;
}
public void deactivate() {
logger.debug("MiOS action service activated");
service = null;
}
/**
* {@inheritDoc}
*/
@Override
public String getActionClassName() {
return getActionClass().getCanonicalName();
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getActionClass() {
return MiosAction.class;
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
}
/**
* Setter for use by OSGi injection.
*
* @param actionProvider the MiOS Action Provider (provided by the MiOS Binding).
*/
public void setMiosActionProvider(MiosActionProvider actionProvider) {
this.actionProvider = actionProvider;
logger.debug("MiOS setMiosActionProvider called");
}
/**
* Unsetter for use by OSGi injection.
*
* @param actionProvider MiOS Action Provider to remove.
*/
public void unsetMiosActionProvider(MiosActionProvider actionProvider) {
this.actionProvider = null;
logger.debug("MiOS unsetMiosActionProvider called");
}
/**
* Get the MiosActionProvider instance injected by OSGi.
*
* @return the MiOS Action Provider associated with this Action Service.
*/
public MiosActionProvider getMiosActionProvider() {
return this.actionProvider;
}
}
| epl-1.0 |
a544jh/tmc-netbeans | tmc-plugin/src/fi/helsinki/cs/tmc/actions/CheckForUnopenedExercises.java | 3321 | package fi.helsinki.cs.tmc.actions;
import fi.helsinki.cs.tmc.data.Exercise;
import fi.helsinki.cs.tmc.model.CourseDb;
import fi.helsinki.cs.tmc.model.ProjectMediator;
import fi.helsinki.cs.tmc.model.TmcProjectInfo;
import fi.helsinki.cs.tmc.model.TmcSettings;
import fi.helsinki.cs.tmc.ui.TmcNotificationDisplayer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
import org.openide.awt.NotificationDisplayer;
import org.openide.util.ImageUtilities;
public class CheckForUnopenedExercises implements ActionListener {
public static boolean shouldRunOnStartup() {
return TmcSettings.getDefault().isCheckingForUnopenedAtStartup();
}
private static final TmcNotificationDisplayer.SingletonToken notifierToken = TmcNotificationDisplayer.createSingletonToken();
private ProjectMediator projects;
private CourseDb courseDb;
private TmcNotificationDisplayer notifier;
public CheckForUnopenedExercises() {
this.projects = ProjectMediator.getInstance();
this.courseDb = CourseDb.getInstance();
this.notifier = TmcNotificationDisplayer.getDefault();
}
@Override
public void actionPerformed(ActionEvent e) {
run();
}
public void run() {
projects.callWhenProjectsCompletelyOpened(new Runnable() {
@Override
public void run() {
List<Exercise> unopenedExercises = new ArrayList<Exercise>();
for (Exercise ex : courseDb.getCurrentCourseExercises()) {
TmcProjectInfo project = projects.tryGetProjectForExercise(ex);
if (project != null && !projects.isProjectOpen(project)) {
unopenedExercises.add(ex);
}
}
if (!unopenedExercises.isEmpty()) {
showNotification(unopenedExercises);
}
}
});
}
private void showNotification(List<Exercise> unopenedExercises) {
int count = unopenedExercises.size();
String msg;
String prompt;
if (count == 1) {
msg = "There is one exercise that is downloaded but not opened.";
prompt = "Click here to open it.";
} else {
msg = "There are " + count + " exercises that are downloaded but not opened.";
prompt = "Click here to open them.";
}
notifier.notify(notifierToken, msg, getNotificationIcon(), prompt, openAction(unopenedExercises), NotificationDisplayer.Priority.LOW);
}
private ActionListener openAction(final List<Exercise> exercises) {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (Exercise ex : exercises) {
TmcProjectInfo project = projects.tryGetProjectForExercise(ex);
if (project != null && !projects.isProjectOpen(project)) {
projects.openProject(project);
}
}
}
};
}
private Icon getNotificationIcon() {
return ImageUtilities.loadImageIcon("fi/helsinki/cs/tmc/smile.gif", false);
}
}
| gpl-2.0 |
md-5/jdk10 | test/langtools/jdk/javadoc/doclet/testRepeatedAnnotations/pkg1/RegContaineeNotDoc.java | 1306 | /*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pkg1;
import java.lang.annotation.*;
/**
* This annotation is a non-documented annotation contained by RegContainerValDoc.
* It will be used to annotate Class C using a non-synthesized form.
*/
public @interface RegContaineeNotDoc {
}
| gpl-2.0 |
zapster/graal-core | graal/com.oracle.graal.jtt/src/com/oracle/graal/jtt/bytecode/BC_fcmp01.java | 1486 | /*
* Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.jtt.bytecode;
import org.junit.Test;
import com.oracle.graal.jtt.JTTTest;
/*
*/
public class BC_fcmp01 extends JTTTest {
public static boolean test(float a, float b) {
return a < b;
}
@Test
public void run0() throws Throwable {
runTest("test", 0f, -0.1f);
}
@Test
public void run1() throws Throwable {
runTest("test", 78.00f, 78.001f);
}
}
| gpl-2.0 |
hexbinary/landing | src/main/java/oscar/oscarRx/pageUtil/RxClearPendingForm.java | 2451 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarRx.pageUtil;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public final class RxClearPendingForm extends ActionForm {
private String action = null;
public String getAction() {
return this.action;
}
public void setAction(String RHS) {
this.action = RHS;
}
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
/**
* Validate the properties that have been set from this HTTP request,
* and return an <code>ActionErrors</code> object that encapsulates any
* validation errors that have been found. If no errors are found, return
* <code>null</code> or an <code>ActionErrors</code> object with no
* recorded error messages.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
return errors;
}
}
| gpl-2.0 |
rcaa/Freemind-SPL | src/freemind/icons/RemoveLastIconXmlActionTypeImpl.java | 11979 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.1-05/30/2003 05:06 AM(java_re)-fcs
// 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: 2008.02.23 at 11:11:43 GMT+01:00
//
package freemind.icons;
import freemind.controller.actions.generated.instance.impl.JAXBVersion;
import freemind.controller.actions.generated.instance.impl.NodeActionImpl;
import freemind.controller.actions.generated.instance.impl.NodeActionImpl.Unmarshaller;
public class RemoveLastIconXmlActionTypeImpl
extends freemind.controller.actions.generated.instance.impl.NodeActionImpl
implements freemind.controller.actions.generated.instance.RemoveLastIconXmlActionType, com.sun.xml.bind.JAXBObject, freemind.controller.actions.generated.instance.impl.runtime.UnmarshallableObject, freemind.controller.actions.generated.instance.impl.runtime.XMLSerializable, freemind.controller.actions.generated.instance.impl.runtime.ValidatableObject
{
public final static java.lang.Class version = (freemind.controller.actions.generated.instance.impl.JAXBVersion.class);
private static com.sun.msv.grammar.Grammar schemaFragment;
private final static java.lang.Class PRIMARY_INTERFACE_CLASS() {
return (freemind.controller.actions.generated.instance.RemoveLastIconXmlActionType.class);
}
public freemind.controller.actions.generated.instance.impl.runtime.UnmarshallingEventHandler createUnmarshaller(freemind.controller.actions.generated.instance.impl.runtime.UnmarshallingContext context) {
return new freemind.icons.RemoveLastIconXmlActionTypeImpl.Unmarshaller(context);
}
public void serializeElementBody(freemind.controller.actions.generated.instance.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
super.serializeElementBody(context);
}
public void serializeAttributes(freemind.controller.actions.generated.instance.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
super.serializeAttributes(context);
}
public void serializeAttributeBody(freemind.controller.actions.generated.instance.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
super.serializeAttributeBody(context);
}
public void serializeURIs(freemind.controller.actions.generated.instance.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
super.serializeURIs(context);
}
public java.lang.Class getPrimaryInterface() {
return (freemind.controller.actions.generated.instance.RemoveLastIconXmlActionType.class);
}
public com.sun.msv.verifier.DocumentDeclaration createRawValidator() {
if (schemaFragment == null) {
schemaFragment = com.sun.xml.bind.validator.SchemaDeserializer.deserialize((
"\u00ac\u00ed\u0000\u0005sr\u0000 com.sun.msv.grammar.AttributeExp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002L\u0000\u0003expt\u0000 "
+"Lcom/sun/msv/grammar/Expression;L\u0000\tnameClasst\u0000\u001fLcom/sun/msv/"
+"grammar/NameClass;xr\u0000\u001ecom.sun.msv.grammar.Expression\u00f8\u0018\u0082\u00e8N5~O"
+"\u0002\u0000\u0003I\u0000\u000ecachedHashCodeL\u0000\u0013epsilonReducibilityt\u0000\u0013Ljava/lang/Bool"
+"ean;L\u0000\u000bexpandedExpq\u0000~\u0000\u0001xp\u0003:\u000e\u00a3ppsr\u0000\u001bcom.sun.msv.grammar.DataE"
+"xp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0003L\u0000\u0002dtt\u0000\u001fLorg/relaxng/datatype/Datatype;L\u0000\u0006excep"
+"tq\u0000~\u0000\u0001L\u0000\u0004namet\u0000\u001dLcom/sun/msv/util/StringPair;xq\u0000~\u0000\u0003\u0001\u0086\u00d4\u0094ppsr\u0000"
+"#com.sun.msv.datatype.xsd.StringType\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0001Z\u0000\risAlwaysVa"
+"lidxr\u0000*com.sun.msv.datatype.xsd.BuiltinAtomicType\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000"
+"xr\u0000%com.sun.msv.datatype.xsd.ConcreteType\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xr\u0000\'com."
+"sun.msv.datatype.xsd.XSDatatypeImpl\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0003L\u0000\fnamespaceUr"
+"it\u0000\u0012Ljava/lang/String;L\u0000\btypeNameq\u0000~\u0000\u000eL\u0000\nwhiteSpacet\u0000.Lcom/s"
+"un/msv/datatype/xsd/WhiteSpaceProcessor;xpt\u0000 http://www.w3.o"
+"rg/2001/XMLSchemat\u0000\u0006stringsr\u00005com.sun.msv.datatype.xsd.White"
+"SpaceProcessor$Preserve\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xr\u0000,com.sun.msv.datatype.x"
+"sd.WhiteSpaceProcessor\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xp\u0001sr\u00000com.sun.msv.grammar."
+"Expression$NullSetExpression\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xq\u0000~\u0000\u0003\u0000\u0000\u0000\nppsr\u0000\u001bcom.s"
+"un.msv.util.StringPair\u00d0t\u001ejB\u008f\u008d\u00a0\u0002\u0000\u0002L\u0000\tlocalNameq\u0000~\u0000\u000eL\u0000\fnamespa"
+"ceURIq\u0000~\u0000\u000expq\u0000~\u0000\u0012q\u0000~\u0000\u0011sr\u0000#com.sun.msv.grammar.SimpleNameClas"
+"s\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002L\u0000\tlocalNameq\u0000~\u0000\u000eL\u0000\fnamespaceURIq\u0000~\u0000\u000exr\u0000\u001dcom.sun"
+".msv.grammar.NameClass\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xpt\u0000\u0004nodet\u0000\u0000sr\u0000\"com.sun.msv"
+".grammar.ExpressionPool\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0001L\u0000\bexpTablet\u0000/Lcom/sun/msv"
+"/grammar/ExpressionPool$ClosedHash;xpsr\u0000-com.sun.msv.grammar"
+".ExpressionPool$ClosedHash\u00d7j\u00d0N\u00ef\u00e8\u00ed\u001c\u0002\u0000\u0004I\u0000\u0005countI\u0000\tthresholdL\u0000\u0006"
+"parentq\u0000~\u0000 [\u0000\u0005tablet\u0000![Lcom/sun/msv/grammar/Expression;xp\u0000\u0000\u0000"
+"\u0000\u0000\u0000\u00009pur\u0000![Lcom.sun.msv.grammar.Expression;\u00d68D\u00c3]\u00ad\u00a7\n\u0002\u0000\u0000xp\u0000\u0000\u0000\u00bf"
+"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"
+"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"
+"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"
+"ppppppppppp"));
}
return new com.sun.msv.verifier.regexp.REDocumentDeclaration(schemaFragment);
}
public class Unmarshaller
extends freemind.controller.actions.generated.instance.impl.runtime.AbstractUnmarshallingEventHandlerImpl
{
public Unmarshaller(freemind.controller.actions.generated.instance.impl.runtime.UnmarshallingContext context) {
super(context, "--");
}
protected Unmarshaller(freemind.controller.actions.generated.instance.impl.runtime.UnmarshallingContext context, int startState) {
this(context);
state = startState;
}
public java.lang.Object owner() {
return freemind.icons.RemoveLastIconXmlActionTypeImpl.this;
}
public void enterElement(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname, org.xml.sax.Attributes __atts)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 0 :
attIdx = context.getAttribute("", "node");
if (attIdx >= 0) {
context.consumeAttribute(attIdx);
context.getCurrentHandler().enterElement(___uri, ___local, ___qname, __atts);
return ;
}
break;
case 1 :
revertToParentFromEnterElement(___uri, ___local, ___qname, __atts);
return ;
}
super.enterElement(___uri, ___local, ___qname, __atts);
break;
}
}
public void leaveElement(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 0 :
attIdx = context.getAttribute("", "node");
if (attIdx >= 0) {
context.consumeAttribute(attIdx);
context.getCurrentHandler().leaveElement(___uri, ___local, ___qname);
return ;
}
break;
case 1 :
revertToParentFromLeaveElement(___uri, ___local, ___qname);
return ;
}
super.leaveElement(___uri, ___local, ___qname);
break;
}
}
public void enterAttribute(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 0 :
if (("node" == ___local)&&("" == ___uri)) {
spawnHandlerFromEnterAttribute((((freemind.controller.actions.generated.instance.impl.NodeActionImpl)freemind.icons.RemoveLastIconXmlActionTypeImpl.this).new Unmarshaller(context)), 1, ___uri, ___local, ___qname);
return ;
}
break;
case 1 :
revertToParentFromEnterAttribute(___uri, ___local, ___qname);
return ;
}
super.enterAttribute(___uri, ___local, ___qname);
break;
}
}
public void leaveAttribute(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 0 :
attIdx = context.getAttribute("", "node");
if (attIdx >= 0) {
context.consumeAttribute(attIdx);
context.getCurrentHandler().leaveAttribute(___uri, ___local, ___qname);
return ;
}
break;
case 1 :
revertToParentFromLeaveAttribute(___uri, ___local, ___qname);
return ;
}
super.leaveAttribute(___uri, ___local, ___qname);
break;
}
}
public void handleText(final java.lang.String value)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
try {
switch (state) {
case 0 :
attIdx = context.getAttribute("", "node");
if (attIdx >= 0) {
context.consumeAttribute(attIdx);
context.getCurrentHandler().text(value);
return ;
}
break;
case 1 :
revertToParentFromText(value);
return ;
}
} catch (java.lang.RuntimeException e) {
handleUnexpectedTextException(value, e);
}
break;
}
}
}
}
| gpl-2.0 |
austgl/transdroid | android/src/org/transdroid/rss/RssFeedSettings.java | 2167 | /*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.rss;
public final class RssFeedSettings {
final private String key;
final private String name;
final private String url;
final private boolean needsAuth;
private String lastNew;
public RssFeedSettings(String key, String name, String url, boolean needsAuth, String lastNew) {
this.key = key;
this.name = name;
this.url = url;
this.needsAuth = needsAuth;
this.lastNew = lastNew;
}
/**
* Returns the unique key for this feed settings object (used as postfix in storing this settings to the user preferences)
* @return The unique rss feed preferences (postfix) key
*/
public String getKey() {
return this.key;
}
/**
* The custom name of the RSS feed, as given by the user
* @return The feed name
*/
public String getName() {
return this.name;
}
/**
* The full url of the RSS feed
* @return The feed url as url-encoded string
*/
public String getUrl() {
return this.url;
}
/**
* Whether this feed is secured and requires authentication
* @return True if it is secured with some authentication mechanism
*/
public boolean needsAuthentication() {
return this.needsAuth;
}
/**
* Returns the url of the item that was the newest last time we checked this feed
* @return The last new item's url as url-encoded string
*/
public String getLastNew() {
return this.lastNew;
}
public void setLastNew(String lastNew) {
this.lastNew = lastNew;
}
}
| gpl-3.0 |
jmcPereira/overture | core/typechecker/src/test/java/org/overture/typechecker/tests/utils/TypeSetAnalysis.java | 1850 | /*
* #%~
* The VDM Type Checker
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #~%
*/
package org.overture.typechecker.tests.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.overture.ast.analysis.AnalysisException;
import org.overture.ast.analysis.DepthFirstAnalysisAdaptor;
import org.overture.ast.node.INode;
public class TypeSetAnalysis extends DepthFirstAnalysisAdaptor
{
@Override
public void defaultInINode(INode node) throws AnalysisException
{
try
{
Method m = node.getClass().getMethod("getType");
if (m.invoke(node) == null)
{
throw new AnalysisException("Type not set for type: "
+ node.getClass().getSimpleName());
}
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e)
{
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| gpl-3.0 |
hgl888/todo.txt-android | src/com/todotxt/todotxttouch/AddTask.java | 14520 | /**
* This file is part of Todo.txt for Android, an app for managing your todo.txt file (http://todotxt.com).
*
* Copyright (c) 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*
* LICENSE:
*
* Todo.txt for Android is free software: you can redistribute it and/or modify it under the terms of the GNU General
* Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
*
* Todo.txt for Android is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with Todo.txt for Android. If not, see
* <http://www.gnu.org/licenses/>.
*
* Todo.txt for Android's source code is available at https://github.com/ginatrapani/todo.txt-android
*
* @author Todo.txt for Android contributors <todotxt@yahoogroups.com>
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2009-2013 Todo.txt for Android contributors (http://todotxt.com)
*/
package com.todotxt.todotxttouch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Random;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.todotxt.todotxttouch.remote.RemoteClient;
import com.todotxt.todotxttouch.task.Priority;
import com.todotxt.todotxttouch.task.Task;
import com.todotxt.todotxttouch.task.TaskBag;
import com.todotxt.todotxttouch.util.Util;
public class AddTask extends SherlockActivity {
private final static String TAG = AddTask.class.getSimpleName();
private ProgressDialog m_ProgressDialog = null;
private Task m_backup;
private TodoApplication m_app;
private TaskBag taskBag;
private EditText textInputField;
private String share_text;
private ArrayList<String> mLists;
private ListView mDrawerList;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.add_task, menu);
if (hasDrawer()) {
menu.findItem(R.id.menu_add_tag).setVisible(false);
}
return true;
}
private void noteToSelf(Intent intent) {
String task = intent.getStringExtra(Intent.EXTRA_TEXT);
taskBag.addAsTask(task);
m_app.m_prefs.storeNeedToPush(true);
sendBroadcast(new Intent(Constants.INTENT_START_SYNC_TO_REMOTE));
m_app.showToast(R.string.taskadded);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.menu_save_task:
final String input = textInputField.getText().toString();
if (input.trim().equalsIgnoreCase("")) {
Util.showToastLong(this, R.string.add_empty_task);
} else {
addEditAsync(input);
}
break;
case R.id.menu_add_prio:
showPrioMenu(findViewById(R.id.menu_add_prio));
break;
case R.id.menu_add_tag:
showProjectContextMenu();
break;
}
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
m_app = (TodoApplication) getApplication();
// FIXME: save intent so we can come back after login
if (!isAuthenticated()) {
Intent i = new Intent(this, LoginScreen.class);
startActivity(i);
finish();
return;
}
taskBag = m_app.getTaskBag();
sendBroadcast(new Intent(Constants.INTENT_START_SYNC_WITH_REMOTE));
final Intent intent = getIntent();
final String action = intent.getAction();
// create shortcut and exit
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
Log.d(TAG, "Setting up shortcut icon");
setupShortcut();
finish();
return;
} else if (Intent.ACTION_SEND.equals(action)) {
Log.d(TAG, "Share");
share_text = (String) intent
.getCharSequenceExtra(Intent.EXTRA_TEXT);
Log.d(TAG, share_text);
} else if ("com.google.android.gm.action.AUTO_SEND".equals(action)) {
// Called as note to self from google search/now
noteToSelf(intent);
finish();
return;
}
// text
textInputField = (EditText) findViewById(R.id.taskText);
textInputField.setGravity(Gravity.TOP);
// Set up fortune hint text
Random rand = new Random();
int fortune_hint_index = Math.abs(rand.nextInt()) % 5;
int fortune_hint_text;
switch (fortune_hint_index) {
case 0:
fortune_hint_text = R.string.tasktexthint0;
break;
case 1:
fortune_hint_text = R.string.tasktexthint1;
break;
case 2:
fortune_hint_text = R.string.tasktexthint2;
break;
case 3:
fortune_hint_text = R.string.tasktexthint3;
break;
case 4:
fortune_hint_text = R.string.tasktexthint4;
break;
default:
fortune_hint_text = R.string.tasktexthint2;
}
textInputField.setHint(fortune_hint_text);
if (share_text != null) {
textInputField.setText(share_text);
}
Task iniTask = null;
Task task = (Task) getIntent().getSerializableExtra(
Constants.EXTRA_TASK);
if (task != null) {
m_backup = task;
iniTask = m_backup;
textInputField.setText(task.inFileFormat());
setTitle(R.string.updatetask);
} else {
setTitle(R.string.addtask);
if (textInputField.getText().length() == 0) {
@SuppressWarnings("unchecked")
ArrayList<Priority> prios = (ArrayList<Priority>) intent
.getSerializableExtra(Constants.EXTRA_PRIORITIES_SELECTED);
@SuppressWarnings("unchecked")
ArrayList<String> contexts = (ArrayList<String>) intent
.getSerializableExtra(Constants.EXTRA_CONTEXTS_SELECTED);
@SuppressWarnings("unchecked")
ArrayList<String> projects = (ArrayList<String>) intent
.getSerializableExtra(Constants.EXTRA_PROJECTS_SELECTED);
iniTask = new Task(1, "");
iniTask.initWithFilters(prios, contexts, projects);
}
}
if (hasDrawer()) {
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mLists = new ArrayList<String>();
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, R.id.left_drawer_text, mLists));
updateNavigationDrawer();
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
textInputField.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
updateNavigationDrawer();
return false;
}
});
}
textInputField.setSelection(textInputField.getText().toString()
.length());
textInputField.requestFocus();
}
private boolean isAuthenticated() {
RemoteClient remoteClient = m_app.getRemoteClientManager()
.getRemoteClient();
return remoteClient.isAuthenticated();
}
private void updateNavigationDrawer() {
mLists.clear();
mLists.addAll(labelsInTaskbagAndText());
((ArrayAdapter<?>) mDrawerList.getAdapter()).notifyDataSetChanged();
}
private void showProjectContextMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final ArrayList<String> labels = new ArrayList<String>();
labels.addAll(labelsInTaskbagAndText());
if (labels.size() == 0) {
onHelpClick();
return;
}
builder.setItems(labels.toArray(new String[0]), new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int which) {
replaceTextAtSelection(labels.get(which) + " ");
}
});
// Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.setTitle(R.string.addcontextproject);
dialog.show();
}
private void showPrioMenu(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final Priority[] priorities = Priority.values();
ArrayList<String> priorityCodes = new ArrayList<String>();
for (Priority prio : priorities) {
priorityCodes.add(prio.getCode());
}
builder.setItems(priorityCodes.toArray(new String[0]),
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int which) {
replacePriority(priorities[which].getCode());
}
});
// Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.setTitle(R.string.assignpriority);
dialog.show();
}
private void replacePriority(CharSequence newPrio) {
// save current selection and length
int start = textInputField.getSelectionStart();
int end = textInputField.getSelectionEnd();
int length = textInputField.getText().length();
int sizeDelta;
ArrayList<String> lines = new ArrayList<String>();
for (String line : textInputField.getText().toString()
.split("\\r\\n|\\r|\\n")) {
lines.add(line);
}
// figure out what task the cursor is on
CharSequence enteredText = textInputField.getText().toString();
CharSequence textToCursor = enteredText.subSequence(0, start);
ArrayList<String> linesBeforeCursor = new ArrayList<String>();
for (String line : textToCursor.toString().split("\\r\\n|\\r|\\n")) {
linesBeforeCursor.add(line);
}
int currentLine = 0;
if (linesBeforeCursor.size() > 0) {
currentLine = linesBeforeCursor.size() - 1;
}
Task t = new Task(0, lines.get(currentLine));
t.setPriority(Priority.toPriority(newPrio.toString()));
lines.set(currentLine, t.inFileFormat());
textInputField.setText(Util.join(lines, "\n"));
// restore selection
sizeDelta = textInputField.getText().length() - length;
textInputField.setSelection(start + sizeDelta, end + sizeDelta);
}
private void replaceTextAtSelection(CharSequence title) {
int start = textInputField.getSelectionStart();
int end = textInputField.getSelectionEnd();
if (start == end && start != 0) {
// no selection prefix with space if needed
if (!(textInputField.getText().charAt(start - 1) == ' ')) {
title = " " + title;
}
}
textInputField.getText().replace(Math.min(start, end),
Math.max(start, end), title, 0, title.length());
}
private void addEditAsync(final String input) {
new AsyncTask<Object, Void, Boolean>() {
protected void onPreExecute() {
m_ProgressDialog = ProgressDialog.show(AddTask.this,
getTitle(), "Please wait...", true);
}
@Override
protected Boolean doInBackground(Object... params) {
try {
Task task = (Task) params[0];
String input = (String) params[1];
if (task != null) {
input = input.replaceAll("\\r\\n|\\r|\\n", " ");
task.update(input);
taskBag.update(task);
} else {
for (String text : input.split("\\r\\n|\\r|\\n")) {
taskBag.addAsTask(text);
}
}
// make widgets update
m_app.broadcastWidgetUpdate();
return true;
} catch (Exception e) {
Log.e(TAG, "input: " + input + " - " + e.getMessage());
return false;
}
}
protected void onPostExecute(Boolean result) {
if (result) {
String res = m_backup != null ? getString(R.string.updated_task)
: getString(R.string.added_task);
Util.showToastLong(AddTask.this, res);
sendBroadcast(new Intent(
Constants.INTENT_START_SYNC_TO_REMOTE));
finish();
} else {
String res = m_backup != null ? getString(R.string.update_task_failed)
: getString(R.string.add_task_failed);
Util.showToastLong(AddTask.this, res);
}
m_ProgressDialog.dismiss();
}
}.execute(m_backup, input);
}
private void setupShortcut() {
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, this.getClass().getName());
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getString(R.string.shortcut_addtask_name));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this,
R.drawable.todotxt_touch_icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (m_ProgressDialog != null) {
m_ProgressDialog.dismiss();
}
}
/** Handle help message **/
public void onHelpClick() {
Intent intent = new Intent(getApplicationContext(), HelpActivity.class);
startActivity(intent);
}
private ArrayList<String> labelsInTaskbagAndText() {
/*
* Returns the defined labels in the taskbag and the current task being
* added. This way when adding multiple tasks labels from previous lines
* will be included as well
*/
ArrayList<String> labels = new ArrayList<String>();
Task temp = new Task(1, textInputField.getText().toString());
ArrayList<String> contexts = taskBag.getContexts(false);
contexts.addAll(temp.getContexts());
Collections.sort(contexts);
for (String item : contexts) {
labels.add("@" + item);
}
ArrayList<String> projects = taskBag.getProjects(false);
projects.addAll(temp.getProjects());
Collections.sort(projects);
for (String item : projects) {
labels.add("+" + item);
}
// Pass through a LinkedHashSet to remove duplicates without
// messing up sort order
return new ArrayList<String>(new LinkedHashSet<String>(labels));
}
/**
* Returns true if the left drawer is shown.
*/
private boolean hasDrawer() {
return findViewById(R.id.left_drawer) != null;
}
private class DrawerItemClickListener implements
AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView tv = (TextView) view.findViewById(R.id.left_drawer_text);
String itemTitle = tv.getText().toString();
Log.v(TAG, "Clicked on drawer " + itemTitle);
replaceTextAtSelection(itemTitle);
mDrawerList.clearChoices();
}
}
}
| gpl-3.0 |
LasseBP/overture | core/ast/src/main/java/org/overture/ast/typechecker/ClassDefinitionSettings.java | 875 | /*
* #%~
* The Overture Abstract Syntax Tree
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #~%
*/
package org.overture.ast.typechecker;
public enum ClassDefinitionSettings
{
UNSET, INPROGRESS, DONE
}
| gpl-3.0 |
mukadder/kc | coeus-impl/src/main/java/org/kuali/kra/protocol/auth/UnitAclLoadService.java | 1502 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.protocol.auth;
import org.kuali.coeus.common.framework.auth.perm.Permissionable;
/**
* This service loads the KraAuthorizationService with the proper access control list based on
* the documents unit. The document must implement the UnitAclLoadable interface in order to utilize this
* service.
*
* Administrators can maintain the access control list by assigning users to document roles within a
* specific unit.
*/
public interface UnitAclLoadService {
/**
* Loads the access control list of a specific unit into the document's authorization service.
*
*/
void loadUnitAcl(Permissionable permissionable, String creatorPrincipalId);
}
| agpl-3.0 |
sanjupolus/kc-coeus-1508.3 | coeus-impl/src/main/java/org/kuali/coeus/common/framework/auth/KcWorkflowDocumentAuthorizerBase.java | 6246 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.coeus.common.framework.auth;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kuali.coeus.common.framework.auth.perm.Permissionable;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.kim.bo.KcKimAttributes;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.impl.KimDocumentTypeAuthorizer;
import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class KcWorkflowDocumentAuthorizerBase extends KimDocumentTypeAuthorizer {
protected static final Log LOG = LogFactory.getLog(KcWorkflowDocumentAuthorizerBase.class);
private transient DocumentService documentService;
private transient BusinessObjectService businessObjectService;
/**
* Implements {@link org.kuali.rice.kew.doctype.service.DocumentTypePermissionService#canRecall(String, org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue)}
*/
@Override
public boolean canRecall(String principalId, DocumentRouteHeaderValue document) {
validatePrincipalId(principalId);
validateDocument(document);
String documentId = document.getDocumentId();
DocumentType documentType = document.getDocumentType();
String documentStatus = document.getDocRouteStatus();
String appDocStatus = document.getAppDocStatus();
List<String> routeNodeNames = document.getCurrentNodeNames();
validateDocumentType(documentType);
validateDocumentStatus(documentStatus);
// no need to validate appdocstatus, this is a free-form application defined value
// add appDocStatus to the details
List<Map<String, String>> permissionDetailList = buildDocumentTypePermissionDetailsForNodes(documentType, routeNodeNames, documentStatus, null);
if (!StringUtils.isBlank(appDocStatus)) {
for (Map<String, String> details: permissionDetailList) {
details.put(KewApiConstants.APP_DOC_STATUS_DETAIL, appDocStatus);
}
}
// loop over permission details, only one of them needs to be authorized
for (Map<String, String> permissionDetails : permissionDetailList) {
if (useKimPermission(KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, permissionDetails, false)) {
if (getPermissionService().isPermissionDefinedByTemplate(KewApiConstants.KEW_NAMESPACE, KewApiConstants.RECALL_PERMISSION, permissionDetails)) {
List<Map<String, String>> qualifierList = getSetsOfRoleQualifiers(document, permissionDetails.get(KewApiConstants.ROUTE_NODE_NAME_DETAIL));
for (Map<String, String> roleQualifiers : qualifierList) {
if (getPermissionService().isAuthorizedByTemplate(principalId, KewApiConstants.KEW_NAMESPACE,
KewApiConstants.RECALL_PERMISSION, permissionDetails, roleQualifiers)) {
return true;
}
}
}
}
}
return false;
}
protected List<Map<String, String>> getSetsOfRoleQualifiers(DocumentRouteHeaderValue document, String routeNodeName) {
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
Map<String, String> defaultQualifications = buildDocumentRoleQualifiers(document, routeNodeName);
result.add(defaultQualifications);
Permissionable permissionable = getPermissionable(document.getDocumentId());
if (permissionable != null) {
Map<String, String> docNbrQualifiers = new HashMap<String, String>();
docNbrQualifiers.put(permissionable.getDocumentKey(), permissionable.getDocumentNumberForPermission());
docNbrQualifiers.putAll(defaultQualifications);
result.add(docNbrQualifiers);
Map<String, String> unitNumberQualifiers = new HashMap<String, String>();
unitNumberQualifiers.put(KcKimAttributes.UNIT_NUMBER, permissionable.getLeadUnitNumber());
unitNumberQualifiers.putAll(defaultQualifications);
result.add(unitNumberQualifiers);
}
return result;
}
protected abstract Permissionable getPermissionable(String documentId);
public DocumentService getDocumentService() {
if (documentService == null) {
documentService = KcServiceLocator.getService(DocumentService.class);
}
return documentService;
}
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
public BusinessObjectService getBusinessObjectService() {
if (businessObjectService == null) {
businessObjectService = KcServiceLocator.getService(BusinessObjectService.class);
}
return businessObjectService;
}
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
}
| agpl-3.0 |
deerwalk/voltdb | third_party/java/src/com/google_voltpatches/common/cache/AbstractLoadingCache.java | 2706 | /*
* Copyright (C) 2011 The Guava 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 com.google_voltpatches.common.cache;
import com.google_voltpatches.common.annotations.GwtIncompatible;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.collect.Maps;
import com.google_voltpatches.common.util.concurrent.UncheckedExecutionException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* This class provides a skeletal implementation of the {@code Cache} interface to minimize the
* effort required to implement this interface.
*
* <p>To implement a cache, the programmer needs only to extend this class and provide an
* implementation for the {@link #get(Object)} and {@link #getIfPresent} methods.
* {@link #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in
* terms of {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent};
* {@link #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is
* implemented in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other
* methods throw an {@link UnsupportedOperationException}.
*
* @author Charles Fry
* @since 11.0
*/
@GwtIncompatible
public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V>
implements LoadingCache<K, V> {
/** Constructor for use by subclasses. */
protected AbstractLoadingCache() {}
@Override
public V getUnchecked(K key) {
try {
return get(key);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
Map<K, V> result = Maps.newLinkedHashMap();
for (K key : keys) {
if (!result.containsKey(key)) {
result.put(key, get(key));
}
}
return ImmutableMap.copyOf(result);
}
@Override
public final V apply(K key) {
return getUnchecked(key);
}
@Override
public void refresh(K key) {
throw new UnsupportedOperationException();
}
}
| agpl-3.0 |
jstourac/wildfly | webservices/server-integration/src/main/java/org/jboss/as/webservices/dmr/PropertyAdd.java | 4313 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.webservices.dmr;
import static org.jboss.as.webservices.dmr.PackageUtils.getConfigServiceName;
import static org.jboss.as.webservices.dmr.PackageUtils.getPropertyServiceName;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.webservices.logging.WSLogger;
import org.jboss.as.webservices.service.PropertyService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import java.util.function.Consumer;
/**
* @author <a href="mailto:alessio.soldano@jboss.com">Alessio Soldano</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
final class PropertyAdd extends AbstractAddStepHandler {
static final PropertyAdd INSTANCE = new PropertyAdd();
private PropertyAdd() {
// forbidden instantiation
}
@Override
protected void rollbackRuntime(OperationContext context, ModelNode operation, Resource resource) {
super.rollbackRuntime(context, operation, resource);
if (!context.isBooting()) {
context.revertReloadRequired();
}
}
@Override
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
//modify the runtime if we're booting, otherwise set reload required and leave the runtime unchanged
if (context.isBooting()) {
final PathAddress address = context.getCurrentAddress();
final String propertyName = context.getCurrentAddressValue();
final PathElement confElem = address.getElement(address.size() - 2);
final String configType = confElem.getKey();
final String configName = confElem.getValue();
final String propertyValue = Attributes.VALUE.resolveModelAttribute(context, model).asStringOrNull();
final ServiceTarget target = context.getServiceTarget();
final ServiceName configServiceName = getConfigServiceName(configType, configName);
if (context.getServiceRegistry(false).getService(configServiceName) == null) {
throw WSLogger.ROOT_LOGGER.missingConfig(configName);
}
final ServiceName propertyServiceName = getPropertyServiceName(configServiceName, propertyName);
final ServiceBuilder<?> propertyServiceBuilder = target.addService(propertyServiceName);
final Consumer<PropertyService> propertyServiceConsumer = propertyServiceBuilder.provides(propertyServiceName);
propertyServiceBuilder.setInstance(new PropertyService(propertyName, propertyValue, propertyServiceConsumer));
propertyServiceBuilder.install();
} else {
context.reloadRequired();
}
}
@Override
protected void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException {
Attributes.VALUE.validateAndSet(operation,model);
}
}
| lgpl-2.1 |
jolie/jolie | lib/xsom/src/main/java/com/sun/xml/xsom/impl/scd/SCDParserConstants.java | 1086 | /* Generated By:JavaCC: Do not edit this line. SCDParserConstants.java */
package com.sun.xml.xsom.impl.scd;
public interface SCDParserConstants {
int EOF = 0;
int NCNAME = 6;
int NUMBER = 7;
int FACETNAME = 8;
int DEFAULT = 0;
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\n\"",
"\"\\r\"",
"\"\\f\"",
"<NCNAME>",
"<NUMBER>",
"<FACETNAME>",
"\":\"",
"\"/\"",
"\"//\"",
"\"attribute::\"",
"\"@\"",
"\"element::\"",
"\"substitutionGroup::\"",
"\"type::\"",
"\"~\"",
"\"baseType::\"",
"\"primitiveType::\"",
"\"itemType::\"",
"\"memberType::\"",
"\"scope::\"",
"\"attributeGroup::\"",
"\"group::\"",
"\"identityContraint::\"",
"\"key::\"",
"\"notation::\"",
"\"model::sequence\"",
"\"model::choice\"",
"\"model::all\"",
"\"model::*\"",
"\"any::*\"",
"\"anyAttribute::*\"",
"\"facet::*\"",
"\"facet::\"",
"\"component::*\"",
"\"*\"",
"\"0\"",
};
}
| lgpl-2.1 |
jstourac/wildfly | clustering/marshalling/protostream/src/main/java/org/wildfly/clustering/marshalling/protostream/time/OffsetDateTimeMarshaller.java | 3704 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.marshalling.protostream.time;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import org.infinispan.protostream.descriptors.WireType;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter;
/**
* Marshaller for {@link OffsetDateTime} instances, using the following strategy:
* <ol>
* <li>Marshal local date</li>
* <li>Marshal local time</li>
* <li>Marshal zone offset</li>
* </ol>
* @author Paul Ferraro
*/
public class OffsetDateTimeMarshaller implements ProtoStreamMarshaller<OffsetDateTime> {
private static final int DATE_INDEX = 1;
private static final int TIME_INDEX = DATE_INDEX + LocalDateMarshaller.INSTANCE.getFields();
private static final int OFFSET_INDEX = TIME_INDEX + LocalTimeMarshaller.INSTANCE.getFields();
@Override
public OffsetDateTime readFrom(ProtoStreamReader reader) throws IOException {
LocalDate date = LocalDateMarshaller.INSTANCE.getBuilder();
LocalTime time = LocalTimeMarshaller.INSTANCE.getBuilder();
ZoneOffset offset = ZoneOffsetMarshaller.INSTANCE.getBuilder();
while (!reader.isAtEnd()) {
int tag = reader.readTag();
int index = WireType.getTagFieldNumber(tag);
if (index >= DATE_INDEX && index < TIME_INDEX) {
date = LocalDateMarshaller.INSTANCE.readField(reader, index - DATE_INDEX, date);
} else if (index >= TIME_INDEX && index < OFFSET_INDEX) {
time = LocalTimeMarshaller.INSTANCE.readField(reader, index - TIME_INDEX, time);
} else if (index >= OFFSET_INDEX && index < OFFSET_INDEX + ZoneOffsetMarshaller.INSTANCE.getFields()) {
offset = ZoneOffsetMarshaller.INSTANCE.readField(reader, index - OFFSET_INDEX, offset);
} else {
reader.skipField(tag);
}
}
return OffsetDateTime.of(date, time, offset);
}
@Override
public void writeTo(ProtoStreamWriter writer, OffsetDateTime value) throws IOException {
LocalDateMarshaller.INSTANCE.writeFields(writer, DATE_INDEX, value.toLocalDate());
LocalTimeMarshaller.INSTANCE.writeFields(writer, TIME_INDEX, value.toLocalTime());
ZoneOffsetMarshaller.INSTANCE.writeFields(writer, OFFSET_INDEX, value.getOffset());
}
@Override
public Class<? extends OffsetDateTime> getJavaClass() {
return OffsetDateTime.class;
}
}
| lgpl-2.1 |
JoeCarlson/intermine | intermine/web/main/src/org/intermine/webservice/server/query/CodeService.java | 9263 | package org.intermine.webservice.server.query;
/*
* Copyright (C) 2002-2016 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.codegen.WebserviceCodeGenInfo;
import org.intermine.api.query.codegen.WebserviceCodeGenerator;
import org.intermine.api.query.codegen.WebserviceJavaCodeGenerator;
import org.intermine.api.query.codegen.WebserviceJavaScriptCodeGenerator;
import org.intermine.api.query.codegen.WebservicePerlCodeGenerator;
import org.intermine.api.query.codegen.WebservicePythonCodeGenerator;
import org.intermine.api.query.codegen.WebserviceRubyCodeGenerator;
import org.intermine.api.tag.TagNames;
import org.intermine.api.tag.TagTypes;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.export.ResponseUtil;
import org.intermine.web.util.URLGenerator;
import org.intermine.webservice.server.Format;
import org.intermine.webservice.server.exceptions.BadRequestException;
import org.intermine.webservice.server.output.JSONFormatter;
import org.intermine.webservice.server.query.result.PathQueryBuilder;
import org.json.JSONObject;
/**
* A service for generating code based on a query.
* @author Alex Kalderimis
*
*/
public class CodeService extends AbstractQueryService
{
protected static final Logger LOG = Logger.getLogger(CodeService.class);
private String perlModuleVersion;
private static final String PERL_MODULE_URI =
"http://api.metacpan.org/v0/module/Webservice::InterMine";
/**
* Constructor.
* @param im The InterMine application object.
*/
public CodeService(InterMineAPI im) {
super(im);
}
@Override
protected Format getDefaultFormat() {
return Format.TEXT;
}
@Override
protected boolean canServe(Format format) {
switch (format) {
case JSON:
return true;
case TEXT:
return true;
default:
return false;
}
}
@Override
protected String getDefaultFileName() {
return "query";
}
@Override
protected String getExtension() {
String extension = super.getExtension();
String lang = request.getParameter("lang");
if ("perl".equals(lang) || "pl".equals(lang)) {
return ".pl" + extension;
} else if ("java".equals(lang)) {
return ".java" + extension;
} else if ("python".equals(lang) || "py".equals(lang)) {
return ".py" + extension;
} else if ("javascript".equals(lang) || "js".equals(lang)) {
return ".html" + extension;
} else if ("ruby".equals(lang) || "rb".equals(lang)) {
return ".rb" + extension;
} else {
throw new BadRequestException("Unknown code generation language: " + lang);
}
}
private WebserviceCodeGenerator getCodeGenerator(String lang) {
lang = StringUtils.lowerCase(lang);
// Ordered by expected popularity.
if ("js".equals(lang) || "javascript".equals(lang)) {
return new WebserviceJavaScriptCodeGenerator();
} else if ("py".equals(lang) || "python".equals(lang)) {
return new WebservicePythonCodeGenerator();
} else if ("java".equals(lang)) {
return new WebserviceJavaCodeGenerator();
} else if ("pl".equals(lang) || "perl".equals(lang)) {
return new WebservicePerlCodeGenerator();
} else if ("rb".equals(lang) || "ruby".equals(lang)) {
return new WebserviceRubyCodeGenerator();
} else {
throw new BadRequestException("Unknown code generation language: " + lang);
}
}
@Override
protected void execute() {
Profile profile = getPermission().getProfile();
// Ref to OrthologueLinkController and OrthologueLinkManager
String serviceBaseURL = new URLGenerator(request).getPermanentBaseURL();
// set in project properties
String projectTitle = webProperties.getProperty("project.title");
// set in global.web.properties
String perlWSModuleVer = getPerlModuleVersion();
String lang = request.getParameter("lang");
PathQuery pq = getPathQuery();
String name = pq.getTitle() != null ? pq.getTitle() : "query";
String fileName = name.replaceAll("[^a-zA-Z0-9_,.()-]", "_") + getExtension();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
WebserviceCodeGenInfo info = new WebserviceCodeGenInfo(
pq,
serviceBaseURL,
projectTitle,
perlWSModuleVer,
pathQueryIsPublic(pq, im, profile),
profile,
getLineBreak());
info.readWebProperties(webProperties);
WebserviceCodeGenerator codeGen = getCodeGenerator(lang);
String sc = codeGen.generate(info);
if (formatIsJSON()) {
ResponseUtil.setJSONHeader(response, "querycode.json");
Map<String, Object> attributes = new HashMap<String, Object>();
if (formatIsJSONP()) {
String callback = getCallback();
if (callback == null || "".equals(callback)) {
callback = DEFAULT_CALLBACK;
}
attributes.put(JSONFormatter.KEY_CALLBACK, callback);
}
attributes.put(JSONFormatter.KEY_INTRO, "\"code\":");
attributes.put(JSONFormatter.KEY_OUTRO, "");
output.setHeaderAttributes(attributes);
// Oddly, here escape Java is correct, not escapeJavaScript.
// This is due to syntax errors thrown by escaped single quotes.
sc = "\"" + StringEscapeUtils.escapeJava(sc) + "\"";
}
output.addResultItem(Arrays.asList(sc));
}
private String getPerlModuleVersion() {
if (perlModuleVersion == null) {
BufferedReader reader = null;
try {
URL url = new URL(PERL_MODULE_URI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "InterMine-" + Constants.WEB_SERVICE_VERSION);
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
return null;
}
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer body = new StringBuffer();
while ((line = reader.readLine()) != null) {
body.append(line);
}
String json = body.toString();
JSONObject data = new JSONObject(json);
perlModuleVersion = data.getString("version");
} catch (Exception e) {
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
return perlModuleVersion;
}
/**
* Utility function to determine whether the PathQuery is publicly accessible.
* PathQueries are accessibly publicly as long as they do not reference
* private lists.
* @param pq The query to interrogate
* @param im A reference to the InterMine API
* @param p A user's profile
* @return whether the query is accessible publicly or not
*/
protected static boolean pathQueryIsPublic(PathQuery pq, InterMineAPI im, Profile p) {
Set<String> listNames = pq.getBagNames();
TagManager tm = im.getTagManager();
for (String name: listNames) {
Set<String> tags = tm.getObjectTagNames(name, TagTypes.BAG, p.getUsername());
if (!tags.contains(TagNames.IM_PUBLIC)) {
return false;
}
}
return true;
}
private PathQuery getPathQuery() {
String xml = new QueryRequestParser(im.getQueryStore(), request).getQueryXml();
PathQueryBuilder pqb = getQueryBuilder(xml);
PathQuery query = pqb.getQuery();
return query;
}
}
| lgpl-2.1 |
bluenote10/TuxguitarParser | tuxguitar-src/TuxGuitar-editor-utils/src/org/herac/tuxguitar/editor/action/note/TGInsertRestBeatAction.java | 1550 | package org.herac.tuxguitar.editor.action.note;
import org.herac.tuxguitar.action.TGActionContext;
import org.herac.tuxguitar.document.TGDocumentContextAttributes;
import org.herac.tuxguitar.editor.action.TGActionBase;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGMeasure;
import org.herac.tuxguitar.song.models.TGVoice;
import org.herac.tuxguitar.util.TGContext;
public class TGInsertRestBeatAction extends TGActionBase {
public static final String NAME = "action.beat.general.insert-rest";
public TGInsertRestBeatAction(TGContext context) {
super(context, NAME);
}
protected void processAction(TGActionContext context){
TGBeat beat = ((TGBeat) context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_BEAT));
TGVoice voice = ((TGVoice) context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_VOICE));
TGDuration duration = ((TGDuration) context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_DURATION));
TGMeasure measure = ((TGMeasure) context.getAttribute(TGDocumentContextAttributes.ATTRIBUTE_MEASURE));
if( voice.isEmpty() ){
getSongManager(context).getMeasureManager().addSilence(beat, duration.clone(getSongManager(context).getFactory()), voice.getIndex());
}
else {
long start = beat.getStart();
long length = voice.getDuration().getTime();
getSongManager(context).getMeasureManager().moveVoices(measure, start, length, voice.getIndex(), beat.getVoice(voice.getIndex()).getDuration());
}
}
}
| lgpl-2.1 |
iceman11a/CoFHLib | src/main/java/cofh/lib/gui/slot/SlotCustomInventory.java | 1865 | package cofh.lib.gui.slot;
import cofh.api.core.ICustomInventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class SlotCustomInventory extends Slot {
ICustomInventory customInv;
int inventoryIndex = 0;
boolean canTake = true;
public SlotCustomInventory(ICustomInventory tile, int invIndex, IInventory inventory, int slotIndex, int x, int y, boolean lootable) {
super(inventory, slotIndex, x, y);
customInv = tile;
inventoryIndex = invIndex;
canTake = lootable;
}
@Override
public ItemStack getStack() {
return customInv.getInventorySlots(inventoryIndex)[getSlotIndex()];
}
@Override
public void putStack(ItemStack stack) {
customInv.getInventorySlots(inventoryIndex)[getSlotIndex()] = stack;
onSlotChanged();
}
@Override
public void onSlotChanged() {
customInv.onSlotUpdate();
}
@Override
public int getSlotStackLimit() {
return customInv.getSlotStackLimit(getSlotIndex());
}
@Override
public ItemStack decrStackSize(int amount) {
if (customInv.getInventorySlots(inventoryIndex)[getSlotIndex()] == null) {
return null;
}
if (customInv.getInventorySlots(inventoryIndex)[getSlotIndex()].stackSize <= amount) {
amount = customInv.getInventorySlots(inventoryIndex)[getSlotIndex()].stackSize;
}
ItemStack stack = customInv.getInventorySlots(inventoryIndex)[getSlotIndex()].splitStack(amount);
if (customInv.getInventorySlots(inventoryIndex)[getSlotIndex()].stackSize <= 0) {
customInv.getInventorySlots(inventoryIndex)[getSlotIndex()] = null;
}
return stack;
}
@Override
public boolean isSlotInInventory(IInventory inventory, int slot) {
return false;
}
@Override
public boolean canTakeStack(EntityPlayer par1EntityPlayer) {
return canTake;
}
}
| lgpl-3.0 |
OldRepoPreservation/jgentle | src/org/jgentleframework/utils/ObjectClassUtils.java | 39884 | /*
* Copyright 2007-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Project: JGentleFramework
*/
package org.jgentleframework.utils;
import java.beans.Introspector;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Miscellaneous class utility methods. Mainly for internal use within the
* framework; consider Jakarta's Commons Lang for a more comprehensive suite of
* class utilities.
*
* @author Quoc Chung - mailto: <a
* href="mailto:skydunkpro@yahoo.com">skydunkpro@yahoo.com</a>
* @date Feb 10, 2009
*/
public final class ObjectClassUtils {
/** Suffix for array class names: "[]". */
public static final String ARRAY_SUFFIX = "[]";
/** Prefix for internal array class names: "[L". */
private static final String INTERNAL_ARRAY_PREFIX = "[L";
/** The package separator character '.' */
private static final char PACKAGE_SEPARATOR = '.';
/** The inner class separator character '$'. */
private static final char INNER_CLASS_SEPARATOR = '$';
/** The CGLIB class separator character "$$". */
public static final String CGLIB_CLASS_SEPARATOR = "$$";
/** The ".class" file suffix */
public static final String CLASS_FILE_SUFFIX = ".class";
/**
* Map with primitive wrapper type as key and corresponding primitive type
* as value, for example: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<Class<?>, Class<?>>(
8);
/**
* Map with primitive type name as key and corresponding primitive type as
* value, for example: "int" -> "int.class".
*/
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap<String, Class<?>>(
16);
static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);
Set<Class<?>> primitiveTypeNames = new HashSet<Class<?>>(16);
primitiveTypeNames.addAll(primitiveWrapperTypeMap.values());
primitiveTypeNames.addAll(Arrays.asList(new Class<?>[] {
boolean[].class, byte[].class, char[].class, double[].class,
float[].class, int[].class, long[].class, short[].class }));
for (Iterator<Class<?>> it = primitiveTypeNames.iterator(); it
.hasNext();) {
Class<?> primitiveClass = it.next();
primitiveTypeNameMap.put(primitiveClass.getName(), primitiveClass);
}
}
/**
* Return the default ClassLoader to use: typically the thread context
* ClassLoader, if available; the ClassLoader that loaded the
* ObjectClassUtils class will be used as fallback.
* <p>
* Call this method if you intend to use the thread context ClassLoader in a
* scenario where you absolutely need a non-null ClassLoader reference: for
* example, for class path resource loading (but not necessarily for
* <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader
* reference as well).
*
* @return the default ClassLoader (never <code>null</code>)
* @see java.lang.Thread#getContextClassLoader()
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system
// class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ObjectClassUtils.class.getClassLoader();
}
return cl;
}
/**
* Override the thread context ClassLoader with the environment's bean
* ClassLoader if necessary, i.e. if the bean ClassLoader is not equivalent
* to the thread context ClassLoader already.
*
* @param classLoaderToUse
* the actual ClassLoader to use for the thread context
* @return the original thread context ClassLoader, or <code>null</code> if
* not overridden
*/
public static ClassLoader overrideThreadContextClassLoader(
ClassLoader classLoaderToUse) {
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread
.getContextClassLoader();
if (classLoaderToUse != null
&& !classLoaderToUse.equals(threadContextClassLoader)) {
currentThread.setContextClassLoader(classLoaderToUse);
return threadContextClassLoader;
}
else {
return null;
}
}
/**
* Replacement for <code>Class.forName()</code> that also returns Class
* instances for primitives (like "int") and array class names (like
* "String[]").
* <p>
* Always uses the default class loader: that is, preferably the thread
* context class loader, or the ClassLoader that loaded the ObjectClassUtils
* class as fallback.
*
* @param name
* the name of the Class
* @return Class instance for the supplied name
* @throws ClassNotFoundException
* if the class was not found
* @throws LinkageError
* if the class file could not be loaded
* @see Class#forName(String, boolean, ClassLoader)
* @see #getDefaultClassLoader()
*/
public static Class<?> forName(String name) throws ClassNotFoundException,
LinkageError {
return forName(name, getDefaultClassLoader());
}
/**
* Replacement for <code>Class.forName()</code> that also returns Class
* instances for primitives (like "int") and array class names (like
* "String[]").
*
* @param name
* the name of the Class
* @param classLoader
* the class loader to use (may be <code>null</code>, which
* indicates the default class loader)
* @return Class instance for the supplied name
* @throws ClassNotFoundException
* if the class was not found
* @throws LinkageError
* if the class file could not be loaded
* @see Class#forName(String, boolean, ClassLoader)
*/
public static Class<?> forName(String name, ClassLoader classLoader)
throws ClassNotFoundException, LinkageError {
Assertor.notNull(name, "Name must not be null");
Class<?> clazz = resolvePrimitiveClassName(name);
if (clazz != null) {
return clazz;
}
// "java.lang.String[]" style arrays
if (name.endsWith(ARRAY_SUFFIX)) {
String elementClassName = name.substring(0, name.length()
- ARRAY_SUFFIX.length());
Class<?> elementClass = forName(elementClassName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[Ljava.lang.String;" style arrays
int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX);
if (internalArrayMarker != -1 && name.endsWith(";")) {
String elementClassName = null;
if (internalArrayMarker == 0) {
elementClassName = name.substring(INTERNAL_ARRAY_PREFIX
.length(), name.length() - 1);
}
else if (name.startsWith("[")) {
elementClassName = name.substring(1);
}
Class<?> elementClass = forName(elementClassName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = getDefaultClassLoader();
}
return classLoaderToUse.loadClass(name);
}
/**
* Resolve the given class name into a Class instance. Supports primitives
* (like "int") and array class names (like "String[]").
* <p>
* This is effectively equivalent to the <code>forName</code> method with
* the same arguments, with the only difference being the exceptions thrown
* in case of class loading failure.
*
* @param className
* the name of the Class
* @param classLoader
* the class loader to use (may be <code>null</code>, which
* indicates the default class loader)
* @return Class instance for the supplied name
* @throws IllegalArgumentException
* if the class name was not resolvable (that is, the class
* could not be found or the class file could not be loaded)
* @see #forName(String, ClassLoader)
*/
public static Class<?> resolveClassName(String className,
ClassLoader classLoader) throws IllegalArgumentException {
try {
return forName(className, classLoader);
}
catch (ClassNotFoundException ex) {
IllegalArgumentException iae = new IllegalArgumentException(
"Cannot find class [" + className + "]");
iae.initCause(ex);
throw iae;
}
catch (LinkageError ex) {
IllegalArgumentException iae = new IllegalArgumentException(
"Error loading class [" + className
+ "]: problem with class file or dependent class.");
iae.initCause(ex);
throw iae;
}
}
/**
* Resolve the given class name as primitive class, if appropriate,
* according to the JVM's naming rules for primitive classes.
* <p>
* Also supports the JVM's internal class names for primitive arrays. Does
* <i>not</i> support the "[]" suffix notation for primitive arrays; this is
* only supported by {@link #forName}.
*
* @param name
* the name of the potentially primitive class
* @return the primitive class, or <code>null</code> if the name does not
* denote a primitive class or primitive array class
*/
public static Class<?> resolvePrimitiveClassName(String name) {
Class<?> result = null;
// Most class names will be quite long, considering that they
// SHOULD sit in a package, so a length check is worthwhile.
if (name != null && name.length() <= 8) {
// Could be a primitive - likely.
result = (Class<?>) primitiveTypeNameMap.get(name);
}
return result;
}
/**
* Determine whether the {@link Class} identified by the supplied name is
* present and can be loaded. Will return <code>false</code> if either the
* class or one of its dependencies is not present or cannot be loaded.
*
* @param className
* the name of the class to check
* @param classLoader
* the class loader to use (may be <code>null</code>, which
* indicates the default class loader)
* @return whether the specified class is present
*/
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
}
catch (Throwable ex) {
// Class or one of its dependencies is not present...
return false;
}
}
/**
* Return the user-defined class for the given instance: usually simply the
* class of the given instance, but the original class in case of a
* CGLIB-generated subclass.
*
* @param instance
* the instance to check
* @return the user-defined class
*/
public static Class<?> getUserClass(Object instance) {
Assertor.notNull(instance, "Instance must not be null");
return getUserClass(instance.getClass());
}
/**
* Return the user-defined class for the given class: usually simply the
* given class, but the original class in case of a CGLIB-generated
* subclass.
*
* @param clazz
* the class to check
* @return the user-defined class
*/
public static Class<?> getUserClass(Class<?> clazz) {
return (clazz != null
&& clazz.getName().indexOf(CGLIB_CLASS_SEPARATOR) != -1 ? clazz
.getSuperclass() : clazz);
}
/**
* Check whether the given class is cache-safe in the given context, i.e.
* whether it is loaded by the given ClassLoader or a parent of it.
*
* @param clazz
* the class to analyze
* @param classLoader
* the ClassLoader to potentially cache metadata in
* @return true, if checks if is cache safe
*/
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
Assertor.notNull(clazz, "Class must not be null");
ClassLoader target = clazz.getClassLoader();
if (target == null) {
return false;
}
ClassLoader cur = classLoader;
if (cur == target) {
return true;
}
while (cur != null) {
cur = cur.getParent();
if (cur == target) {
return true;
}
}
return false;
}
/**
* Get the class name without the qualified package name.
*
* @param className
* the className to get the short name for
* @return the class name of the class without the package name
* @throws IllegalArgumentException
* if the className is empty
*/
public static String getShortName(String className) {
Assertor.hasLength(className, "Class name must not be empty");
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
if (nameEndIndex == -1) {
nameEndIndex = className.length();
}
String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
return shortName;
}
/**
* Get the class name without the qualified package name.
*
* @param clazz
* the class to get the short name for
* @return the class name of the class without the package name
*/
public static String getShortName(Class<?> clazz) {
return getShortName(getQualifiedName(clazz));
}
/**
* Return the short string name of a Java class in decapitalized JavaBeans
* property format. Strips the outer class name in case of an inner class.
*
* @param clazz
* the class
* @return the short name rendered in a standard JavaBeans property format
* @see java.beans.Introspector#decapitalize(String)
*/
public static String getShortNameAsProperty(Class<?> clazz) {
String shortName = ObjectClassUtils.getShortName(clazz);
int dotIndex = shortName.lastIndexOf('.');
shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1)
: shortName);
return Introspector.decapitalize(shortName);
}
/**
* Determine the name of the class file, relative to the containing package:
* e.g. "String.class"
*
* @param clazz
* the class
* @return the file name of the ".class" file
*/
public static String getClassFileName(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;
}
/**
* Determine the name of the package of the given class: e.g. "java.lang"
* for the <code>java.lang.String</code> class.
*
* @param clazz
* the class
* @return the package name, or the empty String if the class is defined in
* the default package
*/
public static String getPackageName(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return (lastDotIndex != -1 ? className.substring(0, lastDotIndex) : "");
}
/**
* Return the qualified name of the given class: usually simply the class
* name, but component type class name + "[]" for arrays.
*
* @param clazz
* the class
* @return the qualified name of the class
*/
public static String getQualifiedName(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
/**
* Build a nice qualified name for an array: component type class name +
* "[]".
*
* @param clazz
* the array class
* @return a qualified name for the array class
*/
private static String getQualifiedNameForArray(Class<?> clazz) {
StringBuffer buffer = new StringBuffer();
while (clazz.isArray()) {
clazz = clazz.getComponentType();
buffer.append(ObjectClassUtils.ARRAY_SUFFIX);
}
buffer.insert(0, clazz.getName());
return buffer.toString();
}
/**
* Return the qualified name of the given method, consisting of fully
* qualified interface/class name + "." + method name.
*
* @param method
* the method
* @return the qualified name of the method
*/
public static String getQualifiedMethodName(Method method) {
Assertor.notNull(method, "Method must not be null");
return method.getDeclaringClass().getName() + "." + method.getName();
}
/**
* Return a descriptive name for the given object's type: usually simply the
* class name, but component type class name + "[]" for arrays, and an
* appended list of implemented interfaces for JDK proxies.
*
* @param value
* the value to introspect
* @return the qualified name of the class
*/
public static String getDescriptiveType(Object value) {
if (value == null) {
return null;
}
Class<?> clazz = value.getClass();
if (Proxy.isProxyClass(clazz)) {
StringBuffer buf = new StringBuffer(clazz.getName());
buf.append(" implementing ");
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
buf.append(ifcs[i].getName());
if (i < ifcs.length - 1) {
buf.append(',');
}
}
return buf.toString();
}
else if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
/**
* Determine whether the given class has a constructor with the given
* signature.
* <p>
* Essentially translates <code>NoSuchMethodException</code> to "false".
*
* @param clazz
* the clazz to analyze
* @param paramTypes
* the parameter types of the method
* @return whether the class has a corresponding constructor
* @see java.lang.Class#getMethod
*/
public static boolean hasConstructor(Class<?> clazz, Class<?>[] paramTypes) {
return (getConstructorIfAvailable(clazz, paramTypes) != null);
}
/**
* Determine whether the given class has a constructor with the given
* signature, and return it if available (else return <code>null</code>).
* <p>
* Essentially translates <code>NoSuchMethodException</code> to
* <code>null</code>.
*
* @param clazz
* the clazz to analyze
* @param paramTypes
* the parameter types of the method
* @return the constructor, or <code>null</code> if not found
* @see java.lang.Class#getConstructor
*/
public static Constructor<?> getConstructorIfAvailable(Class<?> clazz,
Class<?>[] paramTypes) {
Assertor.notNull(clazz, "Class must not be null");
try {
return clazz.getConstructor(paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Determine whether the given class has a method with the given signature.
* <p>
* Essentially translates <code>NoSuchMethodException</code> to "false".
*
* @param clazz
* the clazz to analyze
* @param methodName
* the name of the method
* @param paramTypes
* the parameter types of the method
* @return whether the class has a corresponding method
* @see java.lang.Class#getMethod
*/
public static boolean hasMethod(Class<?> clazz, String methodName,
Class<?>[] paramTypes) {
return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
}
/**
* Determine whether the given class has a method with the given signature,
* and return it if available (else return <code>null</code>).
* <p>
* Essentially translates <code>NoSuchMethodException</code> to
* <code>null</code>.
*
* @param clazz
* the clazz to analyze
* @param methodName
* the name of the method
* @param paramTypes
* the parameter types of the method
* @return the method, or <code>null</code> if not found
* @see java.lang.Class#getMethod
*/
public static Method getMethodIfAvailable(Class<?> clazz,
String methodName, Class<?>[] paramTypes) {
Assertor.notNull(clazz, "Class must not be null");
Assertor.notNull(methodName, "Method name must not be null");
try {
return clazz.getMethod(methodName, paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Return the number of methods with a given name (with any argument types),
* for the given class and/or its superclasses. Includes non-public methods.
*
* @param clazz
* the clazz to check
* @param methodName
* the name of the method
* @return the number of methods with the given name
*/
public static int getMethodCountForName(Class<?> clazz, String methodName) {
Assertor.notNull(clazz, "Class must not be null");
Assertor.notNull(methodName, "Method name must not be null");
int count = 0;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
Method method = declaredMethods[i];
if (methodName.equals(method.getName())) {
count++;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
count += getMethodCountForName(ifcs[i], methodName);
}
if (clazz.getSuperclass() != null) {
count += getMethodCountForName(clazz.getSuperclass(), methodName);
}
return count;
}
/**
* Does the given class and/or its superclasses at least have one or more
* methods (with any argument types)? Includes non-public methods.
*
* @param clazz
* the clazz to check
* @param methodName
* the name of the method
* @return whether there is at least one method with the given name
*/
public static boolean hasAtLeastOneMethodWithName(Class<?> clazz,
String methodName) {
Assertor.notNull(clazz, "Class must not be null");
Assertor.notNull(methodName, "Method name must not be null");
Method[] declaredMethods = clazz.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
Method method = declaredMethods[i];
if (method.getName().equals(methodName)) {
return true;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
if (hasAtLeastOneMethodWithName(ifcs[i], methodName)) {
return true;
}
}
return (clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(
clazz.getSuperclass(), methodName));
}
/**
* Given a method, which may come from an interface, and a target class used
* in the current reflective invocation, find the corresponding target
* method if there is one. E.g. the method may be <code>IFoo.bar()</code>
* and the target class may be <code>DefaultFoo</code>. In this case, the
* method may be <code>DefaultFoo.bar()</code>. This enables attributes on
* that method to be found.
*
* @param method
* the method to be invoked, which may come from an interface
* @param targetClass
* the target class for the current invocation. May be
* <code>null</code> or may not even implement the method.
* @return the specific target method, or the original method if the
* <code>targetClass</code> doesn't implement it or is
* <code>null</code>
*/
public static Method getMostSpecificMethod(Method method,
Class<?> targetClass) {
if (method != null && targetClass != null
&& !targetClass.equals(method.getDeclaringClass())) {
try {
method = targetClass.getMethod(method.getName(), method
.getParameterTypes());
}
catch (NoSuchMethodException ex) {
// Perhaps the target class doesn't implement this method:
// that's fine, just use the original method.
}
}
return method;
}
/**
* Return a static method of a class.
*
* @param methodName
* the static method name
* @param clazz
* the class which defines the method
* @param args
* the parameter types to the method
* @return the static method, or <code>null</code> if no static method was
* found
* @throws IllegalArgumentException
* if the method name is blank or the clazz is null
*/
public static Method getStaticMethod(Class<?> clazz, String methodName,
Class<?>[] args) {
Assertor.notNull(clazz, "Class must not be null");
Assertor.notNull(methodName, "Method name must not be null");
try {
Method method = clazz.getDeclaredMethod(methodName, args);
if ((method.getModifiers() & Modifier.STATIC) != 0) {
return method;
}
}
catch (NoSuchMethodException ex) {
}
return null;
}
/**
* Check if the given class represents a primitive wrapper, i.e. Boolean,
* Byte, Character, Short, Integer, Long, Float, or Double.
*
* @param clazz
* the class to check
* @return whether the given class is a primitive wrapper class
*/
public static boolean isPrimitiveWrapper(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
return primitiveWrapperTypeMap.containsKey(clazz);
}
/**
* Check if the given class represents a primitive (i.e. boolean, byte,
* char, short, int, long, float, or double) or a primitive wrapper (i.e.
* Boolean, Byte, Character, Short, Integer, Long, Float, or Double).
*
* @param clazz
* the class to check
* @return whether the given class is a primitive or primitive wrapper class
*/
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}
/**
* Check if the given class represents an array of primitives, i.e. boolean,
* byte, char, short, int, long, float, or double.
*
* @param clazz
* the class to check
* @return whether the given class is a primitive array class
*/
public static boolean isPrimitiveArray(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
return (clazz.isArray() && clazz.getComponentType().isPrimitive());
}
/**
* Check if the given class represents an array of primitive wrappers, i.e.
* Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
*
* @param clazz
* the class to check
* @return whether the given class is a primitive wrapper array class
*/
public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
Assertor.notNull(clazz, "Class must not be null");
return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
}
/**
* Check if the right-hand side type may be assigned to the left-hand side
* type, assuming setting by reflection. Considers primitive wrapper classes
* as assignable to the corresponding primitive types.
*
* @param lhsType
* the target type
* @param rhsType
* the value type that should be assigned to the target type
* @return if the target type is assignable from the value type
*/
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Assertor.notNull(lhsType, "Left-hand side type must not be null");
Assertor.notNull(rhsType, "Right-hand side type must not be null");
return (lhsType.isAssignableFrom(rhsType) || lhsType
.equals(primitiveWrapperTypeMap.get(rhsType)));
}
/**
* Determine if the given type is assignable from the given value, assuming
* setting by reflection. Considers primitive wrapper classes as assignable
* to the corresponding primitive types.
*
* @param type
* the target type
* @param value
* the value that should be assigned to the type
* @return if the type is assignable from the value
*/
public static boolean isAssignableValue(Class<?> type, Object value) {
Assertor.notNull(type, "Type must not be null");
return (value != null ? isAssignable(type, value.getClass()) : !type
.isPrimitive());
}
/**
* Convert a "/"-based resource path to a "."-based fully qualified class
* name.
*
* @param resourcePath
* the resource path pointing to a class
* @return the corresponding fully qualified class name
*/
public static String convertResourcePathToClassName(String resourcePath) {
return resourcePath.replace('/', '.');
}
/**
* Convert a "."-based fully qualified class name to a "/"-based resource
* path.
*
* @param className
* the fully qualified class name
* @return the corresponding resource path, pointing to the class
*/
public static String convertClassNameToResourcePath(String className) {
return className.replace('.', '/');
}
/**
* Return a path suitable for use with <code>ClassLoader.getResource</code>
* (also suitable for use with <code>Class.getResource</code> by prepending
* a slash ('/') to the return value. Built by taking the package of the
* specified class file, converting all dots ('.') to slashes ('/'), adding
* a trailing slash if necesssary, and concatenating the specified resource
* name to this. <br/>
*
* @param clazz
* the Class whose package will be used as the base
* @param resourceName
* the resource name to append. A leading slash is optional.
* @return the built-up resource path
* @see java.lang.ClassLoader#getResource
* @see java.lang.Class#getResource
*/
public static String addResourcePathToPackagePath(Class<?> clazz,
String resourceName) {
Assertor.notNull(resourceName, "Resource name must not be null");
if (!resourceName.startsWith("/")) {
return classPackageAsResourcePath(clazz) + "/" + resourceName;
}
return classPackageAsResourcePath(clazz) + resourceName;
}
/**
* Given an input class object, return a string which consists of the
* class's package name as a pathname, i.e., all dots ('.') are replaced by
* slashes ('/'). Neither a leading nor trailing slash is added. The result
* could be concatenated with a slash and the name of a resource, and fed
* directly to <code>ClassLoader.getResource()</code>. For it to be fed to
* <code>Class.getResource</code> instead, a leading slash would also have
* to be prepended to the returned value.
*
* @param clazz
* the input class. A <code>null</code> value or the default
* (empty) package will result in an empty string ("") being
* returned.
* @return a path which represents the package name
* @see ClassLoader#getResource
* @see Class#getResource
*/
public static String classPackageAsResourcePath(Class<?> clazz) {
if (clazz == null) {
return "";
}
String className = clazz.getName();
int packageEndIndex = className.lastIndexOf('.');
if (packageEndIndex == -1) {
return "";
}
String packageName = className.substring(0, packageEndIndex);
return packageName.replace('.', '/');
}
/**
* Build a String that consists of the names of the classes/interfaces in
* the given array.
* <p>
* Basically like <code>AbstractCollection.toString()</code>, but stripping
* the "class "/"interface " prefix before every class name.
*
* @param classes
* a Collection of Class objects (may be <code>null</code>)
* @return a String of form "[com.foo.Bar, com.foo.Baz]"
* @see java.util.AbstractCollection#toString()
*/
public static String classNamesToString(Class<?>[] classes) {
return classNamesToString(Arrays.asList(classes));
}
/**
* Build a String that consists of the names of the classes/interfaces in
* the given collection.
* <p>
* Basically like <code>AbstractCollection.toString()</code>, but stripping
* the "class "/"interface " prefix before every class name.
*
* @param classes
* a Collection of Class objects (may be <code>null</code>)
* @return a String of form "[com.foo.Bar, com.foo.Baz]"
* @see java.util.AbstractCollection#toString()
*/
public static String classNamesToString(Collection<?> classes) {
if (CollectionUtils.isEmpty(classes)) {
return "[]";
}
StringBuffer sb = new StringBuffer("[");
for (Iterator<?> it = classes.iterator(); it.hasNext();) {
Class<?> clazz = (Class<?>) it.next();
sb.append(clazz.getName());
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
/**
* Return all interfaces that the given instance implements as array,
* including ones implemented by superclasses.
*
* @param instance
* the instance to analyse for interfaces
* @return all interfaces that the given instance implements as array
*/
public static Class<?>[] getAllInterfaces(Object instance) {
Assertor.notNull(instance, "Instance must not be null");
return getAllInterfacesForClass(instance.getClass());
}
/**
* Return all interfaces that the given class implements as array, including
* ones implemented by superclasses.
* <p>
* If the class itself is an interface, it gets returned as sole interface.
*
* @param clazz
* the class to analyse for interfaces
* @return all interfaces that the given object implements as array
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, null);
}
/**
* Return all interfaces that the given class implements as array, including
* ones implemented by superclasses.
* <p>
* If the class itself is an interface, it gets returned as sole interface.
*
* @param clazz
* the class to analyse for interfaces
* @param classLoader
* the ClassLoader that the interfaces need to be visible in (may
* be <code>null</code> when accepting all declared interfaces)
* @return all interfaces that the given object implements as array
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz,
ClassLoader classLoader) {
Assertor.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
return new Class[] { clazz };
}
List<Class<?>> interfaces = new ArrayList<Class<?>>();
while (clazz != null) {
for (int i = 0; i < clazz.getInterfaces().length; i++) {
Class<?> ifc = clazz.getInterfaces()[i];
if (!interfaces.contains(ifc)
&& (classLoader == null || isVisible(ifc, classLoader))) {
interfaces.add(ifc);
}
}
clazz = clazz.getSuperclass();
}
return (Class[]) interfaces.toArray(new Class[interfaces.size()]);
}
/**
* Return all interfaces that the given instance implements as Set,
* including ones implemented by superclasses.
*
* @param instance
* the instance to analyse for interfaces
* @return all interfaces that the given instance implements as Set
*/
public static Set<?> getAllInterfacesAsSet(Object instance) {
Assertor.notNull(instance, "Instance must not be null");
return getAllInterfacesForClassAsSet(instance.getClass());
}
/**
* Return all interfaces that the given class implements as Set, including
* ones implemented by superclasses.
* <p>
* If the class itself is an interface, it gets returned as sole interface.
*
* @param clazz
* the class to analyse for interfaces
* @return all interfaces that the given object implements as Set
*/
public static Set<?> getAllInterfacesForClassAsSet(Class<?> clazz) {
return getAllInterfacesForClassAsSet(clazz, null);
}
/**
* Return all interfaces that the given class implements as Set, including
* ones implemented by superclasses.
* <p>
* If the class itself is an interface, it gets returned as sole interface.
*
* @param clazz
* the class to analyse for interfaces
* @param classLoader
* the ClassLoader that the interfaces need to be visible in (may
* be <code>null</code> when accepting all declared interfaces)
* @return all interfaces that the given object implements as Set
*/
public static Set<?> getAllInterfacesForClassAsSet(Class<?> clazz,
ClassLoader classLoader) {
Assertor.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
return Collections.singleton(clazz);
}
Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
while (clazz != null) {
for (int i = 0; i < clazz.getInterfaces().length; i++) {
Class<?> ifc = clazz.getInterfaces()[i];
if (classLoader == null || isVisible(ifc, classLoader)) {
interfaces.add(ifc);
}
}
clazz = clazz.getSuperclass();
}
return interfaces;
}
/**
* Create a composite interface Class for the given interfaces, implementing
* the given interfaces in one single Class.
* <p>
* This implementation builds a JDK proxy class for the given interfaces.
*
* @param interfaces
* the interfaces to merge
* @param classLoader
* the ClassLoader to create the composite Class in
* @return the merged interface as Class
* @see java.lang.reflect.Proxy#getProxyClass
*/
public static Class<?> createCompositeInterface(Class<?>[] interfaces,
ClassLoader classLoader) {
Assertor.notEmpty(interfaces, "Interfaces must not be empty");
Assertor.notNull(classLoader, "ClassLoader must not be null");
return Proxy.getProxyClass(classLoader, interfaces);
}
/**
* Check whether the given class is visible in the given ClassLoader.
*
* @param clazz
* the class to check (typically an interface)
* @param classLoader
* the ClassLoader to check against (may be <code>null</code>, in
* which case this method will always return <code>true</code>)
* @return true, if checks if is visible
*/
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
}
}
| apache-2.0 |
sonu283304/onos | core/api/src/main/java/org/onosproject/net/topology/TopologyStore.java | 6845 | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.topology;
import org.onosproject.event.Event;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.Path;
import org.onosproject.net.DisjointPath;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.store.Store;
import java.util.List;
import java.util.Set;
import java.util.Map;
/**
* Manages inventory of topology snapshots; not intended for direct use.
*/
public interface TopologyStore extends Store<TopologyEvent, TopologyStoreDelegate> {
/**
* Returns the current topology snapshot.
*
* @return current topology descriptor
*/
Topology currentTopology();
/**
* Indicates whether the topology is the latest.
*
* @param topology topology descriptor
* @return true if topology is the most recent one
*/
boolean isLatest(Topology topology);
/**
* Returns the immutable graph view of the current topology.
*
* @param topology topology descriptor
* @return graph view
*/
TopologyGraph getGraph(Topology topology);
/**
* Returns the set of topology SCC clusters.
*
* @param topology topology descriptor
* @return set of clusters
*/
Set<TopologyCluster> getClusters(Topology topology);
/**
* Returns the cluster of the specified topology.
*
* @param topology topology descriptor
* @param clusterId cluster identity
* @return topology cluster
*/
TopologyCluster getCluster(Topology topology, ClusterId clusterId);
/**
* Returns the cluster of the specified topology.
*
* @param topology topology descriptor
* @param cluster topology cluster
* @return set of cluster links
*/
Set<DeviceId> getClusterDevices(Topology topology, TopologyCluster cluster);
/**
* Returns the cluster of the specified topology.
*
* @param topology topology descriptor
* @param cluster topology cluster
* @return set of cluster links
*/
Set<Link> getClusterLinks(Topology topology, TopologyCluster cluster);
/**
* Returns the set of pre-computed shortest paths between src and dest.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @return set of shortest paths
*/
Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst);
/**
* Computes and returns the set of shortest paths between src and dest.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @param weight link weight function
* @return set of shortest paths
*/
Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst,
LinkWeight weight);
/**
* Computes and returns the set of disjoint shortest path pairs
* between src and dst.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @param weight link weight function
* @return set of shortest paths
*/
Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst,
LinkWeight weight);
/**
* Computes and returns the set of disjoint shortest path pairs
* between src and dst.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @return set of shortest paths
*/
Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst);
/**
* Computes and returns the set of SRLG disjoint shortest path pairs between source
* and dst, given a mapping of edges to SRLG risk groups.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @param weight link weight function
* @param riskProfile map of edges to objects. Edges that map to the same object will
* be treated as if they were in the same risk group.
* @return set of shortest paths
*/
Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst,
LinkWeight weight, Map<Link, Object> riskProfile);
/**
* Returns the set of pre-computed SRLG shortest paths between src and dest.
*
* @param topology topology descriptor
* @param src source device
* @param dst destination device
* @param riskProfile map of edges to objects. Edges that map to the same object will
* be treated as if they were in the same risk group.
* @return set of shortest paths
*/
Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst,
Map<Link, Object> riskProfile);
/**
* Indicates whether the given connect point is part of the network fabric.
*
* @param topology topology descriptor
* @param connectPoint connection point
* @return true if infrastructure; false otherwise
*/
boolean isInfrastructure(Topology topology, ConnectPoint connectPoint);
/**
* Indicates whether broadcast is allowed for traffic received on the
* given connection point.
*
* @param topology topology descriptor
* @param connectPoint connection point
* @return true if broadcast allowed; false otherwise
*/
boolean isBroadcastPoint(Topology topology, ConnectPoint connectPoint);
/**
* Generates a new topology snapshot from the specified description.
*
* @param providerId provider identification
* @param graphDescription topology graph description
* @param reasons list of events that triggered the update
* @return topology update event or null if the description is old
*/
TopologyEvent updateTopology(ProviderId providerId,
GraphDescription graphDescription,
List<Event> reasons);
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/EncryptionMaterials.java | 4044 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3.model;
import java.io.Serializable;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
/**
* The "key encrypting key" materials used in encrypt/decryption. These
* materials may be either an asymmetric key pair or a symmetric key but not
* both.
*/
public class EncryptionMaterials implements Serializable {
private final KeyPair keyPair;
private final SecretKey symmetricKey;
private final Map<String, String> desc = new HashMap<String,String>();
/**
* Constructs a new EncryptionMaterials object, storing an asymmetric key pair.
*
* @param keyPair
* The asymmetric key pair to be stored in this EncryptionMaterials object.
*/
public EncryptionMaterials(KeyPair keyPair) {
this(keyPair, null);
}
/**
* Constructs a new EncryptionMaterials object, storing a symmetric key.
*
* @param symmetricKey
* The symmetric key to be stored in this EncryptionMaterials object.
*/
public EncryptionMaterials(SecretKey symmetricKey) {
this(null, symmetricKey);
}
/**
* Base constructor for the EncryptionMaterials object. This is not publicly visible since
* it should not be possible to create an EncryptionMaterials object that contains both an
* asymmetric key pair and a symmetric key.
*/
protected EncryptionMaterials(KeyPair keyPair, SecretKey symmetricKey) {
this.keyPair = keyPair;
this.symmetricKey = symmetricKey;
}
/**
* Returns the key pair stored in this EncryptionMaterials object.
*
* @return the key pair stored in this EncryptionMaterials object.
*
*/
public KeyPair getKeyPair() {
return this.keyPair;
}
/**
* Returns the symmetric key stored in this EncryptionMaterials object.
*
* @return the symmetric key stored in this EncryptionMaterials object.
*/
public SecretKey getSymmetricKey() {
return this.symmetricKey;
}
/**
* Returns a snapshot of the current material description; never null.
*/
public Map<String, String> getMaterialsDescription() {
return new HashMap<String, String>(desc);
}
/**
* Returns null since the EncryptionMaterials base class does not have a materials accessor.
* Subclasses may override this method.
*
* @return null
*/
public EncryptionMaterialsAccessor getAccessor() {
return null;
}
/**
* Fluent API to add material description.
*/
public EncryptionMaterials addDescription(String name, String value) {
desc.put(name, value);
return this;
}
/**
* Fluent API to add all the given material descriptions.
*/
public EncryptionMaterials addDescriptions(Map<String,String> descriptions) {
desc.putAll(descriptions);
return this;
}
/**
* Returns true if this is a KMS material description; false otherwise.
*
* @return false by default
*/
public boolean isKMSEnabled() {
return false;
}
/**
* @throws UnsupportedOperationException by default
*/
public String getCustomerMasterKeyId() {
throw new UnsupportedOperationException();
}
protected String getDescription(String name) {
return desc.get(name);
}
}
| apache-2.0 |
mlevytskiy/u2020-mvp | app/src/internalDebug/java/ru/ltst/u2020mvp/data/api/LoggingInterceptor.java | 1638 | package ru.ltst.u2020mvp.data.api;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import ru.ltst.u2020mvp.data.Clock;
import ru.ltst.u2020mvp.ui.ApplicationScope;
import timber.log.Timber;
/**
* Verbose logging of network calls, which includes path, headers, and times.
*/
@ApplicationScope
public final class LoggingInterceptor implements Interceptor {
private final Clock clock;
@Inject
public LoggingInterceptor(Clock clock) {
this.clock = clock;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = clock.nanos();
Timber.v("Sending request %s%s", request.url(), prettyHeaders(request.headers()));
Response response = chain.proceed(request);
long t2 = clock.nanos();
Timber.v("Received response (%s) for %s in %sms%s", response.code(), response.request().url(),
TimeUnit.NANOSECONDS.toMillis(t2 - t1), prettyHeaders(response.headers()));
return response;
}
private String prettyHeaders(Headers headers) {
if (headers.size() == 0) return "";
StringBuilder builder = new StringBuilder();
builder.append("\n Headers:");
for (int i = 0; i < headers.size(); i++) {
builder.append("\n ").append(headers.name(i)).append(": ").append(headers.value(i));
}
return builder.toString();
}
}
| apache-2.0 |
enom/buddycloud-server-java | src/test/java/org/buddycloud/channelserver/db/jdbc/JDBCNodeStoreOnlineUserTest.java | 2375 | package org.buddycloud.channelserver.db.jdbc;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import junit.framework.Assert;
import org.buddycloud.channelserver.packetHandler.iq.IQTestHandler;
import org.junit.Test;
import org.xmpp.packet.JID;
public class JDBCNodeStoreOnlineUserTest extends JDBCNodeStoreAbstract {
private JID jid1 = new JID("user@server/resource");
private JID jid2 = new JID("user@server/other-resource");
private JID jid3 = new JID("user2@server/resource");
public JDBCNodeStoreOnlineUserTest() throws SQLException, IOException, ClassNotFoundException {
dbTester = new DatabaseTester();
IQTestHandler.readConf();
}
@Test
public void canAddAnOnlineJid() throws Exception {
store.jidOnline(jid1);
HashMap<String, Object> expected = new HashMap<String, Object>();
expected.put("user", jid1.toFullJID());
dbTester.assertions().assertTableContains("online_users", expected);
}
@Test
public void addingTheSameJidDoesntResultInTwoEntries() throws Exception {
store.jidOnline(jid1);
store.jidOnline(jid1);
HashMap<String, Object> expected = new HashMap<String, Object>();
expected.put("user", jid1.toFullJID());
dbTester.assertions().assertTableContains("online_users", expected);
}
@Test
public void canTakeUserOffline() throws Exception {
store.jidOnline(jid1);
store.jidOffline(jid1);
HashMap<String, Object> expected = new HashMap<String, Object>();
expected.put("user", jid1.toFullJID());
dbTester.assertions().assertTableContains("online_users", expected, 0);
}
@Test
public void canGetListOfOnlineJids() throws Exception {
store.jidOnline(jid1);
Thread.sleep(1);
store.jidOnline(jid2);
store.jidOnline(jid3);
Assert.assertEquals(2, store.onlineJids(jid1).size());
Assert.assertEquals(2, store.onlineJids(jid2).size());
Assert.assertEquals(1, store.onlineJids(jid3).size());
ArrayList<JID> onlineJids = store.onlineJids(jid1);
Assert.assertEquals(jid1, onlineJids.get(1));
Assert.assertEquals(jid2, onlineJids.get(0));
Assert.assertEquals(jid3, store.onlineJids(jid3).get(0));
}
}
| apache-2.0 |
dashbuilder/dashbuilder | dashbuilder-client/dashbuilder-common-client/src/main/java/org/dashbuilder/common/client/StringTemplateBuilder.java | 2471 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.common.client;
import java.util.HashSet;
import java.util.Set;
public class StringTemplateBuilder {
protected String keyPrefix;
protected String keySufix;
protected Set<String> keySet = new HashSet<>();
protected String sourceCode;
public StringTemplateBuilder() {
this("${", "}");
}
public StringTemplateBuilder(String keyPrefix, String keySufix) {
this.keyPrefix = keyPrefix;
this.keySufix = keySufix;
}
public void setTemplate(String template) {
this.sourceCode = template;
this.extractKeys();
}
public String getKeyPrefix() {
return keyPrefix;
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
public String getKeySufix() {
return keySufix;
}
public void setKeySufix(String keySufix) {
this.keySufix = keySufix;
}
public String build() {
return sourceCode;
}
public Set<String> keys() {
return keySet;
}
public String asVar(String key) {
return getKeyPrefix() + key + getKeySufix();
}
public StringTemplateBuilder replace(String key, String value) {
sourceCode = sourceCode.replace(keyPrefix + key + keySufix, value);
return this;
}
protected void extractKeys() {
this.keySet.clear();
if (sourceCode != null) {
int idx = 0;
int end = 0;
while (idx != -1 && end != -1) {
idx = sourceCode.indexOf(keyPrefix, end);
end = sourceCode.indexOf(keySufix, idx+keyPrefix.length());
if (idx != -1 && end != -1) {
String key = sourceCode.substring(idx + 2, end);
keySet.add(key);
}
}
}
}
}
| apache-2.0 |
GerritCodeReview/buck | test/com/facebook/buck/cli/testdata/TargetDeviceOptionsTest.java | 2452 | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli.testdata;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.cli.TargetDeviceOptions;
import com.facebook.buck.step.TargetDevice;
import org.junit.Test;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
public class TargetDeviceOptionsTest {
@Test
public void shouldReturnAnAbsentOptionalIfNoTargetDeviceOptionsSet() {
TargetDeviceOptions options = buildOptions();
assertFalse(options.getTargetDeviceOptional().isPresent());
}
@Test
public void shouldReturnAnEmulatorIfOnlyEmulatorFlagSet() {
TargetDeviceOptions options = buildOptions("-e");
TargetDevice device = options.getTargetDeviceOptional().get();
assertTrue(device.isEmulator());
assertNull(device.getIdentifier());
}
@Test
public void shouldReturnADeviceIfOnlyDeviceFlagSet() {
TargetDeviceOptions options = buildOptions("-d");
TargetDevice device = options.getTargetDeviceOptional().get();
assertFalse(device.isEmulator());
assertNull(device.getIdentifier());
}
@Test
public void onlySettingTheSerialFlagAssumesTheTargetIsARealDevice() {
TargetDeviceOptions options = buildOptions("-s", "1234");
TargetDevice device = options.getTargetDeviceOptional().get();
assertFalse(device.isEmulator());
assertEquals("1234", device.getIdentifier());
}
private TargetDeviceOptions buildOptions(String... args) {
TargetDeviceOptions options = new TargetDeviceOptions();
try {
new CmdLineParser(options).parseArgument(args);
} catch (CmdLineException e) {
fail("Unable to parse arguments");
}
return options;
}
}
| apache-2.0 |
zregvart/camel | components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/dataformat/FhirXmlDataformatErrorHandlerTest.java | 4257 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.fhir.dataformat;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParserErrorHandler;
import ca.uhn.fhir.parser.LenientErrorHandler;
import ca.uhn.fhir.parser.StrictErrorHandler;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.fhir.FhirXmlDataFormat;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.hl7.fhir.dstu3.model.Patient;
import org.junit.Before;
import org.junit.Test;
public class FhirXmlDataformatErrorHandlerTest extends CamelTestSupport {
private static final String INPUT = "<Patient><active value=\"true\"/><active value=\"false\"/></Patient>";
private MockEndpoint mockEndpoint;
private final FhirContext fhirContext = FhirContext.forDstu3();
@Override
@Before
public void setUp() throws Exception {
super.setUp();
mockEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
}
@Test(expected = DataFormatException.class)
public void unmarshalParserErrorHandler() throws Throwable {
try {
template.sendBody("direct:unmarshalErrorHandlerStrict", INPUT);
} catch (CamelExecutionException e) {
throw e.getCause();
}
}
@Test
public void unmarshalLenientErrorHandler() throws Exception {
mockEndpoint.expectedMessageCount(1);
template.sendBody("direct:unmarshalErrorHandlerLenient", INPUT);
mockEndpoint.assertIsSatisfied();
Exchange exchange = mockEndpoint.getExchanges().get(0);
Patient patient = (Patient) exchange.getIn().getBody();
assertEquals(true, patient.getActive());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
FhirXmlDataFormat strickErrorHandlerDataformat = getStrictErrorHandlerDataFormat();
FhirXmlDataFormat lenientErrorHandlerDataFormat = getLenientErrorHandlerDataFormat();
from("direct:unmarshalErrorHandlerStrict")
.unmarshal(strickErrorHandlerDataformat)
.to("mock:errorIsThrown");
from("direct:unmarshalErrorHandlerLenient")
.unmarshal(lenientErrorHandlerDataFormat)
.to("mock:result");
}
private FhirXmlDataFormat getStrictErrorHandlerDataFormat() {
FhirXmlDataFormat fhirXmlDataFormat = new FhirXmlDataFormat();
fhirXmlDataFormat.setFhirContext(fhirContext);
IParserErrorHandler parserErrorHandler = new StrictErrorHandler();
fhirXmlDataFormat.setParserErrorHandler(parserErrorHandler);
return fhirXmlDataFormat;
}
private FhirXmlDataFormat getLenientErrorHandlerDataFormat() {
FhirXmlDataFormat fhirXmlDataFormat = new FhirXmlDataFormat();
fhirXmlDataFormat.setFhirContext(fhirContext);
IParserErrorHandler parserErrorHandler = new LenientErrorHandler();
fhirXmlDataFormat.setParserErrorHandler(parserErrorHandler);
return fhirXmlDataFormat;
}
};
}
}
| apache-2.0 |
llllewicki/jmeter-diff | src/monitor/model/org/apache/jmeter/monitor/model/Worker.java | 1628 | /*
* 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.jmeter.monitor.model;
/**
* @version $Revision: 1377071 $
*/
public interface Worker {
int getRequestProcessingTime();
void setRequestProcessingTime(int value);
long getRequestBytesSent();
void setRequestBytesSent(long value);
String getCurrentQueryString();
void setCurrentQueryString(String value);
String getRemoteAddr();
void setRemoteAddr(String value);
String getCurrentUri();
void setCurrentUri(String value);
String getStage();
void setStage(String value);
String getVirtualHost();
void setVirtualHost(String value);
String getProtocol();
void setProtocol(String value);
long getRequestBytesReceived();
void setRequestBytesReceived(long value);
String getMethod();
void setMethod(String value);
}
| apache-2.0 |
apache/wss4j | ws-security-stax/src/main/java/org/apache/wss4j/stax/securityEvent/KeyValueTokenSecurityEvent.java | 1184 | /**
* 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.wss4j.stax.securityEvent;
import org.apache.wss4j.stax.securityToken.KeyValueSecurityToken;
import org.apache.xml.security.stax.securityEvent.TokenSecurityEvent;
public class KeyValueTokenSecurityEvent extends TokenSecurityEvent<KeyValueSecurityToken> {
public KeyValueTokenSecurityEvent() {
super(WSSecurityEventConstants.KeyValueToken);
}
}
| apache-2.0 |
pwong-mapr/incubator-drill | exec/java-exec/src/main/codegen/templates/DateIntervalAggrFunctions1.java | 7182 | /*
* 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.
*/
<@pp.dropOutputFile />
<#list aggrtypes1.aggrtypes as aggrtype>
<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/gaggr/${aggrtype.className}DateTypeFunctions.java" />
<#include "/@includes/license.ftl" />
<#-- A utility class that is used to generate java code for aggr functions for Date, Time, Interval types -->
<#-- that maintain a single running counter to hold the result. This includes: MIN, MAX, SUM, COUNT. -->
package org.apache.drill.exec.expr.fn.impl.gaggr;
import org.apache.drill.exec.expr.DrillAggFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionScope;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.*;
/*
* This class is generated using freemarker and the ${.template_name} template.
*/
@SuppressWarnings("unused")
public class ${aggrtype.className}DateTypeFunctions {
<#list aggrtype.types as type>
<#if type.major == "Date">
@FunctionTemplate(name = "${aggrtype.funcName}", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class ${type.inputType}${aggrtype.className} implements DrillAggFunc{
@Param ${type.inputType}Holder in;
@Workspace ${type.runningType}Holder value;
@Workspace BigIntHolder nonNullCount;
@Output ${type.outputType}Holder out;
public void setup() {
value = new ${type.runningType}Holder();
nonNullCount = new BigIntHolder();
nonNullCount.value = 0;
<#if type.runningType == "Interval">
value.months = ${type.initialValue};
value.days= ${type.initialValue};
value.milliseconds = ${type.initialValue};
<#elseif type.runningType == "IntervalDay">
value.days= ${type.initialValue};
value.milliseconds = ${type.initialValue};
<#else>
value.value = ${type.initialValue};
</#if>
}
@Override
public void add() {
<#if type.inputType?starts_with("Nullable")>
sout: {
if (in.isSet == 0) {
// processing nullable input and the value is null, so don't do anything...
break sout;
}
</#if>
nonNullCount.value = 1;
<#if aggrtype.funcName == "min">
<#if type.outputType?ends_with("Interval")>
long inMS = (long) in.months * org.apache.drill.exec.vector.DateUtilities.monthsToMillis+
in.days * (org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis) +
in.milliseconds;
value.value = Math.min(value.value, inMS);
<#elseif type.outputType?ends_with("IntervalDay")>
long inMS = (long) in.days * (org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis) +
in.milliseconds;
value.value = Math.min(value.value, inMS);
<#else>
value.value = Math.min(value.value, in.value);
</#if>
<#elseif aggrtype.funcName == "max">
<#if type.outputType?ends_with("Interval")>
long inMS = (long) in.months * org.apache.drill.exec.vector.DateUtilities.monthsToMillis+
in.days * (org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis) +
in.milliseconds;
value.value = Math.max(value.value, inMS);
<#elseif type.outputType?ends_with("IntervalDay")>
long inMS = (long) in.days * (org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis) +
in.milliseconds;
value.value = Math.max(value.value, inMS);
<#else>
value.value = Math.max(value.value, in.value);
</#if>
<#elseif aggrtype.funcName == "sum">
<#if type.outputType?ends_with("Interval")>
value.days += in.days;
value.months += in.months;
value.milliseconds += in.milliseconds;
<#elseif type.outputType?ends_with("IntervalDay")>
value.days += in.days;
value.milliseconds += in.milliseconds;
<#else>
value.value += in.value;
</#if>
<#elseif aggrtype.funcName == "count">
value.value++;
<#elseif aggrtype.funcName == "any_value">
<#if type.outputType?ends_with("Interval")>
value.days = in.days;
value.months = in.months;
value.milliseconds = in.milliseconds;
<#elseif type.outputType?ends_with("IntervalDay")>
value.days = in.days;
value.milliseconds = in.milliseconds;
</#if>
<#else>
// TODO: throw an error ?
</#if>
<#if type.inputType?starts_with("Nullable")>
} // end of sout block
</#if>
}
@Override
public void output() {
if (nonNullCount.value > 0) {
out.isSet = 1;
<#if aggrtype.funcName == "max" || aggrtype.funcName == "min">
<#if type.outputType?ends_with("Interval")>
out.months = (int) (value.value / org.apache.drill.exec.vector.DateUtilities.monthsToMillis);
value.value = value.value % org.apache.drill.exec.vector.DateUtilities.monthsToMillis;
out.days = (int) (value.value / org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis);
out.milliseconds = (int) (value.value % org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis);
<#elseif type.outputType?ends_with("IntervalDay")>
out.days = (int) (value.value / org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis);
out.milliseconds = (int) (value.value % org.apache.drill.exec.vector.DateUtilities.daysToStandardMillis);
<#else>
out.value = value.value;
</#if>
<#else>
<#if type.outputType?ends_with("Interval")>
out.months = value.months;
out.days = value.days;
out.milliseconds = value.milliseconds;
<#elseif type.outputType?ends_with("IntervalDay")>
out.days = value.days;
out.milliseconds = value.milliseconds;
<#else>
out.value = value.value;
</#if>
</#if>
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
nonNullCount.value = 0;
<#if type.runningType == "Interval">
value.months = ${type.initialValue};
value.days= ${type.initialValue};
value.milliseconds = ${type.initialValue};
<#elseif type.runningType == "IntervalDay">
value.days= ${type.initialValue};
value.milliseconds = ${type.initialValue};
<#else>
value.value = ${type.initialValue};
</#if>
}
}
</#if>
</#list>
}
</#list>
| apache-2.0 |
pascalrobert/aribaweb | src/widgets/src/main/java/ariba/ui/widgets/FooterIncludes.java | 1269 | /*
Copyright 1996-2008 Ariba, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
$Id: //ariba/platform/ui/widgets/ariba/ui/widgets/FooterIncludes.java#1 $
*/
package ariba.ui.widgets;
import ariba.ui.aribaweb.core.AWComponent;
import ariba.util.core.ListUtil;
import java.util.List;
public class FooterIncludes extends AWComponent {
private static List<String> Includes = ListUtil.list();
public String currentInclude;
public static void registerInclude (String componentName)
{
Includes.add(componentName);
}
public static void registerIncludes (List<String> componentNames)
{
Includes.addAll(componentNames);
}
public List includes ()
{
return Includes;
}
}
| apache-2.0 |
jiangtiqiang/paoding-rose | paoding-rose-web/src/main/java/net/paoding/rose/web/impl/mapping/ignored/IgnoredPathEquals.java | 402 | package net.paoding.rose.web.impl.mapping.ignored;
import net.paoding.rose.web.RequestPath;
public class IgnoredPathEquals implements IgnoredPath {
private String path;
public IgnoredPathEquals(String path) {
this.path = path;
}
@Override
public boolean hit(RequestPath requestPath) {
return requestPath.getRosePath().equals(path);
}
}
| apache-2.0 |
cschenyuan/hive-hack | ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFEWAHBitmapEmpty.java | 4303 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.udf.generic;
import java.io.IOException;
import java.util.ArrayList;
import javaewah.EWAHCompressedBitmap;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.index.bitmap.BitmapObjectInput;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.LongWritable;
@Description(name = "ewah_bitmap_empty", value = "_FUNC_(bitmap) - "
+ "Predicate that tests whether an EWAH-compressed bitmap is all zeros ")
public class GenericUDFEWAHBitmapEmpty extends GenericUDF {
private transient ObjectInspector bitmapOI;
private transient BooleanObjectInspector boolOI;
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments.length != 1) {
throw new UDFArgumentLengthException(
"The function EWAH_BITMAP_EMPTY(b) takes exactly 1 argument");
}
if (arguments[0].getCategory().equals(Category.LIST)) {
bitmapOI = (ListObjectInspector) arguments[0];
} else {
throw new UDFArgumentTypeException(0, "\""
+ Category.LIST.toString().toLowerCase()
+ "\" is expected at function EWAH_BITMAP_EMPTY, but \""
+ arguments[0].getTypeName() + "\" is found");
}
boolOI = PrimitiveObjectInspectorFactory.writableBooleanObjectInspector;
return boolOI;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
assert (arguments.length == 1);
Object b = arguments[0].get();
ListObjectInspector lloi = (ListObjectInspector) bitmapOI;
int length = lloi.getListLength(b);
ArrayList<LongWritable> bitmapArray = new ArrayList<LongWritable>();
for (int i = 0; i < length; i++) {
long l = PrimitiveObjectInspectorUtils.getLong(
lloi.getListElement(b, i),
(PrimitiveObjectInspector) lloi.getListElementObjectInspector());
bitmapArray.add(new LongWritable(l));
}
BitmapObjectInput bitmapObjIn = new BitmapObjectInput(bitmapArray);
EWAHCompressedBitmap bitmap = new EWAHCompressedBitmap();
try {
bitmap.readExternal(bitmapObjIn);
} catch (IOException e) {
throw new RuntimeException(e);
}
// Add return true only if bitmap is all zeros.
return new BooleanWritable(!bitmap.iterator().hasNext());
}
@Override
public String getDisplayString(String[] children) {
StringBuilder sb = new StringBuilder();
sb.append("EWAH_BITMAP_EMPTY(");
for (int i = 0; i < children.length; i++) {
sb.append(children[i]);
if (i + 1 != children.length) {
sb.append(",");
}
}
sb.append(")");
return sb.toString();
}
}
| apache-2.0 |
hekonsek/fabric8 | sandbox/fabric/fabric-partition/src/main/java/io/fabric8/partition/internal/TaskContextImpl.java | 1869 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.partition.internal;
import io.fabric8.partition.TaskContext;
import java.util.Collections;
import java.util.Map;
public class TaskContextImpl implements TaskContext {
private final String id;
private final Map<String, ?> configuration;
public TaskContextImpl(String id, Map<String, ?> configuration) {
this.id = id;
this.configuration = Collections.unmodifiableMap(configuration);
}
public String getId() {
return id;
}
public Map<String, ?> getConfiguration() {
return configuration;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskContextImpl that = (TaskContextImpl) o;
if (configuration != null ? !configuration.equals(that.configuration) : that.configuration != null) return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (configuration != null ? configuration.hashCode() : 0);
return result;
}
}
| apache-2.0 |
facebook/presto | presto-benchmark/src/main/java/com/facebook/presto/benchmark/HashJoinBenchmark.java | 6303 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.benchmark;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.execution.Lifespan;
import com.facebook.presto.operator.Driver;
import com.facebook.presto.operator.DriverContext;
import com.facebook.presto.operator.DriverFactory;
import com.facebook.presto.operator.HashBuilderOperator.HashBuilderOperatorFactory;
import com.facebook.presto.operator.JoinBridgeManager;
import com.facebook.presto.operator.LookupJoinOperators;
import com.facebook.presto.operator.LookupSourceProvider;
import com.facebook.presto.operator.OperatorFactory;
import com.facebook.presto.operator.PagesIndex;
import com.facebook.presto.operator.PartitionedLookupSourceFactory;
import com.facebook.presto.operator.TaskContext;
import com.facebook.presto.spi.plan.PlanNodeId;
import com.facebook.presto.spiller.SingleStreamSpillerFactory;
import com.facebook.presto.testing.LocalQueryRunner;
import com.facebook.presto.testing.NullOutputOperator.NullOutputOperatorFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Ints;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.Future;
import static com.facebook.airlift.concurrent.MoreFutures.getFutureValue;
import static com.facebook.presto.benchmark.BenchmarkQueryRunner.createLocalQueryRunner;
import static com.facebook.presto.operator.PipelineExecutionStrategy.UNGROUPED_EXECUTION;
import static com.facebook.presto.spiller.PartitioningSpillerFactory.unsupportedPartitioningSpillerFactory;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
public class HashJoinBenchmark
extends AbstractOperatorBenchmark
{
private static final LookupJoinOperators LOOKUP_JOIN_OPERATORS = new LookupJoinOperators();
private DriverFactory probeDriverFactory;
public HashJoinBenchmark(LocalQueryRunner localQueryRunner)
{
super(localQueryRunner, "hash_join", 4, 50);
}
/*
select orderkey, quantity, totalprice
from lineitem join orders using (orderkey)
*/
@Override
protected List<Driver> createDrivers(TaskContext taskContext)
{
if (probeDriverFactory == null) {
List<Type> ordersTypes = getColumnTypes("orders", "orderkey", "totalprice");
OperatorFactory ordersTableScan = createTableScanOperator(0, new PlanNodeId("test"), "orders", "orderkey", "totalprice");
JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory(
ordersTypes,
ImmutableList.of(0, 1).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
Ints.asList(0).stream()
.map(ordersTypes::get)
.collect(toImmutableList()),
1,
requireNonNull(ImmutableMap.of(), "layout is null"),
false));
HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory(
1,
new PlanNodeId("test"),
lookupSourceFactoryManager,
ImmutableList.of(0, 1),
Ints.asList(0),
OptionalInt.empty(),
Optional.empty(),
Optional.empty(),
ImmutableList.of(),
1_500_000,
new PagesIndex.TestingFactory(false),
false,
SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory(),
false);
DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext();
DriverFactory buildDriverFactory = new DriverFactory(0, false, false, ImmutableList.of(ordersTableScan, hashBuilder), OptionalInt.empty(), UNGROUPED_EXECUTION, Optional.empty());
List<Type> lineItemTypes = getColumnTypes("lineitem", "orderkey", "quantity");
OperatorFactory lineItemTableScan = createTableScanOperator(0, new PlanNodeId("test"), "lineitem", "orderkey", "quantity");
OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(1, new PlanNodeId("test"), lookupSourceFactoryManager, lineItemTypes, Ints.asList(0), OptionalInt.empty(), Optional.empty(), OptionalInt.empty(), unsupportedPartitioningSpillerFactory());
NullOutputOperatorFactory output = new NullOutputOperatorFactory(2, new PlanNodeId("test"));
this.probeDriverFactory = new DriverFactory(1, true, true, ImmutableList.of(lineItemTableScan, joinOperator, output), OptionalInt.empty(), UNGROUPED_EXECUTION, Optional.empty());
Driver driver = buildDriverFactory.createDriver(driverContext);
Future<LookupSourceProvider> lookupSourceProvider = lookupSourceFactoryManager.getJoinBridge(Lifespan.taskWide()).createLookupSourceProvider();
while (!lookupSourceProvider.isDone()) {
driver.process();
}
getFutureValue(lookupSourceProvider).close();
}
DriverContext driverContext = taskContext.addPipelineContext(1, true, true, false).addDriverContext();
Driver driver = probeDriverFactory.createDriver(driverContext);
return ImmutableList.of(driver);
}
public static void main(String[] args)
{
new HashJoinBenchmark(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out));
}
}
| apache-2.0 |
leonhong/hadoop-common | src/mapred/org/apache/hadoop/mapred/LocalJobRunner.java | 19965 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.filecache.TaskDistributedCacheManager;
import org.apache.hadoop.filecache.TrackerDistributedCacheManager;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.serializer.SerializationFactory;
import org.apache.hadoop.io.serializer.Serializer;
import org.apache.hadoop.mapreduce.split.SplitMetaInfoReader;
import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitMetaInfo;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.mapreduce.security.TokenCache;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.security.token.Token;
/** Implements MapReduce locally, in-process, for debugging. */
class LocalJobRunner implements JobSubmissionProtocol {
public static final Log LOG =
LogFactory.getLog(LocalJobRunner.class);
private FileSystem fs;
private HashMap<JobID, Job> jobs = new HashMap<JobID, Job>();
private JobConf conf;
private int map_tasks = 0;
private int reduce_tasks = 0;
final Random rand = new Random();
private JobTrackerInstrumentation myMetrics = null;
private static final String jobDir = "localRunner/";
public long getProtocolVersion(String protocol, long clientVersion) {
return JobSubmissionProtocol.versionID;
}
private class Job extends Thread
implements TaskUmbilicalProtocol {
// The job directory on the system: JobClient places job configurations here.
// This is analogous to JobTracker's system directory.
private Path systemJobDir;
private Path systemJobFile;
// The job directory for the task. Analagous to a task's job directory.
private Path localJobDir;
private Path localJobFile;
private JobID id;
private JobConf job;
private JobStatus status;
private ArrayList<TaskAttemptID> mapIds = new ArrayList<TaskAttemptID>();
private JobProfile profile;
private FileSystem localFs;
boolean killed = false;
private TrackerDistributedCacheManager trackerDistributerdCacheManager;
private TaskDistributedCacheManager taskDistributedCacheManager;
// Counters summed over all the map/reduce tasks which
// have successfully completed
private Counters completedTaskCounters = new Counters();
// Current counters, including incomplete task(s)
private Counters currentCounters = new Counters();
public long getProtocolVersion(String protocol, long clientVersion) {
return TaskUmbilicalProtocol.versionID;
}
public Job(JobID jobid, String jobSubmitDir) throws IOException {
this.systemJobDir = new Path(jobSubmitDir);
this.systemJobFile = new Path(systemJobDir, "job.xml");
this.id = jobid;
this.localFs = FileSystem.getLocal(conf);
this.localJobDir = localFs.makeQualified(conf.getLocalPath(jobDir));
this.localJobFile = new Path(this.localJobDir, id + ".xml");
// Manage the distributed cache. If there are files to be copied,
// this will trigger localFile to be re-written again.
this.trackerDistributerdCacheManager =
new TrackerDistributedCacheManager(conf, new DefaultTaskController());
this.taskDistributedCacheManager =
trackerDistributerdCacheManager.newTaskDistributedCacheManager(conf);
taskDistributedCacheManager.setup(
new LocalDirAllocator("mapred.local.dir"),
new File(systemJobDir.toString()),
"archive", "archive");
if (DistributedCache.getSymlink(conf)) {
// This is not supported largely because,
// for a Child subprocess, the cwd in LocalJobRunner
// is not a fresh slate, but rather the user's working directory.
// This is further complicated because the logic in
// setupWorkDir only creates symlinks if there's a jarfile
// in the configuration.
LOG.warn("LocalJobRunner does not support " +
"symlinking into current working dir.");
}
// Setup the symlinks for the distributed cache.
TaskRunner.setupWorkDir(conf, new File(localJobDir.toUri()).getAbsoluteFile());
// Write out configuration file. Instead of copying it from
// systemJobFile, we re-write it, since setup(), above, may have
// updated it.
OutputStream out = localFs.create(localJobFile);
try {
conf.writeXml(out);
} finally {
out.close();
}
this.job = new JobConf(localJobFile);
// Job (the current object) is a Thread, so we wrap its class loader.
if (!taskDistributedCacheManager.getClassPaths().isEmpty()) {
setContextClassLoader(taskDistributedCacheManager.makeClassLoader(
getContextClassLoader()));
}
profile = new JobProfile(job.getUser(), id, systemJobFile.toString(),
"http://localhost:8080/", job.getJobName());
status = new JobStatus(id, 0.0f, 0.0f, JobStatus.RUNNING);
jobs.put(id, this);
this.start();
}
JobProfile getProfile() {
return profile;
}
@SuppressWarnings("unchecked")
@Override
public void run() {
JobID jobId = profile.getJobID();
JobContext jContext = new JobContext(conf, jobId);
OutputCommitter outputCommitter = job.getOutputCommitter();
try {
TaskSplitMetaInfo[] taskSplitMetaInfos =
SplitMetaInfoReader.readSplitMetaInfo(jobId, localFs, conf, systemJobDir);
int numReduceTasks = job.getNumReduceTasks();
if (numReduceTasks > 1 || numReduceTasks < 0) {
// we only allow 0 or 1 reducer in local mode
numReduceTasks = 1;
job.setNumReduceTasks(1);
}
outputCommitter.setupJob(jContext);
status.setSetupProgress(1.0f);
Map<TaskAttemptID, MapOutputFile> mapOutputFiles =
new HashMap<TaskAttemptID, MapOutputFile>();
for (int i = 0; i < taskSplitMetaInfos.length; i++) {
if (!this.isInterrupted()) {
TaskAttemptID mapId = new TaskAttemptID(new TaskID(jobId, true, i),0);
mapIds.add(mapId);
MapTask map = new MapTask(systemJobFile.toString(),
mapId, i,
taskSplitMetaInfos[i].getSplitIndex(), 1);
map.setUser(UserGroupInformation.getCurrentUser().
getShortUserName());
JobConf localConf = new JobConf(job);
TaskRunner.setupChildMapredLocalDirs(map, localConf);
MapOutputFile mapOutput = new MapOutputFile();
mapOutput.setConf(localConf);
mapOutputFiles.put(mapId, mapOutput);
map.setJobFile(localJobFile.toString());
localConf.setUser(map.getUser());
map.localizeConfiguration(localConf);
map.setConf(localConf);
map_tasks += 1;
myMetrics.launchMap(mapId);
map.run(localConf, this);
myMetrics.completeMap(mapId);
map_tasks -= 1;
updateCounters(map);
} else {
throw new InterruptedException();
}
}
TaskAttemptID reduceId =
new TaskAttemptID(new TaskID(jobId, false, 0), 0);
try {
if (numReduceTasks > 0) {
ReduceTask reduce =
new ReduceTask(systemJobFile.toString(), reduceId, 0, mapIds.size(),
1);
reduce.setUser(UserGroupInformation.getCurrentUser().
getShortUserName());
JobConf localConf = new JobConf(job);
TaskRunner.setupChildMapredLocalDirs(reduce, localConf);
// move map output to reduce input
for (int i = 0; i < mapIds.size(); i++) {
if (!this.isInterrupted()) {
TaskAttemptID mapId = mapIds.get(i);
Path mapOut = mapOutputFiles.get(mapId).getOutputFile();
MapOutputFile localOutputFile = new MapOutputFile();
localOutputFile.setConf(localConf);
Path reduceIn =
localOutputFile.getInputFileForWrite(mapId.getTaskID(),
localFs.getFileStatus(mapOut).getLen());
if (!localFs.mkdirs(reduceIn.getParent())) {
throw new IOException("Mkdirs failed to create "
+ reduceIn.getParent().toString());
}
if (!localFs.rename(mapOut, reduceIn))
throw new IOException("Couldn't rename " + mapOut);
} else {
throw new InterruptedException();
}
}
if (!this.isInterrupted()) {
reduce.setJobFile(localJobFile.toString());
localConf.setUser(reduce.getUser());
reduce.localizeConfiguration(localConf);
reduce.setConf(localConf);
reduce_tasks += 1;
myMetrics.launchReduce(reduce.getTaskID());
reduce.run(localConf, this);
myMetrics.completeReduce(reduce.getTaskID());
reduce_tasks -= 1;
updateCounters(reduce);
} else {
throw new InterruptedException();
}
}
} finally {
for (MapOutputFile output : mapOutputFiles.values()) {
output.removeAll();
}
}
// delete the temporary directory in output directory
outputCommitter.commitJob(jContext);
status.setCleanupProgress(1.0f);
if (killed) {
this.status.setRunState(JobStatus.KILLED);
} else {
this.status.setRunState(JobStatus.SUCCEEDED);
}
JobEndNotifier.localRunnerNotification(job, status);
} catch (Throwable t) {
try {
outputCommitter.abortJob(jContext, JobStatus.FAILED);
} catch (IOException ioe) {
LOG.info("Error cleaning up job:" + id);
}
status.setCleanupProgress(1.0f);
if (killed) {
this.status.setRunState(JobStatus.KILLED);
} else {
this.status.setRunState(JobStatus.FAILED);
}
LOG.warn(id, t);
JobEndNotifier.localRunnerNotification(job, status);
} finally {
try {
fs.delete(systemJobFile.getParent(), true); // delete submit dir
localFs.delete(localJobFile, true); // delete local copy
// Cleanup distributed cache
taskDistributedCacheManager.release();
trackerDistributerdCacheManager.purgeCache();
} catch (IOException e) {
LOG.warn("Error cleaning up "+id+": "+e);
}
}
}
// TaskUmbilicalProtocol methods
public JvmTask getTask(JvmContext context) { return null; }
public boolean statusUpdate(TaskAttemptID taskId, TaskStatus taskStatus)
throws IOException, InterruptedException {
LOG.info(taskStatus.getStateString());
float taskIndex = mapIds.indexOf(taskId);
if (taskIndex >= 0) { // mapping
float numTasks = mapIds.size();
status.setMapProgress(taskIndex/numTasks + taskStatus.getProgress()/numTasks);
} else {
status.setReduceProgress(taskStatus.getProgress());
}
currentCounters = Counters.sum(completedTaskCounters, taskStatus.getCounters());
// ignore phase
return true;
}
/**
* Task is reporting that it is in commit_pending
* and it is waiting for the commit Response
*/
public void commitPending(TaskAttemptID taskid,
TaskStatus taskStatus)
throws IOException, InterruptedException {
statusUpdate(taskid, taskStatus);
}
/**
* Updates counters corresponding to completed tasks.
* @param task A map or reduce task which has just been
* successfully completed
*/
private void updateCounters(Task task) {
completedTaskCounters.incrAllCounters(task.getCounters());
}
public void reportDiagnosticInfo(TaskAttemptID taskid, String trace) {
// Ignore for now
}
public void reportNextRecordRange(TaskAttemptID taskid,
SortedRanges.Range range) throws IOException {
LOG.info("Task " + taskid + " reportedNextRecordRange " + range);
}
public boolean ping(TaskAttemptID taskid) throws IOException {
return true;
}
public boolean canCommit(TaskAttemptID taskid)
throws IOException {
return true;
}
public void done(TaskAttemptID taskId) throws IOException {
int taskIndex = mapIds.indexOf(taskId);
if (taskIndex >= 0) { // mapping
status.setMapProgress(1.0f);
} else {
status.setReduceProgress(1.0f);
}
}
public synchronized void fsError(TaskAttemptID taskId, String message)
throws IOException {
LOG.fatal("FSError: "+ message + "from task: " + taskId);
}
public void shuffleError(TaskAttemptID taskId, String message) throws IOException {
LOG.fatal("shuffleError: "+ message + "from task: " + taskId);
}
public synchronized void fatalError(TaskAttemptID taskId, String msg)
throws IOException {
LOG.fatal("Fatal: "+ msg + "from task: " + taskId);
}
public MapTaskCompletionEventsUpdate getMapCompletionEvents(JobID jobId,
int fromEventId, int maxLocs, TaskAttemptID id) throws IOException {
return new MapTaskCompletionEventsUpdate(TaskCompletionEvent.EMPTY_ARRAY,
false);
}
}
public LocalJobRunner(JobConf conf) throws IOException {
this.fs = FileSystem.getLocal(conf);
this.conf = conf;
myMetrics = new JobTrackerMetricsInst(null, new JobConf(conf));
}
// JobSubmissionProtocol methods
private static int jobid = 0;
public synchronized JobID getNewJobId() {
return new JobID("local", ++jobid);
}
public JobStatus submitJob(JobID jobid, String jobSubmitDir,
Credentials credentials)
throws IOException {
Job job = new Job(jobid, jobSubmitDir);
job.job.setCredentials(credentials);
return job.status;
}
public void killJob(JobID id) {
jobs.get(id).killed = true;
jobs.get(id).interrupt();
}
public void setJobPriority(JobID id, String jp) throws IOException {
throw new UnsupportedOperationException("Changing job priority " +
"in LocalJobRunner is not supported.");
}
/** Throws {@link UnsupportedOperationException} */
public boolean killTask(TaskAttemptID taskId, boolean shouldFail) throws IOException {
throw new UnsupportedOperationException("Killing tasks in " +
"LocalJobRunner is not supported");
}
public JobProfile getJobProfile(JobID id) {
Job job = jobs.get(id);
if(job != null)
return job.getProfile();
else
return null;
}
public TaskReport[] getMapTaskReports(JobID id) {
return new TaskReport[0];
}
public TaskReport[] getReduceTaskReports(JobID id) {
return new TaskReport[0];
}
public TaskReport[] getCleanupTaskReports(JobID id) {
return new TaskReport[0];
}
public TaskReport[] getSetupTaskReports(JobID id) {
return new TaskReport[0];
}
public JobStatus getJobStatus(JobID id) {
Job job = jobs.get(id);
if(job != null)
return job.status;
else
return null;
}
public Counters getJobCounters(JobID id) {
Job job = jobs.get(id);
return job.currentCounters;
}
public String getFilesystemName() throws IOException {
return fs.getUri().toString();
}
public ClusterStatus getClusterStatus(boolean detailed) {
return new ClusterStatus(1, 0, 0, map_tasks, reduce_tasks, 1, 1,
JobTracker.State.RUNNING);
}
public JobStatus[] jobsToComplete() {return null;}
public TaskCompletionEvent[] getTaskCompletionEvents(JobID jobid
, int fromEventId, int maxEvents) throws IOException {
return TaskCompletionEvent.EMPTY_ARRAY;
}
public JobStatus[] getAllJobs() {return null;}
/**
* Returns the diagnostic information for a particular task in the given job.
* To be implemented
*/
public String[] getTaskDiagnostics(TaskAttemptID taskid)
throws IOException{
return new String [0];
}
/**
* @see org.apache.hadoop.mapred.JobSubmissionProtocol#getSystemDir()
*/
public String getSystemDir() {
Path sysDir = new Path(conf.get("mapred.system.dir", "/tmp/hadoop/mapred/system"));
return fs.makeQualified(sysDir).toString();
}
/**
* @see org.apache.hadoop.mapred.JobSubmissionProtocol#getQueueAdmins()
*/
public AccessControlList getQueueAdmins(String queueName) throws IOException {
return new AccessControlList(" ");// no queue admins for local job runner
}
/**
* @see org.apache.hadoop.mapred.JobSubmissionProtocol#getStagingAreaDir()
*/
public String getStagingAreaDir() throws IOException {
Path stagingRootDir =
new Path(conf.get("mapreduce.jobtracker.staging.root.dir",
"/tmp/hadoop/mapred/staging"));
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
String user;
if (ugi != null) {
user = ugi.getShortUserName() + rand.nextInt();
} else {
user = "dummy" + rand.nextInt();
}
return fs.makeQualified(new Path(stagingRootDir, user+"/.staging")).toString();
}
@Override
public JobStatus[] getJobsFromQueue(String queue) throws IOException {
return null;
}
@Override
public JobQueueInfo[] getQueues() throws IOException {
return null;
}
@Override
public JobQueueInfo getQueueInfo(String queue) throws IOException {
return null;
}
@Override
public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException{
return null;
}
@Override
public void cancelDelegationToken(Token<DelegationTokenIdentifier> token
) throws IOException,
InterruptedException {
}
@Override
public Token<DelegationTokenIdentifier>
getDelegationToken(Text renewer) throws IOException, InterruptedException {
return null;
}
@Override
public long renewDelegationToken(Token<DelegationTokenIdentifier> token
) throws IOException,InterruptedException{
return 0;
}
}
| apache-2.0 |
DbMaintain/dbmaintain | dbmaintain/src/main/java/org/dbmaintain/script/parser/parsingstate/impl/InSingleQuotesParsingState.java | 3797 | /*
* Copyright DbMaintain.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.dbmaintain.script.parser.parsingstate.impl;
import org.dbmaintain.script.parser.impl.HandleNextCharacterResult;
import org.dbmaintain.script.parser.impl.StatementBuilder;
import org.dbmaintain.script.parser.parsingstate.ParsingState;
/**
* A state for parsing single quotes ('text') part of a script.
*
* @author Tim Ducheyne
* @author Filip Neven
*/
public class InSingleQuotesParsingState implements ParsingState {
private static final Character SINGLE_QUOTE = '\'';
private static final Character BACKSLASH = '\\';
/* Determines whether backslashes can be used to escape characters, e.g. \' for a single quote (= '') */
protected boolean backSlashEscapingEnabled;
/* True if the next character should be escaped */
protected boolean escaping;
/* Still in single quotes */
protected HandleNextCharacterResult stayInSingleQuotesStateResult;
/* End of single quotes reached, go back to normal state */
protected HandleNextCharacterResult backToNormalResult;
/**
* @param backSlashEscapingEnabled True if backslashes can be used for escaping
*/
public InSingleQuotesParsingState(boolean backSlashEscapingEnabled) {
this.backSlashEscapingEnabled = backSlashEscapingEnabled;
}
/**
* Initializes the state with the normal parsing state, that should be returned when the end of the literal is reached..
*
* @param normalParsingState The normal state, not null
*/
public void linkParsingStates(ParsingState normalParsingState) {
this.stayInSingleQuotesStateResult = new HandleNextCharacterResult(this, true);
this.backToNormalResult = new HandleNextCharacterResult(normalParsingState, true);
}
/**
* Determines whether the end of the literal is reached.
* If that is the case, the normal parsing state is returned.
*
* @param previousChar The previous char, null if none
* @param currentChar The current char
* @param nextChar The next char, null if none
* @param statementBuilder The statement builder, not null
* @return The next parsing state, null if the end of the statement is reached
*/
public HandleNextCharacterResult getNextParsingState(Character previousChar, Character currentChar, Character nextChar, StatementBuilder statementBuilder) {
// escape current character
if (escaping) {
escaping = false;
return stayInSingleQuotesStateResult;
}
// check for escaped single quotes
if (SINGLE_QUOTE.equals(currentChar) && SINGLE_QUOTE.equals(nextChar)) {
escaping = true;
return stayInSingleQuotesStateResult;
}
// check escaped characters
if (BACKSLASH.equals(currentChar) && backSlashEscapingEnabled) {
escaping = true;
return stayInSingleQuotesStateResult;
}
// check for ending quote
if (SINGLE_QUOTE.equals(currentChar)) {
return backToNormalResult;
}
return stayInSingleQuotesStateResult;
}
} | apache-2.0 |
JingchengDu/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/utils/ServiceUtils.java | 20021 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.service.utils;
import org.apache.hadoop.util.Preconditions;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.util.ExitUtil;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.service.conf.YarnServiceConstants;
import org.apache.hadoop.yarn.service.containerlaunch.ClasspathConstructor;
import org.apache.hadoop.yarn.service.exceptions.BadClusterStateException;
import org.apache.hadoop.yarn.service.exceptions.SliderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic
.HADOOP_SECURITY_DNS_INTERFACE_KEY;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic
.HADOOP_SECURITY_DNS_NAMESERVER_KEY;
/**
* These are slider-specific Util methods
*/
public final class ServiceUtils {
private static final Logger log = LoggerFactory.getLogger(ServiceUtils.class);
private ServiceUtils() {
}
/**
* Implementation of set-ness, groovy definition of true/false for a string
* @param s string
* @return true iff the string is neither null nor empty
*/
public static boolean isUnset(String s) {
return s == null || s.isEmpty();
}
public static boolean isSet(String s) {
return !isUnset(s);
}
public static boolean isEmpty(Collection l) {
return l == null || l.isEmpty();
}
/**
* Find a containing JAR
* @param clazz class to find
* @return the file
* @throws IOException any IO problem, including the class not having a
* classloader
* @throws FileNotFoundException if the class did not resolve to a file
*/
public static File findContainingJarOrFail(Class clazz) throws IOException {
File localFile = ServiceUtils.findContainingJar(clazz);
if (null == localFile) {
throw new FileNotFoundException("Could not find JAR containing " + clazz);
}
return localFile;
}
/**
* Find a containing JAR
* @param my_class class to find
* @return the file or null if it is not found
* @throws IOException any IO problem, including the class not having a
* classloader
*/
public static File findContainingJar(Class my_class) throws IOException {
ClassLoader loader = my_class.getClassLoader();
if (loader == null) {
throw new IOException(
"Class " + my_class + " does not have a classloader!");
}
String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
Enumeration<URL> urlEnumeration = loader.getResources(class_file);
for (; urlEnumeration.hasMoreElements(); ) {
URL url = urlEnumeration.nextElement();
if ("jar".equals(url.getProtocol())) {
String toReturn = url.getPath();
if (toReturn.startsWith("file:")) {
toReturn = toReturn.substring("file:".length());
}
// URLDecoder is a misnamed class, since it actually decodes
// x-www-form-urlencoded MIME type rather than actual
// URL encoding (which the file path has). Therefore it would
// decode +s to ' 's which is incorrect (spaces are actually
// either unencoded or encoded as "%20"). Replace +s first, so
// that they are kept sacred during the decoding process.
toReturn = toReturn.replaceAll("\\+", "%2B");
toReturn = URLDecoder.decode(toReturn, "UTF-8");
String jarFilePath = toReturn.replaceAll("!.*$", "");
return new File(jarFilePath);
} else {
log.info("could not locate JAR containing {} URL={}", my_class, url);
}
}
return null;
}
/**
* Copy a file to a new FS -both paths must be qualified.
* @param conf conf file
* @param srcFile src file
* @param destFile dest file
*/
@SuppressWarnings("deprecation")
public static void copy(Configuration conf,
Path srcFile,
Path destFile) throws
IOException,
BadClusterStateException {
FileSystem srcFS = FileSystem.get(srcFile.toUri(), conf);
//list all paths in the src.
if (!srcFS.exists(srcFile)) {
throw new FileNotFoundException("Source file not found " + srcFile);
}
if (!srcFS.isFile(srcFile)) {
throw new FileNotFoundException(
"Source file not a file " + srcFile);
}
FileSystem destFS = FileSystem.get(destFile.toUri(), conf);
FileUtil.copy(srcFS, srcFile, destFS, destFile, false, true, conf);
}
/**
* Take a collection, return a list containing the string value of every
* element in the collection.
* @param c collection
* @return a stringified list
*/
public static List<String> collectionToStringList(Collection c) {
List<String> l = new ArrayList<>(c.size());
for (Object o : c) {
l.add(o.toString());
}
return l;
}
/**
* Join an collection of objects with a separator that appears after every
* instance in the list -including at the end
* @param collection collection to call toString() on each element
* @param separator separator string
* @return the joined entries
*/
public static String join(Collection collection, String separator) {
return join(collection, separator, true);
}
/**
* Join an collection of objects with a separator that appears after every
* instance in the list -optionally at the end
* @param collection collection to call toString() on each element
* @param separator separator string
* @param trailing add a trailing entry or not
* @return the joined entries
*/
public static String join(Collection collection,
String separator,
boolean trailing) {
StringBuilder b = new StringBuilder();
// fast return on empty collection
if (collection.isEmpty()) {
return trailing ? separator : "";
}
for (Object o : collection) {
b.append(o)
.append(separator);
}
int length = separator.length();
String s = b.toString();
return (trailing || s.isEmpty()) ?
s : (b.substring(0, b.length() - length));
}
/**
* Join an array of strings with a separator that appears after every
* instance in the list -optionally at the end
* @param collection strings
* @param separator separator string
* @param trailing add a trailing entry or not
* @return the joined entries
*/
public static String join(String[] collection, String separator,
boolean trailing) {
return join(Arrays.asList(collection), separator, trailing);
}
/**
* Resolve a mandatory environment variable
* @param key env var
* @return the resolved value
* @throws BadClusterStateException
*/
public static String mandatoryEnvVariable(String key) throws
BadClusterStateException {
String v = System.getenv(key);
if (v == null) {
throw new BadClusterStateException("Missing Environment variable " + key);
}
return v;
}
/**
* Generic map merge logic
* @param first first map
* @param second second map
* @param <T1> key type
* @param <T2> value type
* @return 'first' merged with the second
*/
public static <T1, T2> Map<T1, T2> mergeMapsIgnoreDuplicateKeys(Map<T1, T2> first,
Map<T1, T2> second) {
Preconditions.checkArgument(first != null, "Null 'first' value");
Preconditions.checkArgument(second != null, "Null 'second' value");
for (Map.Entry<T1, T2> entry : second.entrySet()) {
T1 key = entry.getKey();
if (!first.containsKey(key)) {
first.put(key, entry.getValue());
}
}
return first;
}
/**
* Convert a map to a multi-line string for printing
* @param map map to stringify
* @return a string representation of the map
*/
public static String stringifyMap(Map<String, String> map) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.append(entry.getKey())
.append("=\"")
.append(entry.getValue())
.append("\"\n");
}
return builder.toString();
}
/**
* Convert a YARN URL into a string value of a normal URL
* @param url URL
* @return string representatin
*/
public static String stringify(org.apache.hadoop.yarn.api.records.URL url) {
StringBuilder builder = new StringBuilder();
builder.append(url.getScheme()).append("://");
if (url.getHost() != null) {
builder.append(url.getHost()).append(":").append(url.getPort());
}
builder.append(url.getFile());
return builder.toString();
}
/**
* Get a random open port
* @return true if the port was available for listening on
*/
public static int getOpenPort() throws IOException {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
return socket.getLocalPort();
} finally {
if (socket != null) {
socket.close();
}
}
}
/**
* See if a port is available for listening on by trying to listen
* on it and seeing if that works or fails.
* @param port port to listen to
* @return true if the port was available for listening on
*/
public static boolean isPortAvailable(int port) {
try {
ServerSocket socket = new ServerSocket(port);
socket.close();
return true;
} catch (IOException e) {
return false;
}
}
// Build env map: key -> value;
// value will be replaced by the corresponding value in tokenMap, if any.
public static Map<String, String> buildEnvMap(
org.apache.hadoop.yarn.service.api.records.Configuration conf,
Map<String,String> tokenMap) {
if (tokenMap == null) {
return conf.getEnv();
}
Map<String, String> env = new HashMap<>();
for (Map.Entry<String, String> entry : conf.getEnv().entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
for (Map.Entry<String,String> token : tokenMap.entrySet()) {
val = val.replaceAll(Pattern.quote(token.getKey()),
token.getValue());
}
env.put(key,val);
}
return env;
}
public static String[] getLibDirs() {
String libDirStr = System.getProperty(YarnServiceConstants.PROPERTY_LIB_DIR);
if (isUnset(libDirStr)) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
return StringUtils.split(libDirStr, ',');
}
/**
* Submit a JAR containing a specific class and map it
* @param providerResources provider map to build up
* @param sliderFileSystem remote fs
* @param clazz class to look for
* @param libdir lib directory
* @param jarName <i>At the destination</i>
* @return the local resource ref
* @throws IOException trouble copying to HDFS
*/
public static LocalResource putJar(Map<String, LocalResource> providerResources,
SliderFileSystem sliderFileSystem,
Class clazz,
Path tempPath,
String libdir,
String jarName
)
throws IOException, SliderException {
LocalResource res = sliderFileSystem.submitJarWithClass(
clazz,
tempPath,
libdir,
jarName);
providerResources.put(libdir + "/" + jarName, res);
return res;
}
/**
* Submit a JAR containing and map it
* @param providerResources provider map to build up
* @param sliderFileSystem remote fs
* @param libDir lib directory
* @param srcPath copy jars from
*/
public static void putAllJars(Map<String, LocalResource> providerResources,
SliderFileSystem sliderFileSystem,
Path tempPath,
String libDir,
String srcPath) throws IOException, SliderException {
log.debug("Loading all dependencies from {}", srcPath);
if (ServiceUtils.isSet(srcPath)) {
File srcFolder = new File(srcPath);
FilenameFilter jarFilter = createJarFilter();
File[] listOfJars = srcFolder.listFiles(jarFilter);
if (listOfJars == null || listOfJars.length == 0) {
return;
}
for (File jarFile : listOfJars) {
if (!jarFile.exists()) {
log.debug("File does not exist, skipping: " + jarFile);
continue;
}
LocalResource res = sliderFileSystem.submitFile(jarFile, tempPath, libDir, jarFile.getName());
providerResources.put(libDir + "/" + jarFile.getName(), res);
}
}
}
/**
* Accept all filenames ending with {@code .jar}
* @return a filename filter
*/
public static FilenameFilter createJarFilter() {
return new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase(Locale.ENGLISH).endsWith(".jar");
}
};
}
/**
* Create a file:// path from a local file
* @param file file to point the path
* @return a new Path
*/
public static Path createLocalPath(File file) {
return new Path(file.toURI());
}
/**
* Build up the classpath for execution
* -behaves very differently on a mini test cluster vs a production
* production one.
*
* @param sliderConfDir relative path to the dir containing slider config
* options to put on the classpath -or null
* @param libdir directory containing the JAR files
* @param configClassPath extra class path configured in yarn-site.xml
* @param usingMiniMRCluster flag to indicate the MiniMR cluster is in use
* (and hence the current classpath should be used, not anything built up)
* @return a classpath
*/
public static ClasspathConstructor buildClasspath(String sliderConfDir,
String libdir,
SliderFileSystem sliderFileSystem,
String configClassPath,
boolean usingMiniMRCluster) {
ClasspathConstructor classpath = new ClasspathConstructor();
classpath.append(YarnServiceConstants.YARN_SERVICE_LOG4J_FILENAME);
// add the runtime classpath needed for tests to work
if (usingMiniMRCluster) {
// for mini cluster we pass down the java CP properties
// and nothing else
classpath.appendAll(classpath.localJVMClasspath());
} else {
if (sliderConfDir != null) {
classpath.addClassDirectory(sliderConfDir);
}
classpath.addLibDir(libdir);
if (sliderFileSystem.isFile(sliderFileSystem.getDependencyTarGzip())) {
classpath.addLibDir(YarnServiceConstants.DEPENDENCY_LOCALIZED_DIR_LINK);
}
classpath.addRemoteClasspathEnvVar();
classpath.append(ApplicationConstants.Environment.HADOOP_CONF_DIR.$$());
}
if (!configClassPath.isEmpty()) {
classpath.appendAll(Arrays.asList(configClassPath.split(",")));
}
return classpath;
}
/**
* Given a source folder create a tar.gz file
*
* @param libDirs
* @param tarGzipFile
*
* @throws IOException
*/
public static void tarGzipFolder(String[] libDirs, File tarGzipFile,
FilenameFilter filter) throws IOException {
log.info("Tar-gzipping folders {} to {}", libDirs,
tarGzipFile.getAbsolutePath());
try(TarArchiveOutputStream taos =
new TarArchiveOutputStream(new GZIPOutputStream(
new BufferedOutputStream(new FileOutputStream(tarGzipFile))))) {
for (String libDir : libDirs) {
File srcFolder = new File(libDir);
List<String> files = new ArrayList<>();
generateFileList(files, srcFolder, srcFolder, true, filter);
for (String file : files) {
File srcFile = new File(srcFolder, file);
TarArchiveEntry tarEntry = new TarArchiveEntry(
srcFile, file);
taos.putArchiveEntry(tarEntry);
try(FileInputStream in = new FileInputStream(srcFile)) {
org.apache.commons.io.IOUtils.copy(in, taos);
}
taos.flush();
taos.closeArchiveEntry();
}
}
}
}
private static void generateFileList(List<String> fileList, File node,
File rootFolder, Boolean relative, FilenameFilter filter) {
if (node.isFile()) {
String fileFullPath = node.toString();
if (relative) {
fileList.add(fileFullPath.substring(rootFolder.toString().length() + 1,
fileFullPath.length()));
} else {
fileList.add(fileFullPath);
}
}
if (node.isDirectory()) {
String[] subNode = node.list(filter);
if (subNode == null || subNode.length == 0) {
return;
}
for (String filename : subNode) {
generateFileList(fileList, new File(node, filename), rootFolder,
relative, filter);
}
}
}
public static String createNameTag(String name) {
return "Name: " + name;
}
public static String createVersionTag(String version) {
return "Version: " + version;
}
public static String createDescriptionTag(String description) {
return "Description: " + description;
}
// Copied from SecurityUtil because it is not public
public static String getLocalHostName(@Nullable Configuration conf)
throws UnknownHostException {
if (conf != null) {
String dnsInterface = conf.get(HADOOP_SECURITY_DNS_INTERFACE_KEY);
String nameServer = conf.get(HADOOP_SECURITY_DNS_NAMESERVER_KEY);
if (dnsInterface != null) {
return DNS.getDefaultHost(dnsInterface, nameServer, true);
} else if (nameServer != null) {
throw new IllegalArgumentException(HADOOP_SECURITY_DNS_NAMESERVER_KEY +
" requires " + HADOOP_SECURITY_DNS_INTERFACE_KEY + ". Check your" +
"configuration.");
}
}
// Fallback to querying the default hostname as we did before.
return InetAddress.getLocalHost().getCanonicalHostName();
}
/**
* Process termination handler - exist with specified exit code after
* waiting a while for ATS state to be in sync.
*/
public static class ProcessTerminationHandler {
public void terminate(int exitCode) {
// Sleep for 5 seconds in hope that the state can be recorded in ATS.
// in case there's a client polling the comp state, it can be notified.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
log.info("Interrupted on sleep while exiting.", e);
}
ExitUtil.terminate(exitCode);
}
}
}
| apache-2.0 |
ligi/bitcoinj | core/src/main/java/com/google/bitcoin/core/AbstractBlockChainListener.java | 1443 | /**
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import java.util.List;
/**
* Default no-op implementation of {@link BlockChainListener}.
*/
public class AbstractBlockChainListener implements BlockChainListener {
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
}
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
}
public boolean isTransactionRelevant(Transaction tx) throws ScriptException {
return false;
}
public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType) throws VerificationException {
}
public void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType) throws VerificationException {
}
}
| apache-2.0 |
txazo/struts2 | src/main/java/org/apache/struts2/config/NullResult.java | 1211 | /*
* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.config;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
/**
* Null result to get around annotation defaults that can't be null
*/
public class NullResult implements Result {
public void execute(ActionInvocation invocation) throws Exception {
throw new IllegalStateException("Shouldn't be called");
}
}
| apache-2.0 |
strava/thrift | lib/java/src/org/apache/thrift/transport/TMemoryBuffer.java | 3640 | /*
* 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.thrift.transport;
import org.apache.thrift.TByteArrayOutputStream;
import org.apache.thrift.TConfiguration;
import java.nio.charset.Charset;
/**
* Memory buffer-based implementation of the TTransport interface.
*/
public class TMemoryBuffer extends TEndpointTransport {
/**
* Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The
* internal buffer will grow as necessary to accommodate the size of the data
* being written to it.
*
* @param size the initial size of the buffer
* @throws TTransportException on error initializing the underlying transport.
*/
public TMemoryBuffer(int size) throws TTransportException {
super(new TConfiguration());
arr_ = new TByteArrayOutputStream(size);
updateKnownMessageSize(size);
}
/**
* Create a TMemoryBuffer with an initial buffer size of <i>size</i>. The
* internal buffer will grow as necessary to accommodate the size of the data
* being written to it.
*
* @param config the configuration to use.
* @param size the initial size of the buffer
* @throws TTransportException on error initializing the underlying transport.
*/
public TMemoryBuffer(TConfiguration config, int size) throws TTransportException {
super(config);
arr_ = new TByteArrayOutputStream(size);
updateKnownMessageSize(size);
}
@Override
public boolean isOpen() {
return true;
}
@Override
public void open() {
/* Do nothing */
}
@Override
public void close() {
/* Do nothing */
}
@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
checkReadBytesAvailable(len);
byte[] src = arr_.get();
int amtToRead = (len > arr_.len() - pos_ ? arr_.len() - pos_ : len);
if (amtToRead > 0) {
System.arraycopy(src, pos_, buf, off, amtToRead);
pos_ += amtToRead;
}
return amtToRead;
}
@Override
public void write(byte[] buf, int off, int len) {
arr_.write(buf, off, len);
}
/**
* Output the contents of the memory buffer as a String, using the supplied
* encoding
* @param charset the encoding to use
* @return the contents of the memory buffer as a String
*/
public String toString(Charset charset) {
return arr_.toString(charset);
}
public String inspect() {
StringBuilder buf = new StringBuilder();
byte[] bytes = arr_.toByteArray();
for (int i = 0; i < bytes.length; i++) {
buf.append(pos_ == i ? "==>" : "" ).append(Integer.toHexString(bytes[i] & 0xff)).append(" ");
}
return buf.toString();
}
// The contents of the buffer
private TByteArrayOutputStream arr_;
// Position to read next byte from
private int pos_;
public int length() {
return arr_.size();
}
public byte[] getArray() {
return arr_.get();
}
}
| apache-2.0 |
prasi-in/geode | geode-core/src/main/java/org/apache/geode/management/internal/cli/domain/FixedPartitionAttributesInfo.java | 2145 | /*
* 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.management.internal.cli.domain;
import java.io.Serializable;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.geode.cache.FixedPartitionAttributes;
public class FixedPartitionAttributesInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean isPrimary;
private String partitionName;
private int numBuckets;
public FixedPartitionAttributesInfo(FixedPartitionAttributes fpa) {
this.numBuckets = fpa.getNumBuckets();
this.partitionName = fpa.getPartitionName();
this.isPrimary = fpa.isPrimary();
}
public boolean equals(Object obj) {
if (obj instanceof FixedPartitionAttributesInfo) {
FixedPartitionAttributesInfo fpaInfo = (FixedPartitionAttributesInfo) obj;
return this.numBuckets == fpaInfo.getNumBuckets()
&& StringUtils.equals(this.partitionName, fpaInfo.getPartitionName())
&& this.isPrimary == fpaInfo.isPrimary();
} else {
return false;
}
}
public int hashCode() {
return 42; // any arbitrary constant will do
}
public int getNumBuckets() {
return this.numBuckets;
}
public String getPartitionName() {
return this.partitionName;
}
public boolean isPrimary() {
return this.isPrimary;
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/multimap/impl/operations/CountOperation.java | 2685 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.multimap.impl.operations;
import com.hazelcast.internal.locksupport.LockWaitNotifyKey;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.multimap.impl.MultiMapContainer;
import com.hazelcast.multimap.impl.MultiMapDataSerializerHook;
import com.hazelcast.multimap.impl.MultiMapService;
import com.hazelcast.multimap.impl.MultiMapValue;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.BlockingOperation;
import com.hazelcast.internal.services.DistributedObjectNamespace;
import com.hazelcast.spi.impl.operationservice.ReadonlyOperation;
import com.hazelcast.spi.impl.operationservice.WaitNotifyKey;
public class CountOperation extends AbstractKeyBasedMultiMapOperation implements BlockingOperation, ReadonlyOperation {
public CountOperation() {
}
public CountOperation(String name, Data dataKey) {
super(name, dataKey);
}
@Override
public void run() throws Exception {
MultiMapContainer container = getOrCreateContainer();
((MultiMapService) getService()).getLocalMultiMapStatsImpl(name).incrementOtherOperations();
MultiMapValue multiMapValue = container.getMultiMapValueOrNull(dataKey);
response = multiMapValue == null ? 0 : multiMapValue.getCollection(false).size();
}
@Override
public int getClassId() {
return MultiMapDataSerializerHook.COUNT;
}
@Override
public WaitNotifyKey getWaitKey() {
return new LockWaitNotifyKey(new DistributedObjectNamespace(MultiMapService.SERVICE_NAME, name), dataKey);
}
@Override
public boolean shouldWait() {
MultiMapContainer container = getOrCreateContainer();
if (container.isTransactionallyLocked(dataKey)) {
return !container.canAcquireLock(dataKey, getCallerUuid(), threadId);
}
return false;
}
@Override
public void onWaitExpire() {
sendResponse(new OperationTimeoutException("Cannot read transactionally locked entry!"));
}
}
| apache-2.0 |
zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/CreateVpcUserVpnGatewayRemoteResult.java | 382 | package org.zstack.sdk;
import org.zstack.sdk.VpcUserVpnGatewayInventory;
public class CreateVpcUserVpnGatewayRemoteResult {
public VpcUserVpnGatewayInventory inventory;
public void setInventory(VpcUserVpnGatewayInventory inventory) {
this.inventory = inventory;
}
public VpcUserVpnGatewayInventory getInventory() {
return this.inventory;
}
}
| apache-2.0 |
facebook/buck | test/com/facebook/buck/cli/ServerStatusCommandTest.java | 2510 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.cli;
import static org.junit.Assert.assertEquals;
import com.facebook.buck.httpserver.WebServer;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.util.timing.FakeClock;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
public class ServerStatusCommandTest {
private TestConsole console;
private CommandRunnerParams params;
private int webServerPort;
@Before
public void setUp() {
console = new TestConsole();
WebServer webServer =
new WebServer(0, new FakeProjectFilesystem(), FakeClock.doNotCare()) {
@Override
public int getPort() {
return webServerPort;
}
};
params =
CommandRunnerParamsForTesting.builder()
.setWebserver(Optional.of(webServer))
.setConsole(console)
.build();
}
@Test
public void testWhenHttpserverRunning() throws Exception {
webServerPort = 9000;
ServerStatusCommand command = new ServerStatusCommand();
command.enableShowHttpserverPort();
command.run(params);
assertEquals("http.port=9000", console.getTextWrittenToStdOut().trim());
}
@Test
public void testWhenHttpserverNotRunning() throws Exception {
webServerPort = -1;
ServerStatusCommand command = new ServerStatusCommand();
command.enableShowHttpserverPort();
command.run(params);
assertEquals("http.port=-1", console.getTextWrittenToStdOut().trim());
}
@Test
public void testPrintJson() throws Exception {
webServerPort = 9000;
ServerStatusCommand command = new ServerStatusCommand();
command.enableShowHttpserverPort();
command.enablePrintJson();
command.run(params);
assertEquals("{\"http.port\":9000}", console.getTextWrittenToStdOut().trim());
}
}
| apache-2.0 |
baboune/compass | src/main/test/org/compass/core/test/analyzer/ResourceAnalyzerTests.java | 8240 | /*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.compass.core.test.analyzer;
import org.compass.core.CompassHits;
import org.compass.core.CompassQuery;
import org.compass.core.CompassSession;
import org.compass.core.CompassToken;
import org.compass.core.CompassTransaction;
import org.compass.core.Resource;
import org.compass.core.engine.SearchEngineException;
/**
* @author kimchy
*/
public class ResourceAnalyzerTests extends AbstractAnalyzerTests {
protected String[] getMappings() {
return new String[]{"analyzer/resource.cpm.xml"};
}
public void testResourceNoAnalyzer() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("a");
r.addProperty("id", id);
r.addProperty("value", TEXT);
session.save(r);
CompassHits hits = session.find("a.value:the");
assertEquals(0, hits.getLength());
// test for the all property as well
hits = session.find("the");
assertEquals(0, hits.getLength());
// this one will use the simple analyzer
CompassToken[] tokens = session.analyzerHelper().setAnalyzer("simple").analyze(r.getValue("value"));
assertEquals(9, tokens.length);
assertEquals("the", tokens[0].getTermText());
assertEquals("quick", tokens[1].getTermText());
assertEquals("brown", tokens[2].getTermText());
assertEquals("fox", tokens[3].getTermText());
// this one will use the default analyzer
tokens = session.analyzerHelper().setAnalyzerByAlias("a").analyze(r.getValue("value"));
assertEquals(7, tokens.length);
assertEquals("quick", tokens[0].getTermText());
assertEquals("brown", tokens[1].getTermText());
assertEquals("fox", tokens[2].getTermText());
tr.commit();
}
public void testResourceAnalyzerSetForResource() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("b");
r.addProperty("id", id);
r.addProperty("value", TEXT);
session.save(r);
CompassHits hits = session.find("b.value:the");
assertEquals(1, hits.getLength());
// test for the all property as well
hits = session.find("the");
assertEquals(1, hits.getLength());
tr.commit();
}
public void testResourceAnalyzerSetForResourceWithCompassQuery() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("b");
r.addProperty("id", id);
r.addProperty("value", TEXT);
session.save(r);
CompassHits hits = session.find("b.value:the");
assertEquals(1, hits.getLength());
// test for the all property as well
hits = session.find("the");
assertEquals(1, hits.length());
// this won't take into account without forcing the analyzer
CompassQuery query = session.queryBuilder().queryString("b.value:the").setAnalyzer("default").toQuery();
assertEquals(1, query.hits().getLength());
query = session.queryBuilder().queryString("b.value:the").setAnalyzer("default").forceAnalyzer().toQuery();
assertEquals(0, query.hits().getLength());
query = session.queryBuilder().queryString("b.value:the").setAnalyzer("simple").forceAnalyzer().toQuery();
assertEquals(1, query.hits().length());
tr.commit();
}
public void testResourceAnalyzerSetForProperty() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("d");
r.addProperty("id", id);
r.addProperty("value", TEXT);
r.addProperty("value2", TEXT);
session.save(r);
CompassHits hits = session.find("d.value:the");
assertEquals(1, hits.getLength());
hits = session.find("d.value2:the");
assertEquals(0, hits.getLength());
// test for the all property as well
hits = session.find("the");
assertEquals(1, hits.getLength());
tr.commit();
}
public void testResourceAnalyzerSetForResourceAndProperty() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("e");
r.addProperty("id", id);
r.addProperty("value", TEXT);
r.addProperty("value2", TEXT);
session.save(r);
CompassHits hits = session.find("e.value:the");
assertEquals(0, hits.getLength());
hits = session.find("e.value2:the");
assertEquals(1, hits.getLength());
tr.commit();
}
public void testResourceAnalyzerController() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("g");
r.addProperty("id", id);
r.addProperty("value", TEXT);
r.addProperty("analyzer", "simple");
session.save(r);
CompassHits hits = session.find("g.value:the");
assertEquals(1, hits.getLength());
r = getCompass().getResourceFactory().createResource("g");
r.addProperty("id", id);
r.addProperty("value", TEXT);
try {
session.save(r);
tr.commit();
fail();
} catch (SearchEngineException e) {
tr.rollback();
}
session.close();
}
public void testResourceAnalyzerControllerWithNullAnalyzer() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("g");
r.addProperty("id", id);
r.addProperty("value", TEXT);
r.addProperty("analyzer", "simple");
session.save(r);
CompassHits hits = session.find("g.value:the");
assertEquals(1, hits.getLength());
r = getCompass().getResourceFactory().createResource("h");
r.addProperty("id", id);
r.addProperty("value", TEXT);
session.save(r);
// analyzer controller can't affect query string (since we don't have the resource), just for simple and
// check that both h and i were saved
hits = session.queryBuilder().queryString("value:the").setAnalyzer("simple").forceAnalyzer().toQuery().hits();
assertEquals(2, hits.getLength());
tr.commit();
}
public void testResourceAnalyzerControllerWithNullAnalyzerAndPropertyAnalyzer() {
CompassSession session = openSession();
CompassTransaction tr = session.beginTransaction();
Long id = (long) 1;
Resource r = getCompass().getResourceFactory().createResource("i");
r.addProperty("id", id);
r.addProperty("value", TEXT);
r.addProperty("analyzer", "simple");
session.save(r);
CompassHits hits = session.queryBuilder().queryString("value:the").setAnalyzer("simple").forceAnalyzer().toQuery().hits();
assertEquals(0, hits.getLength());
tr.commit();
}
}
| apache-2.0 |
rockerbox/presto | presto-tests/src/main/java/com/facebook/presto/tests/StandaloneQueryRunner.java | 6611 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.tests;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.AllNodes;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.QualifiedTableName;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.server.testing.TestingPrestoServer;
import com.facebook.presto.spi.Node;
import com.facebook.presto.spi.Plugin;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.QueryRunner;
import com.facebook.presto.testing.TestingAccessControlManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import io.airlift.testing.Closeables;
import org.intellij.lang.annotations.Language;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public final class StandaloneQueryRunner
implements QueryRunner
{
private final TestingPrestoServer server;
private final TestingPrestoClient prestoClient;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public StandaloneQueryRunner(Session defaultSession)
throws Exception
{
checkNotNull(defaultSession, "defaultSession is null");
try {
server = createTestingPrestoServer();
}
catch (Exception e) {
close();
throw e;
}
this.prestoClient = new TestingPrestoClient(server, defaultSession);
refreshNodes();
server.getMetadata().addFunctions(AbstractTestQueries.CUSTOM_FUNCTIONS);
SessionPropertyManager sessionPropertyManager = server.getMetadata().getSessionPropertyManager();
sessionPropertyManager.addSystemSessionProperties(AbstractTestQueries.TEST_SYSTEM_PROPERTIES);
sessionPropertyManager.addConnectorSessionProperties("catalog", AbstractTestQueries.TEST_CATALOG_PROPERTIES);
}
@Override
public MaterializedResult execute(@Language("SQL") String sql)
{
lock.readLock().lock();
try {
return prestoClient.execute(sql);
}
finally {
lock.readLock().unlock();
}
}
@Override
public MaterializedResult execute(Session session, @Language("SQL") String sql)
{
lock.readLock().lock();
try {
return prestoClient.execute(session, sql);
}
finally {
lock.readLock().unlock();
}
}
@Override
public void close()
{
Closeables.closeQuietly(prestoClient);
Closeables.closeQuietly(server);
}
@Override
public int getNodeCount()
{
return 1;
}
@Override
public Session getDefaultSession()
{
return prestoClient.getDefaultSession();
}
@Override
public Metadata getMetadata()
{
return server.getMetadata();
}
@Override
public TestingAccessControlManager getAccessControl()
{
return server.getAccessControl();
}
public TestingPrestoServer getServer()
{
return server;
}
public void refreshNodes()
{
AllNodes allNodes;
do {
try {
MILLISECONDS.sleep(10);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
allNodes = server.refreshNodes();
}
while (allNodes.getActiveNodes().isEmpty());
}
private void refreshNodes(String catalogName)
{
Set<Node> activeNodesWithConnector;
do {
try {
MILLISECONDS.sleep(10);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
activeNodesWithConnector = server.getActiveNodesWithConnector(catalogName);
}
while (activeNodesWithConnector.isEmpty());
}
public void installPlugin(Plugin plugin)
{
server.installPlugin(plugin);
}
public void createCatalog(String catalogName, String connectorName)
{
createCatalog(catalogName, connectorName, ImmutableMap.<String, String>of());
}
public void createCatalog(String catalogName, String connectorName, Map<String, String> properties)
{
server.createCatalog(catalogName, connectorName, properties);
refreshNodes(catalogName);
}
@Override
public List<QualifiedTableName> listTables(Session session, String catalog, String schema)
{
lock.readLock().lock();
try {
return prestoClient.listTables(session, catalog, schema);
}
finally {
lock.readLock().unlock();
}
}
@Override
public boolean tableExists(Session session, String table)
{
lock.readLock().lock();
try {
return prestoClient.tableExists(session, table);
}
finally {
lock.readLock().unlock();
}
}
@Override
public Lock getExclusiveLock()
{
return lock.writeLock();
}
private static TestingPrestoServer createTestingPrestoServer()
throws Exception
{
ImmutableMap.Builder<String, String> properties = ImmutableMap.<String, String>builder()
.put("query.client.timeout", "10m")
.put("exchange.http-client.read-timeout", "1h")
.put("compiler.interpreter-enabled", "false")
.put("node-scheduler.min-candidates", "1")
.put("datasources", "system");
return new TestingPrestoServer(true, properties.build(), null, null, ImmutableList.<Module>of());
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/multimap/MultiMapReturnedCollectionTest.java | 4821 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.multimap;
import com.hazelcast.config.Config;
import com.hazelcast.config.MultiMapConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class MultiMapReturnedCollectionTest extends HazelcastTestSupport {
@Test
public void testGet_withSetBackedValueCollection() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.SET);
multiMap.put(0, 1);
multiMap.put(0, 2);
multiMap.put(0, 3);
Collection<Integer> collection = multiMap.get(0);
assertTrue(collection instanceof Set);
}
@Test
public void testGet_withSetBackedValueCollection_onEmptyMultiMap() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.SET);
Collection<Integer> collection = multiMap.get(0);
assertTrue(collection instanceof Set);
}
@Test
public void testGet_withListBackedValueCollection() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.LIST);
multiMap.put(0, 1);
multiMap.put(0, 2);
multiMap.put(0, 3);
Collection<Integer> collection = multiMap.get(0);
assertTrue(collection instanceof List);
}
@Test
public void testGet_withListBackedValueCollection_onEmptyMultiMap() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.LIST);
Collection<Integer> collection = multiMap.get(0);
assertTrue(collection instanceof List);
}
@Test
public void testRemove_withSetBackedValueCollection() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.SET);
multiMap.put(0, 1);
multiMap.put(0, 2);
multiMap.put(0, 3);
Collection<Integer> collection = multiMap.remove(0);
assertTrue(collection instanceof Set);
}
@Test
public void testRemove_withSetBackedValueCollection_onEmptyMultiMap() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.SET);
Collection<Integer> collection = multiMap.remove(0);
assertTrue(collection instanceof Set);
}
@Test
public void testRemove_withListBackedValueCollection() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.LIST);
multiMap.put(0, 1);
multiMap.put(0, 2);
multiMap.put(0, 3);
Collection<Integer> collection = multiMap.remove(0);
assertTrue(collection instanceof List);
}
@Test
public void testRemove_withListBackedValueCollection_onEmptyMultiMap() {
MultiMap<Integer, Integer> multiMap = createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType.LIST);
Collection<Integer> collection = multiMap.remove(0);
assertTrue(collection instanceof List);
}
private MultiMap<Integer, Integer> createMultiMapWithCollectionType(MultiMapConfig.ValueCollectionType collectionType) {
String multiMapName = randomMapName();
Config config = new Config();
config.getMultiMapConfig(multiMapName)
.setValueCollectionType(collectionType);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance[] instances = factory.newInstances(config);
return instances[0].getMultiMap(multiMapName);
}
}
| apache-2.0 |
hoanganhx86/SeriesGuide | SeriesGuide/src/main/java/com/battlelancer/seriesguide/adapters/ListsAdapter.java | 2618 | /*
* Copyright 2015 Uwe Trottmann
*
* 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.battlelancer.seriesguide.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.loaders.OrderedListsLoader;
import java.util.List;
/**
* Used with {@link com.battlelancer.seriesguide.ui.dialogs.ListsReorderDialogFragment}.
*/
public class ListsAdapter extends ArrayAdapter<OrderedListsLoader.OrderedList> {
static class ListsViewHolder {
public TextView name;
public ListsViewHolder(View v) {
name = (TextView) v.findViewById(R.id.textViewItemListName);
}
}
private List<OrderedListsLoader.OrderedList> dataset;
public ListsAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListsViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_list, parent, false);
viewHolder = new ListsViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ListsViewHolder) convertView.getTag();
}
OrderedListsLoader.OrderedList item = getItem(position);
viewHolder.name.setText(item.name);
return convertView;
}
public synchronized void setData(List<OrderedListsLoader.OrderedList> dataset) {
this.dataset = dataset;
clear();
if (dataset != null) {
addAll(dataset);
}
}
public synchronized void reorderList(int from, int to) {
if (dataset == null || from >= dataset.size()) {
return;
}
OrderedListsLoader.OrderedList list = dataset.remove(from);
dataset.add(to, list);
clear();
addAll(dataset);
}
}
| apache-2.0 |
CIETstudents/Cinder-Krishna-Mona | nova-client/src/main/java/com/woorea/openstack/nova/api/extensions/CredentialsExtension.java | 1847 | package com.woorea.openstack.nova.api.extensions;
import com.woorea.openstack.base.client.HttpMethod;
import com.woorea.openstack.base.client.OpenStackClient;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.nova.model.Certificate;
/**
* @author Govindon.
*/
public class CredentialsExtension {
/**
* The instance of OpenStackClient access the CredentialsExtension class.
*/
private final OpenStackClient CLIENT;
/**
* The instance is used to access the CredentialsExtension class.
*
* @param client the client to set
*/
public CredentialsExtension(OpenStackClient client) {
CLIENT = client;
}
/**
*
* @param id
* @return
*/
public Create createCertificate(String id) {
return new Create(id);
}
/**
* shows the certificate.
*
* @param id the id to set
* @return the certificate
*/
public Show showCertificate(String id) {
return new Show();
}
/**
* The class extends the Certificate class from the Nova Model.
*/
public class Create extends OpenStackRequest<Certificate> {
/**
* Create the Certificate.
*
* @param id the id to set
*/
public Create(String id) {
super(CLIENT, HttpMethod.GET, new StringBuffer("/os-certificates")
.append(id).toString(), null, Certificate.class);
}
}
/**
* The class show extends the Certificate Class from the Nova Model.
*/
public class Show extends OpenStackRequest<Certificate> {
/**
* Shows the certificate.
*/
public Show() {
super(CLIENT, HttpMethod.GET, "/os-certificates", null,
Certificate.class);
}
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/isVariable/Read.java | 142 | package one.two;
public class Read {
public static void main(String[] args) {
int i = KotlinObject.INSTANCE.isVariable();
}
} | apache-2.0 |
facebook/buck | src/com/facebook/buck/query/NoopQueryEvaluator.java | 1039 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.query;
import com.facebook.buck.core.model.QueryTarget;
import java.util.Set;
public class NoopQueryEvaluator<ENV_NODE_TYPE> implements QueryEvaluator<ENV_NODE_TYPE> {
@Override
public <OUTPUT_TYPE extends QueryTarget> Set<OUTPUT_TYPE> eval(
QueryExpression<ENV_NODE_TYPE> exp, QueryEnvironment<ENV_NODE_TYPE> env)
throws QueryException {
return exp.eval(this, env);
}
}
| apache-2.0 |
pwoodworth/intellij-community | python/educational/interactive-learning/src/com/jetbrains/edu/learning/actions/StudyRefreshTaskFileAction.java | 7920 | package com.jetbrains.edu.learning.actions;
import com.intellij.icons.AllIcons;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.KeyboardShortcut;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.problems.WolfTheProblemSolver;
import com.jetbrains.edu.EduAnswerPlaceholderPainter;
import com.jetbrains.edu.EduNames;
import com.jetbrains.edu.EduUtils;
import com.jetbrains.edu.courseFormat.AnswerPlaceholder;
import com.jetbrains.edu.courseFormat.Course;
import com.jetbrains.edu.courseFormat.Task;
import com.jetbrains.edu.courseFormat.TaskFile;
import com.jetbrains.edu.learning.StudyState;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.learning.courseFormat.StudyStatus;
import com.jetbrains.edu.learning.editor.StudyEditor;
import com.jetbrains.edu.learning.navigation.StudyNavigator;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
public class StudyRefreshTaskFileAction extends DumbAwareAction {
public static final String ACTION_ID = "RefreshTaskAction";
public static final String SHORTCUT = "ctrl shift pressed X";
private static final Logger LOG = Logger.getInstance(StudyRefreshTaskFileAction.class.getName());
public StudyRefreshTaskFileAction() {
super("Reset Task File (" + KeymapUtil.getShortcutText(new KeyboardShortcut(KeyStroke.getKeyStroke(SHORTCUT), null)) + ")", "Refresh current task", AllIcons.Actions.Refresh);
}
public static void refresh(@NotNull final Project project) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
@Override
public void run() {
StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project);
StudyState studyState = new StudyState(studyEditor);
if (studyEditor == null || !studyState.isValid()) {
LOG.info("RefreshTaskFileAction was invoked outside of Study Editor");
return;
}
refreshFile(studyState, project);
}
});
}
});
}
private static void refreshFile(@NotNull final StudyState studyState, @NotNull final Project project) {
final Editor editor = studyState.getEditor();
final TaskFile taskFile = studyState.getTaskFile();
if (!resetTaskFile(editor.getDocument(), project, taskFile, studyState.getVirtualFile().getName())) {
return;
}
WolfTheProblemSolver.getInstance(project).clearProblems(studyState.getVirtualFile());
taskFile.setHighlightErrors(false);
StudyUtils.drawAllWindows(editor, taskFile);
EduAnswerPlaceholderPainter.createGuardedBlocks(editor, taskFile, true);
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true);
}
});
StudyNavigator.navigateToFirstAnswerPlaceholder(editor, taskFile);
showBalloon(project, "You can start again now", MessageType.INFO);
}
private static boolean resetTaskFile(@NotNull final Document document,
@NotNull final Project project,
TaskFile taskFile,
String name) {
if (!resetDocument(project, document, taskFile, name)) {
return false;
}
resetAnswerPlaceholders(taskFile, project);
ProjectView.getInstance(project).refresh();
StudyUtils.updateStudyToolWindow(project);
return true;
}
private static void showBalloon(@NotNull final Project project, String text, @NotNull final MessageType messageType) {
BalloonBuilder balloonBuilder =
JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(text, messageType, null);
final Balloon balloon = balloonBuilder.createBalloon();
StudyEditor selectedStudyEditor = StudyUtils.getSelectedStudyEditor(project);
assert selectedStudyEditor != null;
balloon.show(StudyUtils.computeLocation(selectedStudyEditor.getEditor()), Balloon.Position.above);
Disposer.register(project, balloon);
}
private static void resetAnswerPlaceholders(TaskFile selectedTaskFile, Project project) {
final StudyTaskManager taskManager = StudyTaskManager.getInstance(project);
for (AnswerPlaceholder answerPlaceholder : selectedTaskFile.getAnswerPlaceholders()) {
answerPlaceholder.reset();
taskManager.setStatus(answerPlaceholder, StudyStatus.Unchecked);
}
}
private static boolean resetDocument(@NotNull final Project project,
@NotNull final Document document,
@NotNull final TaskFile taskFile,
String fileName) {
StudyUtils.deleteGuardedBlocks(document);
taskFile.setTrackChanges(false);
clearDocument(document);
Task task = taskFile.getTask();
String lessonDir = EduNames.LESSON + String.valueOf(task.getLesson().getIndex());
String taskDir = EduNames.TASK + String.valueOf(task.getIndex());
Course course = task.getLesson().getCourse();
File resourceFile = new File(course.getCourseDirectory());
if (!resourceFile.exists()) {
showBalloon(project, "Course was deleted", MessageType.ERROR);
return false;
}
String patternPath = FileUtil.join(resourceFile.getPath(), lessonDir, taskDir, fileName);
VirtualFile patternFile = VfsUtil.findFileByIoFile(new File(patternPath), true);
if (patternFile == null) {
return false;
}
final Document patternDocument = FileDocumentManager.getInstance().getDocument(patternFile);
if (patternDocument == null) {
return false;
}
document.setText(patternDocument.getCharsSequence());
taskFile.setTrackChanges(true);
return true;
}
private static void clearDocument(@NotNull final Document document) {
final int lineCount = document.getLineCount();
if (lineCount != 0) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
document.deleteString(0, document.getLineEndOffset(lineCount - 1));
}
});
}
}
public void actionPerformed(@NotNull AnActionEvent event) {
final Project project = event.getProject();
if (project != null) {
refresh(project);
}
}
@Override
public void update(AnActionEvent event) {
EduUtils.enableAction(event, false);
final Project project = event.getProject();
if (project != null) {
StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project);
StudyState studyState = new StudyState(studyEditor);
if (studyState.isValid()) {
EduUtils.enableAction(event, true);
}
}
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/client/map/impl/nearcache/ClientMapNearCacheRecordStateStressTest.java | 7289 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.map.impl.nearcache;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.config.Config;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.nearcache.impl.DefaultNearCache;
import com.hazelcast.map.IMap;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.NightlyTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.hazelcast.internal.nearcache.impl.NearCacheTestUtils.getBaseConfig;
import static com.hazelcast.internal.util.RandomPicker.getInt;
import static com.hazelcast.map.impl.nearcache.MapNearCacheRecordStateStressTest.assertNearCacheRecordStates;
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class ClientMapNearCacheRecordStateStressTest extends HazelcastTestSupport {
private static final int KEY_SPACE = 100;
private static final int TEST_RUN_SECONDS = 60;
private static final int GET_ALL_THREAD_COUNT = 3;
private static final int GET_THREAD_COUNT = 2;
private static final int PUT_THREAD_COUNT = 1;
private static final int CLEAR_THREAD_COUNT = 1;
private static final int REMOVE_THREAD_COUNT = 1;
private final TestHazelcastFactory factory = new TestHazelcastFactory();
private final AtomicBoolean stop = new AtomicBoolean();
private IMap<Integer, Integer> memberMap;
private IMap<Integer, Integer> clientMap;
@Before
public void setUp() {
String mapName = randomMapName();
Config config = getBaseConfig();
ClientConfig clientConfig = new ClientConfig()
.addNearCacheConfig(newNearCacheConfig(mapName));
HazelcastInstance member = factory.newHazelcastInstance(config);
factory.newHazelcastInstance(config);
factory.newHazelcastInstance(config);
HazelcastInstance client = factory.newHazelcastClient(clientConfig);
memberMap = member.getMap(mapName);
clientMap = client.getMap(mapName);
}
@After
public void tearDown() {
factory.shutdownAll();
}
@Test
public void allRecordsAreInReadableStateInTheEnd() throws Exception {
// initial population of IMap from member
for (int i = 0; i < KEY_SPACE; i++) {
memberMap.put(i, i);
}
List<Thread> threads = new ArrayList<Thread>();
// member
for (int i = 0; i < PUT_THREAD_COUNT; i++) {
Put put = new Put(memberMap);
threads.add(put);
}
// client
for (int i = 0; i < GET_ALL_THREAD_COUNT; i++) {
GetAll getAll = new GetAll(clientMap);
threads.add(getAll);
}
for (int i = 0; i < GET_THREAD_COUNT; i++) {
Get get = new Get(clientMap);
threads.add(get);
}
for (int i = 0; i < REMOVE_THREAD_COUNT; i++) {
Remove remove = new Remove(clientMap);
threads.add(remove);
}
for (int i = 0; i < CLEAR_THREAD_COUNT; i++) {
Clear clear = new Clear(clientMap);
threads.add(clear);
}
// start threads
for (Thread thread : threads) {
thread.start();
}
// stress for a while
sleepSeconds(TEST_RUN_SECONDS);
// stop threads
stop.set(true);
for (Thread thread : threads) {
thread.join();
}
assertFinalRecordStateIsReadPermitted(clientMap);
}
private NearCacheConfig newNearCacheConfig(String mapName) {
return new NearCacheConfig(mapName)
.setSerializeKeys(false)
.setInvalidateOnChange(true);
}
@SuppressWarnings("unchecked")
private static void assertFinalRecordStateIsReadPermitted(IMap clientMap) {
NearCachedClientMapProxy proxy = (NearCachedClientMapProxy) clientMap;
DefaultNearCache nearCache = (DefaultNearCache) proxy.getNearCache().unwrap(DefaultNearCache.class);
assertNearCacheRecordStates(nearCache, KEY_SPACE);
}
private class Put extends Thread {
private final IMap<Integer, Integer> map;
private Put(IMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
do {
for (int i = 0; i < KEY_SPACE; i++) {
map.put(i, getInt(KEY_SPACE));
}
sleepAtLeastMillis(100);
} while (!stop.get());
}
}
private class Remove extends Thread {
private final IMap<Integer, Integer> map;
private Remove(IMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
do {
for (int i = 0; i < KEY_SPACE; i++) {
map.remove(i);
}
sleepAtLeastMillis(100);
} while (!stop.get());
}
}
private class Clear extends Thread {
private final IMap<Integer, Integer> map;
private Clear(IMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
do {
map.clear();
sleepAtLeastMillis(5000);
} while (!stop.get());
}
}
private class GetAll extends Thread {
private final IMap<Integer, Integer> map;
private GetAll(IMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
HashSet<Integer> keys = new HashSet<Integer>();
for (int i = 0; i < KEY_SPACE; i++) {
keys.add(i);
}
do {
map.getAll(keys);
sleepAtLeastMillis(2);
} while (!stop.get());
}
}
private class Get extends Thread {
private final IMap<Integer, Integer> map;
private Get(IMap<Integer, Integer> map) {
this.map = map;
}
@Override
public void run() {
do {
for (int i = 0; i < KEY_SPACE; i++) {
map.get(i);
}
} while (!stop.get());
}
}
}
| apache-2.0 |
wwatso1/qcraft-mod | src/main/java/dan200/qcraft/shared/BlockQBlock.java | 28147 | /*
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 dan200.qcraft.shared;
import dan200.QCraft;
import net.minecraft.block.*;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class BlockQBlock extends BlockSand
implements ITileEntityProvider, IQuantumObservable
{
public int blockRenderID;
private static IIcon s_transparentIcon;
private static IIcon s_swirlIcon;
private static IIcon s_fuzzIcon;
private static ItemStack[] s_impostorBlocks;
public static enum Appearance
{
Block,
Fuzz,
Swirl
}
public static ItemStack[] getImpostorBlockList()
{
if( s_impostorBlocks == null )
{
s_impostorBlocks = new ItemStack[]{
null,
new ItemStack( Blocks.stone, 1, 0 ),
new ItemStack( Blocks.grass, 1, 0 ),
new ItemStack( Blocks.dirt, 1, 0 ),
new ItemStack( Blocks.bedrock, 1, 0 ),
new ItemStack( Blocks.sand, 1, 0 ),
new ItemStack( Blocks.gravel, 1, 0 ),
new ItemStack( Blocks.gold_ore, 1, 0 ),
new ItemStack( Blocks.iron_ore, 1, 0 ),
new ItemStack( Blocks.coal_ore, 1, 0 ),
new ItemStack( Blocks.log, 1, 0 ),
new ItemStack( Blocks.lapis_ore, 1, 0 ),
new ItemStack( Blocks.sandstone, 1, 0 ),
new ItemStack( Blocks.diamond_ore, 1, 0 ),
new ItemStack( Blocks.redstone_ore, 1, 0 ),
new ItemStack( Blocks.emerald_ore, 1, 0 ),
new ItemStack( Blocks.ice, 1, 0 ),
new ItemStack( Blocks.clay, 1, 0 ),
new ItemStack( Blocks.pumpkin, 1, 0 ),
new ItemStack( Blocks.melon_block, 1, 0 ),
new ItemStack( Blocks.mycelium, 1, 0 ),
new ItemStack( Blocks.obsidian, 1, 0 ), // 21
new ItemStack( Blocks.cobblestone, 1, 0 ),
new ItemStack( Blocks.planks, 1, 0 ),
new ItemStack( Blocks.bookshelf, 1, 0 ),
new ItemStack( Blocks.mossy_cobblestone, 1, 0 ),
new ItemStack( Blocks.netherrack, 1, 0 ),
new ItemStack( Blocks.soul_sand, 1, 0 ),
new ItemStack( Blocks.glowstone, 1, 0 ),
new ItemStack( Blocks.end_stone, 1, 0 ),
new ItemStack( Blocks.iron_block, 1, 0 ),
new ItemStack( Blocks.gold_block, 1, 0 ), // 31
new ItemStack( Blocks.diamond_block, 1, 0 ),
new ItemStack( Blocks.lapis_block, 1, 0 ),
new ItemStack( Blocks.wool, 1, 0 ),
new ItemStack( Blocks.glass, 1, 0 ),
new ItemStack( Blocks.wool, 1, 1 ),
new ItemStack( Blocks.wool, 1, 2 ),
new ItemStack( Blocks.wool, 1, 3 ),
new ItemStack( Blocks.wool, 1, 4 ),
new ItemStack( Blocks.wool, 1, 5 ),
new ItemStack( Blocks.wool, 1, 6 ),
new ItemStack( Blocks.wool, 1, 7 ),
new ItemStack( Blocks.wool, 1, 8 ),
new ItemStack( Blocks.wool, 1, 9 ),
new ItemStack( Blocks.wool, 1, 10 ),
new ItemStack( Blocks.wool, 1, 11 ),
new ItemStack( Blocks.wool, 1, 12 ),
new ItemStack( Blocks.wool, 1, 13 ),
new ItemStack( Blocks.wool, 1, 14 ),
new ItemStack( Blocks.wool, 1, 15 ),
new ItemStack( Blocks.log, 1, 1 ),
new ItemStack( Blocks.log, 1, 2 ),
new ItemStack( Blocks.log, 1, 3 ),
new ItemStack( Blocks.planks, 1, 1 ),
new ItemStack( Blocks.planks, 1, 2 ),
new ItemStack( Blocks.planks, 1, 3 ),
new ItemStack( Blocks.sandstone, 1, 1 ),
new ItemStack( Blocks.sandstone, 1, 2 ),
new ItemStack( Blocks.stonebrick, 1, 0 ),
new ItemStack( Blocks.stonebrick, 1, 1 ),
new ItemStack( Blocks.stonebrick, 1, 2 ),
new ItemStack( Blocks.stonebrick, 1, 3 ),
new ItemStack( Blocks.nether_brick, 1, 0 ),
new ItemStack( Blocks.brick_block, 1, 0 ),
new ItemStack( Blocks.redstone_block, 1, 0 ),
new ItemStack( Blocks.quartz_ore, 1, 0 ),
new ItemStack( Blocks.quartz_block, 1, 0 ),
new ItemStack( Blocks.quartz_block, 1, 1 ),
new ItemStack( Blocks.quartz_block, 1, 2 ),
// New in 1.6.4!
new ItemStack( Blocks.stained_hardened_clay, 1, 0 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 1 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 2 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 3 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 4 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 5 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 6 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 7 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 8 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 9 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 10 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 11 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 12 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 13 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 14 ),
new ItemStack( Blocks.stained_hardened_clay, 1, 15 ),
new ItemStack( Blocks.hay_block, 1, 0 ),
new ItemStack( Blocks.hardened_clay, 1, 0 ),
new ItemStack( Blocks.coal_block, 1, 0 ),
// New in 1.7.2!
new ItemStack( Blocks.log2, 1, 0 ),
new ItemStack( Blocks.log2, 1, 1 ),
new ItemStack( Blocks.dirt, 1, 2 ), // Podzol
new ItemStack( Blocks.planks, 1, 4 ),
new ItemStack( Blocks.planks, 1, 5 ),
new ItemStack( Blocks.sand, 1, 1 ), // Red sand
new ItemStack( Blocks.packed_ice, 1, 0 ),
new ItemStack( Blocks.stained_glass, 1, 0 ),
new ItemStack( Blocks.stained_glass, 1, 1 ),
new ItemStack( Blocks.stained_glass, 1, 2 ),
new ItemStack( Blocks.stained_glass, 1, 3 ),
new ItemStack( Blocks.stained_glass, 1, 4 ),
new ItemStack( Blocks.stained_glass, 1, 5 ),
new ItemStack( Blocks.stained_glass, 1, 6 ),
new ItemStack( Blocks.stained_glass, 1, 7 ),
new ItemStack( Blocks.stained_glass, 1, 8 ),
new ItemStack( Blocks.stained_glass, 1, 9 ),
new ItemStack( Blocks.stained_glass, 1, 10 ),
new ItemStack( Blocks.stained_glass, 1, 11 ),
new ItemStack( Blocks.stained_glass, 1, 12 ),
new ItemStack( Blocks.stained_glass, 1, 13 ),
new ItemStack( Blocks.stained_glass, 1, 14 ),
new ItemStack( Blocks.stained_glass, 1, 15 ),
};
}
return s_impostorBlocks;
}
public static class SubType
{
public static final int Standard = 0;
public static final int FiftyFifty = 1;
public static final int Count = 2;
}
public BlockQBlock()
{
setCreativeTab( QCraft.getCreativeTab() );
setHardness( 5.0f );
setResistance( 10.0f );
setStepSound( Block.soundTypeMetal );
setBlockName( "qcraft:qblock" );
}
@Override
public boolean getUseNeighborBrightness()
{
return true;
}
public int getSubType( IBlockAccess world, int x, int y, int z )
{
return world.getBlockMetadata( x, y, z );
}
// IQuantumObservable implementation
@Override
public boolean isObserved( World world, int x, int y, int z, int side )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock qBlock = (TileEntityQBlock) entity;
if( qBlock.isForceObserved( side ) )
{
return true;
}
}
return false;
}
@Override
public void observe( World world, int x, int y, int z, int side )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock qBlock = (TileEntityQBlock) entity;
qBlock.setForceObserved( side, true );
}
}
@Override
public void reset( World world, int x, int y, int z, int side )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock qBlock = (TileEntityQBlock) entity;
qBlock.setForceObserved( side, false );
}
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public boolean shouldSideBeRendered( IBlockAccess iblockaccess, int i, int j, int k, int l )
{
return true;
}
@Override
public int getRenderType()
{
return blockRenderID;
}
@Override
public boolean isNormalCube( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null && !( block instanceof BlockCompressedPowered ) && block != Blocks.ice && block != Blocks.packed_ice && block != Blocks.glass && block != Blocks.stained_glass )
{
return true;
}
return false;
}
@Override
public int colorMultiplier( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block == Blocks.grass )
{
return block.colorMultiplier( world, x, y, z );
}
return 0xffffff;
}
@Override
public void addCollisionBoxesToList( World world, int x, int y, int z, AxisAlignedBB bigBox, List list, Entity entity )
{
// Determine if solid
boolean solid = false;
int type = getImpostorType( world, x, y, z );
if( type > 0 )
{
// Solid blocks are solid to everyone
solid = true;
}
else if( entity instanceof EntityPlayer )
{
// Air blocks are solid to people with goggles on
EntityPlayer player = (EntityPlayer) entity;
if( QCraft.isPlayerWearingQuantumGoggles( player ) )
{
solid = true;
}
}
// Add AABB if so
if( solid )
{
AxisAlignedBB aabb = AxisAlignedBB.getAABBPool().getAABB(
(double) x, (double) y, (double) z,
(double) x + 1.0, (double) y + 1.0, (double) z + 1.0
);
if( aabb != null && aabb.intersectsWith( bigBox ) )
{
list.add( aabb );
}
}
}
@Override
public boolean isReplaceable( IBlockAccess world, int x, int y, int z )
{
/*
Appearance appearance = getAppearance( world, x, y, z );
int type = getImpostorType( world, x, y, z );
if( appearance == Appearance.Block && type == 0 )
{
return true;
}
*/
return false;
}
@Override
public void setBlockBoundsBasedOnState( IBlockAccess world, int x, int y, int z )
{
Appearance appearance = getAppearance( world, x, y, z );
int type = getImpostorType( world, x, y, z );
if( appearance != Appearance.Block || type > 0 )
{
super.setBlockBounds( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f );
}
else
{
super.setBlockBounds( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f );
}
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool( World world, int x, int y, int z )
{
setBlockBoundsBasedOnState( world, x, y, z );
return super.getCollisionBoundingBoxFromPool( world, x, y, z );
}
@Override
public AxisAlignedBB getSelectedBoundingBoxFromPool( World world, int x, int y, int z )
{
setBlockBoundsBasedOnState( world, x, y, z );
return super.getSelectedBoundingBoxFromPool( world, x, y, z );
}
@Override
public float getBlockHardness( World world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getBlockHardness( world, x, y, z );
}
return 0.0f;
}
@Override
public float getExplosionResistance( Entity entity, World world, int x, int y, int z, double explosionX, double explosionY, double explosionZ )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getExplosionResistance( entity, world, x, y, z, explosionX, explosionY, explosionZ );
}
return 0.0f;
}
@Override
public boolean isSideSolid( IBlockAccess world, int x, int y, int z, ForgeDirection side )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return true;
}
return false;
}
@Override
public boolean isAir( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return false;
}
return true;
}
@Override
public boolean canSustainLeaves( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.canSustainLeaves( world, x, y, z );
}
return false;
}
@Override
public boolean canBeReplacedByLeaves( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return false;
}
return true;
}
@Override
public boolean isWood( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.isWood( world, x, y, z );
}
return true;
}
@Override
public int getFlammability( IBlockAccess world, int x, int y, int z, ForgeDirection face )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getFlammability( world, x, y, z, face );
}
return 0;
}
@Override
public boolean isFlammable( IBlockAccess world, int x, int y, int z, ForgeDirection face )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.isFlammable( world, x, y, z, face );
}
return false;
}
@Override
public int getFireSpreadSpeed( IBlockAccess world, int x, int y, int z, ForgeDirection face )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getFireSpreadSpeed( world, x, y, z, face );
}
return 0;
}
@Override
public boolean isFireSource( World world, int x, int y, int z, ForgeDirection side )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.isFireSource( world, x, y, z, side );
}
return false;
}
@Override
public int getLightOpacity( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getLightOpacity( world, x, y, z );
}
return 0;
}
@Override
public boolean isBeaconBase( IBlockAccess world, int x, int y, int z, int beaconX, int beaconY, int beaconZ )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.isBeaconBase( world, x, y, z, beaconX, beaconY, beaconZ );
}
return false;
}
@Override
public ArrayList<ItemStack> getDrops( World world, int x, int y, int z, int metadata, int fortune )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getDrops( world, x, y, z, getImpostorDamage( world, x, y, z ), fortune );
}
return new ArrayList<ItemStack>();
}
@Override
public void dropBlockAsItemWithChance( World world, int i, int j, int k, int l, float f, int unknown )
{
// removeBlockByPlayer handles this instead
}
@Override
public boolean removedByPlayer( World world, EntityPlayer player, int x, int y, int z )
{
if( world.isRemote )
{
return false;
}
if( !player.capabilities.isCreativeMode )
{
if( EnchantmentHelper.getSilkTouchModifier( player ) )
{
// Silk harvest (get qblock back)
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock qblock = (TileEntityQBlock) entity;
ItemStack item = ItemQBlock.create( qblock.getSubType(), qblock.getTypes(), qblock.getEntanglementFrequency(), 1 );
dropBlockAsItem( world, x, y, z, item );
}
}
else
{
// Regular harvest (get impostor)
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
int metadata = getImpostorDamage( world, x, y, z );
if( block.canHarvestBlock( player, metadata ) )
{
int fortune = EnchantmentHelper.getFortuneModifier( player );
ArrayList<ItemStack> items = getDrops( world, x, y, z, metadata, fortune );
Iterator<ItemStack> it = items.iterator();
while( it.hasNext() )
{
ItemStack item = it.next();
dropBlockAsItem( world, x, y, z, item );
}
}
}
}
}
return super.removedByPlayer( world, player, x, y, z );
}
@Override
public ItemStack getPickBlock( MovingObjectPosition target, World world, int x, int y, int z )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock qblock = (TileEntityQBlock) entity;
return ItemQBlock.create( qblock.getSubType(), qblock.getTypes(), qblock.getEntanglementFrequency(), 1 );
}
return null;
}
@Override
public boolean canHarvestBlock( EntityPlayer player, int metadata )
{
return true;
}
@Override
public void harvestBlock( World world, EntityPlayer player, int x, int y, int z, int metadata )
{
}
@Override
public boolean canSilkHarvest( World world, EntityPlayer player, int x, int y, int z, int metadata )
{
return false;
}
@Override
public void onBlockPlacedBy( World world, int x, int y, int z, EntityLivingBase player, ItemStack stack )
{
int subType = stack.getItemDamage();
int metadata = subType;
world.setBlockMetadataWithNotify( x, y, z, metadata, 3 );
}
@Override
public void updateTick( World world, int x, int y, int z, Random r )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null && block instanceof BlockSand )
{
super.updateTick( world, x, y, z, r );
}
}
@Override
protected void func_149829_a( EntityFallingBlock entityFallingSand ) // onStartFalling
{
// Setup NBT for block to place
World world = entityFallingSand.worldObj;
int x = (int) ( entityFallingSand.posX - 0.5f );
int y = (int) ( entityFallingSand.posY - 0.5f );
int z = (int) ( entityFallingSand.posZ - 0.5f );
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
entity.writeToNBT( nbttagcompound );
entityFallingSand.field_145810_d = nbttagcompound; // data
}
// Prevent the falling qBlock from dropping items
entityFallingSand.field_145813_c = false; // dropItems
}
@Override
public boolean canProvidePower()
{
return true;
}
@Override
public boolean canConnectRedstone( IBlockAccess world, int x, int y, int z, int side )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null && block instanceof BlockCompressedPowered )
{
return true;
}
return false;
}
@Override
public int isProvidingWeakPower( IBlockAccess world, int x, int y, int z, int side )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null && block instanceof BlockCompressedPowered )
{
return 15;
}
return 0;
}
@Override
public int getLightValue( IBlockAccess world, int x, int y, int z )
{
Block block = getImpostorBlock( world, x, y, z );
if( block != null )
{
return block.getLightValue();
}
return 0;
}
public int getColorForType( int side, int type )
{
if( type == 2 ) // grass
{
return ( side == 1 ) ? Blocks.grass.getRenderColor( 0 ) : 0xffffff;
}
return 0xffffff;
}
public IIcon getIconForType( int side, int type, Appearance appearance )
{
if( appearance == Appearance.Swirl )
{
return s_swirlIcon;
}
else if( appearance == Appearance.Fuzz )
{
return s_fuzzIcon;
}
else //if( appearance == Appearance.Block )
{
ItemStack[] blockList = getImpostorBlockList();
if( type >= 0 && type < blockList.length )
{
ItemStack item = blockList[ type ];
if( item != null )
{
Block block = ((ItemBlock)item.getItem()).field_150939_a;
int damage = item.getItemDamage();
return block.getIcon( side, damage );
}
}
return s_transparentIcon;
}
}
@Override
public IIcon getIcon( IBlockAccess world, int x, int y, int z, int side )
{
int type = getImpostorType( world, x, y, z );
Appearance appearance = getAppearance( world, x, y, z );
return getIconForType( side, type, appearance );
}
public static boolean s_forceGrass = false;
@Override
public IIcon getIcon( int side, int damage )
{
if( s_forceGrass )
{
return Blocks.grass.getIcon( side, damage );
}
else
{
return s_swirlIcon;
}
}
@Override
public void registerBlockIcons( IIconRegister iconRegister )
{
s_transparentIcon = iconRegister.registerIcon( "qcraft:transparent" );
s_swirlIcon = iconRegister.registerIcon( "qcraft:qblock_swirl" );
s_fuzzIcon = iconRegister.registerIcon( "qcraft:qblock_fuzz" );
}
@Override
public TileEntity createNewTileEntity( World world, int metadata )
{
return new TileEntityQBlock();
}
@Override
public TileEntity createTileEntity( World world, int metadata )
{
return createNewTileEntity( world, metadata );
}
private Appearance getAppearance( IBlockAccess world, int x, int y, int z )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock quantum = (TileEntityQBlock) entity;
return quantum.getAppearance();
}
return Appearance.Fuzz;
}
private int getImpostorType( IBlockAccess world, int x, int y, int z )
{
int type = 0;
if( y >= 0 )
{
TileEntity entity = world.getTileEntity( x, y, z );
if( entity != null && entity instanceof TileEntityQBlock )
{
TileEntityQBlock quantum = (TileEntityQBlock) entity;
type = quantum.getObservedType();
}
}
return type;
}
public Block getImpostorBlock( IBlockAccess world, int x, int y, int z )
{
// Return block
int type = getImpostorType( world, x, y, z );
ItemStack[] blockList = getImpostorBlockList();
if( type < blockList.length )
{
ItemStack item = blockList[ type ];
if( item != null )
{
return Block.getBlockFromItem( item.getItem() );
}
}
return null;
}
private int getImpostorDamage( IBlockAccess world, int x, int y, int z )
{
// Return damage
int type = getImpostorType( world, x, y, z );
ItemStack[] blockList = getImpostorBlockList();
if( type < blockList.length )
{
ItemStack item = blockList[ type ];
if( item != null )
{
return item.getItemDamage();
}
}
return 0;
}
}
| apache-2.0 |
gonmarques/commons-collections | src/test/java/org/apache/commons/collections4/iterators/SingletonListIteratorTest.java | 4807 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections4.iterators;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.apache.commons.collections4.ResettableListIterator;
/**
* Tests the SingletonListIterator.
*
* @version $Id$
*/
public class SingletonListIteratorTest<E> extends AbstractListIteratorTest<E> {
private static final Object testValue = "foo";
public SingletonListIteratorTest(final String testName) {
super(testName);
}
/**
* Returns a SingletonListIterator from which
* the element has already been removed.
*/
@Override
public SingletonListIterator<E> makeEmptyIterator() {
final SingletonListIterator<E> iter = makeObject();
iter.next();
iter.remove();
iter.reset();
return iter;
}
@Override
@SuppressWarnings("unchecked")
public SingletonListIterator<E> makeObject() {
return new SingletonListIterator<E>((E) testValue);
}
@Override
public boolean supportsAdd() {
return false;
}
@Override
public boolean supportsRemove() {
return true;
}
@Override
public boolean supportsEmptyIterator() {
return true;
}
public void testIterator() {
final ListIterator<E> iter = makeObject();
assertTrue( "Iterator should have next item", iter.hasNext() );
assertTrue( "Iterator should have no previous item", !iter.hasPrevious() );
assertEquals( "Iteration next index", 0, iter.nextIndex() );
assertEquals( "Iteration previous index", -1, iter.previousIndex() );
Object iterValue = iter.next();
assertEquals( "Iteration value is correct", testValue, iterValue );
assertTrue( "Iterator should have no next item", !iter.hasNext() );
assertTrue( "Iterator should have previous item", iter.hasPrevious() );
assertEquals( "Iteration next index", 1, iter.nextIndex() );
assertEquals( "Iteration previous index", 0, iter.previousIndex() );
iterValue = iter.previous();
assertEquals( "Iteration value is correct", testValue, iterValue );
assertTrue( "Iterator should have next item", iter.hasNext() );
assertTrue( "Iterator should have no previous item", !iter.hasPrevious() );
assertEquals( "Iteration next index", 0, iter.nextIndex() );
assertEquals( "Iteration previous index", -1, iter.previousIndex() );
iterValue = iter.next();
assertEquals( "Iteration value is correct", testValue, iterValue );
assertTrue( "Iterator should have no next item", !iter.hasNext() );
assertTrue( "Iterator should have previous item", iter.hasPrevious() );
assertEquals( "Iteration next index", 1, iter.nextIndex() );
assertEquals( "Iteration previous index", 0, iter.previousIndex() );
try {
iter.next();
} catch (final Exception e) {
assertTrue("NoSuchElementException must be thrown",
e.getClass().equals(new NoSuchElementException().getClass()));
}
iter.previous();
try {
iter.previous();
} catch (final Exception e) {
assertTrue("NoSuchElementException must be thrown",
e.getClass().equals(new NoSuchElementException().getClass()));
}
}
public void testReset() {
final ResettableListIterator<E> it = makeObject();
assertEquals(true, it.hasNext());
assertEquals(false, it.hasPrevious());
assertEquals(testValue, it.next());
assertEquals(false, it.hasNext());
assertEquals(true, it.hasPrevious());
it.reset();
assertEquals(true, it.hasNext());
assertEquals(false, it.hasPrevious());
assertEquals(testValue, it.next());
assertEquals(false, it.hasNext());
assertEquals(true, it.hasPrevious());
it.reset();
it.reset();
assertEquals(true, it.hasNext());
}
}
| apache-2.0 |
stoksey69/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201502/cm/CampaignSharedSetServiceLocator.java | 6308 | /**
* CampaignSharedSetServiceLocator.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201502.cm;
public class CampaignSharedSetServiceLocator extends org.apache.axis.client.Service implements com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetService {
public CampaignSharedSetServiceLocator() {
}
public CampaignSharedSetServiceLocator(org.apache.axis.EngineConfiguration config) {
super(config);
}
public CampaignSharedSetServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
super(wsdlLoc, sName);
}
// Use to get a proxy class for CampaignSharedSetServiceInterfacePort
private java.lang.String CampaignSharedSetServiceInterfacePort_address = "https://adwords.google.com/api/adwords/cm/v201502/CampaignSharedSetService";
public java.lang.String getCampaignSharedSetServiceInterfacePortAddress() {
return CampaignSharedSetServiceInterfacePort_address;
}
// The WSDD service name defaults to the port name.
private java.lang.String CampaignSharedSetServiceInterfacePortWSDDServiceName = "CampaignSharedSetServiceInterfacePort";
public java.lang.String getCampaignSharedSetServiceInterfacePortWSDDServiceName() {
return CampaignSharedSetServiceInterfacePortWSDDServiceName;
}
public void setCampaignSharedSetServiceInterfacePortWSDDServiceName(java.lang.String name) {
CampaignSharedSetServiceInterfacePortWSDDServiceName = name;
}
public com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceInterface getCampaignSharedSetServiceInterfacePort() throws javax.xml.rpc.ServiceException {
java.net.URL endpoint;
try {
endpoint = new java.net.URL(CampaignSharedSetServiceInterfacePort_address);
}
catch (java.net.MalformedURLException e) {
throw new javax.xml.rpc.ServiceException(e);
}
return getCampaignSharedSetServiceInterfacePort(endpoint);
}
public com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceInterface getCampaignSharedSetServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
try {
com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceSoapBindingStub(portAddress, this);
_stub.setPortName(getCampaignSharedSetServiceInterfacePortWSDDServiceName());
return _stub;
}
catch (org.apache.axis.AxisFault e) {
return null;
}
}
public void setCampaignSharedSetServiceInterfacePortEndpointAddress(java.lang.String address) {
CampaignSharedSetServiceInterfacePort_address = address;
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
try {
if (com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) {
com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201502.cm.CampaignSharedSetServiceSoapBindingStub(new java.net.URL(CampaignSharedSetServiceInterfacePort_address), this);
_stub.setPortName(getCampaignSharedSetServiceInterfacePortWSDDServiceName());
return _stub;
}
}
catch (java.lang.Throwable t) {
throw new javax.xml.rpc.ServiceException(t);
}
throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
}
/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.
*/
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
if (portName == null) {
return getPort(serviceEndpointInterface);
}
java.lang.String inputPortName = portName.getLocalPart();
if ("CampaignSharedSetServiceInterfacePort".equals(inputPortName)) {
return getCampaignSharedSetServiceInterfacePort();
}
else {
java.rmi.Remote _stub = getPort(serviceEndpointInterface);
((org.apache.axis.client.Stub) _stub).setPortName(portName);
return _stub;
}
}
public javax.xml.namespace.QName getServiceName() {
return new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "CampaignSharedSetService");
}
private java.util.HashSet ports = null;
public java.util.Iterator getPorts() {
if (ports == null) {
ports = new java.util.HashSet();
ports.add(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "CampaignSharedSetServiceInterfacePort"));
}
return ports.iterator();
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
if ("CampaignSharedSetServiceInterfacePort".equals(portName)) {
setCampaignSharedSetServiceInterfacePortEndpointAddress(address);
}
else
{ // Unknown Port Name
throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
}
}
/**
* Set the endpoint address for the specified port name.
*/
public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
setEndpointAddress(portName.getLocalPart(), address);
}
}
| apache-2.0 |
pivotal-amurmann/geode | geode-core/src/test/java/org/apache/geode/cache/query/functional/NonDistinctOrderByTestImplementation.java | 66697 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.functional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.IndexExistsException;
import org.apache.geode.cache.query.IndexInvalidException;
import org.apache.geode.cache.query.IndexNameConflictException;
import org.apache.geode.cache.query.IndexType;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.RegionNotFoundException;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.Struct;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.cache.query.data.Position;
import org.apache.geode.cache.query.internal.QueryObserverAdapter;
import org.apache.geode.cache.query.internal.QueryObserverHolder;
import org.apache.geode.cache.query.types.ObjectType;
/**
*
*
*/
public abstract class NonDistinctOrderByTestImplementation {
@Before
public void setUp() throws java.lang.Exception {
CacheUtils.startCache();
}
@After
public void tearDown() throws java.lang.Exception {
CacheUtils.closeCache();
}
public abstract Region createRegion(String regionName, Class valueConstraint);
public abstract Index createIndex(String indexName, IndexType indexType, String indexedExpression,
String fromClause) throws IndexInvalidException, IndexNameConflictException,
IndexExistsException, RegionNotFoundException, UnsupportedOperationException;
public abstract Index createIndex(String indexName, String indexedExpression, String regionPath)
throws IndexInvalidException, IndexNameConflictException, IndexExistsException,
RegionNotFoundException, UnsupportedOperationException;
public abstract boolean assertIndexUsedOnQueryNode();
@Test
public void testOrderByWithIndexResultDefaultProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID desc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID asc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc ",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc ",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID asc ",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID desc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID asc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc limit 5 ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID asc limit 10",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID desc limit 10",
"SELECT * FROM /portfolio1 pf1 where ID > 0 order by ID desc, pkid desc "};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
SelectResults rcw = (SelectResults) r[i][1];
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
assertTrue("Result size is " + rcw.size() + " and limit is " + limit,
!limitQuery || rcw.size() <= limit);
if (!rcw.getCollectionType().isOrdered()) {
fail("The collection type=" + rcw.getCollectionType().getSimpleClassName()
+ " is not ordered");
}
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
if (!(itr.next().toString()).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + itr.next().toString());
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
// Compare each of the query results with queries fired without order by ,
// but without order by
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testOrderByWithIndexResultWithProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 order by shortID desc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 order by shortID asc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by shortID asc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by shortID desc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by shortID desc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by shortID asc",
"SELECT shortID, description FROM /portfolio1 pf1 where ID != 10 order by shortID asc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID != 10 order by shortID desc ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 order by shortID desc limit 5",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 order by shortID asc limit 5",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by shortID asc limit 5 ",
"SELECT shortID, description FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by shortID desc limit 5",
"SELECT shortID, description FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by shortID desc limit 5",
"SELECT shortID, description FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by shortID asc limit 5",
"SELECT shortID, description FROM /portfolio1 pf1 where ID != 10 order by shortID asc limit 10",
"SELECT shortID, description FROM /portfolio1 pf1 where ID != 10 order by shortID desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
SelectResults rcw = (SelectResults) r[i][1];
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
assertTrue(!limitQuery || rcw.size() <= limit);
// assertIndexDetailsEquals("Set",rcw.getCollectionType().getSimpleClassName());
if (!rcw.getCollectionType().isOrdered()) {
fail("The collection type=" + rcw.getCollectionType().getSimpleClassName()
+ " is not ordered");
}
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
if (!(itr.next().toString()).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + itr.next().toString());
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testMultiColOrderByWithIndexResultDefaultProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID desc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID asc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc , pkid desc",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc, pkid asc",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID asc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID desc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID desc, pkid asc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID > 10 order by ID asc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc, pkid asc limit 5 ",
"SELECT * FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc, pkid asc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID asc, pkid asc limit 10",
"SELECT * FROM /portfolio1 pf1 where ID != 10 order by ID desc, pkid desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
SelectResults rcw = (SelectResults) r[i][1];
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
assertTrue(!limitQuery || rcw.size() <= limit);
assertTrue(rcw.getCollectionType().isOrdered());
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
if (!(itr.next().toString()).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + itr.next().toString());
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testMultiColOrderByWithIndexResultWithProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 order by ID desc, pkid desc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 order by ID asc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc , pkid desc",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc, pkid desc",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID != 10 order by ID asc , pkid desc",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID != 10 order by ID desc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 order by ID desc, pkid desc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 order by ID asc, pkid asc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID asc, pkid desc limit 5 ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID > 10 and ID < 20 order by ID desc, pkid asc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID desc, pkid desc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID >= 10 and ID <= 20 order by ID asc, pkid asc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID != 10 order by ID asc , pkid desc limit 10",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where ID != 10 order by ID desc, pkid desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
SelectResults rcw = (SelectResults) r[i][1];
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
assertTrue(!limitQuery || rcw.size() <= limit);
assertTrue(rcw.getCollectionType().isOrdered());
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
if (!(itr.next().toString()).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + itr.next().toString());
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testMultiColOrderByWithMultiIndexResultDefaultProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT * FROM /portfolio1 pf1 where pkid = '12' and ID > 10 order by ID desc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where pkid > '1' and ID > 10 order by ID asc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where pkid = '13'and ID > 10 and ID < 20 order by ID asc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where pkid <'9' and ID > 10 and ID < 20 order by ID desc , pkid desc",
"SELECT * FROM /portfolio1 pf1 where pkid = '15' and ID >= 10 and ID <= 20 order by ID desc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where pkid > '1' and pkid <='9' and ID >= 10 and ID <= 20 order by ID asc, pkid asc",
"SELECT * FROM /portfolio1 pf1 where pkid > '0' and ID != 10 order by ID asc, pkid asc ",
"SELECT * FROM /portfolio1 pf1 where pkid > '1' and ID != 10 order by ID desc, pkid desc ",
"SELECT * FROM /portfolio1 pf1 where pkid = '17' and ID > 10 order by ID desc, pkid asc limit 5",
"SELECT * FROM /portfolio1 pf1 where pkid > '17' and ID > 10 order by ID asc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where pkid < '7' and ID > 10 and ID < 20 order by ID asc, pkid asc limit 5 ",
"SELECT * FROM /portfolio1 pf1 where pkid = '18' and ID > 10 and ID < 20 order by ID desc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where pkid > '0' and ID >= 10 and ID <= 20 order by ID desc, pkid asc limit 5",
"SELECT * FROM /portfolio1 pf1 where pkid != '17' and ID >= 10 and ID <= 20 order by ID asc, pkid desc limit 5",
"SELECT * FROM /portfolio1 pf1 where pkid > '0' and ID != 10 order by ID asc, pkid asc limit 10",
"SELECT * FROM /portfolio1 pf1 where pkid > '9' and ID != 10 order by ID desc, pkid desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
this.createIndex("PKIDIndexPf1", IndexType.FUNCTIONAL, "pkid", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
SelectResults rcw = (SelectResults) r[i][1];
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
assertTrue(!limitQuery || rcw.size() <= limit);
assertTrue(rcw.getCollectionType().isOrdered());
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
String indexUsed = itr.next().toString();
if (!(indexUsed).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + indexUsed);
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testMultiColOrderByWithMultiIndexResultProjection() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid = '12' and ID > 10 order by ID desc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '1' and ID > 10 order by ID asc, pkid desc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid = '13'and ID > 10 and ID < 20 order by ID asc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid <'9' and ID > 10 and ID < 20 order by ID desc , pkid desc",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid = '15' and ID >= 10 and ID <= 20 order by ID desc, pkid desc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '1' and pkid <='9' and ID >= 10 and ID <= 20 order by ID asc, pkid asc",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '1' and ID != 10 order by ID asc, pkid asc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '1' and ID != 10 order by ID desc, pkid desc ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid = '17' and ID > 10 order by ID desc, pkid asc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '17' and ID > 10 order by ID asc, pkid desc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid < '7' and ID > 10 and ID < 20 order by ID asc, pkid asc limit 5 ",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid = '18' and ID > 10 and ID < 20 order by ID desc, pkid desc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '2' and ID >= 10 and ID <= 20 order by ID desc, pkid asc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid != '17' and ID >= 10 and ID <= 20 order by ID asc, pkid desc limit 5",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '0' and ID != 10 order by ID asc, pkid asc limit 10",
"SELECT ID, description, createTime, pkid FROM /portfolio1 pf1 where pkid > '9' and ID != 10 order by ID desc, pkid desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
this.createIndex("PKIDIndexPf1", IndexType.FUNCTIONAL, "pkid", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
SelectResults rcw = (SelectResults) r[i][1];
assertTrue(rcw.getCollectionType().isOrdered());
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
assertTrue(!limitQuery || rcw.size() <= limit);
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
String indexUsed = itr.next().toString();
if (!(indexUsed).equals("IDIndexPf1")) {
fail("<IDIndexPf1> was expected but found " + indexUsed);
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testLimitNotAppliedIfOrderByNotUsingIndex() throws Exception {
String queries[] = {
// Test case No. IUMR021
"SELECT description, pkid FROM /portfolio1 pf1 where pkid = '12' and ID > 10 order by pkid asc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '1' and ID > 10 order by pkid desc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid = '13'and ID > 10 and ID < 20 order by pkid asc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid <'9' and ID > 10 and ID < 20 order by pkid desc",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid = '15' and ID >= 10 and ID <= 20 order by pkid desc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '1' and pkid <='9' and ID >= 10 and ID <= 20 order by pkid asc",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '1' and ID != 10 order by pkid asc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '1' and ID != 10 order by pkid desc ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid = '17' and ID > 10 order by pkid asc limit 5",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '17' and ID > 10 order by pkid desc limit 5",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid < '7' and ID > 10 and ID < 20 order by pkid asc limit 5 ",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid = '18' and ID > 10 and ID < 20 order by pkid desc limit 5",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '1' and ID >= 10 and ID <= 20 order by pkid asc limit 5",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid != '17' and ID >= 10 and ID <= 20 order by pkid desc limit 5",
"SELECT description, pkid FROM /portfolio1 pf1 where pkid > '0' and ID != 10 order by pkid asc limit 10",
"SELECT description, createTime, pkid FROM /portfolio1 pf1 where pkid > '9' and ID != 10 order by pkid desc limit 10",
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i < 200; ++i) {
Portfolio pf = new Portfolio(i);
pf.shortID = (short) ((short) i / 5);
r1.put("" + i, pf);
}
// Execute Queries without Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
r[i][0] = q.execute();
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
// Create Indexes
this.createIndex("PKIDIndexPf1", IndexType.FUNCTIONAL, "pkid", "/portfolio1");
// Execute Queries with Indexes
for (int i = 0; i < queries.length; i++) {
Query q = null;
try {
q = CacheUtils.getQueryService().newQuery(queries[i]);
CacheUtils.getLogger().info("Executing query: " + queries[i]);
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
r[i][1] = q.execute();
int indexLimit = queries[i].indexOf("limit");
int limit = -1;
boolean limitQuery = indexLimit != -1;
if (limitQuery) {
limit = Integer.parseInt(queries[i].substring(indexLimit + 5).trim());
}
SelectResults rcw = (SelectResults) r[i][1];
assertTrue(rcw.getCollectionType().isOrdered());
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
// assertTrue(!limitQuery || !observer.limitAppliedAtIndex);
Iterator itr = observer.indexesUsed.iterator();
while (itr.hasNext()) {
String indexUsed = itr.next().toString();
if (!(indexUsed).equals("PKIDIndexPf1")) {
fail("<PKIDIndexPf1> was expected but found " + indexUsed);
}
// assertIndexDetailsEquals("statusIndexPf1",itr.next().toString());
}
int indxs = observer.indexesUsed.size();
System.out.println("**************************************************Indexes Used :::::: "
+ indxs + " Index Name: " + observer.indexName);
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
StructSetOrResultsSet ssOrrs = new StructSetOrResultsSet();
ssOrrs.CompareQueryResultsWithoutAndWithIndexes(r, queries.length, true, queries);
ssOrrs.compareExternallySortedQueriesWithOrderBy(queries, r);
}
@Test
public void testOrderByWithNullValues() throws Exception {
// IN ORDER BY NULL values are treated as smallest. E.g For an ascending
// order by field
// its null values are reported first and then the values in ascending
// order.
String queries[] = {"SELECT * FROM /portfolio1 pf1 order by pkid", // 0 null
// values are
// first in the
// order.
"SELECT * FROM /portfolio1 pf1 order by pkid asc", // 1 same
// as
// above.
"SELECT * FROM /portfolio1 order by pkid desc", // 2 null
// values are
// last in the
// order.
"SELECT pkid FROM /portfolio1 pf1 order by pkid", // 3 null
// values
// are first
// in the
// order.
"SELECT pkid FROM /portfolio1 pf1 where pkid != 'XXXX' order by pkid asc", // 4
"SELECT pkid FROM /portfolio1 pf1 where pkid != 'XXXX' order by pkid desc", // 5
// null
// values
// are
// last
// in
// the
// order.
"SELECT ID, pkid FROM /portfolio1 pf1 where ID < 1000 order by pkid", // 6
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 3 order by pkid", // 7
"SELECT ID, pkid FROM /portfolio1 pf1 where ID < 1000 order by pkid", // 8
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 0 order by pkid", // 9
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 0 order by pkid, ID asc", // 10
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 0 order by pkid, ID desc", // 11
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
// Create Regions
final int size = 9;
final int numNullValues = 3;
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i <= size; i++) {
Portfolio pf = new Portfolio(i);
// Add numNullValues null values.
if (i <= numNullValues) {
pf.pkid = null;
pf.status = "a" + i;
}
r1.put(i + "", pf);
}
Query q = null;
SelectResults results = null;
List list = null;
String str = "";
try {
// Query 0 - null values are first in the order.
str = queries[0];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
r[0][0] = results;
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid, p: " + p, p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 1 - null values are first in the order.
str = queries[1];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid", p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 2 - null values are last in the order.
str = queries[2];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i > (size - numNullValues)) {
assertNull("Expected null value for pkid", p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + (size - (i - 1)))) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 3 - 3 null value with pkid.
str = queries[3];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 4 - 3 null value with pkid.
str = queries[4];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i <= 3) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 5 - 1 distinct null value with pkid at the end.
str = queries[5];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i > (list.size() - numNullValues)) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + (size - (i - 1)))) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 6 - ID field values should be in the same order.
str = queries[6];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
int id = (Integer) ((Struct) list.get((i - 1))).getFieldValues()[0];
// ID should be one of 1, 2, 3 because of distinct
if (i <= numNullValues) {
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
} else {
if (id != i) {
fail(" Value of ID is not as expected " + id);
}
}
}
// Query 7 - ID field values should be in the same order.
str = queries[7];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
int id = (Integer) ((Struct) list.get((i - 1))).getFieldValues()[0];
if (id != (numNullValues + i)) {
fail(" Value of ID is not as expected, " + id);
}
}
// Query 8 - ID, pkid field values should be in the same order.
str = queries[8];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
// ID should be one of 1, 2, 3 because of distinct
if (i <= numNullValues) {
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
assertNull("Expected null value for pkid", pkid);
} else {
if (id != i) {
fail(" Value of ID is not as expected " + id);
}
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 9 - ID, pkid field values should be in the same order.
str = queries[9];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
if (i <= numNullValues) {
assertNull("Expected null value for pkid, " + pkid, pkid);
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
} else {
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not as expected, " + pkid);
}
if (id != i) {
fail(" Value of ID is not as expected, " + id);
}
}
}
// Query 10 - ID asc, pkid field values should be in the same order.
str = queries[10];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
if (i <= numNullValues) {
assertNull("Expected null value for pkid, " + pkid, pkid);
if (id != i) {
fail(" Value of ID is not as expected, it is: " + id + " expected :" + i);
}
} else {
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not as expected, " + pkid);
}
if (id != i) {
fail(" Value of ID is not as expected, " + id);
}
}
}
// Query 11 - ID desc, pkid field values should be in the same order.
str = queries[11];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
if (i <= numNullValues) {
assertNull("Expected null value for pkid, " + pkid, pkid);
if (id != (numNullValues - (i - 1))) {
fail(" Value of ID is not as expected " + id);
}
} else {
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not as expected, " + pkid);
}
if (id != i) {
fail(" Value of ID is not as expected, " + id);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
@Test
public void testOrderByWithNullValuesUseIndex() throws Exception {
// IN ORDER BY NULL values are treated as smallest. E.g For an ascending
// order by field
// its null values are reported first and then the values in ascending
// order.
String queries[] = {"SELECT * FROM /portfolio1 pf1 where ID > 0 order by pkid", // 0
// null
// values
// are
// first
// in
// the
// order.
"SELECT * FROM /portfolio1 pf1 where ID > 0 order by pkid asc", // 1
// same
// as
// above.
"SELECT * FROM /portfolio1 where ID > 0 order by pkid desc", // 2
// null
// values
// are
// last
// in
// the
// order.
"SELECT pkid FROM /portfolio1 pf1 where ID > 0 order by pkid", // 3
// null
// values
// are
// first
// in
// the
// order.
"SELECT pkid FROM /portfolio1 pf1 where ID > 0 order by pkid asc", // 4
"SELECT pkid FROM /portfolio1 pf1 where ID > 0 order by pkid desc", // 5
// null
// values
// are
// last
// in
// the
// order.
"SELECT ID, pkid FROM /portfolio1 pf1 where ID < 1000 order by pkid", // 6
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 3 order by pkid", // 7
"SELECT ID, pkid FROM /portfolio1 pf1 where ID < 1000 order by pkid", // 8
"SELECT ID, pkid FROM /portfolio1 pf1 where ID > 0 order by pkid", // 9
};
Object r[][] = new Object[queries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
// Create Regions
final int size = 9;
final int numNullValues = 3;
Region r1 = this.createRegion("portfolio1", Portfolio.class);
for (int i = 1; i <= size; i++) {
Portfolio pf = new Portfolio(i);
// Add numNullValues null values.
if (i <= numNullValues) {
pf.pkid = null;
pf.status = "a" + i;
}
r1.put(i + "", pf);
}
// Create Indexes
this.createIndex("IDIndexPf1", IndexType.FUNCTIONAL, "ID", "/portfolio1");
this.createIndex("PKIDIndexPf1", IndexType.FUNCTIONAL, "pkid", "/portfolio1");
Query q = null;
SelectResults results = null;
List list = null;
String str = "";
try {
// Query 0 - null values are first in the order.
QueryObserverImpl observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
str = queries[0];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
r[0][0] = results;
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid, p: " + p, p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 1 - null values are first in the order.
str = queries[1];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid", p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 2 - null values are last in the order.
str = queries[2];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Portfolio p = (Portfolio) list.get((i - 1));
if (i > (size - numNullValues)) {
assertNull("Expected null value for pkid", p.pkid);
} else {
assertNotNull("Expected not null value for pkid", p.pkid);
if (!p.pkid.equals("" + (size - (i - 1)))) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 3 - 1 distinct null value with pkid.
str = queries[3];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 4 - 1 distinct null value with pkid.
observer = new QueryObserverImpl();
QueryObserverHolder.setInstance(observer);
str = queries[4];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
if (assertIndexUsedOnQueryNode() && !observer.isIndexesUsed) {
fail("Index is NOT uesd");
}
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i <= numNullValues) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 5 - 1 distinct null value with pkid at the end.
str = queries[5];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
String pkid = (String) list.get((i - 1));
if (i > list.size() - numNullValues) {
assertNull("Expected null value for pkid", pkid);
} else {
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + (size - (i - 1)))) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 6 - ID field values should be in the same order.
str = queries[6];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Struct strct = (Struct) list.get(i - 1);
int id = ((Integer) strct.getFieldValues()[0]).intValue();
// ID should be one of 1, 2, 3 because of distinct
if (i <= numNullValues) {
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
} else {
if (id != i) {
fail(" Value of ID is not as expected " + id);
}
}
}
// Query 7 - ID field values should be in the same order.
str = queries[7];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
Struct strct = (Struct) list.get(i - 1);
int id = ((Integer) strct.getFieldValues()[0]).intValue();
if (id != (numNullValues + i)) {
fail(" Value of ID is not as expected, " + id);
}
}
// Query 8 - ID, pkid field values should be in the same order.
str = queries[8];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= size; i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
// ID should be one of 1, 2, 3 because of distinct
if (i <= numNullValues) {
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
assertNull("Expected null value for pkid", pkid);
} else {
if (id != i) {
fail(" Value of ID is not as expected " + id);
}
assertNotNull("Expected not null value for pkid", pkid);
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not in expected order.");
}
}
}
// Query 9 - ID, pkid field values should be in the same order.
str = queries[9];
q = CacheUtils.getQueryService().newQuery(str);
CacheUtils.getLogger().info("Executing query: " + str);
results = (SelectResults) q.execute();
list = results.asList();
for (int i = 1; i <= list.size(); i++) {
Struct vals = (Struct) list.get((i - 1));
int id = ((Integer) vals.get("ID")).intValue();
String pkid = (String) vals.get("pkid");
if (i <= numNullValues) {
assertNull("Expected null value for pkid, " + pkid, pkid);
if (!(id == 1 || id == 2 || id == 3)) {
fail(" Value of ID is not as expected " + id);
}
} else {
if (!pkid.equals("" + i)) {
fail(" Value of pkid is not as expected, " + pkid);
}
if (id != i) {
fail(" Value of ID is not as expected, " + id);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail(q.getQueryString());
}
}
@Test
public void testOrderByForUndefined() throws Exception {
String queries[] = {"SELECT position1.secId FROM /test ORDER BY position1.secId", // 0
"SELECT position1.secId FROM /test ORDER BY position1.secId desc", // 1
"SELECT position1.secId FROM /test where ID > 0 ORDER BY position1.secId", // 2
"SELECT position1.secId FROM /test where ID > 0 ORDER BY position1.secId desc", // 3
"SELECT position1.secId, ID FROM /test ORDER BY position1.secId, ID", // 4
"SELECT position1.secId, ID FROM /test ORDER BY position1.secId desc, ID",// 5
};
Region r1 = this.createRegion("test", Portfolio.class);
for (int i = 0; i < 10; i++) {
Portfolio pf = new Portfolio(i);
if (i % 2 == 0) {
pf.position1 = null;
}
r1.put(i + "", pf);
}
QueryService qs = CacheUtils.getQueryService();
SelectResults[][] sr = new SelectResults[queries.length][2];
Object[] srArr = null;
for (int i = 0; i < queries.length; i++) {
try {
sr[i][0] = (SelectResults) qs.newQuery(queries[i]).execute();
srArr = sr[i][0].toArray();
if (i == 0) {
assertEquals("First result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[0]);
} else if (i == 1) {
assertEquals("Last result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[srArr.length - 1]);
} else if (i == 2) {
assertEquals("First result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[0]);
} else if (i == 3) {
assertEquals("Last result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[srArr.length - 1]);
} else if (i == 4) {
for (int j = 0; j < srArr.length / 2; j++) {
assertEquals("Undefined should have been returned for query " + queries[i],
QueryService.UNDEFINED, ((Struct) srArr[j]).getFieldValues()[0]);
}
} else if (i == 5) {
for (int j = srArr.length - 1; j > srArr.length / 2; j--) {
assertEquals("Undefined should have been returned for query " + queries[i],
QueryService.UNDEFINED, ((Struct) srArr[j]).getFieldValues()[0]);
}
}
} catch (Exception e) {
fail("Query execution failed for: " + queries[i] + " : " + e);
}
}
this.createIndex("secIndex", "position1.secId", r1.getFullPath());
this.createIndex("IDIndex", "ID", r1.getFullPath());
for (int i = 0; i < queries.length; i++) {
try {
sr[i][1] = (SelectResults) qs.newQuery(queries[i]).execute();
srArr = sr[i][1].toArray();
if (i == 0) {
assertEquals("First result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[0]);
} else if (i == 1) {
assertEquals("Last result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[srArr.length - 1]);
} else if (i == 2) {
assertEquals("First result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[0]);
} else if (i == 3) {
assertEquals("Last result should be undefined for query " + queries[i],
QueryService.UNDEFINED, srArr[srArr.length - 1]);
} else if (i == 4) {
for (int j = 0; j < srArr.length / 2; j++) {
assertEquals("Undefined should have been returned for query " + queries[i],
QueryService.UNDEFINED, ((Struct) srArr[j]).getFieldValues()[0]);
}
} else if (i == 5) {
for (int j = srArr.length - 1; j > srArr.length / 2; j--) {
assertEquals("Undefined should have been returned for query " + queries[i],
QueryService.UNDEFINED, ((Struct) srArr[j]).getFieldValues()[0]);
}
}
} catch (Exception e) {
e.printStackTrace();
fail("Query execution failed for: " + queries[i] + " : " + e);
}
}
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
}
class QueryObserverImpl extends QueryObserverAdapter {
boolean isIndexesUsed = false;
ArrayList indexesUsed = new ArrayList();
String indexName;
boolean limitAppliedAtIndex = false;
public void beforeIndexLookup(Index index, int oper, Object key) {
indexName = index.getName();
indexesUsed.add(index.getName());
}
public void afterIndexLookup(Collection results) {
if (results != null) {
isIndexesUsed = true;
}
}
public void limitAppliedAtIndexLevel(Index index, int limit, Collection indexResult) {
this.limitAppliedAtIndex = true;
}
}
}
| apache-2.0 |
UniquePassive/runelite | runelite-api/src/main/java/net/runelite/api/queries/GroundObjectQuery.java | 2150 | /*
* Copyright (c) 2017, Devin French <https://github.com/devinfrench>
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.api.queries;
import net.runelite.api.Client;
import net.runelite.api.GroundObject;
import net.runelite.api.Tile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
public class GroundObjectQuery extends TileObjectQuery<GroundObject, GroundObjectQuery>
{
@Override
public GroundObject[] result(Client client)
{
return getGroundObjects(client).stream()
.filter(Objects::nonNull)
.filter(predicate)
.distinct()
.toArray(GroundObject[]::new);
}
private Collection<GroundObject> getGroundObjects(Client client)
{
Collection<GroundObject> objects = new ArrayList<>();
for (Tile tile : getTiles(client))
{
objects.add(tile.getGroundObject());
}
return objects;
}
}
| bsd-2-clause |
Jgilhuly/VoogaSalad | src/engine/gameobject/test/GamePlayerScreen.java | 6194 | package engine.gameobject.test;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import View.ButtonWrapper;
import View.ViewConcrete2;
import engine.events.ConcreteQueue;
import engine.events.ConstantSpacingWave;
import engine.events.GameObjectQueue;
import engine.events.TimedEvent;
import engine.game.ConcreteGame;
import engine.game.ConcreteLevel;
import engine.game.ConcreteLevelBoard;
import engine.game.Game;
import engine.game.Player;
import engine.game.PlayerUnit;
import engine.game.StoryBoard;
import engine.gameobject.GameObject;
import engine.gameobject.GameObjectSimpleTest;
import engine.goals.Goal;
import engine.goals.HealthGoal;
import engine.goals.NullGoal;
import engine.goals.ScoreGoal;
import engine.shop.ShopModelSimple;
import engine.shop.wallet.ConcreteWallet;
import engine.shop.wallet.Wallet;
import gae.gameView.Main;
import gameworld.FixedWorld;
import gameworld.GameWorld;
public class GamePlayerScreen extends Application {
private VBox myVbox;
private Game myGame;
private Stage myStage;
private ViewConcrete2 myGameView;
public GamePlayerScreen () {
// myGame =
// new ConcreteGame(new Player("myPlayer", null, null, null),
// new ConcreteLevelBoard(), new ArrayList<ButtonWrapper>());
myVbox = new VBox(30);
makeDis();
}
private void addDetails (String label, String text) {
VBox insideBox = new VBox(10);
Label labelText = new Label(label);
Text description = new Text(text);
insideBox.getChildren().addAll(labelText, description);
insideBox.setAlignment(Pos.CENTER);
myVbox.getChildren().addAll(insideBox);
}
public void makeDis () {
addDetails("Name", "this is an example of a name"); // this should be taken in from the GAE
addDetails("Description", "this is an example of a description"); // this should be taken in
// from the GAE
addDetails("Instructions", "this is an example of instructions"); // this should be taken in
// from the GAE
Button scoreBtn = new Button("View high scores");
Button playBtn = new Button("play");
playBtn.setOnAction(e -> startGame());
myVbox.getChildren().addAll(scoreBtn, playBtn);
}
private void startGame () {
// myGameView = new ViewConcrete2(myGame, Main.SCREEN_WIDTH, Main.SCREEN_WIDTH);
Group root = new Group();
root.getChildren().add(makeDemoGame());
Scene scene = new Scene(root);
myStage.setScene(scene);
}
public Node makeDemoGame () {
ConcreteLevelBoard board = new ConcreteLevelBoard();
GameWorld world = new FixedWorld(10,10);
world.addObject(new GameObjectSimpleTest());
world.addObject(new TestTower(1, 270, 270));
List<GameObject> waveObjects = new ArrayList<>();
for (int i = 0; i < 10; i++) {
waveObjects.add(new GameObjectSimpleTest());
}
GameObjectQueue q = new ConcreteQueue(waveObjects);
TimedEvent wave = new ConstantSpacingWave(2.0, q, world);
StoryBoard story = new StoryBoard(wave);
PlayerUnit health = new PlayerUnit(100, "Health");
PlayerUnit scoreUnit = new PlayerUnit(100, "Score");
Wallet wallet = new ConcreteWallet(scoreUnit);
Player myPlayer = new Player("PlayerName", health, scoreUnit, wallet);
// EDIT: temp change -- game won't have accurate shop - Nathan
myGame =
new ConcreteGame(new ShopModelSimple(), myPlayer, board,
new ArrayList<ButtonWrapper>());
// ButtonWrapper wrap=new ButtonWrapper("wave",e->story.startNextEvent(),new NullGoal());
ButtonWrapper wrap = new ButtonWrapper("wave", e -> story.startNextEvent(), new NullGoal());
myGame.addButton(wrap);
HealthGoal healthy = new HealthGoal(myPlayer, 0);
List<Goal> list = new ArrayList<Goal>();
list.add(healthy);
ScoreGoal score = new ScoreGoal(myPlayer, 200);
List<Goal> list2 = new ArrayList<Goal>();
list2.add(score);
List<Goal> list3 = new ArrayList<Goal>();
ScoreGoal score2 = new ScoreGoal(myPlayer, 300);
list3.add(score2);
board.addLevel(new ConcreteLevel("images/Park_Path.png", list2, list, world, story));
board.addLevel(new ConcreteLevel("images/example_path.jpeg", list3, list, new FixedWorld(10,10),
story));
// EDIT: temp change -- game won't have accurate shop - Nathan
myGame =
new ConcreteGame(new ShopModelSimple(), myPlayer, board,
new ArrayList<ButtonWrapper>());
Node node = myGameView.initializeView();
return node;
}
public static void main (String[] args) {
launch(args);
}
@Override
public void start (Stage primaryStage) throws Exception {
myStage = primaryStage;
myStage.setWidth(Main.SCREEN_WIDTH);
myStage.setHeight(Main.SCREEN_HEIGHT);
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(0, 40, 0, 0));
Scene scene = new Scene(pane);
myVbox.setAlignment(Pos.CENTER);
pane.setRight(myVbox);
VBox veebz = new VBox();
ImageView image = new ImageView("images/Park_Path.png");
image.setPreserveRatio(true);
image.setFitHeight(Main.SCREEN_HEIGHT);
Label label = new Label("Game Type");
label.setTextFill(Color.BLUE);
veebz.getChildren().addAll(image, label);
veebz.setAlignment(Pos.CENTER);
pane.setLeft(veebz);
myStage.setScene(scene);
myStage.show();
}
}
| mit |