gt
stringclasses 1
value | context
stringlengths 2.05k
161k
|
---|---|
/*
* Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.twosigma.beaker.chart;
import com.twosigma.beaker.chart.xychart.plotitem.Crosshair;
import com.twosigma.beaker.chart.xychart.plotitem.YAxis;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
public abstract class AbstractChart extends Chart {
private String xLabel;
private final YAxis yAxis = new YAxis();
private final List<YAxis> yAxes = new ArrayList<>();
private double xLowerMargin = 0.05;
private double xUpperMargin = 0.05;
protected TimeZone timeZone;
private Crosshair crosshair;
private boolean omitCheckboxes = false;
protected AbstractChart() {
yAxes.add(yAxis);
}
public AbstractChart setXLabel(String xLabel) {
this.xLabel = xLabel;
return this;
}
public AbstractChart setxLabel(String xLabel) {
this.xLabel = xLabel;
return this;
}
public String getXLabel() {
return this.xLabel;
}
public AbstractChart setYLabel(String yLabel) {
yAxis.setLabel(yLabel);
return this;
}
public AbstractChart setyLabel(String yLabel) {
yAxis.setLabel(yLabel);
return this;
}
public String getYLabel() {
return yAxis.getLabel();
}
public AbstractChart add(YAxis yAxis) {
this.yAxes.add(yAxis);
return this;
}
public AbstractChart leftShift(YAxis yAxis) {
return add(yAxis);
}
public List<YAxis> getYAxes() {
return this.yAxes;
}
public AbstractChart add(List items) {
for (Object o : items) {
if (o instanceof YAxis) {
add((YAxis) o);
}
}
return this;
}
public AbstractChart leftShift(List items) {
return add(items);
}
public AbstractChart setXLowerMargin(double margin) {
this.xLowerMargin = margin;
return this;
}
public AbstractChart setxLowerMargin(double margin) {
this.xLowerMargin = margin;
return this;
}
public double getXLowerMargin() {
return this.xLowerMargin;
}
public AbstractChart setXUpperMargin(double margin) {
this.xUpperMargin = margin;
return this;
}
public AbstractChart setxUpperMargin(double margin) {
this.xUpperMargin = margin;
return this;
}
public double getXUpperMargin() {
return this.xUpperMargin;
}
public AbstractChart setyAutoRange(boolean yAutoRange) {
this.yAxis.setAutoRange(yAutoRange);
return this;
}
public Boolean getYAutoRange() {
return this.yAxis.getAutoRange();
}
public AbstractChart setYAutoRangeIncludesZero(boolean yAutoRangeIncludesZero) {
this.yAxis.setAutoRangeIncludesZero(yAutoRangeIncludesZero);
return this;
}
public AbstractChart setyAutoRangeIncludesZero(boolean yAutoRangeIncludesZero) {
return this.setYAutoRangeIncludesZero(yAutoRangeIncludesZero);
}
public Boolean getYAutoRangeIncludesZero() {
return this.yAxis.getAutoRangeIncludesZero();
}
public AbstractChart setYLowerMargin(double margin) {
this.yAxis.setLowerMargin(margin);
return this;
}
public AbstractChart setyLowerMargin(double margin) {
this.yAxis.setLowerMargin(margin);
return this;
}
public double getYLowerMargin() {
return this.yAxis.getLowerMargin();
}
public AbstractChart setYUpperMargin(double margin) {
this.yAxis.setUpperMargin(margin);
return this;
}
public AbstractChart setyUpperMargin(double margin) {
this.yAxis.setUpperMargin(margin);
return this;
}
public double getYUpperMargin() {
return this.yAxis.getUpperMargin();
}
public AbstractChart setYBound(double lower, double upper) {
this.yAxis.setAutoRange(false);
this.yAxis.setBound(lower, upper);
return this;
}
public AbstractChart setYBound(List bound) {
if (bound.size() != 2) {
throw new IllegalArgumentException("to set the y bound, the list needs to be of size=2");
}
if (!(bound.get(0) instanceof Number) || !(bound.get(1) instanceof Number)) {
throw new IllegalArgumentException("the elements in the list needs to be numbers");
}
Number n0 = (Number) bound.get(0);
Number n1 = (Number) bound.get(1);
setYBound(n0.doubleValue(), n1.doubleValue());
return this;
}
public AbstractChart setyBound(List bound) {
return this.setYBound(bound);
}
public Double getYLowerBound() {
return this.yAxis.getLowerBound();
}
public Double getYUpperBound() {
return this.yAxis.getUpperBound();
}
public AbstractChart setLogY(boolean logY) {
this.yAxis.setLog(logY);
return this;
}
public Boolean getLogY() {
return this.yAxis.getLog();
}
public AbstractChart setYLogBase(double yLogBase) {
this.yAxis.setLogBase(yLogBase);
return this;
}
public AbstractChart setyLogBase(double yLogBase) {
return this.setYLogBase(yLogBase);
}
public Double getYLogBase() {
return this.yAxis.getLogBase();
}
protected AbstractChart setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
return this;
}
public TimeZone getTimeZone() {
return this.timeZone;
}
public AbstractChart setCrosshair(Crosshair crosshair) {
this.crosshair = crosshair;
return this;
}
public Crosshair getCrosshair() {
return this.crosshair;
}
public Boolean getOmitCheckboxes() {
return omitCheckboxes;
}
public AbstractChart setOmitCheckboxes(boolean omitCheckboxes) {
this.omitCheckboxes = omitCheckboxes;
return this;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.tier.sockets;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.Principal;
import java.util.Properties;
import org.apache.geode.DataSerializer;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.HeapDataOutputStream;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.VersionedDataInputStream;
import org.apache.geode.internal.VersionedDataOutputStream;
import org.apache.geode.internal.VersionedDataStream;
import org.apache.geode.internal.cache.tier.CommunicationMode;
import org.apache.geode.internal.cache.tier.Encryptor;
import org.apache.geode.internal.cache.tier.ServerSideHandshake;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.pdx.internal.PeerTypeRegistration;
import org.apache.geode.security.AuthenticationRequiredException;
public class ServerSideHandshakeImpl extends Handshake implements ServerSideHandshake {
private static final Version currentServerVersion =
ServerSideHandshakeFactory.currentServerVersion;
private Version clientVersion;
private final byte replyCode;
@Override
protected byte getReplyCode() {
return replyCode;
}
/**
* HandShake Constructor used by server side connection
*/
public ServerSideHandshakeImpl(Socket sock, int timeout, DistributedSystem sys,
Version clientVersion, CommunicationMode communicationMode, SecurityService securityService)
throws IOException, AuthenticationRequiredException {
this.clientVersion = clientVersion;
this.system = sys;
this.securityService = securityService;
this.encryptor = new EncryptorImpl(sys.getSecurityLogWriter());
int soTimeout = -1;
try {
soTimeout = sock.getSoTimeout();
sock.setSoTimeout(timeout);
InputStream inputStream = sock.getInputStream();
int valRead = inputStream.read();
if (valRead == -1) {
throw new EOFException(
LocalizedStrings.HandShake_HANDSHAKE_EOF_REACHED_BEFORE_CLIENT_CODE_COULD_BE_READ
.toLocalizedString());
}
this.replyCode = (byte) valRead;
if (replyCode != REPLY_OK) {
throw new IOException(
LocalizedStrings.HandShake_HANDSHAKE_REPLY_CODE_IS_NOT_OK.toLocalizedString());
}
try {
DataInputStream dataInputStream = new DataInputStream(inputStream);
DataOutputStream dataOutputStream = new DataOutputStream(sock.getOutputStream());
this.clientReadTimeout = dataInputStream.readInt();
if (clientVersion.compareTo(Version.CURRENT) < 0) {
// versioned streams allow object serialization code to deal with older clients
dataInputStream = new VersionedDataInputStream(dataInputStream, clientVersion);
dataOutputStream = new VersionedDataOutputStream(dataOutputStream, clientVersion);
}
this.id = ClientProxyMembershipID.readCanonicalized(dataInputStream);
// Note: credentials should always be the last piece in handshake for
// Diffie-Hellman key exchange to work
if (clientVersion.compareTo(Version.GFE_603) >= 0) {
setOverrides(new byte[] {dataInputStream.readByte()});
} else {
setClientConflation(dataInputStream.readByte());
}
if (this.clientVersion.compareTo(Version.GFE_65) < 0 || communicationMode.isWAN()) {
this.credentials =
readCredentials(dataInputStream, dataOutputStream, sys, this.securityService);
} else {
this.credentials = this.readCredential(dataInputStream, dataOutputStream, sys);
}
} catch (ClassNotFoundException cnfe) {
throw new IOException(
LocalizedStrings.HandShake_CLIENTPROXYMEMBERSHIPID_CLASS_COULD_NOT_BE_FOUND_WHILE_DESERIALIZING_THE_OBJECT
.toLocalizedString());
}
} finally {
if (soTimeout != -1) {
try {
sock.setSoTimeout(soTimeout);
} catch (IOException ignore) {
}
}
}
}
public Version getClientVersion() {
return this.clientVersion;
}
public Version getVersion() {
return this.clientVersion;
}
@Override
public void handshakeWithClient(OutputStream out, InputStream in, byte endpointType,
int queueSize, CommunicationMode communicationMode, Principal principal) throws IOException {
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis;
if (clientVersion.compareTo(Version.CURRENT) < 0) {
dis = new VersionedDataInputStream(in, clientVersion);
dos = new VersionedDataOutputStream(dos, clientVersion);
} else {
dis = new DataInputStream(in);
}
// Write ok reply
if (communicationMode.isWAN() && principal != null) {
dos.writeByte(REPLY_WAN_CREDENTIALS);
} else {
dos.writeByte(REPLY_OK);// byte 59
}
// additional byte of wan site needs to send for Gateway BC
if (communicationMode.isWAN()) {
Version.writeOrdinal(dos, currentServerVersion.ordinal(), true);
}
dos.writeByte(endpointType);
dos.writeInt(queueSize);
// Write the server's member
DistributedMember member = this.system.getDistributedMember();
Version v = Version.CURRENT;
if (dos instanceof VersionedDataStream) {
v = ((VersionedDataStream) dos).getVersion();
}
HeapDataOutputStream hdos = new HeapDataOutputStream(v);
DataSerializer.writeObject(member, hdos);
DataSerializer.writeByteArray(hdos.toByteArray(), dos);
hdos.close();
// Write no message
dos.writeUTF("");
// Write delta-propagation property value if this is not WAN.
if (!communicationMode.isWAN() && this.clientVersion.compareTo(Version.GFE_61) >= 0) {
dos.writeBoolean(((InternalDistributedSystem) this.system).getConfig().getDeltaPropagation());
}
// Neeraj: Now if the communication mode is GATEWAY_TO_GATEWAY
// and principal not equal to null then send the credentials also
if (communicationMode.isWAN() && principal != null) {
sendCredentialsForWan(dos, dis);
}
// Write the distributed system id if this is a 6.6 or greater client
// on the remote side of the gateway
if (communicationMode.isWAN() && this.clientVersion.compareTo(Version.GFE_66) >= 0
&& currentServerVersion.compareTo(Version.GFE_66) >= 0) {
dos.writeByte(((InternalDistributedSystem) this.system).getDistributionManager()
.getDistributedSystemId());
}
if ((communicationMode.isWAN()) && this.clientVersion.compareTo(Version.GFE_80) >= 0
&& currentServerVersion.compareTo(Version.GFE_80) >= 0) {
int pdxSize = PeerTypeRegistration.getPdxRegistrySize();
dos.writeInt(pdxSize);
}
// Flush
dos.flush();
}
@Override
public Encryptor getEncryptor() {
return encryptor;
}
private void sendCredentialsForWan(OutputStream out, InputStream in) {
try {
Properties wanCredentials = getCredentials(this.id.getDistributedMember());
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
writeCredentials(dos, dis, wanCredentials, false, this.system.getDistributedMember());
}
// The exception while getting the credentials is just logged as severe
catch (Exception e) {
this.system.getSecurityLogWriter().convertToLogWriterI18n().severe(
LocalizedStrings.HandShake_AN_EXCEPTION_WAS_THROWN_WHILE_SENDING_WAN_CREDENTIALS_0,
e.getLocalizedMessage());
}
}
public int getClientReadTimeout() {
return this.clientReadTimeout;
}
}
|
|
/*
* Copyright 2017-2021 Axway Software
*
* 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.axway.ats.core.reflect;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.axway.ats.core.BaseTest;
public class Test_MethodFinder extends BaseTest {
@Test( expected = IllegalArgumentException.class)
public void classConstructorNegativeNullClass() throws NoSuchMethodException, AmbiguousMethodException {
new MethodFinder(null);
}
@Test( expected = IllegalArgumentException.class)
public void classConstructorNegativePrimitiveType() throws NoSuchMethodException,
AmbiguousMethodException {
new MethodFinder(Integer.TYPE);
}
@Test( expected = IllegalArgumentException.class)
public void classConstructorNegativeArrayType() throws NoSuchMethodException, AmbiguousMethodException {
new MethodFinder( (new byte[]{}).getClass());
}
@Test
public void findConstructorInClassPositive() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//one argument
assertNotNull(methodFinder.findConstructor(new Class<?>[]{ File.class }));
//no arguments
methodFinder = new MethodFinder(ArrayList.class);
assertNotNull(methodFinder.findConstructor(null));
}
@Test( expected = NoSuchMethodException.class)
public void findConstructorInClassNegative() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//one argument
methodFinder.findConstructor(new Class<?>[]{});
}
@Test
public void findMethodWithNamePositive() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//null argument
assertNotNull(methodFinder.findMethod("close", null));
//one argument
assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass() }));
//several arguments
assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(),
Integer.TYPE,
Integer.TYPE }));
//unboxing
assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(),
Integer.class,
Integer.class }));
//widening conversion
assertNotNull(methodFinder.findMethod("read", new Class<?>[]{ (new byte[]{}).getClass(),
Byte.class,
Short.TYPE }));
}
@Test( expected = NoSuchMethodException.class)
public void findMethodWithNameNegative() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//one argument
methodFinder.findMethod("read123", new Class<?>[]{});
}
@Test
public void findMethodPositive() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//one argument
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass() }));
//several arguments
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Integer.TYPE,
Integer.TYPE }));
//unboxing
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Integer.class,
Integer.class }));
//widening conversion
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Byte.class,
Short.TYPE }));
}
@Test( expected = NoSuchMethodException.class)
public void findMethodNegative() throws NoSuchMethodException, AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder(FileInputStream.class);
//one argument
methodFinder.findMethod(new Class<?>[]{ Integer.class, Integer.class, Integer.class });
}
@Test
public void findMethodConstructorMethodListPositive() throws NoSuchMethodException,
AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder("methods",
Arrays.asList(FileInputStream.class.getDeclaredMethods()));
//one argument
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass() }));
//several arguments
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Integer.TYPE,
Integer.TYPE }));
//unboxing
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Integer.class,
Integer.class }));
//widening conversion
assertNotNull(methodFinder.findMethod(new Class<?>[]{ (new byte[]{}).getClass(),
Byte.class,
Short.TYPE }));
}
@Test( expected = NoSuchMethodException.class)
public void findMethodConstructorMethodListNegative() throws NoSuchMethodException,
AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder("methods",
Arrays.asList(FileInputStream.class.getDeclaredMethods()));
//one argument
methodFinder.findMethod(new Class<?>[]{ Integer.class, Integer.class, Integer.class });
}
@Test( expected = AmbiguousMethodException.class)
public void findMethodConstructorMethodListNegativeAmbigous() throws NoSuchMethodException,
AmbiguousMethodException {
MethodFinder methodFinder = new MethodFinder("ambiguous",
Arrays.asList(MethodFinderTester.class.getDeclaredMethods()));
//no arguments
methodFinder.findMethod("ambiguousMethod", new Class<?>[]{ Void.TYPE });
}
@Test
public void findMethodConstructorMethodListCustomRulesPositive() throws NoSuchMethodException,
AmbiguousMethodException {
List<TypeComparisonRule> typeComparisonRules = new ArrayList<TypeComparisonRule>();
typeComparisonRules.add(new CustomTypeComparisonRule());
MethodFinder methodFinder = new MethodFinder("methods",
Arrays.asList(MethodFinderTester.class.getDeclaredMethods()),
typeComparisonRules);
//one argument - this argument will be evaulated as String in our custom rule
assertNotNull(methodFinder.findMethod(new Class<?>[]{ Test_MethodFinder.class }));
}
@Test
public void getParameterTypesFromPositive() {
//no arguments
Assert.assertArrayEquals(new Class<?>[]{}, MethodFinder.getParameterTypesFrom(new Object[]{}));
//two parameters and null
Assert.assertArrayEquals(new Class<?>[]{ String.class, Void.TYPE, Integer.class },
MethodFinder.getParameterTypesFrom(new Object[]{ new String("adf"), null, 3 }));
}
@Test
public void getParameterTypesFromByClassNamePositive() throws ClassNotFoundException {
//two parameters
Assert.assertArrayEquals(new Class<?>[]{ Byte.TYPE, String.class },
MethodFinder.getParameterTypesFrom(new String[]{ "byte", "java.lang.String" }));
}
@Test
public void getParameterTypesFromByClassNameClassLoaderPositive() throws ClassNotFoundException {
//two parameters
Assert.assertArrayEquals(new Class<?>[]{ Byte.TYPE, Test_MethodFinder.class },
MethodFinder.getParameterTypesFrom(new String[]{ "byte",
Test_MethodFinder.class.getName() },
Test_MethodFinder.class.getClassLoader()));
}
private static class CustomTypeComparisonRule implements TypeComparisonRule {
public boolean isCompatible(
Class<?> argType,
Class<?> parameterType ) {
if (argType == Test_MethodFinder.class && parameterType == String.class) {
return true;
}
return false;
}
}
}
|
|
/**
* 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.security;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.Sasl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
/**
* A utility class for dealing with SASL on RPC server
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public class SaslRpcServer {
public static final Log LOG = LogFactory.getLog(SaslRpcServer.class);
public static final String SASL_DEFAULT_REALM = "default";
public static final Map<String, String> SASL_PROPS =
new TreeMap<String, String>();
public static final int SWITCH_TO_SIMPLE_AUTH = -88;
public static enum QualityOfProtection {
AUTHENTICATION("auth"),
INTEGRITY("auth-int"),
PRIVACY("auth-conf");
public final String saslQop;
private QualityOfProtection(String saslQop) {
this.saslQop = saslQop;
}
public String getSaslQop() {
return saslQop;
}
}
public static void init(Configuration conf) {
QualityOfProtection saslQOP = QualityOfProtection.AUTHENTICATION;
String rpcProtection = conf.get("hadoop.rpc.protection",
QualityOfProtection.AUTHENTICATION.name().toLowerCase());
if (QualityOfProtection.INTEGRITY.name().toLowerCase()
.equals(rpcProtection)) {
saslQOP = QualityOfProtection.INTEGRITY;
} else if (QualityOfProtection.PRIVACY.name().toLowerCase().equals(
rpcProtection)) {
saslQOP = QualityOfProtection.PRIVACY;
}
SASL_PROPS.put(Sasl.QOP, saslQOP.getSaslQop());
SASL_PROPS.put(Sasl.SERVER_AUTH, "true");
}
static String encodeIdentifier(byte[] identifier) {
return new String(Base64.encodeBase64(identifier));
}
static byte[] decodeIdentifier(String identifier) {
return Base64.decodeBase64(identifier.getBytes());
}
public static <T extends TokenIdentifier> T getIdentifier(String id,
SecretManager<T> secretManager) throws InvalidToken {
byte[] tokenId = decodeIdentifier(id);
T tokenIdentifier = secretManager.createIdentifier();
try {
tokenIdentifier.readFields(new DataInputStream(new ByteArrayInputStream(
tokenId)));
} catch (IOException e) {
throw (InvalidToken) new InvalidToken(
"Can't de-serialize tokenIdentifier").initCause(e);
}
return tokenIdentifier;
}
static char[] encodePassword(byte[] password) {
return new String(Base64.encodeBase64(password)).toCharArray();
}
/** Splitting fully qualified Kerberos name into parts */
public static String[] splitKerberosName(String fullName) {
return fullName.split("[/@]");
}
@InterfaceStability.Evolving
public enum SaslStatus {
SUCCESS (0),
ERROR (1);
public final int state;
private SaslStatus(int state) {
this.state = state;
}
}
/** Authentication method */
@InterfaceStability.Evolving
public static enum AuthMethod {
SIMPLE((byte) 80, "", AuthenticationMethod.SIMPLE),
KERBEROS((byte) 81, "GSSAPI", AuthenticationMethod.KERBEROS),
DIGEST((byte) 82, "DIGEST-MD5", AuthenticationMethod.TOKEN);
/** The code for this method. */
public final byte code;
public final String mechanismName;
public final AuthenticationMethod authenticationMethod;
private AuthMethod(byte code, String mechanismName,
AuthenticationMethod authMethod) {
this.code = code;
this.mechanismName = mechanismName;
this.authenticationMethod = authMethod;
}
private static final int FIRST_CODE = values()[0].code;
/** Return the object represented by the code. */
private static AuthMethod valueOf(byte code) {
final int i = (code & 0xff) - FIRST_CODE;
return i < 0 || i >= values().length ? null : values()[i];
}
/** Return the SASL mechanism name */
public String getMechanismName() {
return mechanismName;
}
/** Read from in */
public static AuthMethod read(DataInput in) throws IOException {
return valueOf(in.readByte());
}
/** Write to out */
public void write(DataOutput out) throws IOException {
out.write(code);
}
};
/** CallbackHandler for SASL DIGEST-MD5 mechanism */
@InterfaceStability.Evolving
public static class SaslDigestCallbackHandler implements CallbackHandler {
private SecretManager<TokenIdentifier> secretManager;
private Server.Connection connection;
public SaslDigestCallbackHandler(
SecretManager<TokenIdentifier> secretManager,
Server.Connection connection) {
this.secretManager = secretManager;
this.connection = connection;
}
private char[] getPassword(TokenIdentifier tokenid) throws InvalidToken {
return encodePassword(secretManager.retrievePassword(tokenid));
}
/** {@inheritDoc} */
@Override
public void handle(Callback[] callbacks) throws InvalidToken,
UnsupportedCallbackException {
NameCallback nc = null;
PasswordCallback pc = null;
AuthorizeCallback ac = null;
for (Callback callback : callbacks) {
if (callback instanceof AuthorizeCallback) {
ac = (AuthorizeCallback) callback;
} else if (callback instanceof NameCallback) {
nc = (NameCallback) callback;
} else if (callback instanceof PasswordCallback) {
pc = (PasswordCallback) callback;
} else if (callback instanceof RealmCallback) {
continue; // realm is ignored
} else {
throw new UnsupportedCallbackException(callback,
"Unrecognized SASL DIGEST-MD5 Callback");
}
}
if (pc != null) {
TokenIdentifier tokenIdentifier = getIdentifier(nc.getDefaultName(), secretManager);
char[] password = getPassword(tokenIdentifier);
UserGroupInformation user = null;
user = tokenIdentifier.getUser(); // may throw exception
connection.attemptingUser = user;
if (LOG.isDebugEnabled()) {
LOG.debug("SASL server DIGEST-MD5 callback: setting password "
+ "for client: " + tokenIdentifier.getUser());
}
pc.setPassword(password);
}
if (ac != null) {
String authid = ac.getAuthenticationID();
String authzid = ac.getAuthorizationID();
if (authid.equals(authzid)) {
ac.setAuthorized(true);
} else {
ac.setAuthorized(false);
}
if (ac.isAuthorized()) {
if (LOG.isDebugEnabled()) {
String username = getIdentifier(authzid, secretManager).getUser()
.getUserName().toString();
LOG.debug("SASL server DIGEST-MD5 callback: setting "
+ "canonicalized client ID: " + username);
}
ac.setAuthorizedID(authzid);
}
}
}
}
/** CallbackHandler for SASL GSSAPI Kerberos mechanism */
@InterfaceStability.Evolving
public static class SaslGssCallbackHandler implements CallbackHandler {
/** {@inheritDoc} */
@Override
public void handle(Callback[] callbacks) throws
UnsupportedCallbackException {
AuthorizeCallback ac = null;
for (Callback callback : callbacks) {
if (callback instanceof AuthorizeCallback) {
ac = (AuthorizeCallback) callback;
} else {
throw new UnsupportedCallbackException(callback,
"Unrecognized SASL GSSAPI Callback");
}
}
if (ac != null) {
String authid = ac.getAuthenticationID();
String authzid = ac.getAuthorizationID();
if (authid.equals(authzid)) {
ac.setAuthorized(true);
} else {
ac.setAuthorized(false);
}
if (ac.isAuthorized()) {
if (LOG.isDebugEnabled())
LOG.debug("SASL server GSSAPI callback: setting "
+ "canonicalized client ID: " + authzid);
ac.setAuthorizedID(authzid);
}
}
}
}
}
|
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.toolbar;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.LayoutDirection;
import android.view.MenuItem;
import android.view.View;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.views.toolbar.events.ToolbarClickEvent;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Manages instances of ReactToolbar.
*/
public class ReactToolbarManager extends ViewGroupManager<ReactToolbar> {
private static final String REACT_CLASS = "ToolbarAndroid";
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected ReactToolbar createViewInstance(ThemedReactContext reactContext) {
return new ReactToolbar(reactContext);
}
@ReactProp(name = "logo")
public void setLogo(ReactToolbar view, @Nullable ReadableMap logo) {
view.setLogoSource(logo);
}
@ReactProp(name = "navIcon")
public void setNavIcon(ReactToolbar view, @Nullable ReadableMap navIcon) {
view.setNavIconSource(navIcon);
}
@ReactProp(name = "overflowIcon")
public void setOverflowIcon(ReactToolbar view, @Nullable ReadableMap overflowIcon) {
view.setOverflowIconSource(overflowIcon);
}
@ReactProp(name = "rtl")
public void setRtl(ReactToolbar view, boolean rtl) {
view.setLayoutDirection(rtl ? LayoutDirection.RTL : LayoutDirection.LTR);
}
@ReactProp(name = "subtitle")
public void setSubtitle(ReactToolbar view, @Nullable String subtitle) {
view.setSubtitle(subtitle);
}
@ReactProp(name = "subtitleColor", customType = "Color")
public void setSubtitleColor(ReactToolbar view, @Nullable Integer subtitleColor) {
int[] defaultColors = getDefaultColors(view.getContext());
if (subtitleColor != null) {
view.setSubtitleTextColor(subtitleColor);
} else {
view.setSubtitleTextColor(defaultColors[1]);
}
}
@ReactProp(name = "title")
public void setTitle(ReactToolbar view, @Nullable String title) {
view.setTitle(title);
}
@ReactProp(name = "titleColor", customType = "Color")
public void setTitleColor(ReactToolbar view, @Nullable Integer titleColor) {
int[] defaultColors = getDefaultColors(view.getContext());
if (titleColor != null) {
view.setTitleTextColor(titleColor);
} else {
view.setTitleTextColor(defaultColors[0]);
}
}
@ReactProp(name = "contentInsetStart", defaultFloat = Float.NaN)
public void setContentInsetStart(ReactToolbar view, float insetStart) {
int inset = Float.isNaN(insetStart) ?
getDefaultContentInsets(view.getContext())[0] :
Math.round(PixelUtil.toPixelFromDIP(insetStart));
view.setContentInsetsRelative(inset, view.getContentInsetEnd());
}
@ReactProp(name = "contentInsetEnd", defaultFloat = Float.NaN)
public void setContentInsetEnd(ReactToolbar view, float insetEnd) {
int inset = Float.isNaN(insetEnd) ?
getDefaultContentInsets(view.getContext())[1] :
Math.round(PixelUtil.toPixelFromDIP(insetEnd));
view.setContentInsetsRelative(view.getContentInsetStart(), inset);
}
@ReactProp(name = "nativeActions")
public void setActions(ReactToolbar view, @Nullable ReadableArray actions) {
view.setActions(actions);
}
@Override
protected void addEventEmitters(final ThemedReactContext reactContext, final ReactToolbar view) {
final EventDispatcher mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class)
.getEventDispatcher();
view.setNavigationOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
mEventDispatcher.dispatchEvent(
new ToolbarClickEvent(view.getId(), -1));
}
});
view.setOnMenuItemClickListener(
new ReactToolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
mEventDispatcher.dispatchEvent(
new ToolbarClickEvent(
view.getId(),
menuItem.getOrder()));
return true;
}
});
}
@Nullable
@Override
public Map<String, Object> getExportedViewConstants() {
return MapBuilder.<String, Object>of(
"ShowAsAction",
MapBuilder.of(
"never", MenuItem.SHOW_AS_ACTION_NEVER,
"always", MenuItem.SHOW_AS_ACTION_ALWAYS,
"ifRoom", MenuItem.SHOW_AS_ACTION_IF_ROOM));
}
@Override
public boolean needsCustomLayoutForChildren() {
return true;
}
private int[] getDefaultContentInsets(Context context) {
Resources.Theme theme = context.getTheme();
TypedArray toolbarStyle = null;
TypedArray contentInsets = null;
try {
toolbarStyle =
theme.obtainStyledAttributes(new int[] {getIdentifier(context, "toolbarStyle")});
int toolbarStyleResId = toolbarStyle.getResourceId(0, 0);
contentInsets =
theme.obtainStyledAttributes(
toolbarStyleResId,
new int[] {
getIdentifier(context, "contentInsetStart"),
getIdentifier(context, "contentInsetEnd"),
});
int contentInsetStart = contentInsets.getDimensionPixelSize(0, 0);
int contentInsetEnd = contentInsets.getDimensionPixelSize(1, 0);
return new int[] {contentInsetStart, contentInsetEnd};
} finally {
recycleQuietly(toolbarStyle);
recycleQuietly(contentInsets);
}
}
private static int[] getDefaultColors(Context context) {
Resources.Theme theme = context.getTheme();
TypedArray toolbarStyle = null;
TypedArray textAppearances = null;
TypedArray titleTextAppearance = null;
TypedArray subtitleTextAppearance = null;
try {
toolbarStyle =
theme.obtainStyledAttributes(new int[] {getIdentifier(context, "toolbarStyle")});
int toolbarStyleResId = toolbarStyle.getResourceId(0, 0);
textAppearances =
theme.obtainStyledAttributes(
toolbarStyleResId,
new int[] {
getIdentifier(context, "titleTextAppearance"),
getIdentifier(context, "subtitleTextAppearance"),
});
int titleTextAppearanceResId = textAppearances.getResourceId(0, 0);
int subtitleTextAppearanceResId = textAppearances.getResourceId(1, 0);
titleTextAppearance = theme
.obtainStyledAttributes(titleTextAppearanceResId, new int[]{android.R.attr.textColor});
subtitleTextAppearance = theme
.obtainStyledAttributes(subtitleTextAppearanceResId, new int[]{android.R.attr.textColor});
int titleTextColor = titleTextAppearance.getColor(0, Color.BLACK);
int subtitleTextColor = subtitleTextAppearance.getColor(0, Color.BLACK);
return new int[] {titleTextColor, subtitleTextColor};
} finally {
recycleQuietly(toolbarStyle);
recycleQuietly(textAppearances);
recycleQuietly(titleTextAppearance);
recycleQuietly(subtitleTextAppearance);
}
}
private static void recycleQuietly(@Nullable TypedArray style) {
if (style != null) {
style.recycle();
}
}
/**
* The appcompat-v7 BUCK dep is listed as a provided_dep, which complains that
* com.facebook.react.R doesn't exist. Since the attributes provided from a parent, we can access
* those attributes dynamically.
*/
private static int getIdentifier(Context context, String name) {
return context.getResources().getIdentifier(name, "attr", context.getPackageName());
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.reef.tang;
import org.apache.reef.tang.ThreeConstructors.TCFloat;
import org.apache.reef.tang.ThreeConstructors.TCInt;
import org.apache.reef.tang.ThreeConstructors.TCString;
import org.apache.reef.tang.annotations.*;
import org.apache.reef.tang.exceptions.BindException;
import org.apache.reef.tang.exceptions.ClassHierarchyException;
import org.apache.reef.tang.exceptions.InjectionException;
import org.apache.reef.tang.exceptions.NameResolutionException;
import org.apache.reef.tang.formats.ConfigurationFile;
import org.apache.reef.tang.util.ReflectionUtilities;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import javax.inject.Inject;
interface SMC {
}
@DefaultImplementation(HaveDefaultImplImpl.class)
interface HaveDefaultImpl {
}
@DefaultImplementation(name = "org.apache.reef.tang.HaveDefaultStringImplImpl")
interface HaveDefaultStringImpl {
}
interface Interf {
}
interface IfaceWithDefault {
}
interface X<T> {
}
interface Bottle<Y> {
}
interface EventHandler<T> {
}
@DefaultImplementation(MyEventHandler.class)
interface MyEventHandlerIface extends EventHandler<Foo> {
}
interface SomeIface {
}
@DefaultImplementation(AHandlerImpl.class)
interface AHandler extends EventHandler<AH> {
}
@DefaultImplementation(BHandlerImpl.class)
interface BHandler extends EventHandler<BH> {
}
interface CheckChildIface {
}
public class TestTang {
@Rule
public ExpectedException thrown = ExpectedException.none();
Tang tang;
@Before
public void setUp() throws Exception {
MustBeSingleton.alreadyInstantiated = false;
tang = Tang.Factory.getTang();
}
@Test
public void testSingleton() throws InjectionException {
Injector injector = tang.newInjector();
Assert.assertNotNull(injector.getInstance(TwoSingletons.class));
Assert.assertNotNull(injector.getInstance(TwoSingletons.class));
}
@Test
public void testNotSingleton() throws InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Could not invoke constructor");
Assert.assertNotNull(tang.newInjector().getInstance(TwoSingletons.class));
tang.newInjector().getInstance(TwoSingletons.class);
}
// TODO: Delete this? (It is handled in TestClassHierarchy!)
@Test(expected = ClassHierarchyException.class)
public void testRepeatedAmbiguousArgs() throws BindException, NameResolutionException {
JavaConfigurationBuilder t = tang.newConfigurationBuilder();
t.getClassHierarchy().getNode(ReflectionUtilities.getFullName(RepeatedAmbiguousArgs.class));
}
@Test
public void testRepeatedOKArgs() throws BindException, InjectionException {
JavaConfigurationBuilder t = tang.newConfigurationBuilder();
t.bindNamedParameter(RepeatedNamedArgs.A.class, "1");
t.bindNamedParameter(RepeatedNamedArgs.B.class, "2");
Injector injector = tang.newInjector(t.build());
injector.getInstance(RepeatedNamedArgs.class);
}
// NamedParameter A has no default_value, so this should throw.
@Test
public void testOneNamedFailArgs() throws InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.OneNamedSingletonArgs: org.apache.reef.tang.OneNamedSingletonArgs missing argument org.apache.reef.tang.OneNamedSingletonArgs$A");
tang.newInjector().getInstance(OneNamedSingletonArgs.class);
}
@Test
public void testOneNamedOKArgs() throws InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.OneNamedSingletonArgs: org.apache.reef.tang.OneNamedSingletonArgs missing argument org.apache.reef.tang.OneNamedSingletonArgs$A");
tang.newInjector().getInstance(OneNamedSingletonArgs.class);
}
// NamedParameter A has no default_value
@Test
public void testOneNamedSingletonFailArgs() throws InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.OneNamedSingletonArgs: org.apache.reef.tang.OneNamedSingletonArgs missing argument org.apache.reef.tang.OneNamedSingletonArgs$A");
tang.newInjector().getInstance(OneNamedSingletonArgs.class);
}
// NamedParameter A get's bound to a volatile, so this should succeed.
@Test
public void testOneNamedSingletonOKArgs() throws BindException, InjectionException {
final Injector i = tang.newInjector();
i.bindVolatileParameter(OneNamedSingletonArgs.A.class,
i.getInstance(MustBeSingleton.class));
i.getInstance(OneNamedSingletonArgs.class);
}
@Test
public void testRepeatedNamedOKArgs() throws BindException,
InjectionException {
final Injector i = tang.newInjector();
i.bindVolatileParameter(RepeatedNamedSingletonArgs.A.class,
i.getInstance(MustBeSingleton.class));
i.bindVolatileParameter(RepeatedNamedSingletonArgs.B.class,
i.getInstance(MustBeSingleton.class));
i.getInstance(RepeatedNamedSingletonArgs.class);
}
@Test
public void testRepeatedNamedArgs() throws BindException,
InjectionException {
Injector i = tang.newInjector();
i.bindVolatileParameter(RepeatedNamedSingletonArgs.A.class,
i.getInstance(MustBeSingleton.class));
i.bindVolatileParameter(RepeatedNamedSingletonArgs.B.class,
i.getInstance(MustBeSingleton.class));
i.getInstance(RepeatedNamedSingletonArgs.class);
}
@Test
public void testStraightforwardBuild() throws BindException,
InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bind(Interf.class, Impl.class);
tang.newInjector(cb.build()).getInstance(Interf.class);
}
@Test
public void testOneNamedStringArgCantRebind() throws BindException,
InjectionException {
thrown.expect(BindException.class);
thrown.expectMessage("Attempt to re-bind named parameter org.apache.reef.tang.OneNamedStringArg$A. Old value was [not default] new value is [volatile]");
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
OneNamedStringArg a = tang.newInjector(cb.build()).getInstance(
OneNamedStringArg.class);
Assert.assertEquals("default", a.s);
cb.bindNamedParameter(OneNamedStringArg.A.class, "not default");
Injector i = tang.newInjector(cb.build());
Assert
.assertEquals("not default", i.getInstance(OneNamedStringArg.class).s);
i.bindVolatileParameter(OneNamedStringArg.A.class, "volatile");
Assert.assertEquals("volatile", i.getInstance(OneNamedStringArg.class).s);
}
@Test
public void testOneNamedStringArgBind() throws BindException,
InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
OneNamedStringArg a = tang.newInjector(cb.build()).getInstance(
OneNamedStringArg.class);
Assert.assertEquals("default", a.s);
cb.bindNamedParameter(OneNamedStringArg.A.class, "not default");
Injector i = tang.newInjector(cb.build());
Assert
.assertEquals("not default", i.getInstance(OneNamedStringArg.class).s);
}
@Test
public void testOneNamedStringArgVolatile() throws BindException,
InjectionException {
OneNamedStringArg a = tang.newInjector().getInstance(
OneNamedStringArg.class);
Assert.assertEquals("default", a.s);
Injector i = tang.newInjector();
i.bindVolatileParameter(OneNamedStringArg.A.class, "volatile");
Assert.assertEquals("volatile", i.getInstance(OneNamedStringArg.class).s);
}
@Test
public void testTwoNamedStringArgsBind() throws BindException,
InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
TwoNamedStringArgs a = tang.newInjector(cb.build()).getInstance(
TwoNamedStringArgs.class);
Assert.assertEquals("defaultA", a.a);
Assert.assertEquals("defaultB", a.b);
cb.bindNamedParameter(TwoNamedStringArgs.A.class, "not defaultA");
cb.bindNamedParameter(TwoNamedStringArgs.B.class, "not defaultB");
Injector i = tang.newInjector(cb.build());
Assert.assertEquals("not defaultA",
i.getInstance(TwoNamedStringArgs.class).a);
Assert.assertEquals("not defaultB",
i.getInstance(TwoNamedStringArgs.class).b);
}
@Test
public void testTwoNamedStringArgsBindVolatile() throws BindException,
InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
TwoNamedStringArgs a = tang.newInjector(cb.build()).getInstance(
TwoNamedStringArgs.class);
Assert.assertEquals("defaultA", a.a);
Assert.assertEquals("defaultB", a.b);
final Injector i = tang.newInjector(cb.build());
i.bindVolatileParameter(TwoNamedStringArgs.A.class, "not defaultA");
i.bindVolatileParameter(TwoNamedStringArgs.B.class, "not defaultB");
Assert.assertEquals("not defaultA",
i.getInstance(TwoNamedStringArgs.class).a);
Assert.assertEquals("not defaultB",
i.getInstance(TwoNamedStringArgs.class).b);
}
@Test//(expected = BindException.class)
public void testTwoNamedStringArgsReBindVolatileFail() throws BindException,
InjectionException {
thrown.expect(BindException.class);
thrown.expectMessage("Attempt to re-bind named parameter org.apache.reef.tang.TwoNamedStringArgs$A. Old value was [not defaultA] new value is [not defaultA]");
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
TwoNamedStringArgs a = tang.newInjector(cb.build()).getInstance(
TwoNamedStringArgs.class);
Assert.assertEquals("defaultA", a.a);
Assert.assertEquals("defaultB", a.b);
cb.bindNamedParameter(TwoNamedStringArgs.A.class, "not defaultA");
cb.bindNamedParameter(TwoNamedStringArgs.B.class, "not defaultB");
Injector i = tang.newInjector(cb.build());
i.bindVolatileParameter(TwoNamedStringArgs.A.class, "not defaultA");
i.bindVolatileParameter(TwoNamedStringArgs.B.class, "not defaultB");
}
@Test
public void testBextendsAinjectA() throws BindException, InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bind(BextendsAinjectA.A.class, BextendsAinjectA.A.class);
tang.newInjector(cb.build()).getInstance(BextendsAinjectA.A.class);
}
@Test
public void testExternalConstructor() throws BindException,
InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindConstructor(ExternalConstructorExample.Legacy.class,
ExternalConstructorExample.LegacyWrapper.class);
Injector i = tang.newInjector(cb.build());
i.bindVolatileInstance(Integer.class, 42);
i.bindVolatileInstance(String.class, "The meaning of life is ");
ExternalConstructorExample.Legacy l = i
.getInstance(ExternalConstructorExample.Legacy.class);
Assert.assertEquals(new Integer(42), l.x);
Assert.assertEquals("The meaning of life is ", l.y);
}
@Test
public void testLegacyConstructor() throws BindException, InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.registerLegacyConstructor(
ReflectionUtilities.getFullName(LegacyConstructor.class),
ReflectionUtilities.getFullName(Integer.class),
ReflectionUtilities.getFullName(String.class));
cb.bind(LegacyConstructor.class, LegacyConstructor.class);
String confString = ConfigurationFile.toConfigurationString(cb.build());
JavaConfigurationBuilder cb2 = tang.newConfigurationBuilder();
// System.err.println(confString);
ConfigurationFile.addConfiguration(cb2, confString);
Injector i = tang.newInjector(cb2.build());
i.bindVolatileInstance(Integer.class, 42);
i.bindVolatileInstance(String.class, "The meaning of life is ");
LegacyConstructor l = i.getInstance(LegacyConstructor.class);
Assert.assertEquals(new Integer(42), l.x);
Assert.assertEquals("The meaning of life is ", l.y);
}
@Test
public void testNamedImpl() throws BindException, InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(NamedImpl.AImplName.class, NamedImpl.Aimpl.class);
cb.bindNamedParameter(NamedImpl.BImplName.class, NamedImpl.Bimpl.class);
Injector i = tang.newInjector(cb.build());
NamedImpl.Aimpl a1 = (NamedImpl.Aimpl) i
.getNamedInstance(NamedImpl.AImplName.class);
NamedImpl.Aimpl a2 = (NamedImpl.Aimpl) i
.getNamedInstance(NamedImpl.AImplName.class);
NamedImpl.Bimpl b1 = (NamedImpl.Bimpl) i
.getNamedInstance(NamedImpl.BImplName.class);
NamedImpl.Bimpl b2 = (NamedImpl.Bimpl) i
.getNamedInstance(NamedImpl.BImplName.class);
Assert.assertSame(a1, a2);
Assert.assertSame(b1, b2);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testWrongNamedImpl() throws BindException {
thrown.expect(BindException.class);
thrown.expectMessage("Name<org.apache.reef.tang.NamedImpl$A> org.apache.reef.tang.NamedImpl$AImplName cannot take non-subclass org.apache.reef.tang.NamedImpl$Cimpl");
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindNamedParameter((Class) NamedImpl.AImplName.class, (Class) NamedImpl.Cimpl.class);
}
@Test
public void testUnit() throws BindException, InjectionException {
Injector inj = tang.newInjector();
OuterUnit.InA a = inj.getInstance(OuterUnit.InA.class);
OuterUnit.InB b = inj.getInstance(OuterUnit.InB.class);
Assert.assertEquals(a.slf, b.slf);
}
@Test
public void testMissedUnit() throws BindException, InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.MissOuterUnit$InA: No known implementations / injectable constructors for org.apache.reef.tang.MissOuterUnit$InA");
Injector inj = tang.newInjector();
MissOuterUnit.InA a = inj.getInstance(MissOuterUnit.InA.class);
}
@Test
public void testMissedUnitButWithInjectInnerClass() throws BindException, InjectionException {
thrown.expect(ClassHierarchyException.class);
thrown.expectMessage("Cannot @Inject non-static member class unless the enclosing class an @Unit. Nested class is:org.apache.reef.tang.MissOuterUnit$InB");
Injector inj = tang.newInjector();
MissOuterUnit.InB b = inj.getInstance(MissOuterUnit.InB.class);
}
@Test
public void testThreeConstructors() throws BindException, InjectionException {
JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCInt.class, "1");
cb.bindNamedParameter(TCString.class, "s");
ThreeConstructors tc = tang.newInjector(cb.build()).getInstance(ThreeConstructors.class);
Assert.assertEquals(1, tc.i);
Assert.assertEquals("s", tc.s);
cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCInt.class, "1");
tc = tang.newInjector(cb.build()).getInstance(ThreeConstructors.class);
Assert.assertEquals(1, tc.i);
Assert.assertEquals("default", tc.s);
cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCString.class, "s");
tc = tang.newInjector(cb.build()).getInstance(ThreeConstructors.class);
Assert.assertEquals(-1, tc.i);
Assert.assertEquals("s", tc.s);
cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCFloat.class, "2");
tc = tang.newInjector(cb.build()).getInstance(ThreeConstructors.class);
Assert.assertEquals(-1, tc.i);
Assert.assertEquals("default", tc.s);
Assert.assertEquals(2.0f, tc.f, 1e-9);
}
@Test
public void testThreeConstructorsAmbiguous() throws BindException, InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.ThreeConstructors Ambigous subplan org.apache.reef.tang.ThreeConstructors");
// thrown.expectMessage("Cannot inject org.apache.reef.tang.ThreeConstructors Multiple ways to inject org.apache.reef.tang.ThreeConstructors");
final JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCString.class, "s");
cb.bindNamedParameter(TCFloat.class, "-2");
// Ambiguous; there is a constructor that takes a string, and another that
// takes a float, but none that takes both.
tang.newInjector(cb.build()).getInstance(ThreeConstructors.class);
}
@Test
public void testTwoConstructorsAmbiguous() throws BindException, InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.TwoConstructors: Multiple infeasible plans: org.apache.reef.tang.TwoConstructors:");
final JavaConfigurationBuilder cb = tang.newConfigurationBuilder();
cb.bindNamedParameter(TCString.class, "s");
cb.bindNamedParameter(TCInt.class, "1");
tang.newInjector(cb.build()).getInstance(TwoConstructors.class);
}
@Test
public void testDefaultImplementation() throws BindException, ClassHierarchyException, InjectionException {
ConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
Injector i = Tang.Factory.getTang().newInjector(cb.build());
@SuppressWarnings("unused")
IfaceWithDefault iwd = i.getNamedInstance(IfaceWithDefaultName.class);
}
@Test
public void testCantGetInstanceOfNamedParameter() throws BindException, InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("getInstance() called on Name org.apache.reef.tang.IfaceWithDefaultName Did you mean to call getNamedInstance() instead?");
ConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
Injector i = Tang.Factory.getTang().newInjector(cb.build());
@SuppressWarnings("unused")
IfaceWithDefaultName iwd = i.getInstance(IfaceWithDefaultName.class);
}
@Test
public void testCanGetDefaultedInterface() throws BindException, InjectionException {
Assert.assertNotNull(Tang.Factory.getTang().newInjector().getInstance(HaveDefaultImpl.class));
}
@Test
public void testCanOverrideDefaultedInterface() throws BindException, InjectionException {
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(HaveDefaultImpl.class, OverrideDefaultImpl.class);
Assert.assertTrue(Tang.Factory.getTang().newInjector(cb.build())
.getInstance(HaveDefaultImpl.class) instanceof OverrideDefaultImpl);
}
@Test
public void testCanGetStringDefaultedInterface() throws BindException, InjectionException {
Assert.assertNotNull(Tang.Factory.getTang().newInjector().getInstance(HaveDefaultStringImpl.class));
}
@Test
public void testCanOverrideStringDefaultedInterface() throws BindException, InjectionException {
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(HaveDefaultStringImpl.class, OverrideDefaultStringImpl.class);
Assert.assertTrue(Tang.Factory.getTang().newInjector(cb.build())
.getInstance(HaveDefaultStringImpl.class) instanceof OverrideDefaultStringImpl);
}
@Test
public void testSingletonWithMultipleConstructors() throws BindException, InjectionException {
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(SMC.class, SingletonMultiConst.class);
cb.bindNamedParameter(SingletonMultiConst.A.class, "foo");
Injector i = Tang.Factory.getTang().newInjector(cb.build());
i.getInstance(SMC.class);
}
@Test
public void testInjectInjector() throws InjectionException, BindException {
Injector i = Tang.Factory.getTang().newInjector();
InjectInjector ii = i.getInstance(InjectInjector.class);
Assert.assertSame(i, ii.i);
}
@Test
public void testProactiveFutures() throws InjectionException, BindException {
Injector i = Tang.Factory.getTang().newInjector();
IsFuture.instantiated = false;
i.getInstance(NeedsFuture.class);
Assert.assertTrue(IsFuture.instantiated);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testGenericEventHandlers() throws BindException, InjectionException {
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
cba.bindNamedParameter(XName.class, (Class) XAA.class);
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(XName.class);
JavaConfigurationBuilder cbb = Tang.Factory.getTang().newConfigurationBuilder();
cbb.bindNamedParameter(XName.class, XBB.class);
Tang.Factory.getTang().newInjector(cbb.build()).getNamedInstance(XName.class);
JavaConfigurationBuilder cbc = Tang.Factory.getTang().newConfigurationBuilder();
cbc.bindNamedParameter(XName.class, (Class) XCC.class);
Tang.Factory.getTang().newInjector(cbc.build()).getNamedInstance(XName.class);
}
@Test
public void testGenericEventHandlerDefaults() throws BindException, InjectionException {
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(XNameDA.class);
JavaConfigurationBuilder cbb = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cbb.build()).getNamedInstance(XNameDB.class);
JavaConfigurationBuilder cbc = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cbc.build()).getNamedInstance(XNameDC.class);
}
@Test
public void testGenericEventHandlerDefaultsBadTreeIndirection() throws BindException, InjectionException {
thrown.expect(ClassHierarchyException.class);
thrown.expectMessage("class org.apache.reef.tang.XNameDAA defines a default class org.apache.reef.tang.XCC with a raw type that does not extend of its target's raw type class org.apache.reef.tang.XBB");
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(XNameDAA.class);
}
@Test
public void testGenericEventHandlerDefaultsGoodTreeIndirection() throws BindException, InjectionException {
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(XNameDDAA.class);
}
@Test
public void testGenericUnrelatedGenericTypeParameters() throws BindException, InjectionException {
thrown.expect(ClassHierarchyException.class);
thrown.expectMessage("class org.apache.reef.tang.WaterBottleName defines a default class org.apache.reef.tang.GasCan with a type that does not extend its target's type org.apache.reef.tang.Bottle<org.apache.reef.tang.Water");
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(WaterBottleName.class);
}
@Test
public void testGenericInterfaceUnboundTypeParametersName() throws BindException, InjectionException {
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(FooEventHandler.class);
}
@Test
public void testGenericInterfaceUnboundTypeParametersNameIface() throws BindException, InjectionException {
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).getNamedInstance(IfaceEventHandler.class);
}
@Test
public void testGenericInterfaceUnboundTypeParametersIface() throws BindException, InjectionException {
thrown.expect(ClassHierarchyException.class);
thrown.expectMessage("interface org.apache.reef.tang.MyEventHandlerIface declares its default implementation to be non-subclass class org.apache.reef.tang.MyEventHandler");
JavaConfigurationBuilder cba = Tang.Factory.getTang().newConfigurationBuilder();
Tang.Factory.getTang().newInjector(cba.build()).isInjectable(MyEventHandlerIface.class);
}
@Test
public void testWantSomeHandlers() throws BindException, InjectionException {
Tang.Factory.getTang().newInjector().getInstance(WantSomeHandlers.class);
}
@Test
public void testWantSomeHandlersBadOrder() throws BindException, InjectionException {
Injector i = Tang.Factory.getTang().newInjector();
i.getInstance(AHandler.class);
i.getInstance(BHandler.class);
i.getInstance(WantSomeFutureHandlers.class);
}
@Test
public void testWantSomeFutureHandlersAlreadyBoundVolatile() throws BindException, InjectionException {
Injector i = Tang.Factory.getTang().newInjector();
i.bindVolatileInstance(AHandler.class, new AHandlerImpl());
i.bindVolatileInstance(BHandler.class, new BHandlerImpl());
i.getInstance(WantSomeFutureHandlers.class);
}
@Test
public void testWantSomeFutureHandlers() throws BindException, InjectionException {
Tang.Factory.getTang().newInjector().getInstance(WantSomeFutureHandlers.class);
}
@Test
public void testWantSomeFutureHandlersUnit() throws BindException, InjectionException {
Tang.Factory.getTang().newInjector().getInstance(WantSomeFutureHandlersUnit.class);
}
@Test
public void testWantSomeFutureHandlersName() throws BindException, InjectionException {
Tang.Factory.getTang().newInjector().getInstance(WantSomeFutureHandlersName.class);
}
@Test
public void testUnitMixedCanInject() throws BindException, InjectionException {
//testing that you should be able to have @Unit and also static inner classes not included
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
Injector i = Tang.Factory.getTang().newInjector(cb.build());
i.getInstance(OuterUnitWithStatic.InnerStaticClass2.class);
}
@Test
public void testUnitMixedCantInject() throws BindException, InjectionException {
thrown.expect(InjectionException.class);
thrown.expectMessage("Cannot inject org.apache.reef.tang.OuterUnitWithStatic$InnerStaticClass: No known implementations / injectable constructors for org.apache.reef.tang.OuterUnitWithStatic$InnerStaticClass");
//testing that you should be able to have @Unit and also static inner classes not included
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
Injector i = Tang.Factory.getTang().newInjector(cb.build());
i.getInstance(OuterUnitWithStatic.InnerStaticClass.class);
}
@Test
public void testForkWorks() throws BindException, InjectionException {
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bind(CheckChildIface.class, CheckChildImpl.class);
Injector i = Tang.Factory.getTang().newInjector(cb.build());
Injector i1 = i.forkInjector();
CheckChildIface c1 = i1.getInstance(CheckChildIface.class);
Injector i2 = i.forkInjector();
CheckChildIface c2 = i2.getInstance(CheckChildIface.class);
Assert.assertTrue(c1 != c2);
}
@Test
public void testReuseFailedInjector() throws BindException, InjectionException {
Injector i = Tang.Factory.getTang().newInjector();
try {
i.getInstance(Fail.class);
Assert.fail("Injecting Fail should not have worked!");
} catch (InjectionException e) {
i.getInstance(Pass.class);
}
}
@Test
public void testForksInjectorInConstructor() throws BindException, InjectionException {
Injector i = Tang.Factory.getTang().newInjector();
i.getInstance(ForksInjectorInConstructor.class);
}
/**
* This is to test multiple inheritance case.
* When a subclass is bound to an interface, it's instance will be created in injection
* When a subsubclass is bound to the interface, the subsubclass instance will be created in injection
*
* @throws BindException
* @throws InjectionException
*/
@Test
public void testMultiInheritanceMiddleClassFirst() throws BindException, InjectionException {
final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(CheckChildIface.class, CheckChildImpl.class);
final Injector i = Tang.Factory.getTang().newInjector(cb.build());
final CheckChildIface o1 = i.getInstance(CheckChildIface.class);
Assert.assertTrue(o1 instanceof CheckChildImpl);
final JavaConfigurationBuilder cb2 = Tang.Factory.getTang().newConfigurationBuilder();
cb2.bindImplementation(CheckChildIface.class, CheckChildImplImpl.class);
final Injector i2 = Tang.Factory.getTang().newInjector(cb2.build());
final CheckChildIface o2 = i2.getInstance(CheckChildIface.class);
Assert.assertTrue(o2 instanceof CheckChildImplImpl);
}
/**
* This is to test multiple inheritance case.
* When CheckChildImplImpl is bound to an interface, the CheckChildImplImpl instance will be created in injection
* When CheckChildImpl is then bound to the same interface, even class hierarchy already knows it has an subclass CheckChildImplImpl,
* Tang will only look at the constructors in CheckChildImpl
*
* @throws BindException
* @throws InjectionException
*/
@Test
public void testMultiInheritanceSubclassFirst() throws BindException, InjectionException {
final JavaConfigurationBuilder cb2 = Tang.Factory.getTang().newConfigurationBuilder();
cb2.bindImplementation(CheckChildIface.class, CheckChildImplImpl.class);
final Injector i2 = Tang.Factory.getTang().newInjector(cb2.build());
final CheckChildIface o2 = i2.getInstance(CheckChildIface.class);
Assert.assertTrue(o2 instanceof CheckChildImplImpl);
final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(CheckChildIface.class, CheckChildImpl.class);
final Injector i = Tang.Factory.getTang().newInjector(cb.build());
final CheckChildIface o1 = i.getInstance(CheckChildIface.class);
Assert.assertTrue(o1 instanceof CheckChildImpl);
}
}
class Fail {
@Inject
public Fail() {
throw new UnsupportedOperationException();
}
}
class Pass {
@Inject
public Pass() {
}
}
class IsFuture {
static boolean instantiated;
@Inject
IsFuture(NeedsFuture nf) {
instantiated = true;
}
}
class NeedsFuture {
@Inject
NeedsFuture(InjectionFuture<IsFuture> isFut) {
}
}
class InjectInjector {
public final Injector i;
@Inject
InjectInjector(Injector i) {
this.i = i;
}
}
class SingletonMultiConst implements SMC {
@Inject
public SingletonMultiConst(@Parameter(A.class) String a) {
}
@Inject
public SingletonMultiConst(@Parameter(A.class) String a, @Parameter(B.class) String b) {
}
@NamedParameter
class A implements Name<String> {
}
@NamedParameter
class B implements Name<String> {
}
}
class HaveDefaultImplImpl implements HaveDefaultImpl {
@Inject
HaveDefaultImplImpl() {
}
}
class OverrideDefaultImpl implements HaveDefaultImpl {
@Inject
public OverrideDefaultImpl() {
}
}
class HaveDefaultStringImplImpl implements HaveDefaultStringImpl {
@Inject
HaveDefaultStringImplImpl() {
}
}
class OverrideDefaultStringImpl implements HaveDefaultStringImpl {
@Inject
public OverrideDefaultStringImpl() {
}
}
@NamedParameter(doc = "woo", short_name = "woo", default_value = "42")
class Param implements Name<Integer> {
}
class Impl implements Interf {
@Inject
Impl(@Parameter(Param.class) int p) {
}
}
class MustBeSingleton {
static boolean alreadyInstantiated;
@Inject
public MustBeSingleton() {
if (alreadyInstantiated) {
throw new IllegalStateException("Can't instantiate me twice!");
}
alreadyInstantiated = true;
}
}
class SubSingleton {
@Inject
SubSingleton(MustBeSingleton a) {
// Does not call super
}
}
class TwoSingletons {
@Inject
TwoSingletons(SubSingleton a, MustBeSingleton b) {
}
}
class RepeatedAmbiguousArgs {
@Inject
RepeatedAmbiguousArgs(int x, int y) {
}
}
class RepeatedNamedArgs {
@Inject
RepeatedNamedArgs(@Parameter(A.class) int x, @Parameter(B.class) int y) {
}
@NamedParameter()
class A implements Name<Integer> {
}
@NamedParameter()
class B implements Name<Integer> {
}
}
class RepeatedNamedSingletonArgs {
@Inject
RepeatedNamedSingletonArgs(@Parameter(A.class) MustBeSingleton a,
@Parameter(B.class) MustBeSingleton b) {
}
@NamedParameter()
class A implements Name<MustBeSingleton> {
}
@NamedParameter()
class B implements Name<MustBeSingleton> {
}
}
class OneNamedSingletonArgs {
@Inject
OneNamedSingletonArgs(@Parameter(A.class) MustBeSingleton a) {
}
@NamedParameter()
class A implements Name<MustBeSingleton> {
}
@NamedParameter()
class B implements Name<MustBeSingleton> {
}
}
class OneNamedStringArg {
public final String s;
@Inject
OneNamedStringArg(@Parameter(A.class) String s) {
this.s = s;
}
@NamedParameter(default_value = "default")
class A implements Name<String> {
}
}
class TwoNamedStringArgs {
public final String a;
public final String b;
@Inject
TwoNamedStringArgs(@Parameter(A.class) String a, @Parameter(B.class) String b) {
this.a = a;
this.b = b;
}
@NamedParameter(default_value = "defaultA")
class A implements Name<String> {
}
@NamedParameter(default_value = "defaultB")
class B implements Name<String> {
}
}
class BextendsAinjectA {
static class A {
@Inject
A() {
}
}
static class B extends A {
}
}
class ExternalConstructorExample {
static class LegacyWrapper implements ExternalConstructor<Legacy> {
final Integer x;
final String y;
@Inject
LegacyWrapper(Integer x, String y) {
this.x = x;
this.y = y;
}
@Override
public Legacy newInstance() {
return new ExternalConstructorExample().new Legacy(x, y);
}
}
class Legacy {
final Integer x;
final String y;
public Legacy(Integer x, String y) {
this.x = x;
this.y = y;
}
}
}
class LegacyConstructor {
final Integer x;
final String y;
public LegacyConstructor(Integer x, String y) {
this.x = x;
this.y = y;
}
}
class NamedImpl {
static interface A {
}
static interface C {
}
@NamedParameter
static class AImplName implements Name<A> {
}
@NamedParameter
static class BImplName implements Name<A> {
}
@NamedParameter
static class CImplName implements Name<C> {
}
static class Aimpl implements A {
@Inject
Aimpl() {
}
}
static class Bimpl implements A {
@Inject
Bimpl() {
}
}
static class Cimpl implements C {
@Inject
Cimpl() {
}
}
static class ABtaker {
@Inject
ABtaker(@Parameter(AImplName.class) A a, @Parameter(BImplName.class) A b) {
Assert.assertTrue("AImplName must be instance of Aimpl",
a instanceof Aimpl);
Assert.assertTrue("BImplName must be instance of Bimpl",
b instanceof Bimpl);
}
}
}
@Unit
class OuterUnit {
final OuterUnit self;
@Inject
OuterUnit() {
self = this;
}
class InA {
OuterUnit slf = self;
}
class InB {
OuterUnit slf = self;
}
}
class MissOuterUnit {
final MissOuterUnit self;
@Inject
MissOuterUnit() {
self = this;
}
class InA {
MissOuterUnit slf = self;
}
class InB {
MissOuterUnit slf = self;
@Inject
InB() {
}
}
}
class ThreeConstructors {
final int i;
final String s;
final Float f;
@Inject
ThreeConstructors(@Parameter(TCInt.class) int i, @Parameter(TCString.class) String s) {
this.i = i;
this.s = s;
this.f = -1.0f;
}
@Inject
ThreeConstructors(@Parameter(TCString.class) String s) {
this(-1, s);
}
@Inject
ThreeConstructors(@Parameter(TCInt.class) int i) {
this(i, "default");
}
@Inject
ThreeConstructors(@Parameter(TCFloat.class) float f) {
this.i = -1;
this.s = "default";
this.f = f;
}
@NamedParameter
static class TCInt implements Name<Integer> {
}
@NamedParameter
static class TCString implements Name<String> {
}
@NamedParameter
static class TCFloat implements Name<Float> {
}
}
class TwoConstructors {
final int i;
final String s;
@Inject
TwoConstructors(@Parameter(TCInt.class) int i, @Parameter(TCString.class) String s) {
this.i = i;
this.s = s;
}
@Inject
TwoConstructors(@Parameter(TCString.class) String s, @Parameter(TCInt.class) int i) {
this.i = i;
this.s = s;
}
@NamedParameter
static class TCInt implements Name<Integer> {
}
@NamedParameter
static class TCString implements Name<String> {
}
}
class IfaceWithDefaultDefaultImpl implements IfaceWithDefault {
@Inject
IfaceWithDefaultDefaultImpl() {
}
}
@NamedParameter(default_class = IfaceWithDefaultDefaultImpl.class)
class IfaceWithDefaultName implements Name<IfaceWithDefault> {
}
@NamedParameter
class XName implements Name<X<BB>> {
}
@NamedParameter(default_class = XAA.class)
class XNameDA implements Name<X<BB>> {
}
@NamedParameter(default_class = XBB.class)
class XNameDB implements Name<X<BB>> {
}
@NamedParameter(default_class = XCC.class)
class XNameDC implements Name<X<BB>> {
}
@NamedParameter(default_class = XCC.class)
class XNameDAA implements Name<XBB> {
}
@NamedParameter(default_class = XXBB.class)
class XNameDDAA implements Name<XBB> {
}
@DefaultImplementation(AA.class)
class AA {
@Inject
AA() {
}
}
@DefaultImplementation(BB.class)
class BB extends AA {
@Inject
BB() {
}
}
@DefaultImplementation(CC.class)
class CC extends BB {
@Inject
CC() {
}
}
class XAA implements X<AA> {
@Inject
XAA(AA aa) {
}
}
@DefaultImplementation(XBB.class)
class XBB implements X<BB> {
@Inject
XBB(BB aa) {
}
}
class XXBB extends XBB {
@Inject
XXBB(BB aa) {
super(aa);
}
}
class XCC implements X<CC> {
@Inject
XCC(CC aa) {
}
}
class WaterBottle implements Bottle<Water> {
}
class GasCan implements Bottle<Gas> {
}
class Water {
}
class Gas {
}
@NamedParameter(default_class = GasCan.class)
class WaterBottleName implements Name<Bottle<Water>> {
}
class MyEventHandler<T> implements EventHandler<T> {
@Inject
MyEventHandler() {
}
}
@NamedParameter(default_class = MyEventHandler.class)
class FooEventHandler implements Name<EventHandler<Foo>> {
}
@NamedParameter(default_class = MyEventHandler.class)
class IfaceEventHandler implements Name<EventHandler<SomeIface>> {
}
class AH {
@Inject
AH() {
}
}
class BH {
@Inject
BH() {
}
}
class AHandlerImpl implements AHandler {
@Inject
AHandlerImpl() {
}
}
class BHandlerImpl implements BHandler {
@Inject
BHandlerImpl() {
}
}
@Unit
class DefaultHandlerUnit {
@Inject
DefaultHandlerUnit() {
}
@DefaultImplementation(AHandlerImpl.class)
interface AHandler extends EventHandler<AH> {
}
@DefaultImplementation(BHandlerImpl.class)
interface BHandler extends EventHandler<BH> {
}
class AHandlerImpl implements AHandler {
AHandlerImpl() {
}
}
class BHandlerImpl implements BHandler {
BHandlerImpl() {
}
}
}
class WantSomeHandlers {
@Inject
WantSomeHandlers(AHandler a, BHandler b) {
}
}
class WantSomeFutureHandlers {
@Inject
WantSomeFutureHandlers(InjectionFuture<AHandler> a, InjectionFuture<BHandler> b) {
}
}
class WantSomeFutureHandlersUnit {
@Inject
WantSomeFutureHandlersUnit(InjectionFuture<DefaultHandlerUnit.AHandler> a, InjectionFuture<DefaultHandlerUnit.BHandler> b) {
}
}
@NamedParameter(default_class = AHandlerImpl.class)
class AHandlerName implements Name<EventHandler<AH>> {
}
@NamedParameter(default_class = BHandlerImpl.class)
class BHandlerName implements Name<EventHandler<BH>> {
}
class WantSomeFutureHandlersName {
@Inject
WantSomeFutureHandlersName(
@Parameter(AHandlerName.class) InjectionFuture<EventHandler<AH>> a,
@Parameter(BHandlerName.class) InjectionFuture<EventHandler<BH>> b) {
}
}
@Unit
class OuterUnitWithStatic {
@Inject
public OuterUnitWithStatic() {
}
public void bar() {
new InnerStaticClass().baz();
}
static class InnerStaticClass {
public InnerStaticClass() {
}
public void baz() {
}
}
static class InnerStaticClass2 {
@Inject
public InnerStaticClass2() {
}
public void baz() {
}
}
public class InnerUnitClass {
public void foo() {
}
}
}
class CheckChildImpl implements CheckChildIface {
@Inject
CheckChildImpl() {
}
}
class CheckChildImplImpl extends CheckChildImpl {
@Inject
CheckChildImplImpl() {
}
}
class ForksInjectorInConstructor {
@Inject
ForksInjectorInConstructor(Injector i) throws BindException {
JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.bindImplementation(Number.class, Integer.class);
i.forkInjector(cb.build());
}
}
|
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.uff.ic.archd.gui.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* @author wallace
*/
public class AnomaliesView extends JFrame{
public final static String ACTION_OK_ANOMALIES = "ACTION_OK_ANOMALIES";
public final static String ACTION_OK_METHODS = "ACTION_OK_METHODS";
public final static String ACTION_OK_CLASSES = "ACTION_OK_CLASSES";
public final static String ACTION_OK_PACKAGES = "ACTION_OK_PACKAGES";
private JComboBox anomaliesComboBox;
private JComboBox methodsComboBox;
private JComboBox classesComboBox;
private JComboBox packagesComboBox;
private JLabel anomaliesLabel;
private JLabel methodsLabel;
private JLabel classesLabel;
private JLabel packagesLabel;
private JButton anomaliesButton;
private JButton methodsButton;
private JButton classesButton;
private JButton packagesButton;
private JScrollPane informationPane;
private JTextArea informationTextArea;
//private JPanel informationPanel;
private JPanel chartPanel;
private JScrollPane chartPane;
private JPanel panel;
public AnomaliesView(String anomalies[], String packages[], String classes[], String methods[]) {
createWidgets(anomalies, packages, classes, methods);
this.setTitle("Anomalies");
this.setPreferredSize(new Dimension(1600, 800));
this.setSize(new Dimension(1600, 800));
this.setMaximumSize(new Dimension(1600, 800));
}
private void createWidgets(String anomalies[], String packages[], String classes[], String methods[]) {
anomaliesComboBox = new JComboBox(anomalies);
methodsComboBox = new JComboBox(methods);
classesComboBox = new JComboBox(classes);
packagesComboBox = new JComboBox(packages);
anomaliesComboBox.setPreferredSize(new Dimension(550,25));
methodsComboBox.setPreferredSize(new Dimension(550,25));
classesComboBox.setPreferredSize(new Dimension(550,25));
packagesComboBox.setPreferredSize(new Dimension(550,25));
anomaliesLabel = new JLabel("Anomalies:");
methodsLabel = new JLabel("Methods:");
classesLabel = new JLabel("Classes:");
packagesLabel = new JLabel("Packages:");
anomaliesButton = new JButton("OK");
methodsButton = new JButton("OK");
classesButton = new JButton("OK");
packagesButton = new JButton("OK");
anomaliesButton.setActionCommand(ACTION_OK_ANOMALIES);
methodsButton.setActionCommand(ACTION_OK_METHODS);
classesButton.setActionCommand(ACTION_OK_CLASSES);
packagesButton.setActionCommand(ACTION_OK_PACKAGES);
informationTextArea = new JTextArea();
informationTextArea.setEditable(false);
informationPane = new JScrollPane();
informationPane.setViewportView(informationTextArea);
informationPane.setPreferredSize(new Dimension(750,160));
JTabbedPane tabbedPane = new JTabbedPane();
//informationPanel = new JPanel();
chartPanel = new JPanel();
chartPane = new JScrollPane();
chartPane.setViewportView(chartPanel);
chartPane.setPreferredSize(new Dimension(1500,500));
//informationPanel.add(informationPane, BorderLayout.CENTER);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints = null;
gridBagConstraints = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(anomaliesLabel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(anomaliesComboBox, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(anomaliesButton, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(methodsLabel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(1, 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(methodsComboBox, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(methodsButton, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(classesLabel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(1, 2, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(classesComboBox, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(2, 2, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(classesButton, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(0, 3, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(packagesLabel, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(1, 3, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(packagesComboBox, gridBagConstraints);
gridBagConstraints = new GridBagConstraints(2, 3, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 0, 0);
panel.add(packagesButton, gridBagConstraints);
tabbedPane.add("Information", informationPane);
tabbedPane.add("Chart", chartPane);
gridBagConstraints = new GridBagConstraints(0, 4, 3, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(25, 20, 0, 20), 0, 0);
panel.add(tabbedPane, gridBagConstraints);
// gridBagConstraints = new GridBagConstraints(3, 0, 1, 4, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(25, 20, 0, 20), 0, 0);
// panel.add(informationPane, gridBagConstraints);
//
// gridBagConstraints = new GridBagConstraints(0, 4, 4, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(25, 20, 0, 0), 0, 0);
// panel.add(chartPane, gridBagConstraints);
this.add(panel, BorderLayout.CENTER);
}
public void setChartPanel(JPanel jpanel){
chartPanel.removeAll();
chartPanel.add(jpanel, BorderLayout.CENTER);
chartPanel.updateUI();
panel.updateUI();
}
public void setInformation(String text){
informationTextArea.setText(text);
informationTextArea.updateUI();
//informationPanel.updateUI();
//panel.updateUI();
}
public void setPackageDisable(){
packagesButton.setEnabled(false);
}
public void setPackageEnable(){
packagesButton.setEnabled(true);
}
public void setClassDisable(){
classesButton.setEnabled(false);
}
public void setClassEnable(){
classesButton.setEnabled(true);
}
public void setMethodDisable(){
methodsButton.setEnabled(false);
}
public void setMethodEnable(){
methodsButton.setEnabled(true);
}
public int getAnomalieIndex(){
return anomaliesComboBox.getSelectedIndex();
}
public int getPackageIndex(){
return packagesComboBox.getSelectedIndex();
}
public int getClassIndex(){
return classesComboBox.getSelectedIndex();
}
public int getMethodIndex(){
return methodsComboBox.getSelectedIndex();
}
public void setController(ActionListener actionListener) {
anomaliesButton.addActionListener(actionListener);
methodsButton.addActionListener(actionListener);
classesButton.addActionListener(actionListener);
packagesButton.addActionListener(actionListener);
}
public void setPackages(List<String> packages){
packagesComboBox.removeAllItems();
for(String str : packages){
packagesComboBox.addItem(str);
}
packagesComboBox.updateUI();
panel.updateUI();
}
public void setClasses(List<String> classes){
classesComboBox.removeAllItems();
for(String str : classes){
classesComboBox.addItem(str);
}
classesComboBox.updateUI();
panel.updateUI();
}
public void setMethods(List<String> methods){
methodsComboBox.removeAllItems();
for(String str : methods){
methodsComboBox.addItem(str);
}
methodsComboBox.updateUI();
panel.updateUI();
}
}
|
|
/* (c) 2014 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package com.linkedin.cubert.operator;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import com.linkedin.cubert.block.Block;
import com.linkedin.cubert.block.BlockSchema;
import com.linkedin.cubert.block.BlockUtils;
import com.linkedin.cubert.block.TupleOperatorBlock;
import com.linkedin.cubert.io.BlockSerializationType;
import com.linkedin.cubert.io.rubix.RubixMemoryBlock;
import com.linkedin.cubert.utils.JsonUtils;
import com.linkedin.cubert.utils.Pair;
import com.linkedin.cubert.utils.RewriteUtils;
/**
* Given an input block with a pivoted column and a side meta-data block, create vector
* blocks for each input in metadata file. * this <code>BlockOperator</code> outputs
* multiple blocks (one combined block for each vector from meta-data block)
*
* @author Mani Parkhe
*/
public class CollateVectorBlockOperator implements BlockOperator
{
private RubixMemoryBlock inputBlock;
private Map<Object, Pair<Integer, Integer>> coord2offsets =
new HashMap<Object, Pair<Integer, Integer>>();
private String metaRelationName;
private Block matchingMetaBlock;
private int[] coordinateColumnIndexes;
private String identifierColumnName = null;
private int identifierColumnIndex;
private JsonNode jsonForCombine = null;
private CombineOperator combineOp = new CombineOperator();
private TupleOperatorBlock combinedBlock = null;
private Map<String, Block> inputGenerator = new HashMap<String, Block>();
private JsonNode jsonForGenerate = null;
private GenerateOperator genOp = null;
private TupleOperatorBlock generatedBlock = null;
@SuppressWarnings("unchecked")
private Class<Tuple> valueClass = (Class<Tuple>) TupleFactory.getInstance()
.newTuple()
.getClass();
@Override
public void setInput(Configuration conf, Map<String, Block> input, JsonNode json) throws IOException,
InterruptedException
{
// #1. input block
inputBlock = (RubixMemoryBlock) input.get(JsonUtils.getText(json, "inputBlock"));
// #2. lookup column
String lookupColumn = json.get("lookupColumn").getTextValue();
BlockSchema inputSchema = inputBlock.getProperties().getSchema();
coord2offsets = BlockUtils.generateColumnIndex(inputBlock, lookupColumn);
// #3. meta data relation name
metaRelationName = new String(JsonUtils.getText(json, "metaRelationName"));
matchingMetaBlock = (Block) input.get(metaRelationName);
BlockSchema metaBlockSchema = matchingMetaBlock.getProperties().getSchema();
// #4. find indexes for coordinate column names in meta relation's schema
String[] coordinateColumns = JsonUtils.asArray(json.get("coordinateColumns"));
coordinateColumnIndexes = new int[coordinateColumns.length];
int idx = 0;
for (String s : JsonUtils.asArray(json.get("coordinateColumns")))
coordinateColumnIndexes[idx++] = metaBlockSchema.getIndex(s);
// #5. find index of identifier column in meta relation's schema
identifierColumnName = new String(JsonUtils.getText(json, "identifierColumn"));
identifierColumnIndex = metaBlockSchema.getIndex(identifierColumnName);
// #6. combine columns
ArrayNode combineColumns = (ArrayNode) json.get("combineColumns");
// setup info for sort operator
/*
* jsonForSort = JsonUtils.cloneNode(json); ((ObjectNode)
* jsonForSort).put("sortBy", combineColumns); sortedBlock = new
* TupleOperatorBlock(sortOp);
*/
// setup info for combiner operator
jsonForCombine = JsonUtils.createObjectNode();
((ObjectNode) jsonForCombine).put("pivotBy", combineColumns);
((ObjectNode) jsonForCombine).put("schema", inputSchema.toJson());
combinedBlock = new TupleOperatorBlock(combineOp, null);
// setup info for generate operator
jsonForGenerate = JsonUtils.createObjectNode();
}
@Override
public Block next() throws IOException,
InterruptedException
{
Tuple metaDataTuple = matchingMetaBlock.next();
if (metaDataTuple == null)
return null; // Done
System.out.println("Collate Vector: metadata tuple = " + metaDataTuple.toString());
return generateVectorBlock(metaDataTuple);
}
private Block generateVectorBlock(Tuple metaDataTuple) throws ExecException,
IOException,
InterruptedException
{
Map<String, Block> inputBlocksToCombiner = new HashMap<String, Block>();
for (int i : coordinateColumnIndexes)
{
Object coordinate = metaDataTuple.get(i);
Block coordBlock = createCoordinateBlock(coordinate);
if (coordBlock == null)
continue;
inputBlocksToCombiner.put(coordinate.toString(), coordBlock);
}
// No data for this vector -- proceed to next one.
if (inputBlocksToCombiner.size() == 0)
return this.next();
if (inputBlocksToCombiner.size() != coordinateColumnIndexes.length)
{
System.out.println("CollateVectorBlock: Found fewer input blocks than number of co-ordinates ");
return this.next();
}
// Combine individual blocks
Object vectorIdentifier = metaDataTuple.get(identifierColumnIndex);
if (!(vectorIdentifier instanceof Integer || vectorIdentifier instanceof String))
throw new RuntimeException("Unexpected data-type for identifier column");
Block combinedBlock = createCombinedBlock(inputBlocksToCombiner);
/*
* // Prepare input args for sort operator inputSorter.clear();
* inputSorter.put("combined_block", combinedBlock);
*
* // Setup sort operator object sortOp.setInput(inputSorter, jsonForSort);
*/
// Prepare input arguments for generator operator
ArrayNode outputTupleJson = createJsonForGenerate(vectorIdentifier);
JsonNode thisGenJson = JsonUtils.cloneNode(jsonForGenerate);
((ObjectNode) thisGenJson).put("outputTuple", outputTupleJson);
inputGenerator.clear();
inputGenerator.put("combined_block", combinedBlock);
// Setup generate operator object.
genOp = new GenerateOperator();
genOp.setInput(inputGenerator, thisGenJson, null);
// Return tuple operator block that contains this generate op.
generatedBlock = new TupleOperatorBlock(genOp, null);
// TODO: generatedBlock.setProperty("identifierColumn", vectorIdentifier);
// System.out.println("CollateVectorBlock: finished setInput");
return generatedBlock;
}
private ArrayNode createJsonForGenerate(Object vectorIdentifier)
{
ArrayNode outputTupleJson = JsonUtils.createArrayNode();
// + First duplicate existing schema
for (String s : inputBlock.getProperties().getSchema().getColumnNames())
{
outputTupleJson.add(RewriteUtils.createProjectionExpressionNode(s, s));
}
// + Add the new generated column
JsonNode constNode;
if (vectorIdentifier instanceof String)
constNode = RewriteUtils.createStringConstant((String) vectorIdentifier);
else
constNode = RewriteUtils.createIntegerConstant((Integer) vectorIdentifier);
String outColName = metaRelationName + "___" + identifierColumnName;
outputTupleJson.add(JsonUtils.createObjectNode("col_name",
outColName,
"expression",
constNode));
return outputTupleJson;
}
private Block createCombinedBlock(Map<String, Block> inputCombiner) throws IOException,
InterruptedException
{
// Special case -- only one block.
if (inputCombiner.size() == 1)
{
return inputCombiner.values().iterator().next();
}
// Setup combine operator object
combineOp.setInput(inputCombiner, jsonForCombine, null);
// Return tuple operator block that contains the combine op.
return combinedBlock;
}
private Block createCoordinateBlock(Object coordinate) throws IOException,
InterruptedException
{
Pair<Integer, Integer> offsets = coord2offsets.get(coordinate);
if (offsets == null)
return null;
int start = offsets.getFirst();
int len = offsets.getSecond() - start;
ByteBuffer inMemBuffer =
ByteBuffer.wrap(inputBlock.getByteBuffer().array(), start, len);
RubixMemoryBlock miniBlock =
new RubixMemoryBlock(null,
PhaseContext.getConf(),
inMemBuffer,
valueClass,
(CompressionCodec) null,
BlockSerializationType.DEFAULT);
// This is because the schema and pivotBy attributes which are set in
// jsonForCombine also apply to this.
miniBlock.configure(jsonForCombine);
return miniBlock;
}
@Override
public PostCondition getPostCondition(Map<String, PostCondition> preConditions,
JsonNode json) throws PreconditionException
{
// TODO Auto-generated method stub
return null;
}
}
|
|
package org.jabref.gui.entryeditor;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
import org.jabref.Globals;
import org.jabref.gui.BasePanel;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.contentselector.FieldContentSelector;
import org.jabref.gui.date.DatePickerButton;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.entryeditor.EntryEditor.StoreFieldAction;
import org.jabref.gui.fieldeditors.FieldEditor;
import org.jabref.gui.mergeentries.FetchAndMergeEntry;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLUtil;
import org.jabref.logic.identifier.DOI;
import org.jabref.logic.identifier.ISBN;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.jabref.model.entry.FieldProperty;
import org.jabref.model.entry.InternalBibtexFields;
import org.jabref.model.entry.MonthUtil;
import org.jabref.preferences.JabRefPreferences;
public class FieldExtraComponents {
private static final String ABBREVIATION_TOOLTIP_TEXT = "<HTML>"
+ Localization.lang("Switches between full and abbreviated journal name if the journal name is known.")
+ "<BR>" + Localization.lang("To set up, go to") + " <B>" + Localization.lang("Options") + " -> "
+ Localization.lang("Manage journal abbreviations") + "</B></HTML>";
/**
* Add controls for switching between abbreviated and full journal names.
* If this field also has a FieldContentSelector, we need to combine these.
*
* @param panel
* @param editor
* @param entry
* @param storeFieldAction
* @return
*/
public static Optional<JComponent> getJournalExtraComponent(JabRefFrame frame, BasePanel panel, FieldEditor editor,
BibEntry entry, Set<FieldContentSelector> contentSelectors, StoreFieldAction storeFieldAction) {
JPanel controls = new JPanel();
controls.setLayout(new BorderLayout());
if (!panel.getBibDatabaseContext().getMetaData().getContentSelectorValuesForField(editor.getFieldName()).isEmpty()) {
FieldContentSelector ws = new FieldContentSelector(frame, panel, frame, editor, storeFieldAction, false,
", ");
contentSelectors.add(ws);
controls.add(ws, BorderLayout.NORTH);
}
// Button to toggle abbreviated/full journal names
JButton button = new JButton(Localization.lang("Toggle abbreviation"));
button.setToolTipText(ABBREVIATION_TOOLTIP_TEXT);
button.addActionListener(actionEvent -> {
String text = editor.getText();
JournalAbbreviationRepository abbreviationRepository = Globals.journalAbbreviationLoader
.getRepository(Globals.prefs.getJournalAbbreviationPreferences());
if (abbreviationRepository.isKnownName(text)) {
String s = abbreviationRepository.getNextAbbreviation(text).orElse(text);
if (s != null) {
editor.setText(s);
storeFieldAction.actionPerformed(new ActionEvent(editor, 0, ""));
panel.getUndoManager().addEdit(new UndoableFieldChange(entry, editor.getFieldName(), text, s));
}
}
});
controls.add(button, BorderLayout.SOUTH);
return Optional.of(controls);
}
/**
* Set up a mouse listener for opening an external viewer for with with EXTRA_EXTERNAL
*
* @param fieldEditor
* @param panel
* @return
*/
public static Optional<JComponent> getExternalExtraComponent(BasePanel panel, FieldEditor fieldEditor) {
JPanel controls = new JPanel();
controls.setLayout(new BorderLayout());
JButton button = new JButton(Localization.lang("Open"));
button.setEnabled(false);
button.addActionListener(actionEvent -> {
try {
JabRefDesktop.openExternalViewer(panel.getBibDatabaseContext(), fieldEditor.getText(), fieldEditor.getFieldName());
} catch (IOException ex) {
panel.output(Localization.lang("Unable to open link."));
}
});
controls.add(button, BorderLayout.SOUTH);
// enable/disable button
JTextComponent url = (JTextComponent) fieldEditor;
url.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
checkUrl();
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
checkUrl();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
checkUrl();
}
private void checkUrl() {
if (URLUtil.isURL(url.getText())) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
});
return Optional.of(controls);
}
/**
* Set up a mouse listener for opening an external viewer and fetching by DOI
*
* @param fieldEditor
* @param panel
* @return
*/
public static Optional<JComponent> getDoiExtraComponent(BasePanel panel, EntryEditor entryEditor, FieldEditor fieldEditor) {
JPanel controls = new JPanel();
controls.setLayout(new BorderLayout());
// open doi link
JButton button = new JButton(Localization.lang("Open"));
button.setEnabled(false);
button.addActionListener(actionEvent -> {
try {
JabRefDesktop.openExternalViewer(panel.getBibDatabaseContext(), fieldEditor.getText(), fieldEditor.getFieldName());
} catch (IOException ex) {
panel.output(Localization.lang("Unable to open link."));
}
});
// lookup doi
JButton doiButton = new JButton(Localization.lang("Lookup DOI"));
doiButton.addActionListener(actionEvent -> {
Optional<DOI> doi = DOI.fromBibEntry(entryEditor.getEntry());
if (doi.isPresent()) {
entryEditor.getEntry().setField(FieldName.DOI, doi.get().getDOI());
} else {
panel.frame().setStatus(Localization.lang("No %0 found", FieldName.getDisplayName(FieldName.DOI)));
}
});
// fetch bibtex data
JButton fetchButton = new JButton(
Localization.lang("Get BibTeX data from %0", FieldName.getDisplayName(FieldName.DOI)));
fetchButton.setEnabled(false);
fetchButton.addActionListener(actionEvent -> {
BibEntry entry = entryEditor.getEntry();
new FetchAndMergeEntry(entry, panel, FieldName.DOI);
});
controls.add(button, BorderLayout.NORTH);
controls.add(doiButton, BorderLayout.CENTER);
controls.add(fetchButton, BorderLayout.SOUTH);
// enable/disable button
JTextComponent doi = (JTextComponent) fieldEditor;
doi.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
checkDoi();
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
checkDoi();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
checkDoi();
}
private void checkDoi() {
Optional<DOI> doiUrl = DOI.build(doi.getText());
if(doiUrl.isPresent()) {
button.setEnabled(true);
fetchButton.setEnabled(true);
} else {
button.setEnabled(false);
fetchButton.setEnabled(false);
}
}
});
return Optional.of(controls);
}
/**
* Add button for fetching by ISBN
*
* @param fieldEditor
* @param panel
* @return
*/
public static Optional<JComponent> getIsbnExtraComponent(BasePanel panel, EntryEditor entryEditor,
FieldEditor fieldEditor) {
// fetch bibtex data
JButton fetchButton = new JButton(
Localization.lang("Get BibTeX data from %0", FieldName.getDisplayName(FieldName.ISBN)));
fetchButton.setEnabled(false);
fetchButton.addActionListener(actionEvent -> {
BibEntry entry = entryEditor.getEntry();
new FetchAndMergeEntry(entry, panel, FieldName.ISBN);
});
// enable/disable button
JTextComponent isbn = (JTextComponent) fieldEditor;
isbn.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
checkIsbn();
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
checkIsbn();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
checkIsbn();
}
private void checkIsbn() {
ISBN isbnString = new ISBN(isbn.getText());
if (isbnString.isValidFormat()) {
fetchButton.setEnabled(true);
} else {
fetchButton.setEnabled(false);
}
}
});
return Optional.of(fetchButton);
}
/**
* Add button for fetching by ISBN
*
* @param fieldEditor
* @param panel
* @return
*/
public static Optional<JComponent> getEprintExtraComponent(BasePanel panel, EntryEditor entryEditor,
FieldEditor fieldEditor) {
// fetch bibtex data
JButton fetchButton = new JButton(
Localization.lang("Get BibTeX data from %0", FieldName.getDisplayName(FieldName.EPRINT)));
fetchButton.setEnabled(false);
fetchButton.addActionListener(actionEvent -> {
BibEntry entry = entryEditor.getEntry();
new FetchAndMergeEntry(entry, panel, FieldName.EPRINT);
});
// enable/disable button
JTextComponent eprint = (JTextComponent) fieldEditor;
eprint.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
checkEprint();
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
checkEprint();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
checkEprint();
}
private void checkEprint() {
if ((eprint.getText() == null) || eprint.getText().trim().isEmpty()) {
fetchButton.setEnabled(false);
} else {
fetchButton.setEnabled(true);
}
}
});
return Optional.of(fetchButton);
}
/**
* Return a dropdown list containing Yes and No for fields with EXTRA_YES_NO
*
* @param fieldEditor
* @param entryEditor
* @return
*/
public static Optional<JComponent> getYesNoExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor) {
final String[] options = {"", "Yes", "No"};
JComboBox<String> yesno = new JComboBox<>(options);
yesno.addActionListener(actionEvent -> {
fieldEditor.setText(((String) yesno.getSelectedItem()).toLowerCase(Locale.ROOT));
entryEditor.updateField(fieldEditor);
});
return Optional.of(yesno);
}
/**
* Return a dropdown list with the month names for fields with EXTRA_MONTH
*
* @param fieldEditor
* @param entryEditor
* @param type
* @return
*/
public static Optional<JComponent> getMonthExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor, BibDatabaseMode type) {
final String[] options = new String[13];
options[0] = Localization.lang("Select");
for (int i = 1; i <= 12; i++) {
options[i] = MonthUtil.getMonthByNumber(i).fullName;
}
JComboBox<String> month = new JComboBox<>(options);
month.addActionListener(actionEvent -> {
int monthnumber = month.getSelectedIndex();
if (monthnumber >= 1) {
if (type == BibDatabaseMode.BIBLATEX) {
fieldEditor.setText(String.valueOf(monthnumber));
} else {
fieldEditor.setText(MonthUtil.getMonthByNumber(monthnumber).bibtexFormat);
}
} else {
fieldEditor.setText("");
}
entryEditor.updateField(fieldEditor);
month.setSelectedIndex(0);
});
return Optional.of(month);
}
/**
* Return a button which sets the owner if the field for fields with EXTRA_SET_OWNER
* @param fieldEditor
* @param storeFieldAction
* @return
*/
public static Optional<JComponent> getSetOwnerExtraComponent(FieldEditor fieldEditor,
StoreFieldAction storeFieldAction) {
JButton button = new JButton(Localization.lang("Auto"));
button.addActionListener(actionEvent -> {
fieldEditor.setText(Globals.prefs.get(JabRefPreferences.DEFAULT_OWNER));
storeFieldAction.actionPerformed(new ActionEvent(fieldEditor, 0, ""));
});
return Optional.of(button);
}
/**
* Return a button opening a content selector for fields where one exists
*
* @param frame
* @param panel
* @param editor
* @param contentSelectors
* @param storeFieldAction
* @return
*/
public static Optional<JComponent> getSelectorExtraComponent(JabRefFrame frame, BasePanel panel, FieldEditor editor,
Set<FieldContentSelector> contentSelectors, StoreFieldAction storeFieldAction) {
FieldContentSelector ws = new FieldContentSelector(frame, panel, frame, editor, storeFieldAction, false,
InternalBibtexFields.getFieldProperties(editor.getFieldName())
.contains(FieldProperty.PERSON_NAMES) ? " and " : ", ");
contentSelectors.add(ws);
return Optional.of(ws);
}
/**
* Set up field such that double click inserts the current date
* If isDataPicker is True, a button with a data picker is returned
*
* @param editor reference to the FieldEditor to display the date value
* @param useDatePicker shows a DatePickerButton if true
* @param useIsoFormat if true ISO format is always used
* @return
*/
public static Optional<JComponent> getDateTimeExtraComponent(FieldEditor editor, boolean useDatePicker,
boolean useIsoFormat) {
((JTextArea) editor).addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {// double click
String date = "";
if(useIsoFormat) {
date = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
} else {
date = DateTimeFormatter.ofPattern(Globals.prefs.get(JabRefPreferences.TIME_STAMP_FORMAT)).format(
LocalDateTime.now());
}
editor.setText(date);
}
}
});
// insert a datepicker, if the extras field contains this command
if (useDatePicker) {
DatePickerButton datePicker = new DatePickerButton(editor, useIsoFormat);
// register a DocumentListener on the underlying text document which notifies the DatePicker which date is currently set
((JTextArea) editor).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
datePicker.updateDatePickerDate(editor.getText());
}
@Override
public void removeUpdate(DocumentEvent e) {
datePicker.updateDatePickerDate(editor.getText());
}
@Override
public void changedUpdate(DocumentEvent e) {
datePicker.updateDatePickerDate(editor.getText());
}
});
return Optional.of(datePicker.getDatePicker());
} else {
return Optional.empty();
}
}
/**
* Return a dropdown list with the alternatives for editor type fields
*
* @param fieldEditor
* @param entryEditor
* @return
*/
public static Optional<JComponent> getEditorTypeExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor) {
final String[] optionValues = {"", "editor", "compiler", "founder", "continuator", "redactor", "reviser",
"collaborator"};
final String[] optionDescriptions = {Localization.lang("Select"), Localization.lang("Editor"),
Localization.lang("Compiler"), Localization.lang("Founder"), Localization.lang("Continuator"),
Localization.lang("Redactor"), Localization.lang("Reviser"), Localization.lang("Collaborator")};
JComboBox<String> editorType = new JComboBox<>(optionDescriptions);
editorType.addActionListener(actionEvent -> {
fieldEditor.setText(optionValues[editorType.getSelectedIndex()]);
entryEditor.updateField(fieldEditor);
});
return Optional.of(editorType);
}
/**
* Return a dropdown list with the alternatives for pagination type fields
*
* @param fieldEditor
* @param entryEditor
* @return
*/
public static Optional<JComponent> getPaginationExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor) {
final String[] optionValues = {"", "page", "column", "line", "verse", "section", "paragraph", "none"};
final String[] optionDescriptions = {Localization.lang("Select"), Localization.lang("Page"),
Localization.lang("Column"), Localization.lang("Line"), Localization.lang("Verse"),
Localization.lang("Section"), Localization.lang("Paragraph"), Localization.lang("None")};
JComboBox<String> pagination = new JComboBox<>(optionDescriptions);
pagination.addActionListener(actionEvent -> {
fieldEditor.setText(optionValues[pagination.getSelectedIndex()]);
entryEditor.updateField(fieldEditor);
});
return Optional.of(pagination);
}
/**
* Return a dropdown list with the alternatives for pagination type fields
*
* @param fieldEditor
* @param entryEditor
* @return
*/
public static Optional<JComponent> getTypeExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor,
boolean isPatent) {
String[] optionValues;
String[] optionDescriptions;
if (isPatent) {
optionValues = new String[] {"", "patent", "patentde", "patenteu", "patentfr", "patentuk", "patentus",
"patreq", "patreqde", "patreqeu", "patreqfr", "patrequk", "patrequs"};
optionDescriptions = new String[] {Localization.lang("Select"), Localization.lang("Patent"),
Localization.lang("German patent"), Localization.lang("European patent"),
Localization.lang("French patent"), Localization.lang("British patent"),
Localization.lang("U.S. patent"), Localization.lang("Patent request"),
Localization.lang("German patent request"), Localization.lang("European patent request"),
Localization.lang("French patent request"), Localization.lang("British patent request"),
Localization.lang("U.S. patent request")};
} else {
optionValues = new String[] {"", "mathesis", "phdthesis", "candthesis", "techreport", "resreport",
"software", "datacd", "audiocd"};
optionDescriptions = new String[] {Localization.lang("Select"), Localization.lang("Master's thesis"),
Localization.lang("PhD thesis"), Localization.lang("Candidate thesis"),
Localization.lang("Technical report"), Localization.lang("Research report"),
Localization.lang("Software"), Localization.lang("Data CD"), Localization.lang("Audio CD")};
}
JComboBox<String> type = new JComboBox<>(optionDescriptions);
type.addActionListener(actionEvent -> {
fieldEditor.setText(optionValues[type.getSelectedIndex()]);
entryEditor.updateField(fieldEditor);
});
return Optional.of(type);
}
/**
* Return a dropdown list with the gender alternatives for fields with GENDER
*
* @param fieldEditor
* @param entryEditor
* @return
*/
public static Optional<JComponent> getGenderExtraComponent(FieldEditor fieldEditor, EntryEditor entryEditor) {
final String[] optionValues = {"", "sf", "sm", "sp", "pf", "pm", "pn", "pp"};
final String[] optionDescriptions = {Localization.lang("Select"), Localization.lang("Female name"),
Localization.lang("Male name"),
Localization.lang("Neuter name"), Localization.lang("Female names"), Localization.lang("Male names"),
Localization.lang("Neuter names"), Localization.lang("Mixed names")};
JComboBox<String> gender = new JComboBox<>(optionDescriptions);
gender.addActionListener(actionEvent -> {
fieldEditor.setText(optionValues[gender.getSelectedIndex()]);
entryEditor.updateField(fieldEditor);
});
return Optional.of(gender);
}
}
|
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.core.grids.client.widget.grid.impl;
import java.util.ArrayList;
import com.ait.lienzo.client.core.event.NodeMouseClickEvent;
import com.ait.lienzo.client.core.shape.Group;
import com.ait.lienzo.client.core.shape.Viewport;
import com.ait.lienzo.client.core.types.Point2D;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.ext.wires.core.grids.client.model.Bounds;
import org.uberfire.ext.wires.core.grids.client.model.GridCell;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.GridRow;
import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.GridRenderer;
import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.impl.BaseGridRendererHelper;
import org.uberfire.ext.wires.core.grids.client.widget.grid.selections.CellSelectionStrategy;
import org.uberfire.ext.wires.core.grids.client.widget.layer.GridSelectionManager;
import org.uberfire.ext.wires.core.grids.client.widget.layer.impl.DefaultGridLayer;
import static org.mockito.Mockito.*;
@RunWith(LienzoMockitoTestRunner.class)
public class GridCellSelectorMouseClickHandlerTest {
@Mock
private GridWidget gridWidget;
@Mock
private Group header;
@Mock
private Viewport viewport;
@Mock
private DefaultGridLayer layer;
@Mock
private GridSelectionManager selectionManager;
@Mock
private GridRenderer renderer;
@Mock
private NodeMouseClickEvent event;
@Mock
private GridData uiModel;
@Mock
private BaseGridRendererHelper helper;
@Mock
private GridColumn<String> uiColumn;
@Mock
private GridRow uiRow;
@Mock
private GridCell uiCell;
@Mock
private CellSelectionStrategy cellSelectionStrategy;
private GridCellSelectorMouseClickHandler handler;
@Before
public void setup() {
when( gridWidget.getViewport() ).thenReturn( viewport );
when( gridWidget.getModel() ).thenReturn( uiModel );
when( gridWidget.getRenderer() ).thenReturn( renderer );
when( gridWidget.getRendererHelper() ).thenReturn( helper );
when( gridWidget.getLayer() ).thenReturn( layer );
when( gridWidget.getHeader() ).thenReturn( header );
when( gridWidget.getHeight() ).thenReturn( 128.0 );
when( gridWidget.getLocation() ).thenReturn( new Point2D( 100,
100 ) );
when( renderer.getHeaderHeight() ).thenReturn( 64.0 );
when( renderer.getHeaderRowHeight() ).thenReturn( 32.0 );
when( uiModel.getHeaderRowCount() ).thenReturn( 2 );
when( uiModel.getColumnCount() ).thenReturn( 1 );
when( uiModel.getColumns() ).thenReturn( new ArrayList<GridColumn<?>>() {{
add( uiColumn );
}} );
when( uiModel.getRowCount() ).thenReturn( 1 );
when( uiModel.getRow( eq( 0 ) ) ).thenReturn( uiRow );
when( uiRow.getHeight() ).thenReturn( 64.0 );
when( uiCell.getSelectionManager() ).thenReturn( cellSelectionStrategy );
final GridCellSelectorMouseClickHandler wrapped = new GridCellSelectorMouseClickHandler( gridWidget,
selectionManager,
renderer );
handler = spy( wrapped );
}
@Test
public void skipInvisibleGrid() {
when( gridWidget.isVisible() ).thenReturn( false );
handler.onNodeMouseClick( event );
verify( handler,
never() ).handleBodyCellClick( any( NodeMouseClickEvent.class ) );
}
@Test
public void basicCheckForBodyHandlerWithinBodyBounds() {
when( gridWidget.isVisible() ).thenReturn( true );
when( event.getX() ).thenReturn( 100 );
when( event.getY() ).thenReturn( 200 );
final BaseGridRendererHelper.ColumnInformation ci = new BaseGridRendererHelper.ColumnInformation( uiColumn,
0,
0 );
when( helper.getColumnInformation( any( Double.class ) ) ).thenReturn( ci );
handler.onNodeMouseClick( event );
verify( handler,
times( 1 ) ).handleBodyCellClick( any( NodeMouseClickEvent.class ) );
verify( gridWidget,
times( 1 ) ).selectCell( any( Point2D.class ),
eq( false ),
eq( false ) );
}
@Test
public void basicCheckForBodyHandlerOutsideBodyBounds() {
when( gridWidget.isVisible() ).thenReturn( true );
when( event.getX() ).thenReturn( 100 );
when( event.getY() ).thenReturn( 120 );
final BaseGridRendererHelper.ColumnInformation ci = new BaseGridRendererHelper.ColumnInformation( uiColumn,
0,
0 );
when( helper.getColumnInformation( any( Double.class ) ) ).thenReturn( ci );
handler.onNodeMouseClick( event );
verify( handler,
times( 1 ) ).handleBodyCellClick( any( NodeMouseClickEvent.class ) );
verify( uiModel,
never() ).getCell( any( Integer.class ),
any( Integer.class ) );
}
@Test
@SuppressWarnings("unchecked")
public void selectSingleCell() {
when( gridWidget.isVisible() ).thenReturn( true );
when( event.getX() ).thenReturn( 100 );
when( event.getY() ).thenReturn( 200 );
when( uiModel.getCell( any( Integer.class ),
any( Integer.class ) ) ).thenReturn( uiCell );
final BaseGridRendererHelper.ColumnInformation ci = new BaseGridRendererHelper.ColumnInformation( uiColumn,
0,
0 );
when( helper.getColumnInformation( any( Double.class ) ) ).thenReturn( ci );
final BaseGridRendererHelper.RenderingInformation ri = new BaseGridRendererHelper.RenderingInformation( mock( Bounds.class ),
new ArrayList<GridColumn<?>>() {{
add( uiColumn );
}},
mock( BaseGridRendererHelper.RenderingBlockInformation.class ),
mock( BaseGridRendererHelper.RenderingBlockInformation.class ),
0,
1,
new ArrayList<Double>() {{
add( 64.0 );
}},
false,
false,
0,
2,
0 );
when( helper.getRenderingInformation() ).thenReturn( ri );
handler.onNodeMouseClick( event );
verify( handler,
times( 1 ) ).handleBodyCellClick( any( NodeMouseClickEvent.class ) );
verify( gridWidget,
times( 1 ) ).selectCell( any( Point2D.class ),
eq( false ),
eq( false ) );
}
}
|
|
/*
* Copyright 2011-2013 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.numeric;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.Nls;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.ig.psiutils.ExpectedTypeUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
public class UnnecessaryExplicitNumericCastInspection extends BaseInspection {
private static final Set<IElementType> binaryPromotionOperators = new HashSet();
static {
binaryPromotionOperators.add(JavaTokenType.ASTERISK);
binaryPromotionOperators.add(JavaTokenType.DIV);
binaryPromotionOperators.add(JavaTokenType.PERC);
binaryPromotionOperators.add(JavaTokenType.PLUS);
binaryPromotionOperators.add(JavaTokenType.MINUS);
binaryPromotionOperators.add(JavaTokenType.LT);
binaryPromotionOperators.add(JavaTokenType.LE);
binaryPromotionOperators.add(JavaTokenType.GT);
binaryPromotionOperators.add(JavaTokenType.GE);
binaryPromotionOperators.add(JavaTokenType.EQEQ);
binaryPromotionOperators.add(JavaTokenType.NE);
binaryPromotionOperators.add(JavaTokenType.AND);
binaryPromotionOperators.add(JavaTokenType.XOR);
binaryPromotionOperators.add(JavaTokenType.OR);
}
@Nls
@Nonnull
@Override
public String getDisplayName() {
return InspectionGadgetsBundle.message("unnecessary.explicit.numeric.cast.display.name");
}
@Nonnull
@Override
protected String buildErrorString(Object... infos) {
final PsiExpression expression = (PsiExpression)infos[0];
return InspectionGadgetsBundle.message("unnecessary.explicit.numeric.cast.problem.descriptor", expression.getText());
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
return new UnnecessaryExplicitNumericCastFix();
}
private static class UnnecessaryExplicitNumericCastFix extends InspectionGadgetsFix {
@Nonnull
@Override
public String getName() {
return InspectionGadgetsBundle.message("unnecessary.explicit.numeric.cast.quickfix");
}
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
final PsiElement parent = element.getParent();
if (!(parent instanceof PsiTypeCastExpression)) {
return;
}
final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression)parent;
if (isPrimitiveNumericCastNecessary(typeCastExpression)) {
return;
}
final PsiExpression operand = typeCastExpression.getOperand();
if (operand == null) {
typeCastExpression.delete();
}
else {
typeCastExpression.replace(operand);
}
}
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new UnnecessaryExplicitNumericCastVisitor();
}
private static class UnnecessaryExplicitNumericCastVisitor extends BaseInspectionVisitor {
@Override
public void visitTypeCastExpression(PsiTypeCastExpression expression) {
super.visitTypeCastExpression(expression);
final PsiType castType = expression.getType();
if (!ClassUtils.isPrimitiveNumericType(castType)) {
return;
}
final PsiExpression operand = expression.getOperand();
if (operand == null) {
return;
}
final PsiType operandType = operand.getType();
if (operandType == null || operandType.equals(castType)) {
return;
}
if (isPrimitiveNumericCastNecessary(expression)) {
return;
}
final PsiTypeElement typeElement = expression.getCastType();
if (typeElement != null) {
registerError(typeElement, ProblemHighlightType.LIKE_UNUSED_SYMBOL, operand);
}
}
}
public static boolean isPrimitiveNumericCastNecessary(PsiTypeCastExpression expression) {
final PsiType castType = expression.getType();
if (castType == null) {
return true;
}
final PsiExpression operand = expression.getOperand();
if (operand == null) {
return true;
}
final PsiType operandType = operand.getType();
PsiElement parent = expression.getParent();
while (parent instanceof PsiParenthesizedExpression) {
parent = parent.getParent();
}
if (parent instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent;
final IElementType tokenType = polyadicExpression.getOperationTokenType();
if (binaryPromotionOperators.contains(tokenType)) {
if (PsiType.INT.equals(castType)) {
return PsiType.LONG.equals(operandType) || PsiType.FLOAT.equals(operandType) || PsiType.DOUBLE.equals(operandType);
}
if (PsiType.LONG.equals(castType) || PsiType.FLOAT.equals(castType) || PsiType.DOUBLE.equals(castType)) {
final PsiExpression[] operands = polyadicExpression.getOperands();
for (PsiExpression operand1 : operands) {
if (!PsiTreeUtil.isAncestor(operand1, expression, false)) {
final PsiType type = operand1.getType();
if (castType.equals(type)) {
return false;
}
}
}
}
}
else if (JavaTokenType.GTGT.equals(tokenType) || JavaTokenType.GTGTGT.equals(tokenType) || JavaTokenType.LTLT.equals(tokenType)) {
final PsiExpression firstOperand = polyadicExpression.getOperands()[0];
if (!PsiTreeUtil.isAncestor(firstOperand, expression, false)) {
return false;
}
return PsiType.LONG.equals(castType) || !isLegalWideningConversion(operand, PsiType.INT);
}
return true;
}
else if (parent instanceof PsiAssignmentExpression) {
final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent;
final PsiType lhsType = assignmentExpression.getType();
return !castType.equals(lhsType) || !isLegalAssignmentConversion(operand, lhsType);
}
else if (parent instanceof PsiVariable) {
final PsiVariable variable = (PsiVariable)parent;
final PsiType lhsType = variable.getType();
return !castType.equals(lhsType) || !isLegalAssignmentConversion(operand, lhsType);
}
else if (parent instanceof PsiExpressionList) {
final PsiExpressionList expressionList = (PsiExpressionList)parent;
final PsiElement grandParent = expressionList.getParent();
if (!(grandParent instanceof PsiCallExpression)) {
return true;
}
final PsiCallExpression callExpression = (PsiCallExpression)grandParent;
final PsiMethod targetMethod = callExpression.resolveMethod();
if (targetMethod == null) {
return true;
}
final PsiElement[] children = callExpression.getChildren();
final StringBuilder newMethodCallText = new StringBuilder();
for (PsiElement child : children) {
if (child != expressionList) {
newMethodCallText.append(child.getText());
continue;
}
newMethodCallText.append('(');
final PsiExpression[] arguments = expressionList.getExpressions();
boolean comma = false;
for (PsiExpression argument : arguments) {
if (comma) {
newMethodCallText.append(',');
}
else {
comma = true;
}
if (PsiTreeUtil.isAncestor(argument, expression, false)) {
newMethodCallText.append(operand.getText());
}
else {
newMethodCallText.append(argument.getText());
}
}
newMethodCallText.append(')');
}
final Project project = expression.getProject();
final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
final PsiElementFactory factory = javaPsiFacade.getElementFactory();
final PsiCallExpression newMethodCall = (PsiCallExpression)
factory.createExpressionFromText(newMethodCallText.toString(), expression);
if (targetMethod != newMethodCall.resolveMethod()) {
return true;
}
}
final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false);
return !castType.equals(expectedType) || !isLegalWideningConversion(operand, castType);
}
static boolean isLegalWideningConversion(PsiExpression expression, PsiType requiredType) {
final PsiType operandType = expression.getType();
if (PsiType.DOUBLE.equals(requiredType)) {
if (PsiType.FLOAT.equals(operandType) ||
PsiType.LONG.equals(operandType) ||
PsiType.INT.equals(operandType) ||
PsiType.CHAR.equals(operandType) ||
PsiType.SHORT.equals(operandType) ||
PsiType.BYTE.equals(operandType)) {
return true;
}
}
else if (PsiType.FLOAT.equals(requiredType)) {
if (PsiType.LONG.equals(operandType) ||
PsiType.INT.equals(operandType) ||
PsiType.CHAR.equals(operandType) ||
PsiType.SHORT.equals(operandType) ||
PsiType.BYTE.equals(operandType)) {
return true;
}
}
else if (PsiType.LONG.equals(requiredType)) {
if (PsiType.INT.equals(operandType) ||
PsiType.CHAR.equals(operandType) ||
PsiType.SHORT.equals(operandType) ||
PsiType.BYTE.equals(operandType)) {
return true;
}
}
else if (PsiType.INT.equals(requiredType)) {
if (PsiType.CHAR.equals(operandType) ||
PsiType.SHORT.equals(operandType) ||
PsiType.BYTE.equals(operandType)) {
return true;
}
}
return false;
}
static boolean isLegalAssignmentConversion(PsiExpression expression, PsiType assignmentType) {
// JLS 5.2 Assignment Conversion
final PsiType operandType = expression.getType();
if (isLegalWideningConversion(expression, assignmentType)) {
return true;
}
else if (PsiType.SHORT.equals(assignmentType)) {
if (PsiType.INT.equals(operandType)) {
final Object constant = ExpressionUtils.computeConstantExpression(expression);
if (!(constant instanceof Integer)) {
return false;
}
final int i = ((Integer)constant).intValue();
if (i >= Short.MIN_VALUE && i <= Short.MAX_VALUE) {
// narrowing
return true;
}
}
}
else if (PsiType.CHAR.equals(assignmentType)) {
if (PsiType.INT.equals(operandType)) {
final Object constant = ExpressionUtils.computeConstantExpression(expression);
if (!(constant instanceof Integer)) {
return false;
}
final int i = ((Integer)constant).intValue();
if (i >= Character.MIN_VALUE && i <= Character.MAX_VALUE) {
// narrowing
return true;
}
}
}
else if (PsiType.BYTE.equals(assignmentType)) {
if (PsiType.INT.equals(operandType)) {
final Object constant = ExpressionUtils.computeConstantExpression(expression);
if (!(constant instanceof Integer)) {
return false;
}
final int i = ((Integer)constant).intValue();
if (i >= Byte.MIN_VALUE && i <= Byte.MAX_VALUE) {
// narrowing
return true;
}
}
}
return false;
}
}
|
|
/*$Id: SRDocumentFactoryImpl.java 3656 2003-06-09 17:17:51Z gunterze $*/
/*****************************************************************************
* *
* Copyright (c) 2001,2002 by TIANI MEDGRAPH AG <[email protected]>*
* *
* This file is part of dcm4che. *
* *
* This library 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 of the License, or *
* (at your option) any later version. *
* *
* This library 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 library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
*****************************************************************************/
package org.dcm4cheri.srom;
import org.dcm4che.srom.*;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmValueException;
import java.util.Date;
/**
*
* @author [email protected]
* @version 1.0
*/
public class SRDocumentFactoryImpl extends SRDocumentFactory
{
// Constants -----------------------------------------------------
static final DcmObjectFactory dsfact = DcmObjectFactory.getInstance();
// Attributes ----------------------------------------------------
// Constructors --------------------------------------------------
// Methodes --------------------------------------------------------
public RefSOP newRefSOP(String refSOPClassUID, String refSOPInstanceUID) {
return new RefSOPImpl(refSOPClassUID, refSOPInstanceUID);
}
public IconImage newIconImage(int rows, int columns, byte[] pixelData) {
return new IconImageImpl(rows, columns, pixelData);
}
public Patient newPatient(String patientID, String patientName,
Patient.Sex patientSex, Date patientBirthDate) {
return new PatientImpl(patientID, patientName, patientSex,
patientBirthDate);
}
public Study newStudy(String studyInstanceUID, String studyID,
Date studyDateTime, String referringPhysicianName,
String accessionNumber, String studyDescription, Code[] procCodes) {
return new StudyImpl(studyInstanceUID, studyID, studyDateTime,
referringPhysicianName, accessionNumber, studyDescription,
procCodes);
}
public Series newSeries(String modality, String seriesInstanceUID,
int seriesNumber, RefSOP refStudyComponent) {
return new SeriesImpl(modality, seriesInstanceUID, seriesNumber,
refStudyComponent);
}
public Series newSRSeries(String seriesInstanceUID, int seriesNumber,
RefSOP refStudyComponent) {
return new SeriesImpl("SR", seriesInstanceUID, seriesNumber,
refStudyComponent);
}
public Series newKOSeries(String seriesInstanceUID, int seriesNumber,
RefSOP refStudyComponent) {
return new SeriesImpl("KO", seriesInstanceUID, seriesNumber,
refStudyComponent);
}
public Equipment newEquipment(String manufacturer, String modelName,
String stationName) {
return new EquipmentImpl(manufacturer, modelName, stationName);
}
public Code newCode(String codeValue, String codingSchemeDesignator,
String codingSchemeVersion, String codeMeaning) {
return new CodeImpl(codeValue, codingSchemeDesignator,
codingSchemeVersion, codeMeaning);
}
public Code newCode(String codeValue, String codingSchemeDesignator,
String codeMeaning) {
return new CodeImpl(codeValue, codingSchemeDesignator,
null, codeMeaning);
}
public Template newTemplate(String templateIdentifier,
String mappingResource, Date templateVersion,
Date templateLocalVersion) {
return new TemplateImpl(templateIdentifier, mappingResource,
templateVersion, templateLocalVersion);
}
public Template newTemplate(String templateIdentifier,
String mappingResource) {
return new TemplateImpl(templateIdentifier, mappingResource, null, null);
}
public Verification newVerification(Date time, String observerName,
String observerOrg, Code observerCode) {
return new VerificationImpl(time, observerName, observerOrg, observerCode);
}
public Request newRequest(String studyInstanceUID,
String accessionNumber, String fillerOrderNumber,
String placerOrderNumber, String procedureID,
String procedureDescription, Code procedureCode) {
return new RequestImpl(studyInstanceUID, accessionNumber,
fillerOrderNumber, placerOrderNumber, procedureID,
procedureDescription, procedureCode);
}
public SOPInstanceRef newSOPInstanceRef(String sopClassUID,
String sopInstanceUID, String seriesInstanceUID,
String studyInstanceUID) {
return new SOPInstanceRefImpl(sopClassUID, sopInstanceUID,
seriesInstanceUID, studyInstanceUID);
}
public TCoordContent.Positions.Sample newSamplePositions(int[] indexes) {
return new TCoordContentImpl.SamplePositions(indexes);
}
public TCoordContent.Positions.Relative newRelativePositions(float[] offsets) {
return new TCoordContentImpl.RelativePositions(offsets);
}
public TCoordContent.Positions.Absolute newAbsolutePositions(Date[] dateTimes) {
return new TCoordContentImpl.AbsolutePositions(dateTimes);
}
public KeyObject newKeyObject(Patient patient, Study study,
Series series, Equipment equipment, String sopInstanceUID,
int instanceNumber, Date obsDateTime, Code title,
boolean separate) {
return new KeyObjectImpl(patient, study, series, equipment,
sopInstanceUID, instanceNumber, obsDateTime, title, separate);
}
public SRDocument newSRDocument(Patient patient, Study study,
Series series, Equipment equipment, String sopClassUID,
String sopInstanceUID, int instanceNumber, Date obsDateTime,
Template template, Code title, boolean separate) {
return new SRDocumentImpl(patient, study, series, equipment,
sopClassUID, sopInstanceUID, instanceNumber,
obsDateTime, template, title, separate);
}
public Patient newPatient(Dataset ds) throws DcmValueException {
return new PatientImpl(ds);
}
public Study newStudy(Dataset ds) throws DcmValueException {
return new StudyImpl(ds);
}
public Series newSeries(Dataset ds) throws DcmValueException {
return new SeriesImpl(ds);
}
public Equipment newEquipment(Dataset ds) throws DcmValueException {
return new EquipmentImpl(ds);
}
public Code newCode(Dataset ds) throws DcmValueException {
return CodeImpl.newCode(ds);
}
public RefSOP newRefSOP(Dataset ds) throws DcmValueException {
return RefSOPImpl.newRefSOP(ds);
}
public Template newTemplate(Dataset ds) throws DcmValueException {
return TemplateImpl.newTemplate(ds);
}
public SRDocument newSRDocument(Dataset ds) throws DcmValueException {
return SRDocumentImpl.newSRDocument(ds);
}
public KeyObject newKeyObject(Dataset ds) throws DcmValueException {
return KeyObjectImpl.newKeyObject(ds);
}
public IconImage newIconImage(Dataset ds) throws DcmValueException {
return IconImageImpl.newIconImage(ds);
}
public HL7SRExport newHL7SRExport(
String sendingApplication, String sendingFacility,
String receivingApplication, String receivingFacility) {
return new HL7SRExportImpl(sendingApplication, sendingFacility,
receivingApplication, receivingFacility);
}
}
|
|
/*
* 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.cassandra.index.sasi.conf;
import java.util.Collections;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.index.sasi.disk.OnDiskIndexBuilder.Mode;
import org.apache.cassandra.utils.ByteBufferUtil;
public class IndexModeTest
{
private final CFMetaData cfm = CFMetaData.Builder.create("ks", "cf")
.addPartitionKey("pkey", AsciiType.instance)
.build();
@BeforeClass
public static void setupDD()
{
DatabaseDescriptor.daemonInitialization();
}
@Test
public void test_notIndexed()
{
Assert.assertEquals(IndexMode.NOT_INDEXED, IndexMode.getMode(null, (Map)null));
Assert.assertEquals(IndexMode.NOT_INDEXED, IndexMode.getMode(null, Collections.EMPTY_MAP));
}
@Test(expected = ConfigurationException.class)
public void test_bad_mode_option()
{
IndexMode.getMode(null, Collections.singletonMap("mode", "invalid"));
}
@Test
public void test_asciiType()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), AsciiType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("something", "nothing"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertTrue(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_asciiType_notLiteral()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), AsciiType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("is_literal", "false"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_asciiType_errLiteral()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), AsciiType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("is_literal", "junk"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_asciiType_analyzed()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), AsciiType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("analyzed", "true"));
Assert.assertNull(result.analyzerClass);
Assert.assertTrue(result.isAnalyzed);
Assert.assertTrue(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_utf8Type()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), UTF8Type.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("something", "nothing"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertTrue(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("something", "nothing"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_isLiteral()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("is_literal", "true"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertTrue(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_errLiteral()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("is_literal", "junk"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_analyzed()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("analyzed", "true"));
Assert.assertNull(result.analyzerClass);
Assert.assertTrue(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_analyzer()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("analyzer_class", "java.lang.Object"));
Assert.assertEquals(Object.class, result.analyzerClass);
Assert.assertTrue(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_analyzer_unanalyzed()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, ImmutableMap.of("analyzer_class", "java.lang.Object",
"analyzed", "false"));
Assert.assertEquals(Object.class, result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals((long)(1073741824 * 0.15), result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
@Test
public void test_bytesType_maxCompactionFlushMemoryInBytes()
{
ColumnDefinition cd = ColumnDefinition.regularDef(cfm, ByteBufferUtil.bytes("TestColumnDefinition"), BytesType.instance);
IndexMode result = IndexMode.getMode(cd, Collections.singletonMap("max_compaction_flush_memory_in_mb", "1"));
Assert.assertNull(result.analyzerClass);
Assert.assertFalse(result.isAnalyzed);
Assert.assertFalse(result.isLiteral);
Assert.assertEquals(1048576L, result.maxCompactionFlushMemoryInBytes);
Assert.assertEquals(Mode.PREFIX, result.mode);
}
}
|
|
package org.rfcx.cellmapping.activities;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.SQLException;
import java.util.ArrayList;
import org.rfcx.cellmapping.CellMappingApp;
import org.rfcx.cellmapping.R;
import org.rfcx.cellmapping.exceptions.UnauthorizeException;
import org.rfcx.cellmapping.interfaces.CheckinsCallback;
import org.rfcx.cellmapping.model.Poi;
import org.rfcx.cellmapping.model.User;
import org.rfcx.cellmapping.services.RFCXLocationService;
import org.rfcx.cellmapping.services.RFCXPhoneStateService;
import org.rfcx.cellmapping.utils.Utils;
public class MainActivity extends ActionBarActivity{
private TelephonyManager telephonyManager;
private LocationListener locationListener;
private LocationManager locationManager;
private Button startBtt;
private Button stopBtt;
private Button syncBtt;
private static Location _location;
private int _serviceState, _signalStrength, _signalCDMADbm, _signalEVODbm;
private Location myLocation;
private boolean isSynchronizing = false;
private TextView signalStregthTextView;
private TextView locationTextView;
private TextView serviceStateTextView;
private User user;
private TextView checkinsFound;
private ArrayList<Poi> pois = new ArrayList<Poi>();
private ProgressDialog dialog;
private TextView accuracyTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
user = CellMappingApp.getUser();
getSupportActionBar().setTitle(
String.format(getResources().getString(R.string.welcome), user.getName())
);
}catch(UnauthorizeException e) {
CellMappingApp.logout();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
syncBtt = (Button) findViewById(R.id.syncBtt);
syncBtt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
syncData();
}
});
Intent stateIntent = new Intent(MainActivity.this, RFCXPhoneStateService.class);
stateIntent.putExtra(RFCXPhoneStateService.INTENTACTION, RFCXPhoneStateService.STARTSERVICE);
startService(stateIntent);
Intent locationIntent = new Intent(MainActivity.this, RFCXLocationService.class);
locationIntent.putExtra(RFCXLocationService.INTENTACTION, RFCXLocationService.STARTSERVICE);
startService(locationIntent);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Get Current Location
myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = myLocation.getLatitude();
lon = myLocation.getLongitude();
refreshUI();
} catch (Exception e) {}
signalStregthTextView = (TextView) findViewById(R.id.signalStrength);
locationTextView = (TextView) findViewById(R.id.latLngTextView);
serviceStateTextView = (TextView) findViewById(R.id.serviceStateTextView);
checkinsFound = (TextView) findViewById(R.id.checkinsFound);
accuracyTextView = (TextView) findViewById(R.id.accuracyTextView);
checkinsFound.setText(String.format(
getResources().getString(R.string.checkinsfound),
pois.size()
));
// before start listening signal strength and service states
// we validate the SIM is available
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int simState = telephonyManager.getSimState();
if(simState != TelephonyManager.SIM_STATE_READY) {
Utils.Toast(MainActivity.this, R.string.simnull);
}
// we validate the SIM carrier is available
String carrier = telephonyManager.getSimOperatorName();
if(carrier == null) {
Utils.Toast(MainActivity.this, R.string.carriernull);
}
}
private void syncData() {
dialog = ProgressDialog.show(MainActivity.this, null, null, true);
dialog.setCancelable(false);
/*
CellMappingApp.getApiController().sync(pois, new CheckinsCallback() {
@Override
public void onSucess() {
}
@Override
public void onError() {
}
});
*/
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(phoneStateReceiver);
unregisterReceiver(phoneLocationReceiver);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(phoneStateReceiver, new IntentFilter(RFCXPhoneStateService.NOTIFICATION));
registerReceiver(phoneLocationReceiver, new IntentFilter(RFCXLocationService.NOTIFICATION));
}
private void saveSignal() {
if(isSynchronizing) return;
if(_serviceState != ServiceState.STATE_IN_SERVICE) {
Utils.Toast(MainActivity.this, R.string.outofservice);
return;
}
if(lat == 0 || lon == 0) {
Utils.Toast(MainActivity.this, R.string.latlngnotfound);
return;
}
// Just a bit of theory
/*
* Arbitrary Strength Unit (ASU) is an integer value proportional to the received signal
* strength measured by the mobile phone.
*
* In GSM networks, ASU maps to RSSI (received signal strength indicator, see TS 27.007[1] sub clause 8.5).
* dBm = 2 ?????? ASU - 113, ASU in the range of 0..31 and 99 (for not known or not detectable).
*
* In UMTS networks, ASU maps to RSCP level (received signal code power, see TS 27.007[1] sub clause 8.69 and TS 27.133 sub clause 9.1.1.3).
* dBm = ASU - 116, ASU in the range of -5..91 and 255 (for not known or not detectable).
*
* In LTE networks, ASU maps to RSRP (reference signal received power, see TS 36.133, sub-clause 9.1.4).
* The valid range of ASU is from 0 to 97. For the range 1 to 96, ASU maps to (ASU - 141) ????????? dBm < (ASU - 140).
* The value of 0 maps to RSRP below -140 dBm and the value of 97 maps to RSRP above -44 dBm.
*
*/
// We will use GSM Networks
/*
* 0 -113 dBm or less
* 1 -111 dBm
* 2...30 -109... -53 dBm
* 31 -51 dBm or greater
* 99 not known or not detectable
*/
Poi poi = new Poi();
poi.setLat(lat);
poi.setLng(lon);
poi.setCdmaDbm(_signalCDMADbm);
poi.setEvoDbm(_signalEVODbm);
poi.setSignalstrenth(_signalStrength);
poi.setAccuracy(accuracy);
poi.setSid(String.valueOf(user.getSid()));
poi.setName(user.getName());
poi.setGuid(user.getGUID());
try {
CellMappingApp.getController().savePoi(MainActivity.this, poi);
pois.add(poi);
refreshUI();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
private BroadcastReceiver phoneStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String result = extras.getString(RFCXPhoneStateService.RESULT);
if(result.equals(RFCXPhoneStateService.SIGNALSTATECHANGE)) {
_signalStrength = extras.getInt(RFCXPhoneStateService.SIGNALSTRENGTH);
_signalCDMADbm = extras.getInt(RFCXPhoneStateService.SIGNALCDMADBM);
_signalEVODbm = extras.getInt(RFCXPhoneStateService.SIGNALEVDODBM);
}else if(result.equals(RFCXPhoneStateService.SERVICESTATECHANGE)) {
_serviceState = extras.getInt(RFCXPhoneStateService.SIGNALSTATECHANGE);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
saveSignal();
}
});
}
};
private double lat;
private double lon;
private double accuracy;
private BroadcastReceiver phoneLocationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String result = extras.getString(RFCXLocationService.RESULT);
if(result.equals(RFCXLocationService.LOCATIONSTATECHANGE)) {
lat = extras.getDouble(RFCXLocationService.LAT);
lon = extras.getDouble(RFCXLocationService.LON);
accuracy = extras.getInt(RFCXLocationService.ACCURACY);
runOnUiThread(new Runnable() {
@Override
public void run() {
saveSignal();
}
});
}
}
};
private void refreshUI() {
String state;
switch (_serviceState){
case ServiceState.STATE_IN_SERVICE:
state = "State in service"; break;
case ServiceState.STATE_EMERGENCY_ONLY:
state = "State Emergency Only"; break;
case ServiceState.STATE_POWER_OFF:
state = "State State power off"; break;
default:
state = "State out of service"; break;
}
serviceStateTextView.setText(String.format(
getResources().getString(R.string.servicestate),
state
));
signalStregthTextView.setText(String.format(
getResources().getString(R.string.signalstrength),
String.valueOf(_signalStrength)
));
locationTextView.setText(String.format(
getResources().getString(R.string.location),
String.valueOf(lat),
String.valueOf(lon)
));
checkinsFound.setText(String.format(
getResources().getString(R.string.checkinsfound),
pois.size()
));
accuracyTextView.setText(String.format(
getResources().getString(R.string.accuracy),
accuracy
));
}
}
|
|
/*
* Copyright 2015-2017 Austin Keener & Michael Ritter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.managers;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.PermissionOverride;
import net.dv8tion.jda.core.exceptions.PermissionException;
import net.dv8tion.jda.core.requests.Request;
import net.dv8tion.jda.core.requests.Response;
import net.dv8tion.jda.core.requests.RestAction;
import net.dv8tion.jda.core.requests.Route;
import org.apache.http.util.Args;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Collection;
/**
* An {@link #update() updatable} manager that allows
* to modify {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride} settings
* such as the granted and denied {@link net.dv8tion.jda.core.Permission Permissions}.
*
* <p>This manager allows to modify multiple fields at once followed by a call of {@link #update()}!
* <br>Default is no permissions granted/denied.
*
* <p>The {@link net.dv8tion.jda.core.managers.PermOverrideManager PermOverrideManager} implementation
* simplifies this process by giving simple setters that return the {@link #update() update} {@link net.dv8tion.jda.core.requests.RestAction RestAction}
*
* <p><b>Note</b>: To {@link #update() update} this manager
* the currently logged in account requires the Permission {@link net.dv8tion.jda.core.Permission#MANAGE_PERMISSIONS MANAGE_PERMISSIONS}
* in the parent {@link net.dv8tion.jda.core.entities.Channel Channel}
*/
public class PermOverrideManagerUpdatable
{
protected final PermissionOverride override;
protected Long allow;
protected Long deny;
protected boolean set;
/**
* Creates a new PermOverrideManagerUpdatable instance
*
* @param override
* The {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride} to manage
*/
public PermOverrideManagerUpdatable(PermissionOverride override)
{
this.override = override;
}
/**
* The {@link net.dv8tion.jda.core.JDA JDA} instance of this Manager
*
* @return the corresponding JDA instance
*/
public JDA getJDA()
{
return override.getJDA();
}
/**
* The {@link net.dv8tion.jda.core.entities.Guild Guild} this Manager's
* {@link net.dv8tion.jda.core.entities.Channel Channel} is in.
* <br>This is logically the same as calling {@code getPermissionOverride().getGuild()}
*
* @return The parent {@link net.dv8tion.jda.core.entities.Guild Guild}
*/
public Guild getGuild()
{
return override.getGuild();
}
/**
* The {@link net.dv8tion.jda.core.entities.Channel Channel} this Manager's
* {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride} is in.
* <br>This is logically the same as calling {@code getPermissionOverride().getChannel()}
*
* @return The parent {@link net.dv8tion.jda.core.entities.Channel Channel}
*/
public Channel getChannel()
{
return override.getChannel();
}
/**
* The target {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride}
* that will be modified by this Manager
*
* @return The target {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride}
*/
public PermissionOverride getPermissionOverride()
{
return override;
}
/**
* Grants the specified permission bits
* to the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Raw permission bits to grant
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable grant(long permissions)
{
return grant(Permission.getPermissions(permissions));
}
/**
* Grants the specified {@link net.dv8tion.jda.core.Permission Permissions}
* to the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Permissions to grant
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable grant(Permission... permissions)
{
return grant(Arrays.asList(permissions));
}
/**
* Grants the specified {@link net.dv8tion.jda.core.Permission Permissions}
* to the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Permissions to grant
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable grant(Collection<Permission> permissions)
{
Args.notNull(permissions, "Permission Collection");
permissions.forEach(perm ->
{
Args.notNull(perm, "Permission in Permission Collection");
//checkPermission(perm);
});
setupValues();
long allowBits = Permission.getRaw(permissions);
allow |= allowBits;
deny &= ~allowBits;
return this;
}
/**
* Denies the specified permission bits
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Raw permission bits to deny
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable deny(long permissions)
{
return deny(Permission.getPermissions(permissions));
}
/**
* Denies the specified {@link net.dv8tion.jda.core.Permission Permissions}
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Permissions to deny
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable deny(Permission... permissions)
{
return deny(Arrays.asList(permissions));
}
/**
* Denies the specified {@link net.dv8tion.jda.core.Permission Permissions}
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
*
* @param permissions
* Permissions to deny
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable deny(Collection<Permission> permissions)
{
Args.notNull(permissions, "Permission Collection");
permissions.forEach(perm ->
{
Args.notNull(perm, "Permission in Permission Collection");
//checkPermission(perm);
});
setupValues();
long denyBits = Permission.getRaw(permissions);
allow &= ~denyBits;
deny |= denyBits;
return this;
}
/**
* Clears the specified permission bits
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
* <br>This will make the specified Permissions be inherited
*
* @param permission
* Raw permission bits to clear
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable clear(long permission)
{
return clear(Permission.getPermissions(permission));
}
/**
* Clears the specified {@link net.dv8tion.jda.core.Permission Permissions}
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
* <br>This will make the specified Permissions be inherited
*
* @param permissions
* Permissions to clear
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable clear(Permission... permissions)
{
return clear(Arrays.asList(permissions));
}
/**
* Clears the specified {@link net.dv8tion.jda.core.Permission Permissions}
* from the target {@link net.dv8tion.jda.core.entities.PermissionOverride}
* <br>This will make the specified Permissions be inherited
*
* @param permissions
* Permissions to clear
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If any of the provided permissions are not accessible
* @throws IllegalArgumentException
* If any of the provided permissions is {@code null}
*
* @return The current Manager instance for chaining convenience
*/
public PermOverrideManagerUpdatable clear(Collection<Permission> permissions)
{
Args.notNull(permissions, "Permission Collection");
permissions.forEach(perm ->
{
Args.notNull(perm, "Permission in Permission Collection");
//checkPermission(perm);
});
setupValues();
long clearBits = Permission.getRaw(permissions);
allow &= ~clearBits;
deny &= ~clearBits;
return this;
}
/**
* The granted {@link net.dv8tion.jda.core.Permission Permissions}
* value represented as raw long bits.
* <br>Use {@link Permission#getPermissions(long)} to retrieve a list of {@link net.dv8tion.jda.core.Permission Permissions}
* from the returned bits.
*
* <p>This value represents all permissions that should be granted by this {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride}
*
* @return Granted {@link net.dv8tion.jda.core.Permission Permissions} value
* or {@code null} if {@link #isSet()} is {@code false}
*/
public Long getAllowBits()
{
return allow;
}
/**
* The denied {@link net.dv8tion.jda.core.Permission Permissions}
* value represented as raw long bits.
* <br>Use {@link Permission#getPermissions(long)} to retrieve a list of {@link net.dv8tion.jda.core.Permission Permissions}
* from the returned bits.
*
* <p>This value represents all permissions that should be denied by this {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride}
*
* @return Denied {@link net.dv8tion.jda.core.Permission Permissions} value
* or {@code null} if {@link #isSet()} is {@code false}
*/
public Long getDenyBits()
{
return deny;
}
/**
* The inherited {@link net.dv8tion.jda.core.Permission Permissions}
* value represented as raw long bits.
* <br>Use {@link Permission#getPermissions(long)} to retrieve a list of {@link net.dv8tion.jda.core.Permission Permissions}
* from the returned bits.
*
* <p>This value represents all permissions that are not granted or denied by the settings of this Manager instance
* - thus they represent all permissions that are set to inherit from other overrides.
*
* @return Inherited {@link net.dv8tion.jda.core.Permission Permissions} value
* or {@code null} if {@link #isSet()} is {@code false}
*/
public Long getInheritBits()
{
if (!set)
return null;
long maxPerms = 0;
for (Permission perm : Permission.values())
{
if (perm.getOffset() > maxPerms)
maxPerms = perm.getOffset();
}
maxPerms = ~(1 << (maxPerms + 1)); //push 1 to max offset + 1, then flip to get a full-permission bit mask.
return (~allow | ~deny) & maxPerms;
}
/**
* Whether anything has been modified yet
*
* @return Whether anything has been modified
*/
public boolean isSet()
{
return set;
}
/**
* Resets all {@link net.dv8tion.jda.core.Permission Permission} values
* <br>This is automatically called by {@link #update()}
*/
public void reset()
{
set = false;
allow = null;
deny = null;
}
/**
* Creates a new {@link net.dv8tion.jda.core.requests.RestAction RestAction} instance
* that will apply <b>all</b> changes that have been made to this manager instance.
* <br>If no changes have been made this will simply return {@link net.dv8tion.jda.core.requests.RestAction.EmptyRestAction EmptyRestAction}.
*
* <p>Before applying new changes it is recommended to call {@link #reset()} to reset previous changes.
* <br>This is automatically called if this method returns successfully.
*
* <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} for this
* update include the following:
* <ul>
* <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_OVERRIDE UNKNOWN_OVERRIDE}
* <br>If the PermissionOverride was deleted before finishing the task</li>
*
* <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
* <br>If the currently logged in account was removed from the Guild before finishing the task</li>
*
* <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
* <br>If the currently logged in account loses the {@link net.dv8tion.jda.core.Permission#MANAGE_PERMISSIONS MANAGE_PERMISSIONS Permission}</li>
* </ul>
*
* @throws net.dv8tion.jda.core.exceptions.PermissionException
* If the currently logged in account does not have the Permission {@link net.dv8tion.jda.core.Permission#MANAGE_PERMISSIONS MANAGE_PERMISSIONS}
* in the {@link #getChannel() Channel}
*
* @return {@link net.dv8tion.jda.core.requests.RestAction RestAction}
* <br>Applies all changes that have been made in a single api-call.
*/
public RestAction<Void> update()
{
checkPermission(Permission.MANAGE_PERMISSIONS);
if (!shouldUpdate())
return new RestAction.EmptyRestAction<>(null);
String targetId = override.isRoleOverride() ? override.getRole().getId() : override.getMember().getUser().getId();
JSONObject body = new JSONObject()
.put("id", targetId)
.put("type", override.isRoleOverride() ? "role" : "member")
.put("allow", getAllowBits())
.put("deny", getDenyBits());
reset();
Route.CompiledRoute route = Route.Channels.MODIFY_PERM_OVERRIDE.compile(override.getChannel().getId(), targetId);
return new RestAction<Void>(getJDA(), route, body)
{
@Override
protected void handleResponse(Response response, Request<Void> request)
{
if (response.isOk())
request.onSuccess(null);
else
request.onFailure(response);
}
};
}
protected boolean shouldUpdate()
{
return set && (allow != override.getAllowedRaw() || deny != override.getDeniedRaw());
}
protected void setupValues()
{
if (!set)
{
set = true;
allow = override.getAllowedRaw();
deny = override.getDeniedRaw();
}
}
protected void checkPermission(Permission perm)
{
if (!getGuild().getSelfMember().hasPermission(getChannel(), perm))
throw new PermissionException(perm);
}
}
|
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.sandbox;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionStatusMessage;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionStrategy;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnActionContext;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.exec.SpawnInputExpander;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandException;
import com.google.devtools.build.lib.shell.CommandResult;
import com.google.devtools.build.lib.standalone.StandaloneSpawnStrategy;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/** Strategy that uses sandboxing to execute a process, for Darwin */
@ExecutionStrategy(
name = {"sandboxed", "darwin-sandbox"},
contextType = SpawnActionContext.class
)
public class DarwinSandboxedStrategy extends SandboxStrategy {
private final Path execRoot;
private final boolean sandboxDebug;
private final boolean verboseFailures;
private final String productName;
private final SpawnInputExpander spawnInputExpander;
/**
* The set of directories that always should be writable, independent of the Spawn itself.
*
* <p>We cache this, because creating it involves executing {@code getconf}, which is expensive.
*/
private final ImmutableSet<Path> alwaysWritableDirs;
private DarwinSandboxedStrategy(
CommandEnvironment cmdEnv,
BuildRequest buildRequest,
Path sandboxBase,
boolean verboseFailures,
String productName,
ImmutableSet<Path> alwaysWritableDirs) {
super(
cmdEnv,
buildRequest,
sandboxBase,
verboseFailures,
buildRequest.getOptions(SandboxOptions.class));
this.execRoot = cmdEnv.getExecRoot();
this.sandboxDebug = buildRequest.getOptions(SandboxOptions.class).sandboxDebug;
this.verboseFailures = verboseFailures;
this.productName = productName;
this.alwaysWritableDirs = alwaysWritableDirs;
this.spawnInputExpander = new SpawnInputExpander(false);
}
public static DarwinSandboxedStrategy create(
CommandEnvironment cmdEnv,
BuildRequest buildRequest,
Path sandboxBase,
boolean verboseFailures,
String productName)
throws IOException {
return new DarwinSandboxedStrategy(
cmdEnv,
buildRequest,
sandboxBase,
verboseFailures,
productName,
getAlwaysWritableDirs(cmdEnv.getDirectories().getFileSystem()));
}
private static void addPathToSetIfExists(FileSystem fs, Set<Path> paths, String path)
throws IOException {
if (path != null) {
addPathToSetIfExists(paths, fs.getPath(path));
}
}
private static void addPathToSetIfExists(Set<Path> paths, Path path) throws IOException {
if (path.exists()) {
paths.add(path.resolveSymbolicLinks());
}
}
private static ImmutableSet<Path> getAlwaysWritableDirs(FileSystem fs) throws IOException {
HashSet<Path> writableDirs = new HashSet<>();
addPathToSetIfExists(fs, writableDirs, "/dev");
addPathToSetIfExists(fs, writableDirs, System.getenv("TMPDIR"));
addPathToSetIfExists(fs, writableDirs, "/tmp");
addPathToSetIfExists(fs, writableDirs, "/private/tmp");
addPathToSetIfExists(fs, writableDirs, "/private/var/tmp");
// On macOS, in addition to what is specified in $TMPDIR, two other temporary directories may be
// written to by processes. We have to get their location by calling "getconf".
addPathToSetIfExists(fs, writableDirs, getConfStr("DARWIN_USER_TEMP_DIR"));
addPathToSetIfExists(fs, writableDirs, getConfStr("DARWIN_USER_CACHE_DIR"));
// ~/Library/Cache and ~/Library/Logs need to be writable (cf. issue #2231).
Path homeDir = fs.getPath(System.getProperty("user.home"));
addPathToSetIfExists(writableDirs, homeDir.getRelative("Library/Cache"));
addPathToSetIfExists(writableDirs, homeDir.getRelative("Library/Logs"));
// Certain Xcode tools expect to be able to write to this path.
addPathToSetIfExists(writableDirs, homeDir.getRelative("Library/Developer"));
return ImmutableSet.copyOf(writableDirs);
}
/**
* Returns the value of a POSIX or X/Open system configuration variable.
*/
private static String getConfStr(String confVar) throws IOException {
String[] commandArr = new String[2];
commandArr[0] = "/usr/bin/getconf";
commandArr[1] = confVar;
Command cmd = new Command(commandArr);
CommandResult res;
try {
res = cmd.execute();
} catch (CommandException e) {
throw new IOException("getconf failed", e);
}
return new String(res.getStdout(), UTF_8).trim();
}
@Override
protected void actuallyExec(
Spawn spawn,
ActionExecutionContext actionExecutionContext,
AtomicReference<Class<? extends SpawnActionContext>> writeOutputFiles)
throws ExecException, InterruptedException, IOException {
Executor executor = actionExecutionContext.getExecutor();
executor
.getEventBus()
.post(ActionStatusMessage.runningStrategy(spawn.getResourceOwner(), "darwin-sandbox"));
SandboxHelpers.reportSubcommand(executor, spawn);
// Each invocation of "exec" gets its own sandbox.
Path sandboxPath = getSandboxRoot();
Path sandboxExecRoot = sandboxPath.getRelative("execroot").getRelative(execRoot.getBaseName());
ImmutableMap<String, String> spawnEnvironment =
StandaloneSpawnStrategy.locallyDeterminedEnv(execRoot, productName, spawn.getEnvironment());
HashSet<Path> writableDirs = new HashSet<>(alwaysWritableDirs);
ImmutableSet<Path> extraWritableDirs = getWritableDirs(sandboxExecRoot, spawnEnvironment);
writableDirs.addAll(extraWritableDirs);
SymlinkedExecRoot symlinkedExecRoot = new SymlinkedExecRoot(sandboxExecRoot);
ImmutableSet<PathFragment> outputs = SandboxHelpers.getOutputFiles(spawn);
symlinkedExecRoot.createFileSystem(
SandboxHelpers.getInputFiles(
spawnInputExpander, this.execRoot, spawn, actionExecutionContext),
outputs,
writableDirs);
// This will add the resolved versions of the spawn-dependant writable paths (e.g. its execroot
// or TEST_TMPDIR) to the set, now that they have been created by the SymlinkedExecRoot.
for (Path extraWritableDir : extraWritableDirs) {
addPathToSetIfExists(writableDirs, extraWritableDir);
}
DarwinSandboxRunner runner =
new DarwinSandboxRunner(
sandboxPath, sandboxExecRoot, writableDirs, getInaccessiblePaths(), verboseFailures);
try {
runSpawn(
spawn,
actionExecutionContext,
spawnEnvironment,
symlinkedExecRoot,
outputs,
runner,
writeOutputFiles);
} finally {
if (!sandboxDebug) {
try {
FileSystemUtils.deleteTree(sandboxPath);
} catch (IOException e) {
// This usually means that the Spawn itself exited, but still has children running that
// we couldn't wait for, which now block deletion of the sandbox directory. On Linux this
// should never happen, as we use PID namespaces and where they are not available the
// subreaper feature to make sure all children have been reliably killed before returning,
// but on other OS this might not always work. The SandboxModule will try to delete them
// again when the build is all done, at which point it hopefully works, so let's just go
// on here.
}
}
}
}
}
|
|
package net.peterd.zombierun.activity;
import java.util.ArrayList;
import java.util.Collection;
import net.peterd.zombierun.R;
import net.peterd.zombierun.constants.BundleConstants;
import net.peterd.zombierun.constants.Constants;
import net.peterd.zombierun.constants.Constants.GAME_MENU_OPTION;
import net.peterd.zombierun.game.GameEvent;
import net.peterd.zombierun.game.GameSettings;
import net.peterd.zombierun.overlay.MotoCliqSafeMyLocationOverlay;
import net.peterd.zombierun.service.GameEventBroadcaster;
import net.peterd.zombierun.service.GameService;
import net.peterd.zombierun.util.FloatingPointGeoPoint;
import net.peterd.zombierun.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.maps.MapView;
/**
* TODO: make the 'back' button go to the home screen (with a quit confirmation dialog), instead of
* back to the last activity.
*
* @author Peter Dolan ([email protected])
*/
public class GameMapActivity extends BaseMapActivity {
protected GameService service;
protected final Collection<GAME_MENU_OPTION> menuOptions = new ArrayList<GAME_MENU_OPTION>();
protected MapView mapView;
protected Drawable myLocationDrawable;
protected MotoCliqSafeMyLocationOverlay myLocationOverlay;
protected GameSettings gameSettings;
/**
* Initialize the Map that activity takes place on.
*/
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.game);
service = new GameService(this);
mapView = (MapView) findViewById(R.id.mapview);
MapView map = mapView;
map.setFocusableInTouchMode(true);
map.setClickable(true);
map.setBuiltInZoomControls(true);
map.getOverlays().clear();
myLocationDrawable = getResources().getDrawable(R.drawable.mylocationdot);
myLocationDrawable.setBounds(0,
0,
myLocationDrawable.getIntrinsicWidth(),
myLocationDrawable.getIntrinsicHeight());
myLocationOverlay =
new MotoCliqSafeMyLocationOverlay(this, map, myLocationDrawable);
service.getHardwareManager().registerLocationListener(myLocationOverlay);
map.getOverlays().add(myLocationOverlay);
map.setSatellite(true);
Bundle intentExtras = getIntent().getExtras();
if (intentExtras != null) {
GameSettings settings = GameSettings.fromBundle(intentExtras);
if (settings != null) {
gameSettings = settings;
}
}
if (state != null) {
GameSettings settings = GameSettings.fromBundle(state);
if (settings != null) {
gameSettings = settings;
}
}
// Restore from state after setting map view to satellite mode, so that the map's stored state
// can override it if it's been set to map mode.
if (state != null) {
onRestoreInstanceState(state);
}
}
@Override
protected void onRestart() {
super.onRestart();
service.getEventHandler().broadcastEvent(GameEvent.GAME_RESUME);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showQuitGameConfirmationDialogue();
return true;
}
return false;
}
@Override
protected void onResume() {
super.onResume();
service.getEventHandler().broadcastEvent(GameEvent.GAME_RESUME);
Log.d("ZombieRun.GameMapActivity", "enabling mylocationoverlay");
myLocationOverlay.enableMyLocation();
}
@Override
protected void onPause() {
super.onPause();
service.getEventHandler().broadcastEvent(GameEvent.GAME_PAUSE);
Log.d("ZombieRun.GameMapActivity", "disabling mylocationoverlay");
myLocationOverlay.disableMyLocation();
}
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
Log.d("ZombieRun.GameMapActivity", "onRestoreInstanceState");
if (mapView != null &&
state != null &&
state.containsKey(BundleConstants.MAP_MODE_IS_SATELLITE)) {
mapView.setSatellite(state.getBoolean(BundleConstants.MAP_MODE_IS_SATELLITE));
}
service.onRestoreInstanceState(state);
GameSettings settings = GameSettings.fromBundle(state);
if (settings != null) {
gameSettings = settings;
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
Log.d("ZombieRun.GameMapActivity", "onSaveInstanceState");
state.putBoolean(BundleConstants.MAP_MODE_IS_SATELLITE, mapView.isSatellite());
service.onSaveInstanceState(state);
if (gameSettings != null) {
gameSettings.toBundle(state);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
int menuIndex = 0;
for (Constants.GAME_MENU_OPTION option : menuOptions) {
if (option == GAME_MENU_OPTION.MAP_VIEW && !mapView.isSatellite()) {
// Don't offer map view when we're showing map view.
continue;
}
if (option == GAME_MENU_OPTION.SATELLITE_VIEW && mapView.isSatellite()) {
// Don't offer satellite view when we're showing satellite view.
continue;
}
menu.add(menuIndex, option.getValue(), Menu.NONE, option.getStringId());
menuIndex++;
}
return true;
}
@Override
public final boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
int itemId = item.getItemId();
MapView mapView = this.mapView;
final GameEventBroadcaster gameEventBroadcaster = service.getEventHandler();
if (Constants.GAME_MENU_OPTION.PAUSE.getValue() == itemId) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.paused))
.setCancelable(false)
.setPositiveButton(getString(R.string.resume),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
gameEventBroadcaster.broadcastEvent(GameEvent.GAME_RESUME);
}
})
.show();
gameEventBroadcaster.broadcastEvent(GameEvent.GAME_PAUSE);
} else if (Constants.GAME_MENU_OPTION.STOP.getValue() == itemId) {
showQuitGameConfirmationDialogue();
} else if (Constants.GAME_MENU_OPTION.MAP_VIEW.getValue() == itemId) {
mapView.setSatellite(false);
} else if (Constants.GAME_MENU_OPTION.SATELLITE_VIEW.getValue() == itemId) {
mapView.setSatellite(true);
} else if (Constants.GAME_MENU_OPTION.MY_LOCATION.getValue() == itemId) {
FloatingPointGeoPoint point = service.getHardwareManager().getLastKnownLocation();
if (point != null) {
mapView.getController().animateTo(point.getGeoPoint());
}
}
return false;
}
private void showQuitGameConfirmationDialogue() {
final GameEventBroadcaster gameEventBroadcaster = service.getEventHandler();
// Showing a quit game confirmation dialogue.
final Intent quitGameIntent = new Intent(this, WinOrLoseGame.class);
quitGameIntent.putExtra(BundleConstants.GAME_WON, false);
new AlertDialog.Builder(this)
.setMessage(R.string.confirm_menu_stop)
.setPositiveButton(getString(R.string.quit_confirm),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
gameEventBroadcaster.broadcastEvent(GameEvent.GAME_QUIT);
startActivity(quitGameIntent);
}
})
.setNegativeButton(getString(R.string.quit_cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Nothing, just go back to the game.
}
})
.show();
}
}
|
|
/**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.model;
import net.fortuna.ical4j.util.Numbers;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Objects;
/**
* $Id$
*
* Created: 19/12/2004
*
* Defines a day of the week with a possible offset related to
* a MONTHLY or YEARLY occurrence.
*
* @author Ben Fortuna
*/
public class WeekDay implements Serializable {
private static final long serialVersionUID = -4412000990022011469L;
/**
* Sunday.
*/
public static final WeekDay SU = new WeekDay(Day.SU, 0);
/**
* Monday.
*/
public static final WeekDay MO = new WeekDay(Day.MO, 0);
/**
* Tuesday.
*/
public static final WeekDay TU = new WeekDay(Day.TU, 0);
/**
* Wednesday.
*/
public static final WeekDay WE = new WeekDay(Day.WE, 0);
/**
* Thursday.
*/
public static final WeekDay TH = new WeekDay(Day.TH, 0);
/**
* Friday.
*/
public static final WeekDay FR = new WeekDay(Day.FR, 0);
/**
* Saturday.
*/
public static final WeekDay SA = new WeekDay(Day.SA, 0);
public enum Day { SU, MO, TU, WE, TH, FR, SA }
private Day day;
private int offset;
/**
* @param value a string representation of a week day
*/
public WeekDay(final String value) {
if (value.length() > 2) {
offset = Numbers.parseInt(value.substring(0, value.length() - 2));
}
else {
offset = 0;
}
day = Day.valueOf(value.substring(value.length() - 2));
validateDay();
}
/**
* @param day a string representation of a week day
* @param offset a month offset value
*/
private WeekDay(final Day day, final int offset) {
this.day = day;
this.offset = offset;
}
/**
* Constructs a new weekday instance based on the specified
* instance and offset.
* @param weekDay a week day template for the instance
* @param offset a month offset value
*/
public WeekDay(final WeekDay weekDay, final int offset) {
this.day = weekDay.getDay();
this.offset = offset;
}
private void validateDay() {
if (!SU.day.equals(day)
&& !MO.day.equals(day)
&& !TU.day.equals(day)
&& !WE.day.equals(day)
&& !TH.day.equals(day)
&& !FR.day.equals(day)
&& !SA.day.equals(day)) {
throw new IllegalArgumentException("Invalid day: " + day);
}
}
/**
* @return Returns the day.
*/
public final Day getDay() {
return day;
}
/**
* @return Returns the offset.
*/
public final int getOffset() {
return offset;
}
/**
* {@inheritDoc}
*/
public final String toString() {
final StringBuilder b = new StringBuilder();
if (getOffset() != 0) {
b.append(getOffset());
}
b.append(getDay());
return b.toString();
}
public static WeekDay getWeekDay(Day day) {
switch (day) {
case SU: return SU;
case MO: return MO;
case TU: return TU;
case WE: return WE;
case TH: return TH;
case FR: return FR;
case SA: return SA;
default: return null;
}
}
/**
* Returns a weekday representation of the specified calendar.
* @param cal a calendar (java.util)
* @return a weekday instance representing the specified calendar
*/
public static WeekDay getWeekDay(final Calendar cal) {
return new WeekDay(getDay(cal.get(Calendar.DAY_OF_WEEK)), 0);
}
/**
* Returns a weekday/offset representation of the specified calendar.
* @param cal a calendar (java.util)
* @return a weekday instance representing the specified calendar
*/
public static WeekDay getMonthlyOffset(final Calendar cal) {
return new WeekDay(getDay(cal.get(Calendar.DAY_OF_WEEK)), cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
}
/**
* Returns a weekday/negative offset representation of the specified calendar.
* @param cal a calendar (java.util)
* @return a weekday instance representing the specified calendar
*/
public static WeekDay getNegativeMonthlyOffset(final Calendar cal) {
Calendar calClone = (Calendar) cal.clone();
int delta = -1;
do {
calClone.add(7, Calendar.DAY_OF_YEAR);
if(calClone.get(Calendar.MONTH)==cal.get(Calendar.MONTH)) {
delta -= 1;
}else {
break;
}
}while(delta>-5);
return new WeekDay(getDay(cal.get(Calendar.DAY_OF_WEEK)), delta);
}
/**
* Returns the corresponding day constant to the specified
* java.util.Calendar.DAY_OF_WEEK property.
* @param calDay a property value of java.util.Calendar.DAY_OF_WEEK
* @return a string, or null if an invalid DAY_OF_WEEK property is
* specified
*/
public static WeekDay getDay(final int calDay) {
WeekDay day = null;
switch (calDay) {
case Calendar.SUNDAY:
day = SU;
break;
case Calendar.MONDAY:
day = MO;
break;
case Calendar.TUESDAY:
day = TU;
break;
case Calendar.WEDNESDAY:
day = WE;
break;
case Calendar.THURSDAY:
day = TH;
break;
case Calendar.FRIDAY:
day = FR;
break;
case Calendar.SATURDAY:
day = SA;
break;
default:
break;
}
return day;
}
/**
* Returns the corresponding <code>java.util.Calendar.DAY_OF_WEEK</code>
* constant for the specified <code>WeekDay</code>.
* @param weekday a week day instance
* @return the corresponding <code>java.util.Calendar</code> day
*/
public static int getCalendarDay(final WeekDay weekday) {
int calendarDay = -1;
if (SU.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.SUNDAY;
}
else if (MO.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.MONDAY;
}
else if (TU.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.TUESDAY;
}
else if (WE.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.WEDNESDAY;
}
else if (TH.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.THURSDAY;
}
else if (FR.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.FRIDAY;
}
else if (SA.getDay().equals(weekday.getDay())) {
calendarDay = Calendar.SATURDAY;
}
return calendarDay;
}
/**
* {@inheritDoc}
*/
public final boolean equals(final Object arg0) {
if (arg0 == null) {
return false;
}
if (!(arg0 instanceof WeekDay)) {
return false;
}
final WeekDay wd = (WeekDay) arg0;
return Objects.equals(wd.getDay(), getDay())
&& wd.getOffset() == getOffset();
}
/**
* {@inheritDoc}
*/
public final int hashCode() {
return new HashCodeBuilder().append(getDay())
.append(getOffset()).toHashCode();
}
}
|
|
/*
* 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.
*/
/**
* @author Evgeniya G. Maenkova
* @version $Revision$
*/
package javax.swing.text;
import java.awt.Color;
import java.awt.Rectangle;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.SwingTestCase;
import javax.swing.SwingUtilities;
import junit.framework.AssertionFailedError;
public class DefaultFormatterTest extends SwingTestCase {
DefaultFormatter formatter;
JFormattedTextField ftf;
boolean bWasException;
String message;
AssertionFailedError assertion;
@Override
protected void setUp() throws Exception {
super.setUp();
formatter = new DefaultFormatter();
ftf = new JFormattedTextField();
bWasException = false;
message = null;
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testClone() {
Object clone = null;
formatter.install(ftf);
formatter.setValueClass(Integer.class);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
formatter.setOverwriteMode(false);
try {
clone = formatter.clone();
} catch (CloneNotSupportedException e) {
assertFalse("Unexpected exception: " + e.getMessage(), true);
}
assertTrue(clone instanceof DefaultFormatter);
DefaultFormatter form = (DefaultFormatter) clone;
assertEquals(Integer.class, form.getValueClass());
assertFalse(form.getAllowsInvalid());
assertTrue(form.getCommitsOnValidEdit());
assertFalse(form.getOverwriteMode());
}
public void testGetDocumentFilter() {
assertNotNull(formatter.getDocumentFilter());
}
public void testValueToString() {
Object value = Color.RED;
try {
assertEquals(value.toString(), formatter.valueToString(value));
value = "just value";
assertEquals(value.toString(), formatter.valueToString(value));
value = new Integer(123);
assertEquals(value.toString(), formatter.valueToString(value));
} catch (ParseException e) {
assertTrue("Unexpected exception: " + e.getMessage(), false);
}
}
public void testDefaultFormatter() {
assertNull(formatter.getValueClass());
assertTrue(formatter.getAllowsInvalid());
assertFalse(formatter.getCommitsOnValidEdit());
assertTrue(formatter.getOverwriteMode());
}
public void testSetGetAllowsInvalid_NumberFormatter() {
String text = "444555666";
ftf.setValue(new Integer(334580));
NumberFormatter numFormatter = (NumberFormatter) ftf.getFormatter();
ftf.setText(text);
assertEquals(text, ftf.getText());
text = "111222333";
numFormatter.setAllowsInvalid(false);
ftf.setText(text);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
assertEquals(NumberFormat.getNumberInstance()
.format(new Integer(111222333)), ftf.getText());
} catch (AssertionFailedError e) {
assertion = e;
}
}
});
if (assertion != null) {
throw assertion;
}
}
public void testSetGetCommitsOnValidEdit_NumberFormatter() {
ftf.setValue(new Integer(334580));
formatter = (DefaultFormatter) ftf.getFormatter();
ftf.setText("567");
assertEquals(new Integer(334580), ftf.getValue());
formatter.setCommitsOnValidEdit(true);
assertTrue(formatter.getCommitsOnValidEdit());
ftf.setText("123456");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
assertEquals(new Long(123456), ftf.getValue());
} catch (AssertionFailedError e) {
assertion = e;
}
}
});
if (assertion != null) {
throw assertion;
}
}
public void testSetGetCommitsOnValidEdit() {
ftf.setValue(Boolean.TRUE);
formatter = (DefaultFormatter) ftf.getFormatter();
ftf.setText("false");
assertEquals(Boolean.TRUE, ftf.getValue());
formatter.setCommitsOnValidEdit(true);
assertTrue(formatter.getCommitsOnValidEdit());
ftf.setText("false");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
assertEquals(Boolean.FALSE, ftf.getValue());
} catch (AssertionFailedError e) {
assertion = e;
}
}
});
if (assertion != null) {
throw assertion;
}
}
public void testSetGetOverwriteMode_NumberFormatter() {
ftf.setValue(new Integer(334580));
NumberFormatter numFormatter = (NumberFormatter) ftf.getFormatter();
try {
AbstractDocument doc = (AbstractDocument) ftf.getDocument();
ftf.setText("00");
doc.insertString(0, "123", null);
assertEquals("12300", ftf.getText());
doc.insertString(0, "456", null);
assertEquals("45612300", ftf.getText());
numFormatter.setOverwriteMode(true);
doc.insertString(0, "789", null);
assertEquals("78912300", ftf.getText());
doc.insertString(3, "xxx", null);
assertEquals("789xxx00", ftf.getText());
assertEquals(numFormatter, ftf.getFormatter());
} catch (BadLocationException e) {
assertTrue("Unexpected exception: " + e.getMessage(), false);
}
}
public void testSetGetOverwriteMode() {
ftf.setValue(Boolean.FALSE);
DefaultFormatter formatter = (DefaultFormatter) ftf.getFormatter();
try {
AbstractDocument doc = (AbstractDocument) ftf.getDocument();
ftf.setText("00");
doc.insertString(0, "123", null);
assertEquals("123", ftf.getText());
doc.insertString(0, "456", null);
assertEquals("456", ftf.getText());
formatter.setOverwriteMode(false);
doc.insertString(0, "789", null);
assertEquals("789456", ftf.getText());
doc.insertString(3, "xxx", null);
assertEquals("789xxx456", ftf.getText());
assertEquals(formatter, ftf.getFormatter());
} catch (BadLocationException e) {
assertTrue("Unexpected exception: " + e.getMessage(), false);
}
}
public void testStringToValue() {
formatter.install(ftf);
assertNull(ftf.getValue());
assertNull(formatter.getValueClass());
try {
assertEquals("java.lang.String", formatter.stringToValue("546").getClass()
.getName());
ftf.setValue(Boolean.TRUE);
assertEquals("java.lang.Boolean", formatter.stringToValue("true").getClass()
.getName());
formatter.setValueClass(Float.class);
assertEquals("java.lang.Float", formatter.stringToValue("546").getClass().getName());
formatter.setValueClass(Rectangle.class);
assertEquals("java.lang.String", formatter.stringToValue("546").getClass()
.getName());
} catch (ParseException e) {
assertTrue("Unexpected exception: " + e.getMessage(), false);
}
try {
formatter.setValueClass(Integer.class);
formatter.stringToValue("ttt");
} catch (ParseException e) {
bWasException = true;
message = e.getMessage();
}
assertTrue(bWasException);
assertEquals("Error creating instance", message);
}
public void testSetGetValueClass() {
assertNull(formatter.getValueClass());
formatter.setValueClass(Rectangle.class);
assertEquals(Rectangle.class, formatter.getValueClass());
}
}
|
|
/*
* 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.hcatalog.templeton;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.web.AuthFilter;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.GenericOptionsParser;
import org.eclipse.jetty.rewrite.handler.RedirectPatternRule;
import org.eclipse.jetty.rewrite.handler.RewriteHandler;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.bridge.SLF4JBridgeHandler;
/**
* The main executable that starts up and runs the Server.
*/
public class Main {
public static final String SERVLET_PATH = "templeton";
private static final Log LOG = LogFactory.getLog(Main.class);
public static final int DEFAULT_PORT = 8080;
private static volatile AppConfig conf;
/**
* Retrieve the config singleton.
*/
public static synchronized AppConfig getAppConfigInstance() {
if (conf == null)
LOG.error("Bug: configuration not yet loaded");
return conf;
}
public Main(String[] args) {
init(args);
}
public void init(String[] args) {
initLogger();
conf = loadConfig(args);
conf.startCleanup();
LOG.debug("Loaded conf " + conf);
}
// Jersey uses java.util.logging - bridge to slf4
private void initLogger() {
java.util.logging.Logger rootLogger
= java.util.logging.LogManager.getLogManager().getLogger("");
for (java.util.logging.Handler h : rootLogger.getHandlers())
rootLogger.removeHandler(h);
SLF4JBridgeHandler.install();
}
public AppConfig loadConfig(String[] args) {
AppConfig cf = new AppConfig();
try {
GenericOptionsParser parser = new GenericOptionsParser(cf, args);
if (parser.getRemainingArgs().length > 0)
usage();
} catch (IOException e) {
LOG.error("Unable to parse options: " + e);
usage();
}
return cf;
}
public void usage() {
System.err.println("usage: templeton [-Dtempleton.port=N] [-D...]");
System.exit(1);
}
public void run() {
int port = conf.getInt(AppConfig.PORT, DEFAULT_PORT);
try {
checkEnv();
runServer(port);
System.out.println("templeton: listening on port " + port);
LOG.info("Templeton listening on port " + port);
} catch (Exception e) {
System.err.println("templeton: Server failed to start: " + e.getMessage());
LOG.fatal("Server failed to start: " + e);
System.exit(1);
}
}
private void checkEnv() {
checkCurrentDirPermissions();
}
private void checkCurrentDirPermissions() {
//org.apache.commons.exec.DefaultExecutor requires
// that current directory exists
File pwd = new File(".");
if(!pwd.exists()){
String msg = "Server failed to start: templeton: Current working directory '.' does not exist!";
System.err.println(msg);
LOG.fatal( msg);
System.exit(1);
}
}
public Server runServer(int port)
throws Exception
{
//Authenticate using keytab
if(UserGroupInformation.isSecurityEnabled()){
UserGroupInformation.loginUserFromKeytab(conf.kerberosPrincipal(),
conf.kerberosKeytab());
}
// Create the Jetty server
Server server = new Server(port);
ServletContextHandler root = new ServletContextHandler(server, "/");
// Add the Auth filter
root.addFilter(makeAuthFilter(), "/*", FilterMapping.REQUEST);
// Connect Jersey
ServletHolder h = new ServletHolder(new ServletContainer(makeJerseyConfig()));
root.addServlet(h, "/" + SERVLET_PATH + "/*");
// Add any redirects
addRedirects(server);
// Start the server
server.start();
return server;
}
// Configure the AuthFilter with the Kerberos params iff security
// is enabled.
public FilterHolder makeAuthFilter() {
FilterHolder authFilter = new FilterHolder(AuthFilter.class);
if (UserGroupInformation.isSecurityEnabled()) {
authFilter.setInitParameter("dfs.web.authentication.signature.secret",
conf.kerberosSecret());
authFilter.setInitParameter("dfs.web.authentication.kerberos.principal",
conf.kerberosPrincipal());
authFilter.setInitParameter("dfs.web.authentication.kerberos.keytab",
conf.kerberosKeytab());
}
return authFilter;
}
public PackagesResourceConfig makeJerseyConfig() {
PackagesResourceConfig rc
= new PackagesResourceConfig("org.apache.hcatalog.templeton");
HashMap<String, Object> props = new HashMap<String, Object>();
props.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
props.put("com.sun.jersey.config.property.WadlGeneratorConfig",
"org.apache.hcatalog.templeton.WadlConfig");
rc.setPropertiesAndFeatures(props);
return rc;
}
public void addRedirects(Server server) {
RewriteHandler rewrite = new RewriteHandler();
RedirectPatternRule redirect = new RedirectPatternRule();
redirect.setPattern("/templeton/v1/application.wadl");
redirect.setLocation("/templeton/application.wadl");
rewrite.addRule(redirect);
HandlerList handlerlist = new HandlerList();
ArrayList<Handler> handlers = new ArrayList<Handler>();
// Any redirect handlers need to be added first
handlers.add(rewrite);
// Now add all the default handlers
for (Handler handler : server.getHandlers()) {
handlers.add(handler);
}
Handler[] newlist = new Handler[handlers.size()];
handlerlist.setHandlers(handlers.toArray(newlist));
server.setHandler(handlerlist);
}
public static void main(String[] args) {
Main templeton = new Main(args);
templeton.run();
}
}
|
|
package org.antlr.intellij.plugin.configdialogs;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import org.antlr.intellij.plugin.parsing.RunANTLROnGrammarFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import static com.google.common.base.MoreObjects.firstNonNull;
public class ConfigANTLRPerGrammar extends DialogWrapper {
public static final String PROP_LANGUAGE = "language";
private JPanel dialogContents;
private JCheckBox generateParseTreeListenerCheckBox;
private JCheckBox generateParseTreeVisitorCheckBox;
private JTextField packageField;
private TextFieldWithBrowseButton outputDirField;
private TextFieldWithBrowseButton libDirField;
private JTextField fileEncodingField;
protected JCheckBox autoGenerateParsersCheckBox;
protected JTextField languageField;
public ConfigANTLRPerGrammar(final Project project, String qualFileName) {
super(project, false);
init();
FileChooserDescriptor dirChooser =
FileChooserDescriptorFactory.createSingleFolderDescriptor();
outputDirField.addBrowseFolderListener("Select output dir", null, project, dirChooser);
outputDirField.setTextFieldPreferredWidth(50);
dirChooser =
FileChooserDescriptorFactory.createSingleFolderDescriptor();
libDirField.addBrowseFolderListener("Select lib dir", null, project, dirChooser);
libDirField.setTextFieldPreferredWidth(50);
loadValues(project, qualFileName);
}
public static String getOutputDirName(Project project, String qualFileName, VirtualFile contentRoot, String package_) {
String outputDirName = firstNonNull(
getSettings(project, qualFileName).outputDir,
RunANTLROnGrammarFile.OUTPUT_DIR_NAME
);
File f = new File(outputDirName);
if ( !f.isAbsolute() ) { // if not absolute file spec, it's relative to project root
outputDirName = contentRoot.getPath()+File.separator+outputDirName;
}
// add package if any
if ( package_!=RunANTLROnGrammarFile.MISSING ) {
outputDirName += File.separator+package_.replace('.', File.separatorChar);
}
return outputDirName;
}
@Deprecated
private static String getPropNameForFile(String qualFileName, String prop) {
return qualFileName+"::/"+prop;
}
public static String getParentDir(VirtualFile vfile) {
return vfile.getParent().getPath();
}
public static VirtualFile getContentRoot(Project project, VirtualFile vfile) {
VirtualFile root =
ProjectRootManager.getInstance(project)
.getFileIndex().getContentRootForFile(vfile);
if ( root!=null ) return root;
return vfile.getParent();
}
public static PerGrammarGenerationSettings getSettings(Project project, String qualFileName) {
PerGrammarGenerationSettings settings = ANTLRGenerationSettingsComponent.getInstance(project)
.getSettings().findSettingsForFile(qualFileName);
migrateOldSettingsIfNeeded(project, qualFileName, settings);
return settings;
}
@SuppressWarnings("deprecation")
private static void migrateOldSettingsIfNeeded(Project project, String qualFileName,
PerGrammarGenerationSettings newSettings) {
PropertiesComponent props = PropertiesComponent.getInstance(project);
String v;
if ((v = props.getValue(getPropNameForFile(qualFileName, "output-dir"))) != null) {
newSettings.outputDir = v;
}
props.unsetValue(getPropNameForFile(qualFileName, "output-dir"));
if ((v = props.getValue(getPropNameForFile(qualFileName, "lib-dir"))) != null) {
newSettings.libDir = v;
}
props.unsetValue(getPropNameForFile(qualFileName, "lib-dir"));
if ((v = props.getValue(getPropNameForFile(qualFileName, "encoding"))) != null) {
newSettings.encoding = v;
}
props.unsetValue(getPropNameForFile(qualFileName, "encoding"));
if ((v = props.getValue(getPropNameForFile(qualFileName, "package"))) != null) {
newSettings.pkg = v;
}
props.unsetValue(getPropNameForFile(qualFileName, "package"));
if ((v = props.getValue(getPropNameForFile(qualFileName, "language"))) != null) {
newSettings.language = v;
}
props.unsetValue(getPropNameForFile(qualFileName, "language"));
if (props.isValueSet(getPropNameForFile(qualFileName, "auto-gen"))) {
newSettings.autoGen = props.getBoolean(getPropNameForFile(qualFileName, "auto-gen"));
props.unsetValue(getPropNameForFile(qualFileName, "auto-gen"));
}
if (props.isValueSet(getPropNameForFile(qualFileName, "gen-listener"))) {
newSettings.generateListener = props.getBoolean(getPropNameForFile(qualFileName, "gen-listener"));
props.unsetValue(getPropNameForFile(qualFileName, "gen-listener"));
}
if (props.isValueSet(getPropNameForFile(qualFileName, "gen-visitor"))) {
newSettings.generateVisitor = props.getBoolean(getPropNameForFile(qualFileName, "gen-visitor"));
props.unsetValue(getPropNameForFile(qualFileName, "gen-visitor"));
}
}
private void loadValues(Project project, String qualFileName) {
PerGrammarGenerationSettings settings = getSettings(project, qualFileName);
autoGenerateParsersCheckBox.setSelected(settings.autoGen);
outputDirField.setText(settings.outputDir);
libDirField.setText(settings.libDir);
fileEncodingField.setText(settings.encoding);
packageField.setText(settings.pkg);
languageField.setText(settings.language);
generateParseTreeListenerCheckBox.setSelected(settings.generateListener);
generateParseTreeVisitorCheckBox.setSelected(settings.generateVisitor);
}
@Nullable
private String trim(@NotNull String val) {
return val.trim().equals("") ? null : val;
}
public void saveValues(Project project, String qualFileName) {
PerGrammarGenerationSettings settings = getSettings(project, qualFileName);
settings.autoGen = autoGenerateParsersCheckBox.isSelected();
settings.outputDir = trim(outputDirField.getText());
settings.libDir = trim(libDirField.getText());
settings.encoding = trim(fileEncodingField.getText());
settings.pkg = trim(packageField.getText());
settings.language = trim(languageField.getText());
settings.generateListener = generateParseTreeListenerCheckBox.isSelected();
settings.generateVisitor = generateParseTreeVisitorCheckBox.isSelected();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return dialogContents;
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
@Override
public String toString() {
return "ConfigANTLRPerGrammar{"+
"textField3="+
", generateParseTreeListenerCheckBox="+generateParseTreeListenerCheckBox+
", generateParseTreeVisitorCheckBox="+generateParseTreeVisitorCheckBox+
", packageField="+packageField+
", outputDirField="+outputDirField+
", libDirField="+libDirField+
'}';
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
dialogContents = new JPanel();
dialogContents.setLayout(new GridLayoutManager(8, 2, new Insets(0, 0, 0, 0), -1, -1));
final JLabel label1 = new JLabel();
label1.setText("Location of imported grammars");
dialogContents.add(label1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false));
final JLabel label2 = new JLabel();
label2.setText("Grammar file encoding; e.g., euc-jp");
dialogContents.add(label2, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false));
fileEncodingField = new JTextField();
dialogContents.add(fileEncodingField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
generateParseTreeVisitorCheckBox = new JCheckBox();
generateParseTreeVisitorCheckBox.setText("generate parse tree visitor");
dialogContents.add(generateParseTreeVisitorCheckBox, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
generateParseTreeListenerCheckBox = new JCheckBox();
generateParseTreeListenerCheckBox.setSelected(true);
generateParseTreeListenerCheckBox.setText("generate parse tree listener (default)");
dialogContents.add(generateParseTreeListenerCheckBox, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Package/namespace for the generated code");
dialogContents.add(label3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false));
packageField = new JTextField();
dialogContents.add(packageField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Output directory where all output is generated");
dialogContents.add(label4, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false));
outputDirField = new TextFieldWithBrowseButton();
dialogContents.add(outputDirField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
libDirField = new TextFieldWithBrowseButton();
dialogContents.add(libDirField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
autoGenerateParsersCheckBox = new JCheckBox();
autoGenerateParsersCheckBox.setText("Auto-generate parsers upon save");
dialogContents.add(autoGenerateParsersCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Language (e.g., Java, Python2, CSharp, ...)");
dialogContents.add(label5, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false));
languageField = new JTextField();
dialogContents.add(languageField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return dialogContents;
}
}
|
|
// 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.find.impl.livePreview;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.find.FindManager;
import com.intellij.find.FindModel;
import com.intellij.find.FindResult;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
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.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.PositionTracker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.PrintStream;
import java.util.*;
import java.util.List;
public class LivePreview implements SearchResults.SearchResultsListener, SelectionListener, DocumentListener, EditorColorsListener {
private static final Key<RangeHighlighter> IN_SELECTION_KEY = Key.create("LivePreview.IN_SELECTION_KEY");
private static final String EMPTY_STRING_DISPLAY_TEXT = "<Empty string>";
private final Disposable myDisposable = Disposer.newDisposable("livePreview");
private boolean mySuppressedUpdate = false;
private static final Key<Boolean> MARKER_USED = Key.create("LivePreview.MARKER_USED");
private static final Key<Boolean> SEARCH_MARKER = Key.create("LivePreview.SEARCH_MARKER");
public static PrintStream ourTestOutput;
private String myReplacementPreviewText;
private static boolean NotFound;
private final List<RangeHighlighter> myHighlighters = new ArrayList<>();
private RangeHighlighter myCursorHighlighter;
private VisibleAreaListener myVisibleAreaListener;
private Delegate myDelegate;
private final SearchResults mySearchResults;
private Balloon myReplacementBalloon;
@Override
public void selectionChanged(@NotNull SelectionEvent e) {
updateInSelectionHighlighters();
}
public static void processNotFound() {
NotFound = true;
}
public interface Delegate {
@Nullable
String getStringToReplace(@NotNull Editor editor, @Nullable FindResult findResult)
throws FindManager.MalformedReplacementStringException;
}
@Override
public void searchResultsUpdated(@NotNull SearchResults sr) {
if (mySuppressedUpdate) {
mySuppressedUpdate = false;
return;
}
highlightUsages();
updateCursorHighlighting();
}
private void dumpState() {
if (ApplicationManager.getApplication().isUnitTestMode() && ourTestOutput != null) {
dumpEditorMarkupAndSelection(ourTestOutput);
}
}
private void dumpEditorMarkupAndSelection(PrintStream dumpStream) {
dumpStream.println(mySearchResults.getFindModel());
if (myReplacementPreviewText != null) {
dumpStream.println("--");
dumpStream.println("Replacement Preview: " + myReplacementPreviewText);
}
dumpStream.println("--");
Editor editor = mySearchResults.getEditor();
RangeHighlighter[] highlighters = editor.getMarkupModel().getAllHighlighters();
Arrays.sort(highlighters, Segment.BY_START_OFFSET_THEN_END_OFFSET);
List<Pair<Integer, Character>> ranges = new ArrayList<>();
for (RangeHighlighter highlighter : highlighters) {
ranges.add(new Pair<>(highlighter.getStartOffset(), '['));
ranges.add(new Pair<>(highlighter.getEndOffset(), ']'));
}
SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.getSelectionStart() != selectionModel.getSelectionEnd()) {
ranges.add(new Pair<>(selectionModel.getSelectionStart(), '<'));
ranges.add(new Pair<>(selectionModel.getSelectionEnd(), '>'));
}
ranges.add(new Pair<>(-1, '\n'));
ranges.add(new Pair<>(editor.getDocument().getTextLength() + 1, '\n'));
ContainerUtil.sort(ranges, (pair, pair2) -> {
int res = pair.first - pair2.first;
if (res == 0) {
Character c1 = pair.second;
Character c2 = pair2.second;
if (c1 == '<' && c2 == '[') {
return 1;
}
else if (c1 == '[' && c2 == '<') {
return -1;
}
return c1.compareTo(c2);
}
return res;
});
Document document = editor.getDocument();
for (int i = 0; i < ranges.size()-1; ++i) {
Pair<Integer, Character> pair = ranges.get(i);
Pair<Integer, Character> pair1 = ranges.get(i + 1);
dumpStream.print(pair.second + document.getText(TextRange.create(Math.max(pair.first, 0),
Math.min(pair1.first, document.getTextLength()))));
}
dumpStream.println("\n--");
if (NotFound) {
dumpStream.println("Not Found");
dumpStream.println("--");
NotFound = false;
}
for (RangeHighlighter highlighter : highlighters) {
dumpStream.println(highlighter + " : " + highlighter.getTextAttributes());
}
dumpStream.println("------------");
}
private void clearUnusedHighlighters() {
myHighlighters.removeIf(h -> {
if (h.getUserData(MARKER_USED) == null) {
removeHighlighterWithDependent(h);
return true;
}
else {
h.putUserData(MARKER_USED, null);
return false;
}
});
}
private void removeHighlighterWithDependent(@NotNull RangeHighlighter highlighter) {
removeHighlighter(highlighter);
RangeHighlighter additionalHighlighter = highlighter.getUserData(IN_SELECTION_KEY);
if (additionalHighlighter != null) {
removeHighlighter(additionalHighlighter);
}
}
@Override
public void cursorMoved() {
updateInSelectionHighlighters();
updateCursorHighlighting();
}
@Override
public void updateFinished() {
dumpState();
}
private void updateCursorHighlighting() {
hideBalloon();
if (myCursorHighlighter != null) {
removeHighlighter(myCursorHighlighter);
myCursorHighlighter = null;
}
final FindResult cursor = mySearchResults.getCursor();
Editor editor = mySearchResults.getEditor();
if (cursor != null && cursor.getEndOffset() <= editor.getDocument().getTextLength()) {
Color color = editor.getColorsScheme().getColor(EditorColors.CARET_COLOR);
myCursorHighlighter = addHighlighter(cursor.getStartOffset(), cursor.getEndOffset(),
new TextAttributes(null, null, color, EffectType.ROUNDED_BOX, Font.PLAIN));
editor.getScrollingModel().runActionOnScrollingFinished(() -> showReplacementPreview());
}
}
public LivePreview(@NotNull SearchResults searchResults) {
mySearchResults = searchResults;
searchResultsUpdated(searchResults);
searchResults.addListener(this);
EditorUtil.addBulkSelectionListener(mySearchResults.getEditor(), this, myDisposable);
ApplicationManager.getApplication().getMessageBus().connect(myDisposable).subscribe(EditorColorsManager.TOPIC, this);
}
public Delegate getDelegate() {
return myDelegate;
}
public void setDelegate(Delegate delegate) {
myDelegate = delegate;
}
@Override
public void globalSchemeChange(@Nullable EditorColorsScheme scheme) {
highlightUsages();
updateCursorHighlighting();
}
public void dispose() {
hideBalloon();
for (RangeHighlighter h : myHighlighters) {
removeHighlighterWithDependent(h);
}
myHighlighters.clear();
if (myCursorHighlighter != null) {
removeHighlighter(myCursorHighlighter);
}
myCursorHighlighter = null;
Disposer.dispose(myDisposable);
mySearchResults.removeListener(this);
}
private void highlightUsages() {
List<RangeHighlighter> newHighlighters = mySearchResults.getMatchesCount() < mySearchResults.getMatchesLimit()
? addNewHighlighters() : Collections.emptyList();
clearUnusedHighlighters();
myHighlighters.addAll(newHighlighters);
updateInSelectionHighlighters();
}
private List<RangeHighlighter> addNewHighlighters() {
List<FindResult> occurrences = mySearchResults.getOccurrences();
List<RangeHighlighter> newHighlighters = new ArrayList<>(occurrences.size());
for (FindResult range : occurrences) {
if (range.getEndOffset() > mySearchResults.getEditor().getDocument().getTextLength()) continue;
TextAttributes attributes = createAttributes(range);
RangeHighlighter existingHighlighter = findExistingHighlighter(range.getStartOffset(), range.getEndOffset(), attributes);
if (existingHighlighter == null) {
RangeHighlighter highlighter = addHighlighter(range.getStartOffset(), range.getEndOffset(), attributes);
if (highlighter != null) {
highlighter.putUserData(SEARCH_MARKER, Boolean.TRUE);
newHighlighters.add(highlighter);
}
}
else {
existingHighlighter.putUserData(MARKER_USED, Boolean.TRUE);
}
}
return newHighlighters;
}
private TextAttributes createAttributes(FindResult range) {
EditorColorsScheme colorsScheme = mySearchResults.getEditor().getColorsScheme();
if (mySearchResults.isExcluded(range)) {
return new TextAttributes(null, null, colorsScheme.getDefaultForeground(), EffectType.STRIKEOUT, Font.PLAIN);
}
TextAttributes attributes = colorsScheme.getAttributes(EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES);
if (range.getLength() == 0) {
attributes = attributes.clone();
attributes.setEffectType(EffectType.BOXED);
attributes.setEffectColor(attributes.getBackgroundColor());
}
return attributes;
}
private RangeHighlighter findExistingHighlighter(int startOffset, int endOffset, TextAttributes attributes) {
MarkupModelEx markupModel = (MarkupModelEx)mySearchResults.getEditor().getMarkupModel();
RangeHighlighter[] existing = new RangeHighlighter[1];
markupModel.processRangeHighlightersOverlappingWith(startOffset, startOffset, highlighter -> {
if (highlighter.getUserData(SEARCH_MARKER) != null &&
highlighter.getStartOffset() == startOffset && highlighter.getEndOffset() == endOffset &&
Objects.equals(highlighter.getTextAttributes(), attributes)) {
existing[0] = highlighter;
return false;
}
return true;
});
return existing[0];
}
private void updateInSelectionHighlighters() {
final SelectionModel selectionModel = mySearchResults.getEditor().getSelectionModel();
int[] starts = selectionModel.getBlockSelectionStarts();
int[] ends = selectionModel.getBlockSelectionEnds();
for (RangeHighlighter highlighter : myHighlighters) {
if (!highlighter.isValid()) continue;
boolean needsAdditionalHighlighting = false;
TextRange cursor = mySearchResults.getCursor();
if (cursor == null ||
highlighter.getStartOffset() != cursor.getStartOffset() || highlighter.getEndOffset() != cursor.getEndOffset()) {
for (int i = 0; i < starts.length; ++i) {
TextRange selectionRange = new TextRange(starts[i], ends[i]);
needsAdditionalHighlighting = selectionRange.intersects(highlighter.getStartOffset(), highlighter.getEndOffset()) &&
selectionRange.getEndOffset() != highlighter.getStartOffset() &&
highlighter.getEndOffset() != selectionRange.getStartOffset();
if (needsAdditionalHighlighting) break;
}
}
RangeHighlighter inSelectionHighlighter = highlighter.getUserData(IN_SELECTION_KEY);
if (inSelectionHighlighter != null) {
if (!needsAdditionalHighlighting) {
removeHighlighter(inSelectionHighlighter);
}
} else if (needsAdditionalHighlighting) {
RangeHighlighter additionalHighlighter = addHighlighter(highlighter.getStartOffset(), highlighter.getEndOffset(),
new TextAttributes(null, null,
Color.WHITE, EffectType.ROUNDED_BOX, Font.PLAIN));
highlighter.putUserData(IN_SELECTION_KEY, additionalHighlighter);
}
}
}
private void showReplacementPreview() {
hideBalloon();
if (!mySearchResults.isUpToDate()) return;
final FindResult cursor = mySearchResults.getCursor();
final Editor editor = mySearchResults.getEditor();
final FindModel findModel = mySearchResults.getFindModel();
if (myDelegate != null && cursor != null && findModel.isReplaceState() && findModel.isRegularExpressions()) {
String replacementPreviewText;
try {
replacementPreviewText = myDelegate.getStringToReplace(editor, cursor);
}
catch (FindManager.MalformedReplacementStringException e) {
return;
}
if (replacementPreviewText == null) {
return;//malformed replacement string
}
if (Registry.is("ide.find.show.replacement.hint.for.simple.regexp")) {
showBalloon(editor, replacementPreviewText.isEmpty() ? EMPTY_STRING_DISPLAY_TEXT : replacementPreviewText);
}
else if (!replacementPreviewText.equals(findModel.getStringToReplace())) {
showBalloon(editor, replacementPreviewText);
}
}
}
private void showBalloon(Editor editor, String replacementPreviewText) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
myReplacementPreviewText = replacementPreviewText;
return;
}
ReplacementView replacementView = new ReplacementView(replacementPreviewText);
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createBalloonBuilder(replacementView);
balloonBuilder.setFadeoutTime(0);
balloonBuilder.setFillColor(IdeTooltipManager.GRAPHITE_COLOR);
balloonBuilder.setAnimationCycle(0);
balloonBuilder.setHideOnClickOutside(false);
balloonBuilder.setHideOnKeyOutside(false);
balloonBuilder.setHideOnAction(false);
balloonBuilder.setCloseButtonEnabled(true);
myReplacementBalloon = balloonBuilder.createBalloon();
EditorUtil.disposeWithEditor(editor, myReplacementBalloon);
myReplacementBalloon.show(new ReplacementBalloonPositionTracker(editor), Balloon.Position.below);
}
private void hideBalloon() {
if (ApplicationManager.getApplication().isUnitTestMode()) {
myReplacementPreviewText = null;
return;
}
if (myReplacementBalloon != null) {
myReplacementBalloon.hide();
myReplacementBalloon = null;
}
removeVisibleAreaListener();
}
private void removeVisibleAreaListener() {
if (myVisibleAreaListener != null) {
mySearchResults.getEditor().getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener);
myVisibleAreaListener = null;
}
}
private RangeHighlighter addHighlighter(int startOffset, int endOffset, @NotNull TextAttributes attributes) {
Project project = mySearchResults.getProject();
if (project == null || project.isDisposed()) return null;
List<RangeHighlighter> sink = new ArrayList<>();
HighlightManager.getInstance(project).addRangeHighlight(mySearchResults.getEditor(), startOffset, endOffset, attributes, false, sink);
RangeHighlighter result = ContainerUtil.getFirstItem(sink);
if (result instanceof RangeHighlighterEx) ((RangeHighlighterEx)result).setVisibleIfFolded(true);
return result;
}
private void removeHighlighter(@NotNull RangeHighlighter highlighter) {
Project project = mySearchResults.getProject();
if (project == null || project.isDisposed()) return;
HighlightManager.getInstance(project).removeSegmentHighlighter(mySearchResults.getEditor(), highlighter);
}
private class ReplacementBalloonPositionTracker extends PositionTracker<Balloon> {
private final Editor myEditor;
ReplacementBalloonPositionTracker(Editor editor) {
super(editor.getContentComponent());
myEditor = editor;
}
@Override
public RelativePoint recalculateLocation(final Balloon object) {
FindResult cursor = mySearchResults.getCursor();
if (cursor == null) return null;
final TextRange cur = cursor;
int startOffset = cur.getStartOffset();
int endOffset = cur.getEndOffset();
if (endOffset > myEditor.getDocument().getTextLength()) {
if (!object.isDisposed()) {
requestBalloonHiding(object);
}
return null;
}
if (!SearchResults.insideVisibleArea(myEditor, cur)) {
requestBalloonHiding(object);
removeVisibleAreaListener();
myVisibleAreaListener = new VisibleAreaListener() {
@Override
public void visibleAreaChanged(@NotNull VisibleAreaEvent e) {
if (SearchResults.insideVisibleArea(myEditor, cur)) {
showReplacementPreview();
}
}
};
myEditor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
}
Point startPoint = myEditor.visualPositionToXY(myEditor.offsetToVisualPosition(startOffset));
Point endPoint = myEditor.visualPositionToXY(myEditor.offsetToVisualPosition(endOffset));
Point point = new Point((startPoint.x + endPoint.x)/2, startPoint.y + myEditor.getLineHeight());
return new RelativePoint(myEditor.getContentComponent(), point);
}
}
private static void requestBalloonHiding(final Balloon object) {
ApplicationManager.getApplication().invokeLater(() -> object.hide());
}
}
|
|
package com.texasgamer.zephyr.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.texasgamer.zephyr.BuildConfig;
import com.texasgamer.zephyr.Constants;
import com.texasgamer.zephyr.R;
import com.texasgamer.zephyr.model.Token;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TokenUtils {
private final String TAG = this.getClass().getSimpleName();
private static TokenUtils instance;
private Token mToken;
private long mLastCheck;
public static TokenUtils getInstance(Context context) {
if (instance == null) {
instance = new TokenUtils(context);
}
return instance;
}
private TokenUtils(Context context) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
mLastCheck = sharedPrefs.getLong(context.getString(R.string.token_last_checked_key), 0);
String token = sharedPrefs.getString(context.getString(R.string.token_key), "");
mToken = jsonToToken(token);
updateTokenFromServer(context);
}
public void saveToken(Context context, Token token) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(context.getString(R.string.token_key), token == null ? "" : token.toString())
.apply();
mToken = token;
updateTokenFromServer(context);
}
public void destroyToken(Context context) {
saveToken(context, null);
mToken = null;
mLastCheck = 0;
}
public boolean doesTokenExist() {
return mToken != null;
}
private void updateTokenFromServer(final Context context) {
if (!shouldCheckToken()) {
return;
}
Log.i(TAG, "Updating token from server...");
try {
JSONObject bodyJson = new JSONObject();
bodyJson.put("token", getToken());
bodyJson.put("device", PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.pref_device_name), context.getString(R.string.pref_default_device_name)));
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
Request request = new Request.Builder()
.header("Authorization", BuildConfig.ZEPHYR_API_KEY)
.url(Constants.ZEPHYR_BASE_WEB_URL + "/api/v2/2/verify")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
Log.i(TAG, response.body().string());
JSONObject responseBody = new JSONObject(response.body().string());
if (responseBody.getBoolean("valid")) {
Log.i(TAG, "Token valid.");
JSONObject user = responseBody.getJSONObject("user");
mToken.updateUser(user.getString("name"), user.getString("avatar"));
mLastCheck = System.currentTimeMillis();
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putLong(context.getString(R.string.token_last_checked_key), mLastCheck)
.apply();
saveToken(context, mToken);
} else {
Log.i(TAG, "Token is invalid! Destroying...");
destroyToken(context);
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, e.getMessage());
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAuthToken(final Context context) {
Log.i(TAG, "Getting auth token from server...");
try {
JSONObject bodyJson = new JSONObject();
bodyJson.put("token", getToken());
bodyJson.put("device", PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.pref_device_name), context.getString(R.string.pref_default_device_name)));
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
Request request = new Request.Builder()
.header("Authorization", BuildConfig.ZEPHYR_API_KEY)
.url(Constants.ZEPHYR_BASE_WEB_URL + "/api/v2/2/verify")
.post(body)
.build();
Response response = client.newCall(request).execute();
JSONObject responseBody = new JSONObject(response.body().string());
if (responseBody.getBoolean("valid")) {
Log.i(TAG, "Token valid. Returning auth token.");
JSONObject user = responseBody.getJSONObject("user");
mToken.updateUser(user.getString("name"), user.getString("avatar"));
mLastCheck = System.currentTimeMillis();
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putLong(context.getString(R.string.token_last_checked_key), mLastCheck)
.apply();
saveToken(context, mToken);
return responseBody.getString("jwtToken");
} else {
Log.i(TAG, "Token is invalid! Destroying...");
destroyToken(context);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private boolean shouldCheckToken() {
return doesTokenExist() && System.currentTimeMillis() - mLastCheck > Constants.ZEPHYR_TOKEN_CHECK_TIME;
}
public String getName() {
if (doesTokenExist()) {
return mToken.getName();
} else {
return null;
}
}
public String getAvatar() {
if (doesTokenExist()) {
return mToken.getAvatar();
} else {
return null;
}
}
public String getRoom() {
if (doesTokenExist()) {
return mToken.getRoom();
} else {
return null;
}
}
public String getToken() {
if (doesTokenExist()) {
return mToken.getToken();
} else {
return null;
}
}
private Token jsonToToken(String tokenString) {
if (tokenString.isEmpty()) {
return null;
} else {
try {
JSONObject tokenObj = new JSONObject(tokenString);
return new Token(tokenObj.getString("name"), tokenObj.getString("avatar"),
tokenObj.getString("room"), tokenObj.getString("token"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
|
|
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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.neo4j.backup;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.NoSuchElementException;
import org.neo4j.backup.BackupService.BackupOutcome;
import org.neo4j.com.ComException;
import org.neo4j.consistency.ConsistencyCheckSettings;
import org.neo4j.graphdb.TransactionFailureException;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.Args;
import org.neo4j.helpers.HostnamePort;
import org.neo4j.helpers.Service;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.kernel.DefaultFileSystemAbstraction;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.logging.SimpleLogService;
import org.neo4j.kernel.impl.store.MismatchingStoreIdException;
import org.neo4j.kernel.impl.storemigration.LogFiles;
import org.neo4j.kernel.impl.storemigration.StoreFile;
import org.neo4j.kernel.impl.storemigration.StoreFileType;
import org.neo4j.kernel.impl.storemigration.UpgradeNotAllowedByConfigurationException;
import org.neo4j.logging.FormattedLogProvider;
import org.neo4j.logging.NullLogProvider;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.impl.storemigration.FileOperation.MOVE;
public class BackupTool
{
private static final String TO = "to";
private static final String HOST = "host";
private static final String PORT = "port";
@Deprecated // preferred -host and -port separately
private static final String FROM = "from";
private static final String VERIFY = "verify";
private static final String CONFIG = "config";
private static final String CONSISTENCY_CHECKER = "consistency-checker";
private static final String TIMEOUT = "timeout";
private static final String FORENSICS = "gather-forensics";
public static final String DEFAULT_SCHEME = "single";
static final String MISMATCHED_STORE_ID = "You tried to perform a backup from database %s, " +
"but the target directory contained a backup from database %s. ";
static final String WRONG_FROM_ADDRESS_SYNTAX = "Please properly specify a location to backup in the" +
" form " + dash( HOST ) + " <host> " + dash( PORT ) + " <port>";
static final String UNKNOWN_SCHEMA_MESSAGE_PATTERN = "%s was specified as a backup module but it was not found. " +
"Please make sure that the implementing service is on the classpath.";
static final String NO_SOURCE_SPECIFIED = "Please specify " + dash( HOST ) + " and optionally " + dash( PORT ) +
", examples:\n" +
" " + dash( HOST ) + " 192.168.1.34\n" +
" " + dash( HOST ) + " 192.168.1.34 " + dash( PORT ) + " 1234";
public static void main( String[] args )
{
BackupTool tool = new BackupTool( new BackupService(), System.out );
try
{
BackupOutcome backupOutcome = tool.run( args );
if ( !backupOutcome.isConsistent() )
{
exitFailure( "WARNING: The database is inconsistent." );
}
}
catch ( ToolFailureException e )
{
System.out.println( "Backup failed." );
exitFailure( e.getMessage() );
}
}
private final BackupService backupService;
private final PrintStream systemOut;
private final FileSystemAbstraction fs;
BackupTool( BackupService backupService, PrintStream systemOut )
{
this.backupService = backupService;
this.systemOut = systemOut;
this.fs = new DefaultFileSystemAbstraction();
}
BackupOutcome run( String[] args ) throws ToolFailureException
{
Args arguments = Args.withFlags( VERIFY ).parse( args );
if ( !arguments.hasNonNull( TO ) )
{
throw new ToolFailureException( "Specify target location with " + dash( TO ) + " <target-directory>" );
}
if ( arguments.hasNonNull( FROM ) && !arguments.has( HOST ) && !arguments.has( PORT ) )
{
return runBackupWithLegacyArgs( arguments );
}
else if ( arguments.hasNonNull( HOST ) )
{
return runBackup( arguments );
}
else
{
throw new ToolFailureException( NO_SOURCE_SPECIFIED );
}
}
private BackupOutcome runBackupWithLegacyArgs( Args args ) throws ToolFailureException
{
String from = args.get( FROM ).trim();
String to = args.get( TO ).trim();
Config tuningConfiguration = readTuningConfiguration( args );
boolean forensics = args.getBoolean( FORENSICS, false, true );
ConsistencyCheck consistencyCheck = parseConsistencyChecker( args );
long timeout = args.getDuration( TIMEOUT, BackupClient.BIG_READ_TIMEOUT );
URI backupURI = resolveBackupUri( from, args, tuningConfiguration );
HostnamePort hostnamePort = newHostnamePort( backupURI );
return executeBackup( hostnamePort, new File( to ), consistencyCheck, tuningConfiguration, timeout, forensics );
}
private static ConsistencyCheck parseConsistencyChecker( Args args )
{
boolean verify = args.getBoolean( VERIFY, true, true );
if ( verify )
{
String consistencyCheckerName = args.get( CONSISTENCY_CHECKER, ConsistencyCheck.DEFAULT.toString(),
ConsistencyCheck.DEFAULT.toString() );
return ConsistencyCheck.fromString( consistencyCheckerName );
}
return ConsistencyCheck.NONE;
}
private BackupOutcome runBackup( Args args ) throws ToolFailureException
{
String host = args.get( HOST ).trim();
int port = args.getNumber( PORT, BackupServer.DEFAULT_PORT ).intValue();
String to = args.get( TO ).trim();
Config tuningConfiguration = readTuningConfiguration( args );
boolean forensics = args.getBoolean( FORENSICS, false, true );
ConsistencyCheck consistencyCheck = parseConsistencyChecker( args );
if ( host.contains( ":" ) )
{
if ( !host.startsWith( "[" ) )
{
host = "[" + host;
}
if ( !host.endsWith( "]" ) )
{
host += "]";
}
}
long timeout = args.getDuration( TIMEOUT, BackupClient.BIG_READ_TIMEOUT );
URI backupURI = newURI( DEFAULT_SCHEME + "://" + host + ":" + port ); // a bit of validation
HostnamePort hostnamePort = newHostnamePort( backupURI );
return executeBackup( hostnamePort, new File( to ), consistencyCheck, tuningConfiguration, timeout, forensics );
}
private BackupOutcome executeBackup( HostnamePort hostnamePort, File to, ConsistencyCheck consistencyCheck,
Config tuningConfiguration, long timeout, boolean forensics ) throws ToolFailureException
{
try
{
systemOut.println( "Performing backup from '" + hostnamePort + "'" );
return doBackup( hostnamePort, to, consistencyCheck, tuningConfiguration, timeout, forensics );
}
catch ( TransactionFailureException tfe )
{
if ( tfe.getCause() instanceof UpgradeNotAllowedByConfigurationException )
{
try
{
systemOut.println( "The database present in the target directory is of an older version. " +
"Backing that up in target and performing a full backup from source" );
moveExistingDatabase( fs, to );
}
catch ( IOException e )
{
throw new ToolFailureException( "There was a problem moving the old database out of the way" +
" - cannot continue, aborting.", e );
}
return doBackup( hostnamePort, to, consistencyCheck, tuningConfiguration, timeout, forensics );
}
else
{
throw new ToolFailureException( "TransactionFailureException " +
"from existing backup at '" + hostnamePort + "'.", tfe );
}
}
}
private BackupOutcome doBackup( HostnamePort hostnamePort, File to, ConsistencyCheck consistencyCheck,
Config config, long timeout, boolean forensics ) throws ToolFailureException
{
try
{
String host = hostnamePort.getHost();
int port = hostnamePort.getPort();
BackupOutcome outcome = backupService.doIncrementalBackupOrFallbackToFull( host, port, to, consistencyCheck,
config, timeout, forensics );
systemOut.println( "Done" );
return outcome;
}
catch ( MismatchingStoreIdException e )
{
throw new ToolFailureException( String.format( MISMATCHED_STORE_ID, e.getExpected(), e.getEncountered() ) );
}
catch ( ComException e )
{
throw new ToolFailureException( "Couldn't connect to '" + hostnamePort + "'", e );
}
catch ( IncrementalBackupNotPossibleException e )
{
throw new ToolFailureException( e.getMessage(), e );
}
}
private static Config readTuningConfiguration( Args arguments ) throws ToolFailureException
{
Map<String,String> specifiedProperties = stringMap();
String propertyFilePath = arguments.get( CONFIG, null );
if ( propertyFilePath != null )
{
File propertyFile = new File( propertyFilePath );
try
{
specifiedProperties = MapUtil.load( propertyFile );
}
catch ( IOException e )
{
throw new ToolFailureException( String.format( "Could not read configuration properties file [%s]",
propertyFilePath ), e );
}
}
return new Config( specifiedProperties, GraphDatabaseSettings.class, ConsistencyCheckSettings.class );
}
private static URI resolveBackupUri( String from, Args arguments, Config config ) throws ToolFailureException
{
if ( from.contains( "," ) )
{
if ( !from.startsWith( "ha://" ) )
{
checkNoSchemaIsPresent( from );
from = "ha://" + from;
}
return resolveUriWithProvider( "ha", from, arguments, config );
}
if ( !from.startsWith( "single://" ) )
{
from = from.replace( "ha://", "" );
checkNoSchemaIsPresent( from );
from = "single://" + from;
}
return newURI( from );
}
private static void checkNoSchemaIsPresent( String address ) throws ToolFailureException
{
if ( address.contains( "://" ) )
{
throw new ToolFailureException( WRONG_FROM_ADDRESS_SYNTAX );
}
}
private static URI newURI( String uriString ) throws ToolFailureException
{
try
{
return new URI( uriString );
}
catch ( URISyntaxException e )
{
throw new ToolFailureException( WRONG_FROM_ADDRESS_SYNTAX );
}
}
private static URI resolveUriWithProvider( String providerName, String from, Args args, Config config )
throws ToolFailureException
{
BackupExtensionService service;
try
{
service = Service.load( BackupExtensionService.class, providerName );
}
catch ( NoSuchElementException e )
{
throw new ToolFailureException( String.format( UNKNOWN_SCHEMA_MESSAGE_PATTERN, providerName ) );
}
try
{
return service.resolve( from, args, new SimpleLogService( FormattedLogProvider.toOutputStream( System.out ),
NullLogProvider.getInstance() ) );
}
catch ( Throwable t )
{
throw new ToolFailureException( t.getMessage() );
}
}
private static HostnamePort newHostnamePort( URI backupURI ) throws ToolFailureException
{
if ( backupURI == null || backupURI.getHost() == null )
{
throw new ToolFailureException( WRONG_FROM_ADDRESS_SYNTAX );
}
String host = backupURI.getHost();
int port = backupURI.getPort();
if ( port == -1 )
{
port = BackupServer.DEFAULT_PORT;
}
return new HostnamePort( host, port );
}
private static void moveExistingDatabase( FileSystemAbstraction fs, File toDir ) throws IOException
{
File backupDir = new File( toDir, "old-version" );
if ( !fs.mkdir( backupDir ) )
{
throw new IOException( "Trouble making target backup directory " + backupDir.getAbsolutePath() );
}
StoreFile.fileOperation( MOVE, fs, toDir, backupDir, StoreFile.currentStoreFiles(), false, false,
StoreFileType.values() );
LogFiles.move( fs, toDir, backupDir );
}
private static String dash( String name )
{
return "-" + name;
}
static void exitFailure( String msg )
{
System.out.println( msg );
System.exit( 1 );
}
static class ToolFailureException extends Exception
{
ToolFailureException( String message )
{
super( message );
}
ToolFailureException( String message, Throwable cause )
{
super( message, cause );
}
}
}
|
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.workflow.instance.node;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.drools.mvel.MVELSafeHelper;
import org.jbpm.process.core.ContextContainer;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.instance.ContextInstance;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.jbpm.workflow.core.node.ForEachNode;
import org.jbpm.workflow.core.node.ForEachNode.ForEachJoinNode;
import org.jbpm.workflow.core.node.ForEachNode.ForEachSplitNode;
import org.jbpm.workflow.instance.NodeInstance;
import org.jbpm.workflow.instance.NodeInstanceContainer;
import org.jbpm.workflow.instance.impl.NodeInstanceImpl;
import org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory;
import org.kie.api.definition.process.Connection;
import org.kie.api.definition.process.Node;
import org.mvel2.integration.VariableResolver;
import org.mvel2.integration.impl.SimpleValueResolver;
/**
* Runtime counterpart of a for each node.
*/
public class ForEachNodeInstance extends CompositeContextNodeInstance {
private static final long serialVersionUID = 510L;
private static final String TEMP_OUTPUT_VAR = "foreach_output";
private int sequentialCounter = 0;
public ForEachNode getForEachNode() {
return (ForEachNode) getNode();
}
@Override
public NodeInstance getNodeInstance(final Node node) {
if (node instanceof ForEachSplitNode) {
ForEachSplitNodeInstance nodeInstance = new ForEachSplitNodeInstance();
nodeInstance.setNodeId(node.getId());
nodeInstance.setNodeInstanceContainer(this);
nodeInstance.setProcessInstance(getProcessInstance());
String uniqueID = (String) node.getMetaData().get("UniqueId");
if (uniqueID == null) {
uniqueID = node.getId() + "";
}
int level = this.getLevelForNode(uniqueID);
nodeInstance.setLevel(level);
return nodeInstance;
} else if (node instanceof ForEachJoinNode) {
ForEachJoinNodeInstance nodeInstance = (ForEachJoinNodeInstance)
getFirstNodeInstance(node.getId());
if (nodeInstance == null) {
nodeInstance = new ForEachJoinNodeInstance();
nodeInstance.setNodeId(node.getId());
nodeInstance.setNodeInstanceContainer(this);
nodeInstance.setProcessInstance(getProcessInstance());
String uniqueID = (String) node.getMetaData().get("UniqueId");
if (uniqueID == null) {
uniqueID = node.getId() + "";
}
int level = this.getLevelForNode(uniqueID);
nodeInstance.setLevel(level);
}
return nodeInstance;
}
return super.getNodeInstance(node);
}
@Override
public ContextContainer getContextContainer() {
return getForEachNode().getCompositeNode();
}
private Collection<?> evaluateCollectionExpression(String collectionExpression) {
Object collection;
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, collectionExpression);
if (variableScopeInstance != null) {
collection = variableScopeInstance.getVariable(collectionExpression);
} else {
try {
collection = MVELSafeHelper.getEvaluator().eval(collectionExpression, new NodeInstanceResolverFactory(this));
} catch (Throwable t) {
throw new IllegalArgumentException(
"Could not find collection " + collectionExpression);
}
}
if (collection == null) {
return Collections.emptyList();
}
if (collection instanceof Collection<?>) {
return (Collection<?>) collection;
}
if (collection.getClass().isArray()) {
List<Object> list = new ArrayList<>();
Collections.addAll(list, (Object[]) collection);
return list;
}
throw new IllegalArgumentException(
"Unexpected collection type: " + collection.getClass());
}
public class ForEachSplitNodeInstance extends NodeInstanceImpl {
private static final long serialVersionUID = 510l;
public ForEachSplitNode getForEachSplitNode() {
return (ForEachSplitNode) getNode();
}
@Override
public void internalTrigger(org.kie.api.runtime.process.NodeInstance fromm, String type) {
String collectionExpression = getForEachNode().getCollectionExpression();
Collection<?> collection = evaluateCollectionExpression(collectionExpression);
((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);
if (collection.isEmpty()) {
ForEachNodeInstance.this.triggerCompleted(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE, true);
} else {
List<NodeInstance> nodeInstances = new ArrayList<>();
for (Object o: collection) {
String variableName = getForEachNode().getVariableName();
NodeInstance nodeInstance =
((NodeInstanceContainer) getNodeInstanceContainer()).getNodeInstance(getForEachSplitNode().getTo().getTo());
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
nodeInstance.resolveContextInstance(VariableScope.VARIABLE_SCOPE, variableName);
variableScopeInstance.getVariableScope().validateVariable(getProcessInstance().getProcessName(), variableName, o);
variableScopeInstance.setVariable(variableName, o);
nodeInstances.add(nodeInstance);
if (getForEachNode().isSequential()) {
// for sequential mode trigger only first item from the list
sequentialCounter++;
break;
}
}
for (NodeInstance nodeInstance: nodeInstances) {
logger.debug( "Triggering [{}] in multi-instance loop.", nodeInstance.getNodeId() );
nodeInstance.trigger(this, getForEachSplitNode().getTo().getToType());
}
if (!getForEachNode().isWaitForCompletion()) {
ForEachNodeInstance.this.triggerCompleted(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE, false);
}
}
}
}
public class ForEachJoinNodeInstance extends NodeInstanceImpl {
private static final long serialVersionUID = 510l;
public ForEachJoinNode getForEachJoinNode() {
return (ForEachJoinNode) getNode();
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void internalTrigger(org.kie.api.runtime.process.NodeInstance from, String type) {
Map<String, Object> tempVariables = new HashMap<>();
VariableScopeInstance subprocessVariableScopeInstance = null;
if (getForEachNode().getOutputVariableName() != null) {
subprocessVariableScopeInstance = (VariableScopeInstance) getContextInstance(VariableScope.VARIABLE_SCOPE);
Collection<Object> outputCollection = (Collection<Object>) subprocessVariableScopeInstance.getVariable(TEMP_OUTPUT_VAR);
if (outputCollection == null) {
outputCollection = new ArrayList<>();
}
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
((NodeInstanceImpl) from).resolveContextInstance(VariableScope.VARIABLE_SCOPE, getForEachNode().getOutputVariableName());
Object outputVariable = null;
if (variableScopeInstance != null) {
outputVariable = variableScopeInstance.getVariable(getForEachNode().getOutputVariableName());
}
outputCollection.add(outputVariable);
subprocessVariableScopeInstance.setVariable(TEMP_OUTPUT_VAR, outputCollection);
// add temp collection under actual mi output name for completion condition evaluation
tempVariables.put(getForEachNode().getOutputVariableName(), outputVariable);
String outputCollectionName = getForEachNode().getOutputCollectionExpression();
tempVariables.put(outputCollectionName, outputCollection);
}
boolean isCompletionConditionMet = evaluateCompletionCondition(getForEachNode().getCompletionConditionExpression(), tempVariables);
if (getForEachNode().isSequential() && !isCompletionConditionMet) {
String collectionExpression = getForEachNode().getCollectionExpression();
Collection<?> collection = evaluateCollectionExpression(collectionExpression);
if (collection.size() > sequentialCounter) {
String variableName = getForEachNode().getVariableName();
NodeInstance nodeInstance = (NodeInstance)
((NodeInstanceContainer) getNodeInstanceContainer()).getNodeInstance(getForEachNode().getForEachSplitNode().getTo().getTo());
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
nodeInstance.resolveContextInstance(VariableScope.VARIABLE_SCOPE, variableName);
variableScopeInstance.setVariable(variableName, new ArrayList<>(collection).get(sequentialCounter));
sequentialCounter++;
logger.debug( "Triggering [{}] in multi-instance loop.", ((NodeInstanceImpl) nodeInstance).getNodeId() );
((org.jbpm.workflow.instance.NodeInstance) nodeInstance).trigger(null, getForEachNode().getForEachSplitNode().getTo().getToType());
}
}
if (getNodeInstanceContainer().getNodeInstances().size() == 1 || isCompletionConditionMet) {
String outputCollection = getForEachNode().getOutputCollectionExpression();
if (outputCollection != null) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, outputCollection);
Collection<?> outputVariable = (Collection<?>) variableScopeInstance.getVariable(outputCollection);
if (outputVariable != null) {
outputVariable.addAll((Collection) subprocessVariableScopeInstance.getVariable(TEMP_OUTPUT_VAR));
} else {
outputVariable = (Collection<Object>) subprocessVariableScopeInstance.getVariable(TEMP_OUTPUT_VAR);
}
variableScopeInstance.setVariable(outputCollection, outputVariable);
}
((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);
if (getForEachNode().isWaitForCompletion()) {
if (!"true".equals(System.getProperty("jbpm.enable.multi.con"))) {
triggerConnection(getForEachJoinNode().getTo());
} else {
List<Connection> connections = getForEachJoinNode().getOutgoingConnections(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE);
for (Connection connection : connections) {
triggerConnection(connection);
}
}
}
}
}
private boolean evaluateCompletionCondition(String expression, Map<String, Object> tempVariables) {
if (expression == null || expression.isEmpty()) {
return false;
}
try {
Object result = MVELSafeHelper.getEvaluator().eval(expression, new ForEachNodeInstanceResolverFactory(this, tempVariables));
if (!(result instanceof Boolean)) {
throw new RuntimeException("Completion condition expression must return boolean values: " + result
+ " for expression " + expression);
}
return ((Boolean) result).booleanValue();
} catch (Throwable t) {
throw new IllegalArgumentException("Could not evaluate completion condition " + expression, t);
}
}
}
@Override
public ContextInstance getContextInstance(String contextId) {
ContextInstance contextInstance = super.getContextInstance(contextId);
if (contextInstance == null) {
contextInstance = resolveContextInstance(contextId, TEMP_OUTPUT_VAR);
setContextInstance(contextId, contextInstance);
}
return contextInstance;
}
@Override
public int getLevelForNode(String uniqueID) {
// always 1 for for each
return 1;
}
public void setInternalSequentialCounter(int counter) {
this.sequentialCounter = counter;
}
public int getSequentialCounter() {
return this.sequentialCounter;
}
private class ForEachNodeInstanceResolverFactory extends NodeInstanceResolverFactory {
private static final long serialVersionUID = -8856846610671009685L;
private Map<String, Object> tempVariables;
public ForEachNodeInstanceResolverFactory(NodeInstance nodeInstance, Map<String, Object> tempVariables) {
super(nodeInstance);
this.tempVariables = tempVariables;
}
@Override
public boolean isResolveable(String name) {
boolean result = tempVariables.containsKey(name);
if (result) {
return result;
}
return super.isResolveable(name);
}
@Override
public VariableResolver getVariableResolver(String name) {
if (tempVariables.containsKey(name)) {
return new SimpleValueResolver(tempVariables.get(name));
}
return super.getVariableResolver(name);
}
}
}
|
|
/*
* Copyright (C) 2010 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.googlecode.android_scripting.facade;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.googlecode.android_scripting.event.Event;
import com.googlecode.android_scripting.future.FutureResult;
import com.googlecode.android_scripting.jsonrpc.JsonBuilder;
import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
import com.googlecode.android_scripting.rpc.Rpc;
import com.googlecode.android_scripting.rpc.RpcDefault;
import com.googlecode.android_scripting.rpc.RpcDeprecated;
import com.googlecode.android_scripting.rpc.RpcName;
import com.googlecode.android_scripting.rpc.RpcOptional;
import com.googlecode.android_scripting.rpc.RpcParameter;
import java.util.HashMap;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
/**
* Manage the event queue. <br>
* <br>
* <b>Usage Notes:</b><br>
* EventFacade APIs interact with the Event Queue (a data buffer containing up to 1024 event
* entries).<br>
* Events are automatically entered into the Event Queue following API calls such as startSensing()
* and startLocating().<br>
* The Event Facade provides control over how events are entered into (and removed from) the Event
* Queue.<br>
* The Event Queue provides a useful means of recording background events (such as sensor data) when
* the phone is busy with foreground activities.
*
* @author Felix Arends ([email protected])
*
*/
public class EventFacade extends RpcReceiver {
/**
* The maximum length of the event queue. Old events will be discarded when this limit is
* exceeded.
*/
private static final int MAX_QUEUE_SIZE = 1024;
private final Queue<Event> mEventQueue = new ConcurrentLinkedQueue<Event>();
private final CopyOnWriteArrayList<EventObserver> mGlobalEventObservers =
new CopyOnWriteArrayList<EventObserver>();
private final Multimap<String, EventObserver> mNamedEventObservers = Multimaps
.synchronizedListMultimap(ArrayListMultimap.<String, EventObserver> create());
private EventServer mEventServer = null;
private final HashMap<String, BroadcastListener> mBroadcastListeners =
new HashMap<String, BroadcastListener>();
private final Context mContext;
public EventFacade(FacadeManager manager) {
super(manager);
mContext = manager.getService().getApplicationContext();
}
/**
* Example (python): droid.eventClearBuffer()
*/
@Rpc(description = "Clears all events from the event buffer.")
public void eventClearBuffer() {
mEventQueue.clear();
}
/**
* Registers a listener for a new broadcast signal
*/
@Rpc(description = "Registers a listener for a new broadcast signal")
public boolean eventRegisterForBroadcast(
@RpcParameter(name = "category") String category,
@RpcParameter(name = "enqueue", description = "Should this events be added to the event queue or only dispatched") @RpcDefault(value = "true") Boolean enqueue) {
if (mBroadcastListeners.containsKey(category)) {
return false;
}
BroadcastListener b = new BroadcastListener(this, enqueue.booleanValue());
IntentFilter c = new IntentFilter(category);
mContext.registerReceiver(b, c);
mBroadcastListeners.put(category, b);
return true;
}
@Rpc(description = "Stop listening for a broadcast signal")
public void eventUnregisterForBroadcast(@RpcParameter(name = "category") String category) {
if (!mBroadcastListeners.containsKey(category)) {
return;
}
mContext.unregisterReceiver(mBroadcastListeners.get(category));
mBroadcastListeners.remove(category);
}
@Rpc(description = "Lists all the broadcast signals we are listening for")
public Set<String> eventGetBrodcastCategories() {
return mBroadcastListeners.keySet();
}
/**
* Actual data returned in the map will depend on the type of event.
*
* <pre>
* Example (python):
* import android, time
* droid = android.Android()
* droid.startSensing()
* time.sleep(1)
* droid.eventClearBuffer()
* time.sleep(1)
* e = eventPoll(1).result
* event_entry_number = 0
* x = e[event_entry_ number]['data']['xforce']
* </pre>
*
* e has the format:<br>
* [{u'data': {u'accuracy': 0, u'pitch': -0.48766891956329345, u'xmag': -5.6875, u'azimuth':
* 0.3312483489513397, u'zforce': 8.3492730000000002, u'yforce': 4.5628165999999997, u'time':
* 1297072704.813, u'ymag': -11.125, u'zmag': -42.375, u'roll': -0.059393649548292161, u'xforce':
* 0.42223078000000003}, u'name': u'sensors', u'time': 1297072704813000L}]<br>
* x has the string value of the x force data (0.42223078000000003) at the time of the event
* entry. </pre>
*/
@Rpc(description = "Returns and removes the oldest n events (i.e. location or sensor update, etc.) from the event buffer.", returns = "A List of Maps of event properties.")
public List<Event> eventPoll(
@RpcParameter(name = "number_of_events") @RpcDefault("1") Integer number_of_events) {
List<Event> events = Lists.newArrayList();
for (int i = 0; i < number_of_events; i++) {
Event event = mEventQueue.poll();
if (event == null) {
break;
}
events.add(event);
}
return events;
}
@Rpc(description = "Blocks until an event with the supplied name occurs. The returned event is not removed from the buffer.", returns = "Map of event properties.")
public Event eventWaitFor(
@RpcParameter(name = "eventName") final String eventName,
@RpcParameter(name = "timeout", description = "the maximum time to wait (in ms)") @RpcOptional Integer timeout)
throws InterruptedException {
synchronized (mEventQueue) { // First check to make sure it isn't already there
for (Event event : mEventQueue) {
if (event.getName().equals(eventName)) {
return event;
}
}
}
final FutureResult<Event> futureEvent = new FutureResult<Event>();
addNamedEventObserver(eventName, new EventObserver() {
@Override
public void onEventReceived(Event event) {
if (event.getName().equals(eventName)) {
synchronized (futureEvent) {
if (!futureEvent.isDone()) {
futureEvent.set(event);
removeEventObserver(this);
}
}
}
}
});
if (timeout != null) {
return futureEvent.get(timeout, TimeUnit.MILLISECONDS);
} else {
return futureEvent.get();
}
}
@Rpc(description = "Blocks until an event occurs. The returned event is removed from the buffer.", returns = "Map of event properties.")
public Event eventWait(
@RpcParameter(name = "timeout", description = "the maximum time to wait") @RpcOptional Integer timeout)
throws InterruptedException {
Event result = null;
final FutureResult<Event> futureEvent = new FutureResult<Event>();
synchronized (mEventQueue) { // Anything in queue?
if (mEventQueue.size() > 0) {
return mEventQueue.poll(); // return it.
}
}
EventObserver observer = new EventObserver() {
@Override
public void onEventReceived(Event event) { // set up observer for any events.
synchronized (futureEvent) {
if (!futureEvent.isDone()) {
futureEvent.set(event);
removeEventObserver(this);
}
mEventQueue.remove(event);
}
}
};
addGlobalEventObserver(observer);
if (timeout != null) {
result = futureEvent.get(timeout, TimeUnit.MILLISECONDS);
} else {
result = futureEvent.get();
}
removeEventObserver(observer); // Make quite sure this goes away.
return result;
}
/**
* <pre>
* Example:
* import android
* from datetime import datetime
* droid = android.Android()
* t = datetime.now()
* droid.eventPost('Some Event', t)
* </pre>
*/
@Rpc(description = "Post an event to the event queue.")
public void eventPost(
@RpcParameter(name = "name", description = "Name of event") String name,
@RpcParameter(name = "data", description = "Data contained in event.") String data,
@RpcParameter(name = "enqueue", description = "Set to False if you don't want your events to be added to the event queue, just dispatched.") @RpcOptional @RpcDefault("false") Boolean enqueue) {
postEvent(name, data, enqueue.booleanValue());
}
/**
* Post an event and queue it
*/
public void postEvent(String name, Object data) {
postEvent(name, data, true);
}
/**
* Posts an event with to the event queue.
*/
public void postEvent(String name, Object data, boolean enqueue) {
Event event = new Event(name, data);
if (enqueue != false) {
mEventQueue.add(event);
if (mEventQueue.size() > MAX_QUEUE_SIZE) {
mEventQueue.remove();
}
}
synchronized (mNamedEventObservers) {
for (EventObserver observer : mNamedEventObservers.get(name)) {
observer.onEventReceived(event);
}
}
synchronized (mGlobalEventObservers) {
for (EventObserver observer : mGlobalEventObservers) {
observer.onEventReceived(event);
}
}
}
@RpcDeprecated(value = "eventPost", release = "r4")
@Rpc(description = "Post an event to the event queue.")
@RpcName(name = "postEvent")
public void rpcPostEvent(@RpcParameter(name = "name") String name,
@RpcParameter(name = "data") String data) {
postEvent(name, data);
}
@RpcDeprecated(value = "eventPoll", release = "r4")
@Rpc(description = "Returns and removes the oldest event (i.e. location or sensor update, etc.) from the event buffer.", returns = "Map of event properties.")
public Event receiveEvent() {
return mEventQueue.poll();
}
@RpcDeprecated(value = "eventWaitFor", release = "r4")
@Rpc(description = "Blocks until an event with the supplied name occurs. The returned event is not removed from the buffer.", returns = "Map of event properties.")
public Event waitForEvent(
@RpcParameter(name = "eventName") final String eventName,
@RpcParameter(name = "timeout", description = "the maximum time to wait") @RpcOptional Integer timeout)
throws InterruptedException {
return eventWaitFor(eventName, timeout);
}
@Rpc(description = "Opens up a socket where you can read for events posted")
public int startEventDispatcher(
@RpcParameter(name = "port", description = "Port to use") @RpcDefault("0") @RpcOptional() Integer port) {
if (mEventServer == null) {
mEventServer = new EventServer(port);
addGlobalEventObserver(mEventServer);
}
return mEventServer.getAddress().getPort();
}
@Rpc(description = "Stops the event server, you can't read in the port anymore")
public void stopEventDispatcher() throws RuntimeException {
if (mEventServer == null) {
throw new RuntimeException("Not running");
}
mEventServer.shutdown();
removeEventObserver(mEventServer);
mEventServer = null;
return;
}
@Override
public void shutdown() {
try {
stopEventDispatcher();
} catch (Exception err) {
}
// let others (like webviews) know we're going down
postEvent("sl4a", "{\"shutdown\": \"event-facade\"}");
}
public void addNamedEventObserver(String eventName, EventObserver observer) {
mNamedEventObservers.put(eventName, observer);
}
public void addGlobalEventObserver(EventObserver observer) {
mGlobalEventObservers.add(observer);
}
public void removeEventObserver(EventObserver observer) {
mNamedEventObservers.removeAll(observer);
mGlobalEventObservers.remove(observer);
}
public interface EventObserver {
public void onEventReceived(Event event);
}
public class BroadcastListener extends android.content.BroadcastReceiver {
private EventFacade mParent;
private boolean mEnQueue;
public BroadcastListener(EventFacade parent, boolean enqueue) {
mParent = parent;
mEnQueue = enqueue;
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = (Bundle) intent.getExtras().clone();
data.putString("action", intent.getAction());
try {
mParent.eventPost("sl4a", JsonBuilder.build(data).toString(), mEnQueue);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
|
/*
* Copyright (c) 2016 Gridtec. 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 at.gridtec.lambda4j.function.tri.obj;
import at.gridtec.lambda4j.Lambda;
import at.gridtec.lambda4j.consumer.tri.obj.ObjBiLongConsumer;
import at.gridtec.lambda4j.function.BooleanFunction;
import at.gridtec.lambda4j.function.ByteFunction;
import at.gridtec.lambda4j.function.CharFunction;
import at.gridtec.lambda4j.function.FloatFunction;
import at.gridtec.lambda4j.function.Function2;
import at.gridtec.lambda4j.function.LongFunction2;
import at.gridtec.lambda4j.function.ShortFunction;
import at.gridtec.lambda4j.function.bi.BiLongFunction;
import at.gridtec.lambda4j.function.bi.obj.ObjLongFunction;
import at.gridtec.lambda4j.function.conversion.BooleanToLongFunction;
import at.gridtec.lambda4j.function.conversion.ByteToLongFunction;
import at.gridtec.lambda4j.function.conversion.CharToLongFunction;
import at.gridtec.lambda4j.function.conversion.FloatToLongFunction;
import at.gridtec.lambda4j.function.conversion.ShortToLongFunction;
import at.gridtec.lambda4j.function.tri.TriBooleanFunction;
import at.gridtec.lambda4j.function.tri.TriByteFunction;
import at.gridtec.lambda4j.function.tri.TriCharFunction;
import at.gridtec.lambda4j.function.tri.TriDoubleFunction;
import at.gridtec.lambda4j.function.tri.TriFloatFunction;
import at.gridtec.lambda4j.function.tri.TriFunction;
import at.gridtec.lambda4j.function.tri.TriIntFunction;
import at.gridtec.lambda4j.function.tri.TriLongFunction;
import at.gridtec.lambda4j.function.tri.TriShortFunction;
import org.apache.commons.lang3.tuple.Triple;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.DoubleFunction;
import java.util.function.DoubleToLongFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntToLongFunction;
import java.util.function.LongFunction;
import java.util.function.LongUnaryOperator;
import java.util.function.ToLongFunction;
/**
* Represents an operation that accepts one object-valued and two {@code long}-valued input arguments and produces a
* result.
* This is a (reference, long, long) specialization of {@link TriFunction}.
* <p>
* This is a {@link FunctionalInterface} whose functional method is {@link #apply(Object, long, long)}.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @see TriFunction
*/
@SuppressWarnings("unused")
@FunctionalInterface
public interface ObjBiLongFunction<T, R> extends Lambda {
/**
* Constructs a {@link ObjBiLongFunction} based on a lambda expression or a method reference. Thereby the given
* lambda expression or method reference is returned on an as-is basis to implicitly transform it to the desired
* type. With this method, it is possible to ensure that correct type is used from lambda expression or method
* reference.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method}
* @return A {@code ObjBiLongFunction} from given lambda expression or method reference.
* @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given,
* {@code null} will be returned.
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda
* Expression</a>
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a>
*/
static <T, R> ObjBiLongFunction<T, R> of(@Nullable final ObjBiLongFunction<T, R> expression) {
return expression;
}
/**
* Lifts a partial {@link ObjBiLongFunction} into a total {@link ObjBiLongFunction} that returns an {@link Optional}
* result.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param partial A function that is only defined for some values in its domain
* @return A partial {@code ObjBiLongFunction} lifted into a total {@code ObjBiLongFunction} that returns an {@code
* Optional} result.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static <T, R> ObjBiLongFunction<T, Optional<R>> lift(
@Nonnull final ObjBiLongFunction<? super T, ? extends R> partial) {
Objects.requireNonNull(partial);
return (t, value1, value2) -> Optional.ofNullable(partial.apply(t, value1, value2));
}
/**
* Calls the given {@link ObjBiLongFunction} with the given arguments and returns its result.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param function The function to be called
* @param t The first argument to the function
* @param value1 The second argument to the function
* @param value2 The third argument to the function
* @return The result from the given {@code ObjBiLongFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
static <T, R> R call(@Nonnull final ObjBiLongFunction<? super T, ? extends R> function, T t, long value1,
long value2) {
Objects.requireNonNull(function);
return function.apply(t, value1, value2);
}
/**
* Creates a {@link ObjBiLongFunction} which uses the {@code first} parameter of this one as argument for the given
* {@link Function}.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param function The function which accepts the {@code first} parameter of this one
* @return Creates a {@code ObjBiLongFunction} which uses the {@code first} parameter of this one as argument for
* the given {@code Function}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static <T, R> ObjBiLongFunction<T, R> onlyFirst(@Nonnull final Function<? super T, ? extends R> function) {
Objects.requireNonNull(function);
return (t, value1, value2) -> function.apply(t);
}
/**
* Creates a {@link ObjBiLongFunction} which uses the {@code second} parameter of this one as argument for the given
* {@link LongFunction}.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param function The function which accepts the {@code second} parameter of this one
* @return Creates a {@code ObjBiLongFunction} which uses the {@code second} parameter of this one as argument for
* the given {@code LongFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static <T, R> ObjBiLongFunction<T, R> onlySecond(@Nonnull final LongFunction<? extends R> function) {
Objects.requireNonNull(function);
return (t, value1, value2) -> function.apply(value1);
}
/**
* Creates a {@link ObjBiLongFunction} which uses the {@code third} parameter of this one as argument for the given
* {@link LongFunction}.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param function The function which accepts the {@code third} parameter of this one
* @return Creates a {@code ObjBiLongFunction} which uses the {@code third} parameter of this one as argument for
* the given {@code LongFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static <T, R> ObjBiLongFunction<T, R> onlyThird(@Nonnull final LongFunction<? extends R> function) {
Objects.requireNonNull(function);
return (t, value1, value2) -> function.apply(value2);
}
/**
* Creates a {@link ObjBiLongFunction} which always returns a given value.
*
* @param <T> The type of the first argument to the function
* @param <R> The type of return value from the function
* @param ret The return value for the constant
* @return A {@code ObjBiLongFunction} which always returns a given value.
*/
@Nonnull
static <T, R> ObjBiLongFunction<T, R> constant(R ret) {
return (t, value1, value2) -> ret;
}
/**
* Applies this function to the given arguments.
*
* @param t The first argument to the function
* @param value1 The second argument to the function
* @param value2 The third argument to the function
* @return The return value from the function, which is its result.
*/
R apply(T t, long value1, long value2);
/**
* Applies this function partially to some arguments of this one, producing a {@link BiLongFunction} as result.
*
* @param t The first argument to this function used to partially apply this function
* @return A {@code BiLongFunction} that represents this function partially applied the some arguments.
*/
@Nonnull
default BiLongFunction<R> papply(T t) {
return (value1, value2) -> this.apply(t, value1, value2);
}
/**
* Applies this function partially to some arguments of this one, producing a {@link LongFunction2} as result.
*
* @param t The first argument to this function used to partially apply this function
* @param value1 The second argument to this function used to partially apply this function
* @return A {@code LongFunction2} that represents this function partially applied the some arguments.
*/
@Nonnull
default LongFunction2<R> papply(T t, long value1) {
return (value2) -> this.apply(t, value1, value2);
}
/**
* Applies this function partially to some arguments of this one, producing a {@link ObjLongFunction} as result.
*
* @param value1 The second argument to this function used to partially apply this function
* @return A {@code ObjLongFunction} that represents this function partially applied the some arguments.
*/
@Nonnull
default ObjLongFunction<T, R> papply(long value1) {
return (t, value2) -> this.apply(t, value1, value2);
}
/**
* Applies this function partially to some arguments of this one, producing a {@link Function2} as result.
*
* @param value1 The second argument to this function used to partially apply this function
* @param value2 The third argument to this function used to partially apply this function
* @return A {@code Function2} that represents this function partially applied the some arguments.
*/
@Nonnull
default Function2<T, R> papply(long value1, long value2) {
return (t) -> this.apply(t, value1, value2);
}
/**
* Returns the number of arguments for this function.
*
* @return The number of arguments for this function.
* @implSpec The default implementation always returns {@code 3}.
*/
@Nonnegative
default int arity() {
return 3;
}
/**
* Returns a composed {@link TriFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
*
* @param <A> The type of the argument to the first given function, and of composed function
* @param <B> The type of the argument to the second given function, and of composed function
* @param <C> The type of the argument to the third given function, and of composed function
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriFunction} that first applies the {@code before} functions to its input, and then
* applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle every type.
*/
@Nonnull
default <A, B, C> TriFunction<A, B, C, R> compose(@Nonnull final Function<? super A, ? extends T> before1,
@Nonnull final ToLongFunction<? super B> before2, @Nonnull final ToLongFunction<? super C> before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (a, b, c) -> apply(before1.apply(a), before2.applyAsLong(b), before3.applyAsLong(c));
}
/**
* Returns a composed {@link TriBooleanFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code boolean} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriBooleanFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* boolean}.
*/
@Nonnull
default TriBooleanFunction<R> composeFromBoolean(@Nonnull final BooleanFunction<? extends T> before1,
@Nonnull final BooleanToLongFunction before2, @Nonnull final BooleanToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriByteFunction} that first applies the {@code before} functions to
* its input, and then applies this function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
* This method is just convenience, to provide the ability to execute an operation which accepts {@code byte} input,
* before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriByteFunction} that first applies the {@code before} functions to its input, and then
* applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* byte}.
*/
@Nonnull
default TriByteFunction<R> composeFromByte(@Nonnull final ByteFunction<? extends T> before1,
@Nonnull final ByteToLongFunction before2, @Nonnull final ByteToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriCharFunction} that first applies the {@code before} functions to
* its input, and then applies this function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
* This method is just convenience, to provide the ability to execute an operation which accepts {@code char} input,
* before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriCharFunction} that first applies the {@code before} functions to its input, and then
* applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* char}.
*/
@Nonnull
default TriCharFunction<R> composeFromChar(@Nonnull final CharFunction<? extends T> before1,
@Nonnull final CharToLongFunction before2, @Nonnull final CharToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriDoubleFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code double} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriDoubleFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* double}.
*/
@Nonnull
default TriDoubleFunction<R> composeFromDouble(@Nonnull final DoubleFunction<? extends T> before1,
@Nonnull final DoubleToLongFunction before2, @Nonnull final DoubleToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriFloatFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code float} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriFloatFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* float}.
*/
@Nonnull
default TriFloatFunction<R> composeFromFloat(@Nonnull final FloatFunction<? extends T> before1,
@Nonnull final FloatToLongFunction before2, @Nonnull final FloatToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriIntFunction} that first applies the {@code before} functions to
* its input, and then applies this function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
* This method is just convenience, to provide the ability to execute an operation which accepts {@code int} input,
* before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriIntFunction} that first applies the {@code before} functions to its input, and then
* applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* int}.
*/
@Nonnull
default TriIntFunction<R> composeFromInt(@Nonnull final IntFunction<? extends T> before1,
@Nonnull final IntToLongFunction before2, @Nonnull final IntToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriLongFunction} that first applies the {@code before} functions to
* its input, and then applies this function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
* This method is just convenience, to provide the ability to execute an operation which accepts {@code long} input,
* before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second operator to apply before this function is applied
* @param before3 The third operator to apply before this function is applied
* @return A composed {@code TriLongFunction} that first applies the {@code before} functions to its input, and then
* applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* long}.
*/
@Nonnull
default TriLongFunction<R> composeFromLong(@Nonnull final LongFunction<? extends T> before1,
@Nonnull final LongUnaryOperator before2, @Nonnull final LongUnaryOperator before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link TriShortFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code short} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriShortFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is a able to handle primitive values. In this case this is {@code
* short}.
*/
@Nonnull
default TriShortFunction<R> composeFromShort(@Nonnull final ShortFunction<? extends T> before1,
@Nonnull final ShortToLongFunction before2, @Nonnull final ShortToLongFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> apply(before1.apply(value1), before2.applyAsLong(value2),
before3.applyAsLong(value3));
}
/**
* Returns a composed {@link ObjBiLongFunction} that first applies this function to its input, and then applies the
* {@code after} function to the result.
* If evaluation of either operation throws an exception, it is relayed to the caller of the composed operation.
*
* @param <S> The type of return value from the {@code after} function, and of the composed function
* @param after The function to apply after this function is applied
* @return A composed {@code ObjBiLongFunction} that first applies this function to its input, and then applies the
* {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return every type.
*/
@Nonnull
default <S> ObjBiLongFunction<T, S> andThen(@Nonnull final Function<? super R, ? extends S> after) {
Objects.requireNonNull(after);
return (t, value1, value2) -> after.apply(apply(t, value1, value2));
}
/**
* Returns a composed {@link ObjBiLongConsumer} that fist applies this function to its input, and then consumes the
* result using the given {@link Consumer}. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation.
*
* @param consumer The operation which consumes the result from this operation
* @return A composed {@code ObjBiLongConsumer} that first applies this function to its input, and then consumes the
* result using the given {@code Consumer}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
default ObjBiLongConsumer<T> consume(@Nonnull final Consumer<? super R> consumer) {
Objects.requireNonNull(consumer);
return (t, value1, value2) -> consumer.accept(apply(t, value1, value2));
}
/**
* Returns a memoized (caching) version of this {@link ObjBiLongFunction}. Whenever it is called, the mapping
* between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
* memoized value instead of computing the return value again.
* <p>
* Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
* forever.
*
* @return A memoized (caching) version of this {@code ObjBiLongFunction}.
* @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
* resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
* @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
* thread-safe.
*/
@Nonnull
default ObjBiLongFunction<T, R> memoized() {
if (isMemoized()) {
return this;
} else {
final Map<Triple<T, Long, Long>, R> cache = new ConcurrentHashMap<>();
final Object lock = new Object();
return (ObjBiLongFunction<T, R> & Memoized) (t, value1, value2) -> {
final R returnValue;
synchronized (lock) {
returnValue = cache.computeIfAbsent(Triple.of(t, value1, value2),
key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
}
return returnValue;
};
}
}
/**
* Converts this function to an equal function, which ensures that its result is not
* {@code null} using {@link Optional}. This method mainly exists to avoid unnecessary {@code NullPointerException}s
* through referencing {@code null} from this function.
*
* @return An equal function, which ensures that its result is not {@code null}.
* @deprecated Use {@code lift} method for lifting this function.
*/
@Deprecated
@Nonnull
default ObjBiLongFunction<T, Optional<R>> nonNull() {
return (t, value1, value2) -> Optional.ofNullable(apply(t, value1, value2));
}
/**
* Returns a composed {@link TriFunction} which represents this {@link ObjBiLongFunction}. Thereby the primitive
* input argument for this function is autoboxed. This method provides the possibility to use this
* {@code ObjBiLongFunction} with methods provided by the {@code JDK}.
*
* @return A composed {@code TriFunction} which represents this {@code ObjBiLongFunction}.
*/
@Nonnull
default TriFunction<T, Long, Long, R> boxed() {
return this::apply;
}
}
|
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.keycloak.adapters.authorization;
import org.jboss.logging.Logger;
import org.keycloak.AuthorizationContext;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.OIDCHttpFacade;
import org.keycloak.adapters.spi.HttpFacade.Request;
import org.keycloak.adapters.spi.HttpFacade.Response;
import org.keycloak.authorization.client.AuthzClient;
import org.keycloak.authorization.client.representation.ResourceRepresentation;
import org.keycloak.authorization.client.resource.ProtectedResource;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.config.PolicyEnforcerConfig;
import org.keycloak.representations.adapters.config.PolicyEnforcerConfig.EnforcementMode;
import org.keycloak.representations.adapters.config.PolicyEnforcerConfig.PathConfig;
import org.keycloak.representations.idm.authorization.Permission;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Pedro Igor</a>
*/
public abstract class AbstractPolicyEnforcer {
private static Logger LOGGER = Logger.getLogger(AbstractPolicyEnforcer.class);
private final PolicyEnforcerConfig enforcerConfig;
private final PolicyEnforcer policyEnforcer;
private List<PathConfig> paths;
private AuthzClient authzClient;
private PathMatcher pathMatcher;
public AbstractPolicyEnforcer(PolicyEnforcer policyEnforcer) {
this.policyEnforcer = policyEnforcer;
this.enforcerConfig = policyEnforcer.getEnforcerConfig();
this.authzClient = policyEnforcer.getClient();
this.pathMatcher = new PathMatcher();
this.paths = new ArrayList<>(policyEnforcer.getPaths());
}
public AuthorizationContext authorize(OIDCHttpFacade httpFacade) {
EnforcementMode enforcementMode = this.enforcerConfig.getEnforcementMode();
if (EnforcementMode.DISABLED.equals(enforcementMode)) {
return createEmptyAuthorizationContext(true);
}
KeycloakSecurityContext securityContext = httpFacade.getSecurityContext();
if (securityContext != null) {
AccessToken accessToken = securityContext.getToken();
if (accessToken != null) {
Request request = httpFacade.getRequest();
Response response = httpFacade.getResponse();
String pathInfo = URI.create(request.getURI()).getPath().substring(1);
String path = pathInfo.substring(pathInfo.indexOf('/'), pathInfo.length());
PathConfig pathConfig = this.pathMatcher.matches(path, this.paths);
LOGGER.debugf("Checking permissions for path [%s] with config [%s].", request.getURI(), pathConfig);
if (pathConfig == null) {
if (EnforcementMode.PERMISSIVE.equals(enforcementMode)) {
return createAuthorizationContext(accessToken);
}
LOGGER.debugf("Could not find a configuration for path [%s]", path);
response.sendError(403, "Could not find a configuration for path [" + path + "].");
return createEmptyAuthorizationContext(false);
}
if (EnforcementMode.DISABLED.equals(pathConfig.getEnforcementMode())) {
return createEmptyAuthorizationContext(true);
}
PathConfig actualPathConfig = resolvePathConfig(pathConfig, request);
Set<String> requiredScopes = getRequiredScopes(actualPathConfig, request);
if (isAuthorized(actualPathConfig, requiredScopes, accessToken, httpFacade)) {
try {
return createAuthorizationContext(accessToken);
} catch (Exception e) {
throw new RuntimeException("Error processing path [" + actualPathConfig.getPath() + "].", e);
}
}
if (!challenge(actualPathConfig, requiredScopes, httpFacade)) {
LOGGER.debugf("Sending challenge to the client. Path [%s]", pathConfig);
response.sendError(403, "Authorization failed.");
}
}
}
return createEmptyAuthorizationContext(false);
}
protected abstract boolean challenge(PathConfig pathConfig, Set<String> requiredScopes, OIDCHttpFacade facade);
protected boolean isAuthorized(PathConfig actualPathConfig, Set<String> requiredScopes, AccessToken accessToken, OIDCHttpFacade httpFacade) {
Request request = httpFacade.getRequest();
PolicyEnforcerConfig enforcerConfig = getEnforcerConfig();
String accessDeniedPath = enforcerConfig.getOnDenyRedirectTo();
if (accessDeniedPath != null) {
if (request.getURI().contains(accessDeniedPath)) {
return true;
}
}
AccessToken.Authorization authorization = accessToken.getAuthorization();
if (authorization == null) {
return false;
}
List<Permission> permissions = authorization.getPermissions();
boolean hasPermission = false;
for (Permission permission : permissions) {
if (permission.getResourceSetId() != null) {
if (isResourcePermission(actualPathConfig, permission)) {
hasPermission = true;
if (actualPathConfig.isInstance() && !matchResourcePermission(actualPathConfig, permission)) {
continue;
}
if (hasResourceScopePermission(requiredScopes, permission, actualPathConfig)) {
LOGGER.debugf("Authorization GRANTED for path [%s]. Permissions [%s].", actualPathConfig, permissions);
if (request.getMethod().equalsIgnoreCase("DELETE") && actualPathConfig.isInstance()) {
this.paths.remove(actualPathConfig);
}
return true;
}
}
} else {
if (hasResourceScopePermission(requiredScopes, permission, actualPathConfig)) {
hasPermission = true;
return true;
}
}
}
if (!hasPermission && EnforcementMode.PERMISSIVE.equals(actualPathConfig.getEnforcementMode())) {
return true;
}
LOGGER.debugf("Authorization FAILED for path [%s]. No enough permissions [%s].", actualPathConfig, permissions);
return false;
}
private boolean hasResourceScopePermission(Set<String> requiredScopes, Permission permission, PathConfig actualPathConfig) {
Set<String> allowedScopes = permission.getScopes();
return (allowedScopes.containsAll(requiredScopes) || allowedScopes.isEmpty());
}
protected AuthzClient getAuthzClient() {
return this.authzClient;
}
protected PolicyEnforcerConfig getEnforcerConfig() {
return enforcerConfig;
}
protected PolicyEnforcer getPolicyEnforcer() {
return policyEnforcer;
}
private AuthorizationContext createEmptyAuthorizationContext(final boolean granted) {
return new AuthorizationContext() {
@Override
public boolean hasPermission(String resourceName, String scopeName) {
return granted;
}
@Override
public boolean hasResourcePermission(String resourceName) {
return granted;
}
@Override
public boolean hasScopePermission(String scopeName) {
return granted;
}
@Override
public List<Permission> getPermissions() {
return Collections.EMPTY_LIST;
}
@Override
public boolean isGranted() {
return granted;
}
};
}
private PathConfig resolvePathConfig(PathConfig originalConfig, Request request) {
if (originalConfig.hasPattern()) {
String pathInfo = URI.create(request.getURI()).getPath().substring(1);
String path = pathInfo.substring(pathInfo.indexOf('/'), pathInfo.length());
ProtectedResource resource = this.authzClient.protection().resource();
Set<String> search = resource.findByFilter("uri=" + path);
if (!search.isEmpty()) {
// resource does exist on the server, cache it
ResourceRepresentation targetResource = resource.findById(search.iterator().next()).getResourceDescription();
PathConfig config = new PathConfig();
config.setId(targetResource.getId());
config.setName(targetResource.getName());
config.setType(targetResource.getType());
config.setPath(targetResource.getUri());
config.setScopes(originalConfig.getScopes());
config.setMethods(originalConfig.getMethods());
config.setParentConfig(originalConfig);
config.setEnforcementMode(originalConfig.getEnforcementMode());
this.paths.add(config);
return config;
}
}
return originalConfig;
}
private Set<String> getRequiredScopes(PathConfig pathConfig, Request request) {
Set<String> requiredScopes = new HashSet<>();
requiredScopes.addAll(pathConfig.getScopes());
String method = request.getMethod();
for (PolicyEnforcerConfig.MethodConfig methodConfig : pathConfig.getMethods()) {
if (methodConfig.getMethod().equals(method)) {
requiredScopes.addAll(methodConfig.getScopes());
}
}
return requiredScopes;
}
private AuthorizationContext createAuthorizationContext(AccessToken accessToken) {
return new AuthorizationContext(accessToken, this.paths);
}
private boolean isResourcePermission(PathConfig actualPathConfig, Permission permission) {
// first we try a match using resource id
boolean resourceMatch = matchResourcePermission(actualPathConfig, permission);
// as a fallback, check if the current path is an instance and if so, check if parent's id matches the permission
if (!resourceMatch && actualPathConfig.isInstance()) {
resourceMatch = matchResourcePermission(actualPathConfig.getParentConfig(), permission);
}
return resourceMatch;
}
private boolean matchResourcePermission(PathConfig actualPathConfig, Permission permission) {
return permission.getResourceSetId().equals(actualPathConfig.getId());
}
}
|
|
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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.
*/
package com.ls.drupal;
import com.google.gson.annotations.Expose;
import com.ls.http.base.BaseRequest;
import com.ls.http.base.BaseRequest.RequestMethod;
import com.ls.http.base.ICharsetItem;
import com.ls.http.base.RequestConfig;
import com.ls.http.base.ResponseData;
import com.ls.util.internal.ObjectComparator;
import com.ls.util.internal.ObjectComparator.Snapshot;
import com.ls.util.internal.VolleyResponseUtils;
import junit.framework.Assert;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractBaseDrupalEntity implements DrupalClient.OnResponseListener, ICharsetItem {
transient private DrupalClient drupalClient;
transient private Snapshot snapshot;
/**
* In case of request canceling - no method will be triggered.
*
* @author lemberg
*/
public interface OnEntityRequestListener {
void onRequestCompleted(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);
void onRequestFailed(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);
void onRequestCanceled(AbstractBaseDrupalEntity entity, Object tag);
}
/**
* @return path to resource. Shouldn't include base URL(domain).
*/
protected abstract String getPath();
/**
* Called for post requests only
*
* @return post parameters to be published on server or null if default
* object serialization has to be performed.
*/
protected abstract Map<String, String> getItemRequestPostParameters();
/**
* @param method is instance od {@link BaseRequest.RequestMethod} enum, this method is called for. it can be "GET", "POST", "PUT" ,"PATCH" or "DELETE".
* @return parameters for the request method specified. In case if collection is passed as map entry value - all entities will be added under corresponding key. Object.toString will be called
* otherwise.
*/
protected abstract Map<String, Object> getItemRequestGetParameters(RequestMethod method);
/**
* Get data object, used to perform perform get/post/patch/delete requests.
*
* @return data object. Can implement {@link com.ls.http.base.IPostableItem} or {@link com.ls.http.base.IResponseItem} in order to handle json/xml serialization/deserialization manually.
*/
@NonNull
abstract Object getManagedData();
/**
* @param method is instance od {@link BaseRequest.RequestMethod} enum, this method is called for. it can be "GET", "POST", "PUT" ,"PATCH" or "DELETE".
* @return headers for the request method specified.
*/
protected Map<String, String> getItemRequestHeaders(RequestMethod method) {
return new HashMap<String, String>();
}
;
@Override
public String getCharset() {
return null;
}
public AbstractBaseDrupalEntity(DrupalClient client) {
this.drupalClient = client;
}
@Deprecated
/**
* Method is deprecated. Use {@link #postToServer(boolean, Class, Object, com.ls.drupal.AbstractBaseDrupalEntity.OnEntityRequestListener)} method. instead
* @param synchronous
* if true - request will be performed synchronously.
* @param resultClass
* class of result or null if no result needed.
* @param tag Object tag, passer to listener after request was finished or failed because of exception.
* Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.
* You can pass null if no tag is needed
* @param listener
* @return @class ResponseData entity, containing server response string and
* code or error in case of synchronous request, null otherwise
*/
public ResponseData pushToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) {
return postToServer(synchronous, resultClass, tag, listener);
}
/**
* @param synchronous if true - request will be performed synchronously.
* @param resultClass class of result or null if no result needed.
* @param tag Object tag, passer to listener after request was finished or failed because of exception.
* Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.
* You can pass null if no tag is needed
* @return @class ResponseData entity, containing server response string and
* code or error in case of synchronous request, null otherwise
*/
public ResponseData postToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) {
Assert.assertNotNull("You have to specify drupal client in order to perform requests", this.drupalClient);
DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);
ResponseData result = this.drupalClient.postObject(this, getRequestConfig(RequestMethod.POST, resultClass), drupalTag, this, synchronous);
return result;
}
/**
* @param synchronous if true - request will be performed synchronously.
* @param resultClass class of result or null if no result needed.
* @param tag Object tag, passer to listener after request was finished or failed because of exception.
* Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.
* You can pass null if no tag is needed
* @return @class ResponseData entity, containing server response string and
* code or error in case of synchronous request, null otherwise
*/
public ResponseData putToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) {
Assert.assertNotNull("You have to specify drupal client in order to perform requests", this.drupalClient);
DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);
ResponseData result = this.drupalClient.putObject(this,
getRequestConfig(RequestMethod.PUT, resultClass), drupalTag, this, synchronous);
return result;
}
/**
* @param synchronous if true - request will be performed synchronously.
* @param tag Object tag, passer to listener after request was finished or failed because of exception.
* Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.
* You can pass null if no tag is needed
* @return @class ResponseData entity, containing server response or error
* in case of synchronous request, null otherwise
*/
public ResponseData pullFromServer(boolean synchronous, Object tag, OnEntityRequestListener listener) {
Assert.assertNotNull("You have to specify drupal client in order to perform requests", this.drupalClient);
DrupalEntityTag drupalTag = new DrupalEntityTag(true, tag, listener);
ResponseData result;
Map postParams = this.getItemRequestPostParameters();
if (postParams == null || postParams.isEmpty()) {
result = this.drupalClient.getObject(this, getRequestConfig(RequestMethod.GET, this.getManagedDataClassSpecifyer()), drupalTag, this, synchronous);
} else {
result = this.drupalClient.postObject(this, getRequestConfig(RequestMethod.POST, this.getManagedDataClassSpecifyer()), drupalTag, this, synchronous);
}
;
return result;
}
/**
* @param synchronous if true - request will be performed synchronously.
* @param resultClass class of result or null if no result needed.
* @param tag Object tag, passer to listener after request was finished or failed because of exception.
* Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.
* You can pass null if no tag is needed
* @return @class ResponseData entity, containing server response or error
* in case of synchronous request, null otherwise
*/
public ResponseData deleteFromServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) {
Assert.assertNotNull("You have to specify drupal client in order to perform requests", this.drupalClient);
DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);
ResponseData result = this.drupalClient.deleteObject(this, getRequestConfig(RequestMethod.DELETE, resultClass), drupalTag, this, synchronous);
return result;
}
// OnResponseListener methods
@Override
public void onResponseReceived(@NonNull final BaseRequest request,
@NonNull final ResponseData data,
@Nullable final Object tag) {
DrupalEntityTag entityTag = (DrupalEntityTag) tag;
if (entityTag != null && entityTag.consumeResponse) {
this.consumeObject(data);
}
if (entityTag != null && entityTag.listener != null) {
entityTag.listener.onRequestCompleted(this, entityTag.requestTag, data);
}
ConnectionManager.instance().setConnected(true);
}
@Override
public void onError(@NonNull final BaseRequest request,
@Nullable final ResponseData data,
@Nullable final Object tag) {
DrupalEntityTag entityTag = (DrupalEntityTag) tag;
if (entityTag != null && entityTag.listener != null) {
entityTag.listener.onRequestFailed(this, entityTag.requestTag, data);
}
if (data != null && VolleyResponseUtils.isNetworkingError(data.getError())) {
ConnectionManager.instance().setConnected(false);
}
}
@Override
public void onCancel(@NonNull final BaseRequest request,
@Nullable final Object tag) {
DrupalEntityTag entityTag = (DrupalEntityTag) tag;
if (entityTag != null && entityTag.listener != null) {
entityTag.listener.onRequestCanceled(this, entityTag.requestTag);
}
}
/**
* Method is used in order to apply server response result object to current instance
* and clone all fields of object specified to current one You can override this
* method in order to perform custom cloning.
*
* @param data response data, containing object to be consumed
*/
protected void consumeObject(ResponseData data) {
Object consumer = this.getManagedDataChecked();
AbstractBaseDrupalEntity.consumeObject(consumer, data.getData());
}
/**
* Method is used in order to apply server error response result object to current instance
* You can override this method in order to perform custom cloning. Default implementation does nothing
*/
protected void consumeError(ResponseData data) {
//Just a method stub to be overriden with children.
}
/**
* @param resultClass class of result or null if no result needed.
*/
protected RequestConfig getRequestConfig(RequestMethod method, Object resultClass) {
RequestConfig config = new RequestConfig(resultClass);
config.setRequestFormat(getItemRequestFormat(method));
config.setResponseFormat(getItemResponseFormat(method));
config.setErrorResponseClassSpecifier(getItemErrorResponseClassSpecifier(method));
return config;
}
/**
* Utility method, used to clone all entities non-transient fields to the consumer
*/
public static void consumeObject(Object consumer, Object entity) {
Class<?> currentClass = consumer.getClass();
while (!Object.class.equals(currentClass)) {
Field[] fields = currentClass.getDeclaredFields();
for (int counter = 0; counter < fields.length; counter++) {
Field field = fields[counter];
Expose expose = field.getAnnotation(Expose.class);
if (expose != null && !expose.deserialize() || Modifier.isTransient(field.getModifiers())) {
continue;// We don't have to copy ignored fields.
}
field.setAccessible(true);
Object value;
try {
value = field.get(entity);
// if(value != null)
// {
field.set(consumer, value);
// }
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
currentClass = currentClass.getSuperclass();
}
}
/**
* You can override this method in order to gain custom classes from "GET"
* Note: you will also have to override {@link AbstractBaseDrupalEntity#consumeObject(com.ls.http.base.ResponseData)} method in order to apply modified response class
* request response.
*
* @return Class or type of managed object.
*/
protected Object getManagedDataClassSpecifyer() {
return this.getManagedData().getClass();
}
/**
* @param method is instance of {@link BaseRequest.RequestMethod} enum, this method is called for. it can be "GET", "POST", "PUT" ,"PATCH" or "DELETE".
* @return the format entity will be serialized to. You can override this method in order to customize return. If null returned - default client format will be performed.
*/
protected BaseRequest.RequestFormat getItemRequestFormat(RequestMethod method) {
return null;
}
;
/**
* @param method is instance of {@link BaseRequest.RequestMethod} enum, this method is called for. it can be "GET", "POST", "PUT" ,"PATCH" or "DELETE".
* @return the format response entity will be formatted to. You can override this method in order to customize return. If null returned - default client format will be performed.
*/
protected BaseRequest.ResponseFormat getItemResponseFormat(RequestMethod method) {
return null;
}
;
/**
* @param method is instance of {@link BaseRequest.RequestMethod} enum, this method is called for. it can be "GET", "POST", "PUT" ,"PATCH" or "DELETE".
* @return Class or Type, returned as parsedError field of ResultData object, can be null if you don't need one.
*/
protected Object getItemErrorResponseClassSpecifier(RequestMethod method) {
return null;
}
;
public DrupalClient getDrupalClient() {
return drupalClient;
}
public void setDrupalClient(DrupalClient drupalClient) {
this.drupalClient = drupalClient;
}
// Request canceling
public void cancellAllRequests() {
this.drupalClient.cancelAllRequestsForListener(this, null);
}
// Patch method management
/**
* Creates snapshot to be used later in order to calculate differences for
* patch request.
*/
public void createSnapshot() {
this.snapshot = getCurrentStateSnapshot();
}
/**
* Release current snapshot (is recommended to perform after successful patch request)
*/
public void clearSnapshot() {
this.snapshot = null;
}
protected Snapshot getCurrentStateSnapshot() {
ObjectComparator comparator = new ObjectComparator();
return comparator.createSnapshot(this.getManagedDataChecked());
}
/**
* @param synchronous if true - request will be performed synchronously.
* @param resultClass class of result or null if no result needed.
* @param tag Object tag, passer to listener after request was finished or failed because of exception
* @return @class ResponseData entity, containing server response and
* resultClass instance or error in case of synchronous request,
* null otherwise
* @throws IllegalStateException in case if there are no changes to post. You can check if
* there are ones, calling <code>isModified()</code> method.
*/
public ResponseData patchServerData(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) throws IllegalStateException {
DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);
ResponseData result = this.drupalClient.patchObject(this,
getRequestConfig(RequestMethod.PATCH, resultClass), drupalTag, this,
synchronous);
return result;
}
public Object getPatchObject() {
ObjectComparator comparator = new ObjectComparator();
Snapshot currentState = comparator.createSnapshot(this.getManagedDataChecked());
@SuppressWarnings("null")
Object difference = this.getDifference(this.snapshot, currentState, comparator);
if (difference != null) {
return difference;
} else {
throw new IllegalStateException("There are no changes to post, check isModified() call before");
}
}
/**
* @return true if there are changes to post, false otherwise
*/
@SuppressWarnings("null")
public boolean isModified() {
ObjectComparator comparator = new ObjectComparator();
return this.isModified(this.snapshot, comparator.createSnapshot(this), comparator);
}
private boolean isModified(@NonNull Snapshot origin, @NonNull Snapshot current, @NonNull ObjectComparator comparator) {
Object difference = this.getDifference(origin, current, comparator);
return (difference != null);
}
private Object getDifference(@NonNull Snapshot origin, @NonNull Snapshot current, ObjectComparator comparator) {
Assert.assertNotNull("You have to specify drupal client in order to perform requests", this.drupalClient);
Assert.assertNotNull("You have to make initial objects snapshot in order to calculate changes", origin);
return comparator.getDifferencesJSON(origin, current);
}
@NonNull
private Object getManagedDataChecked() {
Assert.assertNotNull("You have to specify non null data object", this.getManagedData());
return getManagedData();
}
protected final class DrupalEntityTag {
public OnEntityRequestListener listener;
public Object requestTag;
public boolean consumeResponse;
public DrupalEntityTag(boolean consumeResponse, Object requestTag, OnEntityRequestListener listener) {
this.consumeResponse = consumeResponse;
this.requestTag = requestTag;
this.listener = listener;
}
}
}
|
|
/*
* Copyright 2014 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.execapp.event;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import azkaban.execapp.EventCollectorListener;
import azkaban.execapp.FlowRunner;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutionOptions;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.JavaJob;
import azkaban.executor.MockExecutorLoader;
import azkaban.executor.Status;
import azkaban.flow.Flow;
import azkaban.jobtype.JobTypeManager;
import azkaban.project.Project;
import azkaban.project.ProjectLoader;
import azkaban.project.MockProjectLoader;
import azkaban.utils.JSONUtils;
public class LocalFlowWatcherTest {
private File workingDir;
private JobTypeManager jobtypeManager;
private ProjectLoader fakeProjectLoader;
private int dirVal = 0;
@Before
public void setUp() throws Exception {
jobtypeManager =
new JobTypeManager(null, null, this.getClass().getClassLoader());
jobtypeManager.getJobTypePluginSet().addPluginClass("java", JavaJob.class);
fakeProjectLoader = new MockProjectLoader(workingDir);
}
@After
public void tearDown() throws IOException {
}
public File setupDirectory() throws IOException {
System.out.println("Create temp dir");
File workingDir = new File("_AzkabanTestDir_" + dirVal);
if (workingDir.exists()) {
FileUtils.deleteDirectory(workingDir);
}
workingDir.mkdirs();
dirVal++;
return workingDir;
}
@Ignore @Test
public void testBasicLocalFlowWatcher() throws Exception {
MockExecutorLoader loader = new MockExecutorLoader();
EventCollectorListener eventCollector = new EventCollectorListener();
File workingDir1 = setupDirectory();
FlowRunner runner1 =
createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
null);
Thread runner1Thread = new Thread(runner1);
File workingDir2 = setupDirectory();
LocalFlowWatcher watcher = new LocalFlowWatcher(runner1);
FlowRunner runner2 =
createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2,
watcher, 2);
Thread runner2Thread = new Thread(runner2);
runner1Thread.start();
runner2Thread.start();
runner2Thread.join();
FileUtils.deleteDirectory(workingDir1);
FileUtils.deleteDirectory(workingDir2);
testPipelineLevel2(runner1.getExecutableFlow(), runner2.getExecutableFlow());
}
@Ignore @Test
public void testLevel1LocalFlowWatcher() throws Exception {
MockExecutorLoader loader = new MockExecutorLoader();
EventCollectorListener eventCollector = new EventCollectorListener();
File workingDir1 = setupDirectory();
FlowRunner runner1 =
createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
null);
Thread runner1Thread = new Thread(runner1);
File workingDir2 = setupDirectory();
LocalFlowWatcher watcher = new LocalFlowWatcher(runner1);
FlowRunner runner2 =
createFlowRunner(workingDir2, loader, eventCollector, "exec1", 2,
watcher, 1);
Thread runner2Thread = new Thread(runner2);
runner1Thread.start();
runner2Thread.start();
runner2Thread.join();
FileUtils.deleteDirectory(workingDir1);
FileUtils.deleteDirectory(workingDir2);
testPipelineLevel1(runner1.getExecutableFlow(), runner2.getExecutableFlow());
}
@Ignore @Test
public void testLevel2DiffLocalFlowWatcher() throws Exception {
MockExecutorLoader loader = new MockExecutorLoader();
EventCollectorListener eventCollector = new EventCollectorListener();
File workingDir1 = setupDirectory();
FlowRunner runner1 =
createFlowRunner(workingDir1, loader, eventCollector, "exec1", 1, null,
null);
Thread runner1Thread = new Thread(runner1);
File workingDir2 = setupDirectory();
LocalFlowWatcher watcher = new LocalFlowWatcher(runner1);
FlowRunner runner2 =
createFlowRunner(workingDir2, loader, eventCollector, "exec1-mod", 2,
watcher, 1);
Thread runner2Thread = new Thread(runner2);
runner1Thread.start();
runner2Thread.start();
runner2Thread.join();
FileUtils.deleteDirectory(workingDir1);
FileUtils.deleteDirectory(workingDir2);
testPipelineLevel1(runner1.getExecutableFlow(), runner2.getExecutableFlow());
}
private void testPipelineLevel1(ExecutableFlow first, ExecutableFlow second) {
for (ExecutableNode node : second.getExecutableNodes()) {
Assert.assertEquals(node.getStatus(), Status.SUCCEEDED);
// check it's start time is after the first's children.
ExecutableNode watchedNode = first.getExecutableNode(node.getId());
if (watchedNode == null) {
continue;
}
Assert.assertEquals(watchedNode.getStatus(), Status.SUCCEEDED);
System.out.println("Node " + node.getId() + " start: "
+ node.getStartTime() + " dependent on " + watchedNode.getId() + " "
+ watchedNode.getEndTime() + " diff: "
+ (node.getStartTime() - watchedNode.getEndTime()));
Assert.assertTrue(node.getStartTime() >= watchedNode.getEndTime());
long minParentDiff = 0;
if (node.getInNodes().size() > 0) {
minParentDiff = Long.MAX_VALUE;
for (String dependency : node.getInNodes()) {
ExecutableNode parent = second.getExecutableNode(dependency);
long diff = node.getStartTime() - parent.getEndTime();
minParentDiff = Math.min(minParentDiff, diff);
}
}
long diff = node.getStartTime() - watchedNode.getEndTime();
System.out.println(" minPipelineTimeDiff:" + diff
+ " minDependencyTimeDiff:" + minParentDiff);
Assert.assertTrue(minParentDiff < 100 || diff < 100);
}
}
private void testPipelineLevel2(ExecutableFlow first, ExecutableFlow second) {
for (ExecutableNode node : second.getExecutableNodes()) {
Assert.assertEquals(node.getStatus(), Status.SUCCEEDED);
// check it's start time is after the first's children.
ExecutableNode watchedNode = first.getExecutableNode(node.getId());
if (watchedNode == null) {
continue;
}
Assert.assertEquals(watchedNode.getStatus(), Status.SUCCEEDED);
long minDiff = Long.MAX_VALUE;
for (String watchedChild : watchedNode.getOutNodes()) {
ExecutableNode child = first.getExecutableNode(watchedChild);
if (child == null) {
continue;
}
Assert.assertEquals(child.getStatus(), Status.SUCCEEDED);
long diff = node.getStartTime() - child.getEndTime();
minDiff = Math.min(minDiff, diff);
System.out.println("Node " + node.getId() + " start: "
+ node.getStartTime() + " dependent on " + watchedChild + " "
+ child.getEndTime() + " diff: " + diff);
Assert.assertTrue(node.getStartTime() >= child.getEndTime());
}
long minParentDiff = Long.MAX_VALUE;
for (String dependency : node.getInNodes()) {
ExecutableNode parent = second.getExecutableNode(dependency);
long diff = node.getStartTime() - parent.getEndTime();
minParentDiff = Math.min(minParentDiff, diff);
}
System.out.println(" minPipelineTimeDiff:" + minDiff
+ " minDependencyTimeDiff:" + minParentDiff);
Assert.assertTrue(minParentDiff < 100 || minDiff < 100);
}
}
private FlowRunner createFlowRunner(File workingDir, ExecutorLoader loader,
EventCollectorListener eventCollector, String flowName, int execId,
FlowWatcher watcher, Integer pipeline) throws Exception {
File testDir = new File("unit/executions/exectest1");
ExecutableFlow exFlow =
prepareExecDir(workingDir, testDir, flowName, execId);
ExecutionOptions option = exFlow.getExecutionOptions();
if (watcher != null) {
option.setPipelineLevel(pipeline);
option.setPipelineExecutionId(watcher.getExecId());
}
// MockProjectLoader projectLoader = new MockProjectLoader(new
// File(exFlow.getExecutionPath()));
loader.uploadExecutableFlow(exFlow);
FlowRunner runner =
new FlowRunner(exFlow, loader, fakeProjectLoader, jobtypeManager);
runner.setFlowWatcher(watcher);
runner.addListener(eventCollector);
return runner;
}
private ExecutableFlow prepareExecDir(File workingDir, File execDir,
String flowName, int execId) throws IOException {
FileUtils.copyDirectory(execDir, workingDir);
File jsonFlowFile = new File(workingDir, flowName + ".flow");
@SuppressWarnings("unchecked")
HashMap<String, Object> flowObj =
(HashMap<String, Object>) JSONUtils.parseJSONFromFile(jsonFlowFile);
Project project = new Project(1, "test");
Flow flow = Flow.flowFromObject(flowObj);
ExecutableFlow execFlow = new ExecutableFlow(project, flow);
execFlow.setExecutionId(execId);
execFlow.setExecutionPath(workingDir.getPath());
return execFlow;
}
}
|
|
/* Generated By:JJTree&JavaCC: Do not edit this line. SyntaxTreeBuilderConstants.java */
package org.openrdf.query.parser.sparql.ast;
/**
* Token literal values and constants.
* Generated by org.javacc.parser.OtherFilesGen#start()
*/
public interface SyntaxTreeBuilderConstants {
/** End of File. */
int EOF = 0;
/** RegularExpression Id. */
int WS_CHAR = 1;
/** RegularExpression Id. */
int WHITESPACE = 2;
/** RegularExpression Id. */
int SINGLE_LINE_COMMENT = 3;
/** RegularExpression Id. */
int LPAREN = 4;
/** RegularExpression Id. */
int RPAREN = 5;
/** RegularExpression Id. */
int LBRACE = 6;
/** RegularExpression Id. */
int RBRACE = 7;
/** RegularExpression Id. */
int LBRACK = 8;
/** RegularExpression Id. */
int RBRACK = 9;
/** RegularExpression Id. */
int SEMICOLON = 10;
/** RegularExpression Id. */
int COMMA = 11;
/** RegularExpression Id. */
int DOT = 12;
/** RegularExpression Id. */
int EQ = 13;
/** RegularExpression Id. */
int NE = 14;
/** RegularExpression Id. */
int GT = 15;
/** RegularExpression Id. */
int LT = 16;
/** RegularExpression Id. */
int LE = 17;
/** RegularExpression Id. */
int GE = 18;
/** RegularExpression Id. */
int NOT = 19;
/** RegularExpression Id. */
int OR = 20;
/** RegularExpression Id. */
int AND = 21;
/** RegularExpression Id. */
int PLUS = 22;
/** RegularExpression Id. */
int MINUS = 23;
/** RegularExpression Id. */
int STAR = 24;
/** RegularExpression Id. */
int QUESTION = 25;
/** RegularExpression Id. */
int SLASH = 26;
/** RegularExpression Id. */
int PIPE = 27;
/** RegularExpression Id. */
int INVERSE = 28;
/** RegularExpression Id. */
int DT_PREFIX = 29;
/** RegularExpression Id. */
int NIL = 30;
/** RegularExpression Id. */
int ANON = 31;
/** RegularExpression Id. */
int IS_A = 32;
/** RegularExpression Id. */
int BASE = 33;
/** RegularExpression Id. */
int PREFIX = 34;
/** RegularExpression Id. */
int SELECT = 35;
/** RegularExpression Id. */
int CONSTRUCT = 36;
/** RegularExpression Id. */
int DESCRIBE = 37;
/** RegularExpression Id. */
int ASK = 38;
/** RegularExpression Id. */
int DISTINCT = 39;
/** RegularExpression Id. */
int REDUCED = 40;
/** RegularExpression Id. */
int AS = 41;
/** RegularExpression Id. */
int FROM = 42;
/** RegularExpression Id. */
int NAMED = 43;
/** RegularExpression Id. */
int WHERE = 44;
/** RegularExpression Id. */
int ORDER = 45;
/** RegularExpression Id. */
int GROUP = 46;
/** RegularExpression Id. */
int BY = 47;
/** RegularExpression Id. */
int ASC = 48;
/** RegularExpression Id. */
int DESC = 49;
/** RegularExpression Id. */
int LIMIT = 50;
/** RegularExpression Id. */
int OFFSET = 51;
/** RegularExpression Id. */
int OPTIONAL = 52;
/** RegularExpression Id. */
int GRAPH = 53;
/** RegularExpression Id. */
int UNION = 54;
/** RegularExpression Id. */
int MINUS_SETOPER = 55;
/** RegularExpression Id. */
int FILTER = 56;
/** RegularExpression Id. */
int HAVING = 57;
/** RegularExpression Id. */
int EXISTS = 58;
/** RegularExpression Id. */
int NOT_EXISTS = 59;
/** RegularExpression Id. */
int STR = 60;
/** RegularExpression Id. */
int LANG = 61;
/** RegularExpression Id. */
int LANGMATCHES = 62;
/** RegularExpression Id. */
int DATATYPE = 63;
/** RegularExpression Id. */
int BOUND = 64;
/** RegularExpression Id. */
int SAMETERM = 65;
/** RegularExpression Id. */
int SPATIALOVERLAP = 66;
/** RegularExpression Id. */
int SPATIALEQUAL = 67;
/** RegularExpression Id. */
int SPATIALDISJOINT = 68;
/** RegularExpression Id. */
int SPATIALINTERSECTS = 69;
/** RegularExpression Id. */
int SPATIALTOUCHES = 70;
/** RegularExpression Id. */
int SPATIALWITHIN = 71;
/** RegularExpression Id. */
int SPATIALCONTAIN = 72;
/** RegularExpression Id. */
int SPATIALCROSSES = 73;
/** RegularExpression Id. */
int EHEQUALS = 74;
/** RegularExpression Id. */
int EHDISJOINT = 75;
/** RegularExpression Id. */
int EHOVERLAP = 76;
/** RegularExpression Id. */
int EHCOVERS = 77;
/** RegularExpression Id. */
int EHCOVEREDBY = 78;
/** RegularExpression Id. */
int EHINSIDE = 79;
/** RegularExpression Id. */
int EHCONTAINS = 80;
/** RegularExpression Id. */
int IS_IRI = 81;
/** RegularExpression Id. */
int IS_BLANK = 82;
/** RegularExpression Id. */
int IS_LITERAL = 83;
/** RegularExpression Id. */
int IS_NUMERIC = 84;
/** RegularExpression Id. */
int COALESCE = 85;
/** RegularExpression Id. */
int BNODE = 86;
/** RegularExpression Id. */
int STRDT = 87;
/** RegularExpression Id. */
int STRLANG = 88;
/** RegularExpression Id. */
int UUID = 89;
/** RegularExpression Id. */
int STRUUID = 90;
/** RegularExpression Id. */
int IRI = 91;
/** RegularExpression Id. */
int IF = 92;
/** RegularExpression Id. */
int IN = 93;
/** RegularExpression Id. */
int NOT_IN = 94;
/** RegularExpression Id. */
int COUNT = 95;
/** RegularExpression Id. */
int SUM = 96;
/** RegularExpression Id. */
int MIN = 97;
/** RegularExpression Id. */
int MAX = 98;
/** RegularExpression Id. */
int AVG = 99;
/** RegularExpression Id. */
int SAMPLE = 100;
/** RegularExpression Id. */
int GROUP_CONCAT = 101;
/** RegularExpression Id. */
int SEPARATOR = 102;
/** RegularExpression Id. */
int REGEX = 103;
/** RegularExpression Id. */
int TRUE = 104;
/** RegularExpression Id. */
int FALSE = 105;
/** RegularExpression Id. */
int BIND = 106;
/** RegularExpression Id. */
int SERVICE = 107;
/** RegularExpression Id. */
int BINDINGS = 108;
/** RegularExpression Id. */
int VALUES = 109;
/** RegularExpression Id. */
int UNDEF = 110;
/** RegularExpression Id. */
int STRLEN = 111;
/** RegularExpression Id. */
int SUBSTR = 112;
/** RegularExpression Id. */
int STR_STARTS = 113;
/** RegularExpression Id. */
int STR_ENDS = 114;
/** RegularExpression Id. */
int STR_BEFORE = 115;
/** RegularExpression Id. */
int STR_AFTER = 116;
/** RegularExpression Id. */
int REPLACE = 117;
/** RegularExpression Id. */
int UCASE = 118;
/** RegularExpression Id. */
int LCASE = 119;
/** RegularExpression Id. */
int CONCAT = 120;
/** RegularExpression Id. */
int CONTAINS = 121;
/** RegularExpression Id. */
int ENCODE_FOR_URI = 122;
/** RegularExpression Id. */
int RAND = 123;
/** RegularExpression Id. */
int ABS = 124;
/** RegularExpression Id. */
int CEIL = 125;
/** RegularExpression Id. */
int FLOOR = 126;
/** RegularExpression Id. */
int ROUND = 127;
/** RegularExpression Id. */
int NOW = 128;
/** RegularExpression Id. */
int YEAR = 129;
/** RegularExpression Id. */
int MONTH = 130;
/** RegularExpression Id. */
int DAY = 131;
/** RegularExpression Id. */
int HOURS = 132;
/** RegularExpression Id. */
int MINUTES = 133;
/** RegularExpression Id. */
int SECONDS = 134;
/** RegularExpression Id. */
int TIMEZONE = 135;
/** RegularExpression Id. */
int TZ = 136;
/** RegularExpression Id. */
int MD5 = 137;
/** RegularExpression Id. */
int SHA1 = 138;
/** RegularExpression Id. */
int SHA224 = 139;
/** RegularExpression Id. */
int SHA256 = 140;
/** RegularExpression Id. */
int SHA384 = 141;
/** RegularExpression Id. */
int SHA512 = 142;
/** RegularExpression Id. */
int LOAD = 143;
/** RegularExpression Id. */
int CLEAR = 144;
/** RegularExpression Id. */
int DROP = 145;
/** RegularExpression Id. */
int ADD = 146;
/** RegularExpression Id. */
int MOVE = 147;
/** RegularExpression Id. */
int COPY = 148;
/** RegularExpression Id. */
int CREATE = 149;
/** RegularExpression Id. */
int INSERT = 150;
/** RegularExpression Id. */
int DATA = 151;
/** RegularExpression Id. */
int DELETE = 152;
/** RegularExpression Id. */
int WITH = 153;
/** RegularExpression Id. */
int SILENT = 154;
/** RegularExpression Id. */
int DEFAULT_GRAPH = 155;
/** RegularExpression Id. */
int ALL = 156;
/** RegularExpression Id. */
int INTO = 157;
/** RegularExpression Id. */
int TO = 158;
/** RegularExpression Id. */
int USING = 159;
/** RegularExpression Id. */
int Q_IRI_REF = 160;
/** RegularExpression Id. */
int PNAME_NS = 161;
/** RegularExpression Id. */
int PNAME_LN = 162;
/** RegularExpression Id. */
int BLANK_NODE_LABEL = 163;
/** RegularExpression Id. */
int VAR1 = 164;
/** RegularExpression Id. */
int VAR2 = 165;
/** RegularExpression Id. */
int LANGTAG = 166;
/** RegularExpression Id. */
int INTEGER = 167;
/** RegularExpression Id. */
int INTEGER_POSITIVE = 168;
/** RegularExpression Id. */
int INTEGER_NEGATIVE = 169;
/** RegularExpression Id. */
int DECIMAL = 170;
/** RegularExpression Id. */
int DECIMAL1 = 171;
/** RegularExpression Id. */
int DECIMAL2 = 172;
/** RegularExpression Id. */
int DECIMAL_POSITIVE = 173;
/** RegularExpression Id. */
int DECIMAL_NEGATIVE = 174;
/** RegularExpression Id. */
int DOUBLE = 175;
/** RegularExpression Id. */
int DOUBLE1 = 176;
/** RegularExpression Id. */
int DOUBLE2 = 177;
/** RegularExpression Id. */
int DOUBLE3 = 178;
/** RegularExpression Id. */
int EXPONENT = 179;
/** RegularExpression Id. */
int DOUBLE_POSITIVE = 180;
/** RegularExpression Id. */
int DOUBLE_NEGATIVE = 181;
/** RegularExpression Id. */
int STRING_LITERAL1 = 182;
/** RegularExpression Id. */
int STRING_LITERAL2 = 183;
/** RegularExpression Id. */
int STRING_LITERAL_LONG1 = 184;
/** RegularExpression Id. */
int STRING_LITERAL_LONG2 = 185;
/** RegularExpression Id. */
int SAFE_CHAR1 = 186;
/** RegularExpression Id. */
int SAFE_CHAR2 = 187;
/** RegularExpression Id. */
int SAFE_CHAR_LONG1 = 188;
/** RegularExpression Id. */
int SAFE_CHAR_LONG2 = 189;
/** RegularExpression Id. */
int ECHAR = 190;
/** RegularExpression Id. */
int HEX = 191;
/** RegularExpression Id. */
int ALPHA = 192;
/** RegularExpression Id. */
int NUM = 193;
/** RegularExpression Id. */
int PN_CHARS_BASE = 194;
/** RegularExpression Id. */
int PN_CHARS_U = 195;
/** RegularExpression Id. */
int VAR_CHAR = 196;
/** RegularExpression Id. */
int PN_CHARS = 197;
/** RegularExpression Id. */
int PN_PREFIX = 198;
/** RegularExpression Id. */
int PN_LOCAL = 199;
/** RegularExpression Id. */
int PLX = 200;
/** RegularExpression Id. */
int PERCENT = 201;
/** RegularExpression Id. */
int PN_LOCAL_ESC = 202;
/** RegularExpression Id. */
int VARNAME = 203;
/** Lexical state. */
int DEFAULT = 0;
/** Literal token values. */
String[] tokenImage = {
"<EOF>",
"<WS_CHAR>",
"<WHITESPACE>",
"<SINGLE_LINE_COMMENT>",
"\"(\"",
"\")\"",
"\"{\"",
"\"}\"",
"\"[\"",
"\"]\"",
"\";\"",
"\",\"",
"\".\"",
"\"=\"",
"\"!=\"",
"\">\"",
"\"<\"",
"\"<=\"",
"\">=\"",
"\"!\"",
"\"||\"",
"\"&&\"",
"\"+\"",
"\"-\"",
"\"*\"",
"\"?\"",
"\"/\"",
"\"|\"",
"\"^\"",
"\"^^\"",
"<NIL>",
"<ANON>",
"\"a\"",
"\"base\"",
"\"prefix\"",
"\"select\"",
"\"construct\"",
"\"describe\"",
"\"ask\"",
"\"distinct\"",
"\"reduced\"",
"\"as\"",
"\"from\"",
"\"named\"",
"\"where\"",
"\"order\"",
"\"group\"",
"\"by\"",
"\"asc\"",
"\"desc\"",
"\"limit\"",
"\"offset\"",
"\"optional\"",
"\"graph\"",
"\"union\"",
"\"minus\"",
"\"filter\"",
"\"having\"",
"\"exists\"",
"\"not exists\"",
"\"str\"",
"\"lang\"",
"\"langmatches\"",
"\"datatype\"",
"\"bound\"",
"\"sameTerm\"",
"<SPATIALOVERLAP>",
"<SPATIALEQUAL>",
"<SPATIALDISJOINT>",
"<SPATIALINTERSECTS>",
"<SPATIALTOUCHES>",
"<SPATIALWITHIN>",
"<SPATIALCONTAIN>",
"<SPATIALCROSSES>",
"\"<http://www.opengis.net/def/function/geosparql/ehEquals>\"",
"\"<http://www.opengis.net/def/function/geosparql/ehDisjoint\"",
"\"<http://www.opengis.net/def/function/geosparql/ehOverlaps>\"",
"\"<http://www.opengis.net/def/function/geosparql/ehCovers>\"",
"\"<http://www.opengis.net/def/function/geosparql/ehCoveredBy>\"",
"\"<http://www.opengis.net/def/function/geosparql/ehInside>\"",
"\"<http://www.opengis.net/def/function/geosparql/ehContains>\"",
"<IS_IRI>",
"\"isBlank\"",
"\"isLiteral\"",
"\"isNumeric\"",
"\"coalesce\"",
"\"bnode\"",
"\"strdt\"",
"\"strlang\"",
"\"uuid\"",
"\"struuid\"",
"<IRI>",
"\"if\"",
"\"in\"",
"\"not in\"",
"\"count\"",
"\"sum\"",
"\"min\"",
"\"max\"",
"\"avg\"",
"\"sample\"",
"\"group_concat\"",
"\"separator\"",
"\"regex\"",
"\"true\"",
"\"false\"",
"\"bind\"",
"\"service\"",
"\"bindings\"",
"\"values\"",
"\"UNDEF\"",
"\"strlen\"",
"\"substr\"",
"\"strStarts\"",
"\"strEnds\"",
"\"strBefore\"",
"\"strAfter\"",
"\"replace\"",
"\"ucase\"",
"\"lcase\"",
"\"concat\"",
"\"contains\"",
"\"encode_for_URI\"",
"\"rand\"",
"\"abs\"",
"\"ceil\"",
"\"floor\"",
"\"round\"",
"\"now\"",
"\"year\"",
"\"month\"",
"\"day\"",
"\"hours\"",
"\"minutes\"",
"\"seconds\"",
"\"timezone\"",
"\"tz\"",
"\"md5\"",
"\"sha1\"",
"\"sha224\"",
"\"sha256\"",
"\"sha384\"",
"\"sha512\"",
"\"load\"",
"\"clear\"",
"\"drop\"",
"\"add\"",
"\"move\"",
"\"copy\"",
"\"create\"",
"\"insert\"",
"\"data\"",
"\"delete\"",
"\"with\"",
"\"silent\"",
"\"default\"",
"\"all\"",
"\"into\"",
"\"to\"",
"\"using\"",
"<Q_IRI_REF>",
"<PNAME_NS>",
"<PNAME_LN>",
"<BLANK_NODE_LABEL>",
"<VAR1>",
"<VAR2>",
"<LANGTAG>",
"<INTEGER>",
"<INTEGER_POSITIVE>",
"<INTEGER_NEGATIVE>",
"<DECIMAL>",
"<DECIMAL1>",
"<DECIMAL2>",
"<DECIMAL_POSITIVE>",
"<DECIMAL_NEGATIVE>",
"<DOUBLE>",
"<DOUBLE1>",
"<DOUBLE2>",
"<DOUBLE3>",
"<EXPONENT>",
"<DOUBLE_POSITIVE>",
"<DOUBLE_NEGATIVE>",
"<STRING_LITERAL1>",
"<STRING_LITERAL2>",
"<STRING_LITERAL_LONG1>",
"<STRING_LITERAL_LONG2>",
"<SAFE_CHAR1>",
"<SAFE_CHAR2>",
"<SAFE_CHAR_LONG1>",
"<SAFE_CHAR_LONG2>",
"<ECHAR>",
"<HEX>",
"<ALPHA>",
"<NUM>",
"<PN_CHARS_BASE>",
"<PN_CHARS_U>",
"<VAR_CHAR>",
"<PN_CHARS>",
"<PN_PREFIX>",
"<PN_LOCAL>",
"<PLX>",
"<PERCENT>",
"<PN_LOCAL_ESC>",
"<VARNAME>",
};
}
|
|
/**
Copyright 2008 University of Rochester
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package edu.ur.tag.repository;
import java.io.IOException;
import java.text.DecimalFormat;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* This tag takes a size in bytes an outputs the size
* in bytes if it is less than 1KB, Size in KB if it
* is less than 1MB and the size in MB if the size is
* less than 1GB and in GB otherwise - this continues up
* to exabytes
*
* @author Nathan Sarr
*
*/
public class FileSizeTag extends SimpleTagSupport{
/** bytes in a kiloByte */
public static final long bytesInKilobyte = 1024l;
/** bytes in a megabyte */
public static final long bytesInMegabyte = 1048576l;
/** bytes in a gigabyte */
public static final long bytesInGigabyte = 1073741824l;
/** bytes in a terabyte */
public static final long bytesInTerabyte = 1099511627776l;
/** bytes in a terabyte */
public static final long bytesInPedabyte = 1125899906842624l;
/** bytes in a terabyte */
public static final long bytesInExabyte = 1152921504606846976l;
/** size in bytes */
private long sizeInBytes = 0l;
/** Bytes symbol */
private String bytes = "bytes";
/** kilobytes symbol */
private String kilobytes = "KB";
/** megabytes symbol */
private String megabytes = "MB";
/** gigabytes symbol */
private String gigabytes = "GB";
/** terabytes symbol */
private String terabytes = "TB";
/** pedabytes symbol */
private String pedabytes = "PB";
/** exabytes symbol */
private String exabytes = "EX";
/** format to use when formatting the number */
private String format = "0.00";
public void doTag() throws JspException
{
DecimalFormat numberFormat = new DecimalFormat(format);
JspWriter out = this.getJspContext().getOut();
String output = "";
if( sizeInBytes < bytesInKilobyte )
{
output = sizeInBytes + " " + bytes;
}
else if( sizeInBytes >= bytesInKilobyte && sizeInBytes < bytesInMegabyte)
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInKilobyte));
output = output + " " + kilobytes;
}
else if( sizeInBytes >= bytesInMegabyte && sizeInBytes < bytesInGigabyte )
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInMegabyte));
output = output + " " + megabytes;
}
else if( sizeInBytes >= bytesInGigabyte && sizeInBytes < bytesInTerabyte )
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInGigabyte));
output = output + " " + gigabytes;
}
else if( sizeInBytes >= bytesInTerabyte && sizeInBytes < bytesInPedabyte )
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInTerabyte));
output = output + " " + terabytes;
}
else if( sizeInBytes >= bytesInPedabyte && sizeInBytes < bytesInExabyte )
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInPedabyte));
output = output + " " + pedabytes;
}
else if( sizeInBytes >= bytesInExabyte)
{
output = "" + numberFormat.format(((double)sizeInBytes/(double)bytesInExabyte));
output = output + " " + exabytes;
}
try {
out.write(output);
} catch (IOException e) {
throw new JspException(e);
}
}
public long getSizeInBytes() {
return sizeInBytes;
}
public void setSizeInBytes(long sizeInBytes) {
this.sizeInBytes = sizeInBytes;
}
public String getBytes() {
return bytes;
}
public void setBytes(String bytes) {
this.bytes = bytes;
}
public String getKilobytes() {
return kilobytes;
}
public void setKilobytes(String kilobytes) {
this.kilobytes = kilobytes;
}
public String getMegabytes() {
return megabytes;
}
public void setMegabytes(String megabytes) {
this.megabytes = megabytes;
}
public String getGigabytes() {
return gigabytes;
}
public void setGigabytes(String gigabytes) {
this.gigabytes = gigabytes;
}
public String getTerabytes() {
return terabytes;
}
public void setTerabytes(String terabytes) {
this.terabytes = terabytes;
}
public String getPedabytes() {
return pedabytes;
}
public void setPedabytes(String pedabytes) {
this.pedabytes = pedabytes;
}
public String getExabytes() {
return exabytes;
}
public void setExabytes(String exabytes) {
this.exabytes = exabytes;
}
}
|
|
/******************************************************************
* File: LPRuleStore.java
* Created by: Dave Reynolds
* Created on: 18-Jul-2003
*
* (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
* [See end of file]
* $Id: LPRuleStore.java,v 1.1 2009/06/29 08:55:33 castagna Exp $
*****************************************************************/
package com.hp.hpl.jena.reasoner.rulesys.impl;
import com.hp.hpl.jena.reasoner.TriplePattern;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.graph.*;
import java.util.*;
/**
* Holds the set of backward rules used by an LPEngine. Is responsible
* for compile the rules into internal byte codes before use.
*
* @author <a href="mailto:[email protected]">Dave Reynolds</a>
* @version $Revision: 1.1 $ on $Date: 2009/06/29 08:55:33 $
*/
public class LPRuleStore extends RuleStore {
/** Flag to indicate whether the rules have been compiled into code objects */
protected boolean isCompiled = false;
/** A map from predicate to a list of RuleClauseCode objects for that predicate.
* Uses Node_RuleVariable.WILD for wildcard predicates.
*/
protected Map<Node, List<RuleClauseCode>> predicateToCodeMap;
/** The list of all RuleClauseCode objects, used to implement wildcard queries */
protected ArrayList<RuleClauseCode> allRuleClauseCodes;
/** Two level index map - index on predicate then on object */
protected Map<Node, Map<Node, List<RuleClauseCode>>> indexPredicateToCodeMap;
/** Set of predicates which should be tabled */
protected HashSet<Node> tabledPredicates = new HashSet<Node>();
/** Threshold for number of rule entries in a predicate bucket before second level indexing kicks in */
private static final int INDEX_THRESHOLD = 20;
/** True if all goals should be treated as tabled */
protected boolean allTabled = false;
/**
* Construct a rule store containing the given rules.
* @param rules the rules to initialize the store with.
*/
public LPRuleStore(List<Rule> rules) {
super(rules);
}
/**
* Construct an empty rule store
*/
public LPRuleStore() {
super();
}
/**
* Add all the rules and tabling instructions from an existing rulestore into this one.
*/
public void addAll(LPRuleStore store) {
super.addAll(store);
tabledPredicates.addAll(store.tabledPredicates);
allTabled = tabledPredicates.contains(Node.ANY);
}
/**
* Register an RDF predicate as one whose presence in a goal should force
* the goal to be tabled.
*/
public synchronized void tablePredicate(Node predicate) {
tabledPredicates.add(predicate);
if (predicate == Node.ANY) allTabled = true;
}
/**
* Return an ordered list of RuleClauseCode objects to implement the given
* predicate.
* @param predicate the predicate node or Node_RuleVariable.WILD for wildcards.
*/
public List<RuleClauseCode> codeFor(Node predicate) {
if (!isCompiled) {
compileAll();
}
if (predicate.isVariable()) {
return allRuleClauseCodes;
} else {
List<RuleClauseCode> codeList = predicateToCodeMap.get(predicate);
if (codeList == null) {
// Uknown predicate, so only the wildcard rules apply
codeList = predicateToCodeMap.get(Node_RuleVariable.WILD);
}
return codeList;
}
}
/**
* Return an ordered list of RuleClauseCode objects to implement the given
* query pattern. This may use indexing to narrow the rule set more that the predicate-only case.
* @param goal the triple pattern that makes up the query
*/
public List<RuleClauseCode> codeFor(TriplePattern goal) {
List<RuleClauseCode> allRules = codeFor(goal.getPredicate());
if (allRules == null) {
return allRules;
}
Map<Node, List<RuleClauseCode>> indexedCodeTable = indexPredicateToCodeMap.get(goal.getPredicate());
if (indexedCodeTable != null) {
List<RuleClauseCode> indexedCode = indexedCodeTable.get(goal.getObject());
if (indexedCode != null) {
return indexedCode;
}
}
return allRules;
}
/**
* Return true if the given predicate is indexed.
*/
public boolean isIndexedPredicate(Node predicate) {
return (indexPredicateToCodeMap.get(predicate) != null);
}
/**
* Return true if the given goal is tabled, currently this is true if the
* predicate is a tabled predicate or the predicate is a wildcard and some
* tabled predictes exist.
*/
public boolean isTabled(TriplePattern goal) {
return isTabled(goal.getPredicate());
}
/**
* Return true if the given predicated is tabled, currently this is true if the
* predicate is a tabled predicate or the predicate is a wildcard and some
* tabled predictes exist.
*/
public boolean isTabled(Node predicate) {
if (allTabled) return true;
if (predicate.isVariable() && !tabledPredicates.isEmpty()) {
return true;
} else {
return tabledPredicates.contains(predicate);
}
}
/**
* Compile all the rules in a table. initially just indexed on predicate but want to
* add better indexing for the particular cases of wildcard rules and type rules.
*/
protected void compileAll() {
isCompiled = true;
predicateToCodeMap = new HashMap<Node, List<RuleClauseCode>>();
allRuleClauseCodes = new ArrayList<RuleClauseCode>();
indexPredicateToCodeMap = new HashMap<Node, Map<Node, List<RuleClauseCode>>>();
for (Iterator<Rule> ri = getAllRules().iterator(); ri.hasNext(); ) {
Rule r = ri.next();
ClauseEntry term = r.getHeadElement(0);
if (term instanceof TriplePattern) {
RuleClauseCode code = new RuleClauseCode(r);
allRuleClauseCodes.add(code);
Node predicate = ((TriplePattern)term).getPredicate();
if (predicate.isVariable()) {
predicate = Node_RuleVariable.WILD;
}
List<RuleClauseCode> predicateCode = predicateToCodeMap.get(predicate);
if (predicateCode == null) {
predicateCode = new ArrayList<RuleClauseCode>();
predicateToCodeMap.put(predicate, predicateCode);
}
predicateCode.add(code);
if (predicateCode.size() > INDEX_THRESHOLD) {
indexPredicateToCodeMap.put(predicate, new HashMap<Node, List<RuleClauseCode>>());
}
}
}
// Now add the wild card rules into the list for each non-wild predicate)
List<RuleClauseCode> wildRules = predicateToCodeMap.get(Node_RuleVariable.WILD);
if (wildRules != null) {
for (Iterator<Map.Entry<Node, List<RuleClauseCode>>> i = predicateToCodeMap.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<Node, List<RuleClauseCode>> entry = i.next();
Node predicate = entry.getKey();
List<RuleClauseCode> predicateCode = entry.getValue();
if (predicate != Node_RuleVariable.WILD) {
predicateCode.addAll(wildRules);
}
}
}
indexPredicateToCodeMap.put(Node_RuleVariable.WILD, new HashMap<Node, List<RuleClauseCode>>());
// Now built any required two level indices
for (Iterator<Map.Entry<Node, Map<Node, List<RuleClauseCode>>>> i = indexPredicateToCodeMap.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<Node, Map<Node, List<RuleClauseCode>>> entry = i.next();
Node predicate = entry.getKey();
Map<Node, List<RuleClauseCode>> predicateMap = entry.getValue();
List<RuleClauseCode> wildRulesForPredicate = new ArrayList<RuleClauseCode>();
List<RuleClauseCode> allRulesForPredicate = predicate.isVariable() ? allRuleClauseCodes : predicateToCodeMap.get(predicate);
for (Iterator<RuleClauseCode> j = allRulesForPredicate.iterator(); j.hasNext(); ) {
RuleClauseCode code = j.next();
ClauseEntry head = code.getRule().getHeadElement(0);
boolean indexed = false;
if (head instanceof TriplePattern) {
Node objectPattern = ((TriplePattern)head).getObject();
if (!objectPattern.isVariable() && !Functor.isFunctor(objectPattern)) {
// Index against object
List<RuleClauseCode> indexedCode = predicateMap.get(objectPattern);
if (indexedCode == null) {
indexedCode = new ArrayList<RuleClauseCode>();
predicateMap.put(objectPattern, indexedCode);
}
indexedCode.add(code);
indexed = true;
}
}
if (!indexed) {
wildRulesForPredicate.add(code);
}
}
// Now fold the rules that apply to any index entry into all the indexed entries
for (Iterator<Map.Entry<Node, List<RuleClauseCode>>> k = predicateMap.entrySet().iterator(); k.hasNext(); ) {
Map.Entry<Node, List<RuleClauseCode>> ent = k.next();
Node pred = ent.getKey();
List<RuleClauseCode> predicateCode = ent.getValue();
predicateCode.addAll(wildRulesForPredicate);
}
}
// Now compile all the clauses
for (Iterator<RuleClauseCode> i = allRuleClauseCodes.iterator(); i.hasNext(); ) {
RuleClauseCode code = i.next();
code.compile(this);
}
}
/**
* Add/remove a single rule from the store.
* Overridden in order to reset the "isCompiled" flag.
*
* @param rule the rule, single headed only
* @param isAdd true to add, false to remove
*/
@Override
protected void doAddRemoveRule(Rule rule, boolean isAdd) {
isCompiled = false;
super.doAddRemoveRule(rule, isAdd);
}
}
/*
(c) Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 us.vistacore.vxsync.term.hmp;
import com.fasterxml.jackson.databind.ObjectMapper;
//import gov.va.cpe.vpr.web.IHealthCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.*;
import java.util.*;
/**
* TODO: Add more metadata to the database build part: build date, build by/machine/etc, more metadata from UMLS about source (full name, desc, version, etc)
* TODO: IS there a way to ensure that the database is not in recovery mode? That really slows down the startup/shutdown process.
* @author brian
*/
public class H2TermDataSource extends AbstractTermDataSource implements ITermDataSource//, IHealthCheck
{
private static ObjectMapper MAPPER = new ObjectMapper();
private static final String CREATE_TABLE1_SQL = "CREATE TABLE IF NOT EXISTS concepts (urn VARCHAR(64) PRIMARY KEY, json CLOB NOT NULL)";
private static final String CREATE_TABLE2_SQL = "CREATE TABLE IF NOT EXISTS sources (sab VARCHAR(64) PRIMARY KEY, concept_count INT NOT NULL, term_count INT NOT NULL)";
private static final String PING_SQL = "SELECT * FROM INFORMATION_SCHEMA.users";
private Connection conn;
private PreparedStatement ps_select, ps_save,ps_del,ps_search,ps_list;
private String jdbcURL;
private Map<String,Object> sourceMap;
private static Logger LOGGER = LoggerFactory.getLogger(H2TermDataSource.class);
/**
* Private constructor. Only used for situations where we want to create a new H2 database.
* @param jdbcurl
* @throws SQLException
*/
public H2TermDataSource(String jdbcurl) throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
this.conn = DriverManager.getConnection(jdbcurl, "sa", "");
this.jdbcURL = jdbcurl;
// do the tables exist?
boolean exists = false;
ResultSet rs = this.conn.getMetaData().getTables(null, null, "concepts", null);
if (rs.next()) {
exists = true;
}
rs.close();
// create/initalize the DB if needed
if (!exists) {
this.conn.prepareCall(CREATE_TABLE1_SQL).execute();
this.conn.prepareCall(CREATE_TABLE2_SQL).execute();
// FullTextLucene4.init(this.conn);
}
// setup the prepared statements we will use
ps_select = this.conn.prepareStatement("SELECT json FROM concepts WHERE urn=?");
ps_save = this.conn.prepareStatement("INSERT INTO concepts VALUES (?, ?)");
ps_del = this.conn.prepareStatement("DELETE FROM concepts WHERE urn=?");
ps_list = this.conn.prepareStatement("SELECT urn FROM concepts WHERE urn > ? ORDER BY urn ASC");
ps_list.setMaxRows(1000);
ps_search = this.conn.prepareStatement("SELECT urn FROM concepts WHERE urn=?"); // temporary
// ps_search = this.conn.prepareStatement("SELECT keys[0] as key FROM FTL4_SEARCH_DATA(?,25,0)");
// gather the list of reference terminologies this database file contains
PreparedStatement src_ps = null;
try {
src_ps = this.conn.prepareStatement("SELECT * FROM sources");
ResultSetMetaData meta = src_ps.getMetaData();
rs = src_ps.executeQuery();
Map<String, Object> sources = new HashMap<String,Object>();
while (rs.next()) {
HashMap<String, Object> row = new HashMap<String, Object>();
for (int i=1; i <= meta.getColumnCount(); i++) {
row.put(meta.getColumnName(i), rs.getObject(i));
}
sources.put(rs.getString("sab"), row);
}
this.sourceMap = sources;
} catch (SQLException ex) {
System.err.println("Error reading sources");
ex.printStackTrace();
} finally {
if (src_ps != null) src_ps.close();
}
}
public void save(Map<String, Object> data) {
try {
ps_del.setString(1, (String) data.get("urn"));
ps_del.execute();
ps_save.setString(1, (String) data.get("urn"));
Clob jsondata = this.conn.createClob();
jsondata.setString(1, MAPPER.writeValueAsString(data));
ps_save.setClob(2, jsondata);
ps_save.execute();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Connection getConnection() {
return this.conn;
}
public void commit() throws SQLException {
this.conn.commit();
}
public void close() throws IOException {
//Commenting out the 'shutdown defrag' operation to speed shutdown up
// LOGGER.info("Starting 'shutdown defrag' for " + jdbcURL);
// this.conn.createStatement().execute("shutdown defrag");
// LOGGER.info("'shutdown defrag' complete for " + jdbcURL);
try {
this.conn.close();
} catch (Exception e) {
LOGGER.error("Error in close()", e);
throw new IOException(e);
}
}
public int size() throws SQLException {
int ret = -1;
ResultSet rs = this.conn.createStatement().executeQuery("SELECT count(*) FROM concepts");
if (rs.next()) {
ret = rs.getInt(1);
}
rs.close();
return ret;
}
@Override
public Iterator<String> iterator() {
return new DBIterator();
}
/** Returns a list (of up to 1000) concepts for the given SAB starting at startCode */
public List<String> fetchConceptList(String startCode) {
List<String> ret = new ArrayList<String>();
ResultSet rs = null;
try {
ps_list.setString(1, startCode);
rs = ps_list.executeQuery();
while (rs.next()) {
ret.add(rs.getString(1));
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return ret;
}
@Override
public Set<String> getCodeSystemList() {
if (this.sourceMap == null) return null;
return this.sourceMap.keySet();
}
@Override
public Map<String, Object> getCodeSystemMap() {
return this.sourceMap;
}
@Override
public List<String> search(String text) {
ResultSet rs = null;
try {
List<String> ret = new ArrayList<String>();
ps_search.setString(1, text);
rs = ps_search.executeQuery();
while (rs.next()) {
ret.add(rs.getString(1));
}
return ret;
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public synchronized String getConceptJSON(String urn) {
ResultSet rs = null;
try {
ps_select.setString(1, urn);
rs = ps_select.executeQuery();
if (rs!=null && rs.next()) {
return rs.getString(1);
}
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
@Override
public synchronized Map<String, Object> getConceptData(String urn) {
String json = getConceptJSON(urn);
if (json == null) return null;
Map<String, Object> data = null;
try {
data = MAPPER.readValue(json, Map.class);
} catch (Exception ex) {
throw new RuntimeException("Unable to parse JSON.", ex);
}
// Fix list to set issue for: sameas, parents, ancestors
for (String key : new String[] {"sameas", "parents", "ancestors"}) {
List<String> list = (List<String>) data.get(key);
if (list != null) data.put(key, new HashSet<String>(list));
}
// fix list to set issue for rels.value
if (data.containsKey("rels")) {
Map<String,List<String>> rels = (Map<String, List<String>>) data.get("rels");
Map<String,Set<String>> rels2 = new HashMap<>();
for (String key : rels.keySet()) {
rels2.put(key, new HashSet<String>(rels.get(key)));
}
data.put("rels", rels2);
}
return data;
}
@Override
public String toString() {
return getClass().getName() + ": " + jdbcURL;
}
// @Override
public String getHealthCheckName() {
return jdbcURL;
}
// @Override
public boolean isAlive() {
try {
this.conn.prepareCall(PING_SQL).execute();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private class DBIterator implements Iterator<String> {
private List<String> chunk;
private Iterator<String> itr;
public DBIterator() {
this.chunk = fetchConceptList("");
this.itr = chunk.iterator();
}
@Override
public boolean hasNext() {
if (!itr.hasNext() && chunk.size() > 0) {
// at the end of this chunk, try to get a new one...
String last = chunk.get(chunk.size()-1);
this.chunk = fetchConceptList(last);
this.itr = chunk.iterator();
}
return itr.hasNext();
}
@Override
public String next() {
return itr.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
|
|
package desmoj.core.report;
import java.util.Vector;
/**
* The central object for distributing the messages generated by a simulation
* run. The MessageDistributor can receive messages and reporters and forwards
* them to the <code>MessageReceiver</code> objects registered at this
* MessageDistributor. When registering, the <code>MessageReceiver</code> has
* to pass a type to identify which type of messages they want to have
* forwarded. Note that multiple <code>MessageReceiver</code> s can be
* registered to get the same type of messages as well as a
* <code>MessageReceiver</code> can be registered with different types of
* messages, if it is capable of handling such. This enables a modeller i.e. to
* get the error messages displayed on screen additional to the file being
* stored on harddisk by default. This is also handy if a simulation should be
* run as an Applet thus having no or restricted disk access and using multiple
* scrollable windows instead.
*
* @version DESMO-J, Ver. 2.4.1 copyright (c) 2014
* @author Tim Lechler
*
* 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.
*
*/
public class MessageDistributor implements MessageReceiver {
/**
* The special class for reporters to send all reporters to the experiment's
* standard report ouput.
*/
private static Class<?> reporters;
/**
* The first item of the list of registered message types.
*/
private MLink _head;
/**
* The inner class messagelink keeps track of the types of messages and
* their related messagereceiver objects. Designed as an inner class to
* messagedistributor, not visible outside.
*
* @author Tim Lechler
*/
private static class MLink {
/**
* The link to the next link for the next messagetype
*/
MLink next;
/**
* The type of message that a messagereceiver object is registered with.
*/
Class<?> msgType;
/**
* The Vector filled with messagereceivers registered to receive
* messages of the attached type.
*/
Vector<MessageReceiver> clients;
/**
* Flag to state whether the current type of message is being
* distributed or currently not distributed. Can be set via
* <code>SwitchOn()</code> or <code>SwitchOff()</code> methods.
*/
boolean isOn;
/**
* Counts the number of future messages to be skipped. This is necessary
* to blend out any model activities that are related to internal
* operations and thus would confuse the modeller.
*/
int skipCount;
/**
* Constructs a link with the given parameters. This is just a
* convenient shorthand for setting up the parameters each at a time.
*/
MLink(MLink nextLink, Class<?> messageType, boolean showing) {
isOn = showing; // switches output to receivers on (true) or off
// (false)
next = nextLink; // ref to next messageType
skipCount = 0; // no messages to be skipped now
msgType = messageType; // the class of the MessageType
clients = new Vector<MessageReceiver>(3); // max. number of standard clients are
// 2,
// so we have one spare for each type
}
}
/**
* Constructs a new messagedistributor.
*/
public MessageDistributor() {
super();
try {
reporters = Class.forName("desmoj.core.report.Reporter");
} catch (ClassNotFoundException cnfEx) {
throw (new desmoj.core.exception.DESMOJException(
new ErrorMessage(
null,
"Can't find class \"desmoj.core.report.Reporter\"!",
"MessageDistributor-Contructor.",
"The classfile is probably missing or does not reside in the"
+ "folder /desmoj/report.",
"Make sure to have the DESMOJ framework installed correctly",
null)));
}
}
/**
* De-registers the given messagereceiver from all types of Messages it was
* registered at. The given messagereceiver is taken from all lists of
* messagereceiver.
*
* @param out
* MessageReceiver : The messagereceiver to be removed from all
* messages' lists of receivers
*/
public void deRegister(MessageReceiver out) {
// check parameter
if (out == null)
return; // invalid param, so just return
if (_head == null)
return; // nobody registered yet
// now scan through all queues and issue removal
for (MLink tmp = _head; tmp != null; tmp = tmp.next) {
tmp.clients.removeElement(out);
if (tmp.clients.isEmpty()) { // if last is taken, trash
// messagelink
if (tmp == _head) {
_head = _head.next; // special care for first element in
// list
return; // there can't be any more left to check
} else {
tmp = tmp.next; // remove MessageLink
if (tmp == null)
return; // there can't be any more left to check
}
}
}
}
/**
* De-registers a messagereceiver object to stop receiving messages of the
* given type. The given messagereceiver object is taken from the list of
* messagereceiver receiving messages of the passed messagetype. If invalid
* parameters are given (i.e. <code>null</code> references) this method
* simply returns
*
* @param out
* MessageReceiver : The messagereceiver to be de-registered
* @param messageType
* java.lang.Class : The type of messages the messagereceiver
* should be deregistered from
*/
public void deRegister(MessageReceiver out, Class<?> messageType) {
// check parameters
if (out == null)
return; // invalid params
if (messageType == null)
return; // invalid params
// get link for messageType
MLink tmp = linkOf(messageType);
if (tmp == null)
return; // not registered, so why bother and return
// from here on everything must be checked so...
tmp.clients.removeElement(out); // ...get rid of the client
if (tmp.clients.isEmpty()) { // if last is taken, trash messagelink
if (tmp == _head) {
_head = _head.next; // special care for first element in list
} else {
tmp = tmp.next; // remove MessageLink
}
}
}
/**
* De-registers a messagereceiver object to stop receiving messages of the
* given type. The given messagereceiver object is taken from the list of
* messagereceivers receiving messages of the passed messagetype. If invalid
* parameters are given (i.e. <code>null</code> references) this method
* simply returns
*
* @param out
* MessageReceiver : The messagereceiver to be de-registered
* @param className
* String : The type of messages the messagereceiver
* should be deregistered from
*/
public void deRegister(MessageReceiver out, String className) {
// check parameters
if (out == null)
return; // invalid params
if (className == null)
return; // invalid params
// get the type
Class<?> messageType = null;
try {
messageType = Class.forName(className);
} catch (ClassNotFoundException cnfx) {
return; // send message that class is not in scope
}
// get link for messageType
MLink tmp = linkOf(messageType);
if (tmp == null)
return; // not registered, so why bother and retur
// from here on everything must be checked so...
tmp.clients.removeElement(out); // ...get rid of the client
if (tmp.clients.isEmpty()) { // if last is taken, trash messagelink
if (tmp == _head) {
_head = _head.next; // special care for first element in list
} else {
tmp = tmp.next; // remove MessageLink
}
}
}
/**
* Checks if the current messagetype is switched on to be distributed. If
* not, no messages of the given type are distributed or the given type of
* message is not registered here.
*
* @return boolean : Is <code>true</code> if the type of message is
* distributed <code>false</code> if not or messagetype is not
* registered here
*/
public boolean isOn(Class<?> messageType) {
if (messageType == null)
return false;
MLink tmp = linkOf(messageType);
if (tmp == null)
return false; // type not registered here
if (tmp.isOn) {
return true;
} else
return false;
}
/**
* Checks if the given messagetype is registered at this messagedistributor.
*
* @return boolean : Is <code>true</code> if the messagetype is
* registered, <code>false</code> if not
*/
public boolean isRegistered(Class<?> messageType) {
if (messageType == null)
return false;
MLink tmp = linkOf(messageType);
if (tmp == null)
return false; // type not registered here
else
return true;
}
/**
* Returns the messagelink for the given class or <code>null</code> if the
* class is not already registered.
*
* @return MessageLink : The messagelink for the given class or
* <code>null</code> if the given class is not registered yet
* @param messageType
* java.lang.Class : The class that the link is needed for
*/
private MLink linkOf(Class<?> messageType) {
if (_head == null)
return null;
else {
for (MLink tmp = _head; tmp != null; tmp = tmp.next) {
if (tmp.msgType == messageType)
return tmp;
}
}
return null;
}
/**
* Receives a message and forwards it to all messagereceiver objects
* registered with the type of message sent. Messages are sent, if the type
* of message is switched on and if the skipCounter is zero, thus not
* skipping any messages of that type.
*
* @param m
* Message : The message to be forwarded to all registered
* MessageReceivers
*/
public void receive(Message m) {
if (m == null)
return; // again nulls
MLink tmp = linkOf(m.getClass()); // get link in list of msgTypes
if (tmp == null)
return; // is null if type not registered here, so return???
// checks if the message has to be skipped
if (tmp.skipCount > 0) {
tmp.skipCount--;
return;
}
// check if messages of this type should be distributed to their
// message receivers
if (!tmp.isOn)
return;
// loop + send to all receivers
for (int i = 0; i < tmp.clients.size(); i++) {
tmp.clients.elementAt(i).receive(m);
}
}
/**
* Receives a reporter and forwards it to all messagereceiver objects
* registered with the type of reporter sent.
*
* @param r
* Reporter : The reporter to be forwarded to all registered
* messagereceivers.
*/
public void receive(desmoj.core.report.Reporter r) {
if (r == null)
return; // again nulls
MLink tmp = linkOf(reporters); // get link in list of msgTypes
if (tmp == null)
return; // is null if type not registered here, so return???
for (int i = 0; i < tmp.clients.size(); i++) { // loop and
((MessageReceiver) tmp.clients.elementAt(i)).receive(r);
}
}
/**
* Registers a messagereceiver object to receive messages of the given type.
*
* @param out
* MessageReceiver : The messagereceiver to be registered
* @param messageType
* java.lang.Class : The type of messages the messagereceiver is
* registered with
*/
public void register(MessageReceiver out, Class<?> messageType) {
// check parameters
if (out == null)
return; // invalid param
if (messageType == null)
return; // invalid param
// now look up for link to registered messageType
MLink tmp = linkOf(messageType);
// check link and insert or create new type link
if (tmp != null) { // type is already known!
if (tmp.clients.contains(out)) { // check if already reg'd
return; // already inside
} else { // client is new to this messagetype, so...
tmp.clients.addElement(out); // ...add the client
return; // we're done
}
} else { // messageType not registered here, so do it now
// create the new link. New Links are added at first position
_head = new MLink(_head, messageType, true);
_head.clients.addElement(out); // add the output
}
}
/**
* Registers a messagereceiver object to receive messages of the given type.
*
* @param out
* MessageReceiver : The messagereceiver to be registered
* @param className
* java.lang.String : The name of the type of messages the
* messagereceiver is registered with
*/
public void register(MessageReceiver out, String className) {
// check parameters
if (out == null)
return; // invalid param
if ((className == null) || (className.length() == 0))
return; // invalid param
// identify the corresponding link
Class<?> messageType = null;
try {
messageType = Class.forName(className);
} catch (ClassNotFoundException cnfx) {
return; // send message that class is not in scope???
}
// now look up for link to registered messageType
MLink tmp = linkOf(messageType);
// check link and insert or create new type link
if (tmp != null) { // type is already known!
if (tmp.clients.contains(out)) { // check if already reg'd
return; // already inside
} else { // client is new to this messagetype, so...
tmp.clients.addElement(out); // ...add the client
return; // we're done
}
} else { // messageType not registered here, so do it now
// create the new link. New Links are added at first position
_head = new MLink(_head, messageType, true);
_head.clients.addElement(out); // add the output
}
}
/**
* Skips the transmission of the next tracenote or increases the skipCounter
* by one. This is necessary to blend out any activities managed by the
* framework that would otherwise confuse the modeller.
*/
public void skip(Class<?> messageType) {
if (messageType == null)
return; // no good parameter
MLink tmp = linkOf(messageType); // buffer the link to the msgType
if (tmp == null)
return; // type not registered, return
tmp.skipCount++; // well, just increase by one :-)
}
/**
* Skips the transmission of a number of future messages by increasing the
* skipCount by the given number. This is necessary to blend out any
* activities managed by the framework that would otherwise confuse the
* modeller.
*
* @param skipNumber
* int : The number of messages to skip
*/
public void skip(Class<?> messageType, int skipNumber) {
if (skipNumber < 1)
return; // check parameters for correctness
if (messageType == null)
return;
MLink tmp = linkOf(messageType);
if (tmp == null)
return;
tmp.skipCount += skipNumber; // increase by given number
}
/**
* Disables messages of the given type to be sent to the registered
* receivers.
*
* @param messageType
* Class : The type of messages to be switched off
*/
public void switchOff(Class<?> messageType) {
if (messageType == null)
return; // no good parameter
MLink tmp = linkOf(messageType); // buffer the link to the msgType
if (tmp == null)
return; // type not registered, return
tmp.isOn = false; // well, just stop sending
}
/**
* Enables messages of the given type to be sent to the registered
* receivers.
*
* @param messageType
* Class : The type of messages to be switched on
*/
public void switchOn(Class<?> messageType) {
if (messageType == null)
return; // no good parameter
MLink tmp = linkOf(messageType); // buffer the link to the msgType
if (tmp == null)
return; // type not registered, return
tmp.isOn = true; // well, go on and distribute
}
}
|
|
/**
* 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.pulsar.broker.service;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import com.google.common.collect.Sets;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.test.PortManager;
import org.apache.pulsar.broker.NoOpShutdownService;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageRoutingMode;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerBuilder;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.TypedMessageBuilder;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.TenantInfo;
import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble;
import org.apache.pulsar.zookeeper.ZookeeperServerTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReplicatorTestBase {
URL url1;
URL urlTls1;
ServiceConfiguration config1 = new ServiceConfiguration();
PulsarService pulsar1;
BrokerService ns1;
PulsarAdmin admin1;
LocalBookkeeperEnsemble bkEnsemble1;
URL url2;
URL urlTls2;
ServiceConfiguration config2 = new ServiceConfiguration();
PulsarService pulsar2;
BrokerService ns2;
PulsarAdmin admin2;
LocalBookkeeperEnsemble bkEnsemble2;
URL url3;
URL urlTls3;
ServiceConfiguration config3 = new ServiceConfiguration();
PulsarService pulsar3;
BrokerService ns3;
PulsarAdmin admin3;
LocalBookkeeperEnsemble bkEnsemble3;
ZookeeperServerTest globalZkS;
ExecutorService executor = new ThreadPoolExecutor(5, 20, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
new DefaultThreadFactory("ReplicatorTestBase"));
static final int TIME_TO_CHECK_BACKLOG_QUOTA = 5;
protected final static String TLS_SERVER_CERT_FILE_PATH = "./src/test/resources/certificate/server.crt";
protected final static String TLS_SERVER_KEY_FILE_PATH = "./src/test/resources/certificate/server.key";
// Default frequency
public int getBrokerServicePurgeInactiveFrequency() {
return 60;
}
public boolean isBrokerServicePurgeInactiveTopic() {
return false;
}
void setup() throws Exception {
log.info("--- Starting ReplicatorTestBase::setup ---");
int globalZKPort = PortManager.nextFreePort();
globalZkS = new ZookeeperServerTest(globalZKPort);
globalZkS.start();
// Start region 1
int zkPort1 = PortManager.nextFreePort();
bkEnsemble1 = new LocalBookkeeperEnsemble(3, zkPort1, () -> PortManager.nextFreePort());
bkEnsemble1.start();
int webServicePort1 = PortManager.nextFreePort();
int webServicePortTls1 = PortManager.nextFreePort();
// NOTE: we have to instantiate a new copy of System.getProperties() to make sure pulsar1 and pulsar2 have
// completely
// independent config objects instead of referring to the same properties object
config1.setClusterName("r1");
config1.setAdvertisedAddress("localhost");
config1.setWebServicePort(Optional.ofNullable(webServicePort1));
config1.setWebServicePortTls(Optional.ofNullable(webServicePortTls1));
config1.setZookeeperServers("127.0.0.1:" + zkPort1);
config1.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo");
config1.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic());
config1.setBrokerDeleteInactiveTopicsFrequencySeconds(
inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS));
config1.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort()));
config1.setBrokerServicePortTls(Optional.ofNullable(PortManager.nextFreePort()));
config1.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
config1.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
config1.setTlsTrustCertsFilePath(TLS_SERVER_CERT_FILE_PATH);
config1.setBacklogQuotaCheckIntervalInSeconds(TIME_TO_CHECK_BACKLOG_QUOTA);
config1.setDefaultNumberOfNamespaceBundles(1);
config1.setAllowAutoTopicCreationType("non-partitioned");
pulsar1 = new PulsarService(config1);
pulsar1.setShutdownService(new NoOpShutdownService());
pulsar1.start();
ns1 = pulsar1.getBrokerService();
url1 = new URL("http://localhost:" + webServicePort1);
urlTls1 = new URL("https://localhost:" + webServicePortTls1);
admin1 = PulsarAdmin.builder().serviceHttpUrl(url1.toString()).build();
// Start region 2
// Start zk & bks
int zkPort2 = PortManager.nextFreePort();
bkEnsemble2 = new LocalBookkeeperEnsemble(3, zkPort2, () -> PortManager.nextFreePort());
bkEnsemble2.start();
int webServicePort2 = PortManager.nextFreePort();
int webServicePortTls2 = PortManager.nextFreePort();
config2.setClusterName("r2");
config2.setAdvertisedAddress("localhost");
config2.setWebServicePort(Optional.ofNullable(webServicePort2));
config2.setWebServicePortTls(Optional.ofNullable(webServicePortTls2));
config2.setZookeeperServers("127.0.0.1:" + zkPort2);
config2.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo");
config2.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic());
config2.setBrokerDeleteInactiveTopicsFrequencySeconds(
inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS));
config2.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort()));
config2.setBrokerServicePortTls(Optional.ofNullable(PortManager.nextFreePort()));
config2.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
config2.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
config2.setTlsTrustCertsFilePath(TLS_SERVER_CERT_FILE_PATH);
config2.setBacklogQuotaCheckIntervalInSeconds(TIME_TO_CHECK_BACKLOG_QUOTA);
config2.setDefaultNumberOfNamespaceBundles(1);
config2.setAllowAutoTopicCreationType("non-partitioned");
pulsar2 = new PulsarService(config2);
pulsar2.setShutdownService(new NoOpShutdownService());
pulsar2.start();
ns2 = pulsar2.getBrokerService();
url2 = new URL("http://localhost:" + webServicePort2);
urlTls2 = new URL("https://localhost:" + webServicePortTls2);
admin2 = PulsarAdmin.builder().serviceHttpUrl(url2.toString()).build();
// Start region 3
// Start zk & bks
int zkPort3 = PortManager.nextFreePort();
bkEnsemble3 = new LocalBookkeeperEnsemble(3, zkPort3, () -> PortManager.nextFreePort());
bkEnsemble3.start();
int webServicePort3 = PortManager.nextFreePort();
int webServicePortTls3 = PortManager.nextFreePort();
config3.setClusterName("r3");
config3.setAdvertisedAddress("localhost");
config3.setWebServicePort(Optional.ofNullable(webServicePort3));
config3.setWebServicePortTls(Optional.ofNullable(webServicePortTls3));
config3.setZookeeperServers("127.0.0.1:" + zkPort3);
config3.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo");
config3.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic());
config3.setBrokerDeleteInactiveTopicsFrequencySeconds(
inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS));
config3.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort()));
config3.setBrokerServicePortTls(Optional.ofNullable(PortManager.nextFreePort()));
config3.setTlsEnabled(true);
config3.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
config3.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
config3.setTlsTrustCertsFilePath(TLS_SERVER_CERT_FILE_PATH);
config3.setDefaultNumberOfNamespaceBundles(1);
config3.setAllowAutoTopicCreationType("non-partitioned");
pulsar3 = new PulsarService(config3);
pulsar3.setShutdownService(new NoOpShutdownService());
pulsar3.start();
ns3 = pulsar3.getBrokerService();
url3 = new URL("http://localhost:" + webServicePort3);
urlTls3 = new URL("https://localhost:" + webServicePortTls3);
admin3 = PulsarAdmin.builder().serviceHttpUrl(url3.toString()).build();
// Provision the global namespace
admin1.clusters().createCluster("r1", new ClusterData(url1.toString(), urlTls1.toString(),
pulsar1.getSafeBrokerServiceUrl(), pulsar1.getBrokerServiceUrlTls()));
admin1.clusters().createCluster("r2", new ClusterData(url2.toString(), urlTls2.toString(),
pulsar2.getSafeBrokerServiceUrl(), pulsar2.getBrokerServiceUrlTls()));
admin1.clusters().createCluster("r3", new ClusterData(url3.toString(), urlTls3.toString(),
pulsar3.getSafeBrokerServiceUrl(), pulsar3.getBrokerServiceUrlTls()));
admin1.tenants().createTenant("pulsar",
new TenantInfo(Sets.newHashSet("appid1", "appid2", "appid3"), Sets.newHashSet("r1", "r2", "r3")));
admin1.namespaces().createNamespace("pulsar/ns", Sets.newHashSet("r1", "r2", "r3"));
admin1.namespaces().createNamespace("pulsar/ns1", Sets.newHashSet("r1", "r2"));
assertEquals(admin2.clusters().getCluster("r1").getServiceUrl(), url1.toString());
assertEquals(admin2.clusters().getCluster("r2").getServiceUrl(), url2.toString());
assertEquals(admin2.clusters().getCluster("r3").getServiceUrl(), url3.toString());
assertEquals(admin2.clusters().getCluster("r1").getBrokerServiceUrl(), pulsar1.getSafeBrokerServiceUrl());
assertEquals(admin2.clusters().getCluster("r2").getBrokerServiceUrl(), pulsar2.getSafeBrokerServiceUrl());
assertEquals(admin2.clusters().getCluster("r3").getBrokerServiceUrl(), pulsar3.getSafeBrokerServiceUrl());
// Also create V1 namespace for compatibility check
admin1.clusters().createCluster("global", new ClusterData("http://global:8080", "https://global:8443"));
admin1.namespaces().createNamespace("pulsar/global/ns");
admin1.namespaces().setNamespaceReplicationClusters("pulsar/global/ns", Sets.newHashSet("r1", "r2", "r3"));
Thread.sleep(100);
log.info("--- ReplicatorTestBase::setup completed ---");
}
private int inSec(int time, TimeUnit unit) {
return (int) TimeUnit.SECONDS.convert(time, unit);
}
void shutdown() throws Exception {
log.info("--- Shutting down ---");
executor.shutdown();
admin1.close();
admin2.close();
admin3.close();
pulsar3.close();
pulsar2.close();
pulsar1.close();
bkEnsemble1.stop();
bkEnsemble2.stop();
bkEnsemble3.stop();
globalZkS.stop();
}
static class MessageProducer implements AutoCloseable {
URL url;
String namespace;
String topicName;
PulsarClient client;
Producer<byte[]> producer;
MessageProducer(URL url, final TopicName dest) throws Exception {
this.url = url;
this.namespace = dest.getNamespace();
this.topicName = dest.toString();
client = PulsarClient.builder().serviceUrl(url.toString()).statsInterval(0, TimeUnit.SECONDS).build();
producer = client.newProducer()
.topic(topicName)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.SinglePartition)
.create();
}
MessageProducer(URL url, final TopicName dest, boolean batch) throws Exception {
this.url = url;
this.namespace = dest.getNamespace();
this.topicName = dest.toString();
client = PulsarClient.builder().serviceUrl(url.toString()).statsInterval(0, TimeUnit.SECONDS).build();
ProducerBuilder<byte[]> producerBuilder = client.newProducer()
.topic(topicName)
.enableBatching(batch)
.batchingMaxPublishDelay(1, TimeUnit.SECONDS)
.batchingMaxMessages(5);
producer = producerBuilder.create();
}
void produceBatch(int messages) throws Exception {
log.info("Start sending batch messages");
for (int i = 0; i < messages; i++) {
producer.sendAsync(("test-" + i).getBytes());
log.info("queued message {}", ("test-" + i));
}
producer.flush();
}
void produce(int messages) throws Exception {
log.info("Start sending messages");
for (int i = 0; i < messages; i++) {
producer.send(("test-" + i).getBytes());
log.info("Sent message {}", ("test-" + i));
}
}
TypedMessageBuilder<byte[]> newMessage() {
return producer.newMessage();
}
void produce(int messages, TypedMessageBuilder<byte[]> messageBuilder) throws Exception {
log.info("Start sending messages");
for (int i = 0; i < messages; i++) {
final String m = new String("test-" + i);
messageBuilder.value(m.getBytes()).send();
log.info("Sent message {}", m);
}
}
public void close() {
try {
client.close();
} catch (PulsarClientException e) {
log.warn("Failed to close client", e);
}
}
}
static class MessageConsumer implements AutoCloseable {
final URL url;
final String namespace;
final String topicName;
final PulsarClient client;
final Consumer<byte[]> consumer;
MessageConsumer(URL url, final TopicName dest) throws Exception {
this(url, dest, "sub-id");
}
MessageConsumer(URL url, final TopicName dest, String subId) throws Exception {
this.url = url;
this.namespace = dest.getNamespace();
this.topicName = dest.toString();
client = PulsarClient.builder().serviceUrl(url.toString()).statsInterval(0, TimeUnit.SECONDS).build();
try {
consumer = client.newConsumer().topic(topicName).subscriptionName(subId).subscribe();
} catch (Exception e) {
client.close();
throw e;
}
}
void receive(int messages) throws Exception {
log.info("Start receiving messages");
Message<byte[]> msg;
Set<String> receivedMessages = new TreeSet<>();
int i = 0;
while (i < messages) {
msg = consumer.receive(10, TimeUnit.SECONDS);
assertNotNull(msg);
consumer.acknowledge(msg);
String msgData = new String(msg.getData());
log.info("Received message {}", msgData);
boolean added = receivedMessages.add(msgData);
if (added) {
assertEquals(msgData, "test-" + i);
i++;
} else {
log.info("Ignoring duplicate {}", msgData);
}
}
}
boolean drained() throws Exception {
return consumer.receive(0, TimeUnit.MICROSECONDS) == null;
}
public void close() {
try {
client.close();
} catch (PulsarClientException e) {
log.warn("Failed to close client", e);
}
}
}
private static final Logger log = LoggerFactory.getLogger(ReplicatorTestBase.class);
}
|
|
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Locale;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.DefaultNHttpServerConnection;
import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
import org.apache.http.impl.nio.DefaultHttpServerIODispatch;
import org.apache.http.impl.nio.SSLNHttpServerConnectionFactory;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpConnectionFactory;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BasicAsyncRequestConsumer;
import org.apache.http.nio.protocol.BasicAsyncResponseProducer;
import org.apache.http.nio.protocol.HttpAsyncRequestConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestHandler;
import org.apache.http.nio.protocol.HttpAsyncRequestHandlerRegistry;
import org.apache.http.nio.protocol.HttpAsyncExchange;
import org.apache.http.nio.protocol.HttpAsyncService;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
/**
* HTTP/1.1 file server based on the non-blocking I/O model and capable of direct channel
* (zero copy) data transfer.
*/
public class NHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
// Document root directory
File docRoot = new File(args[0]);
int port = 8080;
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
// HTTP parameters for the server
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
// Create HTTP protocol processing chain
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
// Use standard server-side protocol interceptors
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Create request handler registry
HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
// Register the default handler for all URIs
reqistry.register("*", new HttpFileHandler(docRoot));
// Create server-side HTTP protocol handler
HttpAsyncService protocolHandler = new HttpAsyncService(
httpproc, new DefaultConnectionReuseStrategy(), reqistry, params) {
@Override
public void connected(final NHttpServerConnection conn) {
System.out.println(conn + ": connection open");
super.connected(conn);
}
@Override
public void closed(final NHttpServerConnection conn) {
System.out.println(conn + ": connection closed");
super.closed(conn);
}
};
// Create HTTP connection factory
NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
if (port == 8443) {
// Initialize SSL context
ClassLoader cl = NHttpServer.class.getClassLoader();
URL url = cl.getResource("my.keystore");
if (url == null) {
System.out.println("Keystore not found");
System.exit(1);
}
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "secret".toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, "secret".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
} else {
connFactory = new DefaultNHttpServerConnectionFactory(params);
}
// Create server-side I/O event dispatch
IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
// Create server-side I/O reactor
ListeningIOReactor ioReactor = new DefaultListeningIOReactor();
try {
// Listen of the given port
ioReactor.listen(new InetSocketAddress(port));
// Ready to go!
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler implements HttpAsyncRequestHandler<HttpRequest> {
private final File docRoot;
public HttpFileHandler(final File docRoot) {
super();
this.docRoot = docRoot;
}
public HttpAsyncRequestConsumer<HttpRequest> processRequest(
final HttpRequest request,
final HttpContext context) {
// Buffer request content in memory for simplicity
return new BasicAsyncRequestConsumer();
}
public void handle(
final HttpRequest request,
final HttpAsyncExchange httpexchange,
final HttpContext context) throws HttpException, IOException {
HttpResponse response = httpexchange.getResponse();
handleInternal(request, response, context);
httpexchange.submitResponse(new BasicAsyncResponseProducer(response));
}
private void handleInternal(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
NStringEntity entity = new NStringEntity(
"<html><body><h1>File" + file.getPath() +
" not found</h1></body></html>",
ContentType.create("text/html", "UTF-8"));
response.setEntity(entity);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
NStringEntity entity = new NStringEntity(
"<html><body><h1>Access denied</h1></body></html>",
ContentType.create("text/html", "UTF-8"));
response.setEntity(entity);
System.out.println("Cannot read file " + file.getPath());
} else {
NHttpConnection conn = (NHttpConnection) context.getAttribute(
ExecutionContext.HTTP_CONNECTION);
response.setStatusCode(HttpStatus.SC_OK);
NFileEntity body = new NFileEntity(file, ContentType.create("text/html"));
response.setEntity(body);
System.out.println(conn + ": serving file " + file.getPath());
}
}
}
}
|
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.standalone.pvm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.impl.pvm.ProcessDefinitionBuilder;
import org.camunda.bpm.engine.impl.pvm.PvmExecution;
import org.camunda.bpm.engine.impl.pvm.PvmProcessDefinition;
import org.camunda.bpm.engine.impl.pvm.PvmProcessInstance;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.camunda.bpm.engine.test.standalone.pvm.activities.Automatic;
import org.camunda.bpm.engine.test.standalone.pvm.activities.EmbeddedSubProcess;
import org.camunda.bpm.engine.test.standalone.pvm.activities.End;
import org.camunda.bpm.engine.test.standalone.pvm.activities.ParallelGateway;
import org.camunda.bpm.engine.test.standalone.pvm.activities.WaitState;
import org.junit.Test;
/**
* @author Tom Baeyens
*/
public class PvmEmbeddedSubProcessTest {
/**
* +------------------------------+
* | embedded subprocess |
* +-----+ | +-----------+ +---------+ | +---+
* |start|-->| |startInside|-->|endInside| |-->|end|
* +-----+ | +-----------+ +---------+ | +---+
* +------------------------------+
*/
@Test
public void testEmbeddedSubProcess() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("endInside")
.endActivity()
.createActivity("endInside")
.behavior(new End())
.endActivity()
.transition("end")
.endActivity()
.createActivity("end")
.behavior(new WaitState())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
List<String> expectedActiveActivityIds = new ArrayList<String>();
expectedActiveActivityIds.add("end");
assertEquals(expectedActiveActivityIds, processInstance.findActiveActivityIds());
}
/**
* +----------------------------------------+
* | embeddedsubprocess +----------+ |
* | +---->|endInside1| |
* | | +----------+ |
* | | |
* +-----+ | +-----------+ +----+ +----------+ | +---+
* |start|-->| |startInside|-->|fork|-->|endInside2| |-->|end|
* +-----+ | +-----------+ +----+ +----------+ | +---+
* | | |
* | | +----------+ |
* | +---->|endInside3| |
* | +----------+ |
* +----------------------------------------+
*/
@Test
public void testMultipleConcurrentEndsInsideEmbeddedSubProcess() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("fork")
.endActivity()
.createActivity("fork")
.behavior(new ParallelGateway())
.transition("endInside1")
.transition("endInside2")
.transition("endInside3")
.endActivity()
.createActivity("endInside1")
.behavior(new End())
.endActivity()
.createActivity("endInside2")
.behavior(new End())
.endActivity()
.createActivity("endInside3")
.behavior(new End())
.endActivity()
.transition("end")
.endActivity()
.createActivity("end")
.behavior(new End())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertTrue(processInstance.isEnded());
}
/**
* +-------------------------------------------------+
* | embeddedsubprocess +----------+ |
* | +---->|endInside1| |
* | | +----------+ |
* | | |
* +-----+ | +-----------+ +----+ +----+ +----------+ | +---+
* |start|-->| |startInside|-->|fork|-->|wait|-->|endInside2| |-->|end|
* +-----+ | +-----------+ +----+ +----+ +----------+ | +---+
* | | |
* | | +----------+ |
* | +---->|endInside3| |
* | +----------+ |
* +-------------------------------------------------+
*/
@Test
public void testMultipleConcurrentEndsInsideEmbeddedSubProcessWithWaitState() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("fork")
.endActivity()
.createActivity("fork")
.behavior(new ParallelGateway())
.transition("endInside1")
.transition("wait")
.transition("endInside3")
.endActivity()
.createActivity("endInside1")
.behavior(new End())
.endActivity()
.createActivity("wait")
.behavior(new WaitState())
.transition("endInside2")
.endActivity()
.createActivity("endInside2")
.behavior(new End())
.endActivity()
.createActivity("endInside3")
.behavior(new End())
.endActivity()
.transition("end")
.endActivity()
.createActivity("end")
.behavior(new End())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertFalse(processInstance.isEnded());
PvmExecution execution = processInstance.findExecution("wait");
execution.signal(null, null);
assertTrue(processInstance.isEnded());
}
/**
* +-------------------------------------------------------+
* | embedded subprocess |
* | +--------------------------------+ |
* | | nested embedded subprocess | |
* +-----+ | +-----------+ | +-----------+ +---------+ | | +---+
* |start|-->| |startInside|--> | |startInside|-->|endInside| | |-->|end|
* +-----+ | +-----------+ | +-----------+ +---------+ | | +---+
* | +--------------------------------+ |
* | |
* +-------------------------------------------------------+
*/
@Test
public void testNestedSubProcessNoEnd() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("nestedSubProcess")
.endActivity()
.createActivity("nestedSubProcess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startNestedInside")
.behavior(new Automatic())
.transition("endInside")
.endActivity()
.createActivity("endInside")
.behavior(new End())
.endActivity()
.endActivity()
.transition("end")
.endActivity()
.createActivity("end")
.behavior(new WaitState())
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
List<String> expectedActiveActivityIds = new ArrayList<String>();
expectedActiveActivityIds.add("end");
assertEquals(expectedActiveActivityIds, processInstance.findActiveActivityIds());
}
/**
* +------------------------------+
* | embedded subprocess |
* +-----+ | +-----------+ |
* |start|-->| |startInside| |
* +-----+ | +-----------+ |
* +------------------------------+
*/
@Test
public void testEmbeddedSubProcessWithoutEndEvents() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.endActivity()
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertTrue(processInstance.isEnded());
}
/**
* +-------------------------------------------------------+
* | embedded subprocess |
* | +--------------------------------+ |
* | | nested embedded subprocess | |
* +-----+ | +-----------+ | +-----------+ | |
* |start|-->| |startInside|--> | |startInside| | |
* +-----+ | +-----------+ | +-----------+ | |
* | +--------------------------------+ |
* | |
* +-------------------------------------------------------+
*/
@Test
public void testNestedSubProcessBothNoEnd() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("nestedSubProcess")
.endActivity()
.createActivity("nestedSubProcess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startNestedInside")
.behavior(new Automatic())
.endActivity()
.endActivity()
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertTrue(processInstance.isEnded());
}
/**
* +------------------------------+
* | embedded subprocess |
* +-----+ | +-----------+ +---------+ |
* |start|-->| |startInside|-->|endInside| |
* +-----+ | +-----------+ +---------+ |
* +------------------------------+
*/
@Test
public void testEmbeddedSubProcessNoEnd() {
PvmProcessDefinition processDefinition = new ProcessDefinitionBuilder()
.createActivity("start")
.initial()
.behavior(new Automatic())
.transition("embeddedsubprocess")
.endActivity()
.createActivity("embeddedsubprocess")
.scope()
.behavior(new EmbeddedSubProcess())
.createActivity("startInside")
.behavior(new Automatic())
.transition("endInside")
.endActivity()
.createActivity("endInside")
.behavior(new End())
.endActivity()
.endActivity()
.buildProcessDefinition();
PvmProcessInstance processInstance = processDefinition.createProcessInstance();
processInstance.start();
assertTrue(processInstance.isEnded());
}
}
|
|
package com.stratio.deep.cassandra.entity;
import static com.stratio.deep.cassandra.util.AnnotationUtils.MAP_ABSTRACT_TYPE_CLASSNAME_TO_JAVA_TYPE;
import static com.stratio.deep.commons.utils.AnnotationUtils.deepFieldName;
import static com.stratio.deep.commons.utils.AnnotationUtils.getBeanFieldValue;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import org.apache.cassandra.db.marshal.AbstractType;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ProtocolVersion;
import com.stratio.deep.commons.annotations.DeepField;
import com.stratio.deep.commons.entity.Cell;
import com.stratio.deep.commons.entity.IDeepType;
import com.stratio.deep.commons.exception.DeepGenericException;
import com.stratio.deep.commons.exception.DeepInstantiationException;
/**
* Created by rcrespo on 23/06/14.
*/
@Deprecated
public class CassandraCell extends Cell {
private transient CellValidator cellValidator;
private transient DataType dataType;
/**
* Factory method, creates a new CassandraCell from a basic Cell. The keys in the cell will be partitionsKey<br/>
*
* @param basicCell the cell object carrying the metadata and the value
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(Cell basicCell) {
//TODO if basicCell instanceof CassandraCell => return basicCell;
return new CassandraCell(basicCell);
}
/**
* Factory method, creates a new CassandraCell from its value and metadata information<br/>
*
* @param metadata the cell object carrying the metadata for this new CassandraCell
* @param cellValue the cell value, provided as a ByteBuffer.
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(Cell metadata, Object cellValue) {
return new CassandraCell(metadata, cellValue);
}
/**
* Factory method, creates a new CassandraCell from its value and metadata information<br/>
*
* @param metadata the cell object carrying the metadata for this new CassandraCell
* @param cellValue the cell value, provided as a ByteBuffer.
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(Cell metadata, ByteBuffer cellValue) {
return new CassandraCell(metadata, cellValue);
}
/**
* Factory method, builds a new CassandraCell (isPartitionKey = false and isClusterKey = false).
* The validator will be automatically calculated using the value object type.
*
* @param cellName the cell name
* @param cellValue the cell value, provided as a ByteBuffer.
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(String cellName, Object cellValue) {
return create(cellName, cellValue, Boolean.FALSE, Boolean.FALSE);
}
/**
* Factory method, builds a new CassandraCell (isPartitionKey = false and isClusterKey = false) with value = null.
* The validator will be automatically calculated using the value object type.
*
* @param cellName the cell name
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(String cellName) {
return create(cellName, (Object) null, Boolean.FALSE, Boolean.FALSE);
}
/**
* Factory method, creates a new CassandraCell.<br/>
*
* @param cellName the cell name
* @param cellValue the cell value, provided as a ByteBuffer.
* @param isPartitionKey true if this cell is part of the cassandra's partition key.
* @param isClusterKey true if this cell is part of the cassandra's clustering key.
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(String cellName, Object cellValue, Boolean isPartitionKey,
Boolean isClusterKey) {
return new CassandraCell(cellName, cellValue, isPartitionKey, isClusterKey);
}
/**
* Factory method, creates a new metadata Cell, i.e. a Cell without value.
*
* @param cellName the cell name
* @param cellType the cell value type.
* @param isPartitionKey true if this cell is part of the cassandra's partition key.
* @param isClusterKey true if this cell is part of the cassandra's clustering key.
* @return an instance of a Cell object for the provided parameters.
*/
public static Cell create(String cellName, DataType cellType, Boolean isPartitionKey,
Boolean isClusterKey) {
return new CassandraCell(cellName, cellType, isPartitionKey, isClusterKey);
}
/**
* Constructs a Cell from a {@link com.stratio.deep.commons.annotations.DeepField} property.
*
* @param e instance of the testentity whose field is going to generate a Cell.
* @param field field that will generate the Cell.
* @param <E> a subclass of IDeepType.
* @return an instance of a Cell object for the provided parameters.
*/
public static <E extends IDeepType> Cell create(E e, Field field) {
return new CassandraCell(e, field);
}
/**
* Calculates the Cassandra validator type given the value class type.<br/>
* There's a shortcoming in the case of an UUID. At this level we are not able
* to distinguish between an UUID or a TimeUUID because twe don't have the UUID value.
*
* @param obj the value class type.
* @return the CellValidator object associated to this cell.
*/
public static CellValidator getValueType(DataType obj) {
return CellValidator.cellValidator(obj);
}
/**
* Calculates the Cassandra marshaller given the cell value.
*
* @param obj the cell value.
* @return the CellValidator object associated to this cell.
*/
public static CellValidator getValueType(Object obj) {
return CellValidator.cellValidator(obj);
}
/**
* Private constructor.
*/
private CassandraCell(String cellName, Object cellValue, Boolean isPartitionKey, Boolean isClusterKey) {
if (cellValue != null && !(cellValue instanceof Serializable)) {
throw new DeepInstantiationException("provided cell value " + cellValue + " is not serializable");
}
this.cellName = cellName;
this.cellValue = cellValue;
this.isKey = isPartitionKey;
this.isClusterKey = isClusterKey;
this.cellValidator = getValueType(cellValue);
}
/**
* Private constructor.
*/
private CassandraCell(String cellName, DataType cellType, Boolean isPartitionKey, Boolean isClusterKey) {
this.cellName = cellName;
this.isClusterKey = isClusterKey;
this.dataType = cellType;
this.isKey = isPartitionKey;
}
public DataType getDataType() {
return dataType;
}
/**
* Private constructor.
*/
private CassandraCell(Cell metadata, ByteBuffer cellValue) {
this.cellName = metadata.getCellName();
this.isClusterKey = ((CassandraCell) metadata).isClusterKey;
this.isKey = ((CassandraCell) metadata).isPartitionKey();
this.cellValidator = ((CassandraCell) metadata).cellValidator;
if (cellValue != null) {
if (((CassandraCell) metadata).getDataType() != null) {
this.cellValue = ((CassandraCell) metadata).getDataType().deserialize(cellValue, ProtocolVersion.V2);
} else {
this.cellValue = ((CassandraCell) metadata).marshaller().compose(cellValue);
}
}
}
/**
* Private constructor.
*/
private CassandraCell(Cell metadata, Object cellValue) {
if (!(cellValue instanceof Serializable)) {
throw new DeepInstantiationException("provided cell value " + cellValue + " is not serializable");
}
this.cellName = metadata.getCellName();
this.isClusterKey = ((CassandraCell) metadata).isClusterKey;
this.isKey = ((CassandraCell) metadata).isPartitionKey();
this.cellValidator = ((CassandraCell) metadata).cellValidator;
this.cellValue = cellValue;
}
/**
* Private constructor.Cassandra cell from a basic cell.
*/
private CassandraCell(Cell cell) {
this.cellName = cell.getCellName();
this.cellValue = cell.getCellValue();
this.isKey = cell.isKey();
this.cellValidator = getValueType(cellValue);
}
/**
* Private constructor.
*/
private CassandraCell(IDeepType e, Field field) {
DeepField annotation = field.getAnnotation(DeepField.class);
this.cellName = deepFieldName(field);
this.cellValue = getBeanFieldValue(e, field);
this.isClusterKey = annotation.isPartOfClusterKey();
this.isKey = annotation.isPartOfPartitionKey();
this.cellValidator = CellValidator.cellValidator(field);
}
public CellValidator getCellValidator() {
return cellValidator;
}
public Class getValueType() {
Class valueType = MAP_ABSTRACT_TYPE_CLASSNAME_TO_JAVA_TYPE.get(cellValidator.getValidatorClassName());
if (valueType == null) {
throw new DeepGenericException("Cannot find value type for marshaller " + cellValidator
.getValidatorClassName());
}
return valueType;
}
@SuppressWarnings("unchecked")
public ByteBuffer getDecomposedCellValue() {
if (this.cellValue != null) {
return marshaller().decompose(this.cellValue);
} else {
/* if null we propagate an empty array, see CASSANDRA-5885 and CASSANDRA-6180 */
return ByteBuffer.wrap(new byte[0]);
}
}
public Boolean isClusterKey() {
return isClusterKey;
}
public Boolean isPartitionKey() {
return isKey;
}
public Boolean isKey() {
return isClusterKey || isKey;
}
public AbstractType marshaller() {
if (cellValidator != null) {
return cellValidator.getAbstractType();
} else {
return null;
}
}
public String marshallerClassName() {
if (cellValidator != null) {
return cellValidator.getValidatorClassName();
} else {
return null;
}
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("CassandraCell{");
sb.append("cellName='").append(cellName).append('\'');
sb.append(", cellValue=").append(cellValue);
sb.append(", isPartitionKey=").append(isKey);
sb.append(", isClusterKey=").append(isClusterKey);
sb.append(", cellValidator=").append(cellValidator);
sb.append('}');
return sb.toString();
}
}
|
|
/*
* Copyright 2014-2015 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.intent;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Abstraction of multiple source to single destination connectivity intent.
*/
@Beta
public final class MultiPointToSinglePointIntent extends ConnectivityIntent {
private final Set<ConnectPoint> ingressPoints;
private final ConnectPoint egressPoint;
/**
* Creates a new multi-to-single point connectivity intent for the specified
* traffic selector and treatment.
*
* @param appId application identifier
* @param key intent key
* @param selector traffic selector
* @param treatment treatment
* @param ingressPoints set of ports from which ingress traffic originates
* @param egressPoint port to which traffic will egress
* @param constraints constraints to apply to the intent
* @param priority priority to use for flows generated by this intent
* @throws NullPointerException if {@code ingressPoints} or
* {@code egressPoint} is null.
* @throws IllegalArgumentException if the size of {@code ingressPoints} is
* not more than 1
*/
private MultiPointToSinglePointIntent(ApplicationId appId,
Key key,
TrafficSelector selector,
TrafficTreatment treatment,
Set<ConnectPoint> ingressPoints,
ConnectPoint egressPoint,
List<Constraint> constraints,
int priority) {
super(appId, key, Collections.emptyList(), selector, treatment, constraints,
priority);
checkNotNull(ingressPoints);
checkArgument(!ingressPoints.isEmpty(), "Ingress point set cannot be empty");
checkNotNull(egressPoint);
checkArgument(!ingressPoints.contains(egressPoint),
"Set of ingresses should not contain egress (egress: %s)", egressPoint);
this.ingressPoints = Sets.newHashSet(ingressPoints);
this.egressPoint = egressPoint;
}
/**
* Constructor for serializer.
*/
protected MultiPointToSinglePointIntent() {
super();
this.ingressPoints = null;
this.egressPoint = null;
}
/**
* Returns a new multi point to single point intent builder. The application id,
* ingress points and egress point are required fields. If they are
* not set by calls to the appropriate methods, an exception will
* be thrown.
*
* @return single point to multi point builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder of a multi point to single point intent.
*/
public static final class Builder extends ConnectivityIntent.Builder {
Set<ConnectPoint> ingressPoints;
ConnectPoint egressPoint;
private Builder() {
// Hide constructor
}
@Override
public Builder appId(ApplicationId appId) {
return (Builder) super.appId(appId);
}
@Override
public Builder key(Key key) {
return (Builder) super.key(key);
}
@Override
public Builder selector(TrafficSelector selector) {
return (Builder) super.selector(selector);
}
@Override
public Builder treatment(TrafficTreatment treatment) {
return (Builder) super.treatment(treatment);
}
@Override
public Builder constraints(List<Constraint> constraints) {
return (Builder) super.constraints(constraints);
}
@Override
public Builder priority(int priority) {
return (Builder) super.priority(priority);
}
/**
* Sets the ingress point of the single point to multi point intent
* that will be built.
*
* @param ingressPoints ingress connect points
* @return this builder
*/
public Builder ingressPoints(Set<ConnectPoint> ingressPoints) {
this.ingressPoints = ImmutableSet.copyOf(ingressPoints);
return this;
}
/**
* Sets the egress point of the multi point to single point intent
* that will be built.
*
* @param egressPoint egress connect point
* @return this builder
*/
public Builder egressPoint(ConnectPoint egressPoint) {
this.egressPoint = egressPoint;
return this;
}
/**
* Builds a multi point to single point intent from the
* accumulated parameters.
*
* @return point to point intent
*/
public MultiPointToSinglePointIntent build() {
return new MultiPointToSinglePointIntent(
appId,
key,
selector,
treatment,
ingressPoints,
egressPoint,
constraints,
priority
);
}
}
/**
* Returns the set of ports on which ingress traffic should be connected to
* the egress port.
*
* @return set of ingress ports
*/
public Set<ConnectPoint> ingressPoints() {
return ingressPoints;
}
/**
* Returns the port on which the traffic should egress.
*
* @return egress port
*/
public ConnectPoint egressPoint() {
return egressPoint;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("id", id())
.add("key", key())
.add("appId", appId())
.add("priority", priority())
.add("resources", resources())
.add("selector", selector())
.add("treatment", treatment())
.add("ingress", ingressPoints())
.add("egress", egressPoint())
.add("constraints", constraints())
.toString();
}
}
|
|
/*
* Copyright 2006 The Closure Compiler 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.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback;
import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
import com.google.javascript.rhino.Node;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* Analyzes properties on prototypes.
*
* Uses a reference graph to analyze prototype properties. Each unique property
* name is represented by a node in this graph. An edge from property A to
* property B means that there's a GETPROP access of a property B on some
* object inside of a method named A.
*
* Global functions are also represented by nodes in this graph, with
* similar semantics.
*
* @author [email protected] (Nick Santos)
*/
class AnalyzePrototypeProperties implements CompilerPass {
// Constants for symbol types, for easier readability.
private static final SymbolType PROPERTY = SymbolType.PROPERTY;
private static final SymbolType VAR = SymbolType.VAR;
private final AbstractCompiler compiler;
private final boolean canModifyExterns;
private final boolean anchorUnusedVars;
private final JSModuleGraph moduleGraph;
private final JSModule firstModule;
// Properties that are implicitly used as part of the JS language.
private static final Set<String> IMPLICITLY_USED_PROPERTIES =
ImmutableSet.of("length", "toString", "valueOf");
// A graph where the nodes are property names or variable names,
// and the edges signify the modules where the property is referenced.
// For example, if we had the code:
//
// Foo.prototype.bar = function(x) { x.baz(); }; // in module 2.;
//
// then this would be represented in the graph by a node representing
// "bar", a node representing "baz", and an edge between them representing
// module #2.
//
// Similarly, if we had:
//
// var scotch = function(f) { return f.age(); };
//
// then there would be a node for "scotch", a node for "age", and an edge
// from scotch to age.
private final LinkedDirectedGraph<NameInfo, JSModule> symbolGraph =
LinkedDirectedGraph.createWithoutAnnotations();
// A dummy node for representing global references.
private final NameInfo globalNode = new NameInfo("[global]");
// A dummy node for representing extern references.
private final NameInfo externNode = new NameInfo("[extern]");
// A dummy node for representing all anonymous functions with no names.
private final NameInfo anonymousNode = new NameInfo("[anonymous]");
// All the real NameInfo for prototype properties, hashed by the name
// of the property that they represent.
private final Map<String, NameInfo> propertyNameInfo = new LinkedHashMap<>();
// All the NameInfo for global functions, hashed by the name of the
// global variable that it's assigned to.
private final Map<String, NameInfo> varNameInfo = new LinkedHashMap<>();
/**
* Creates a new pass for analyzing prototype properties.
* @param compiler The compiler.
* @param moduleGraph The graph for resolving module dependencies. May be
* null if we don't care about module dependencies.
* @param canModifyExterns If true, then we can move prototype
* properties that are declared in the externs file.
* @param anchorUnusedVars If true, then we must mark all vars as referenced,
* even if they are never used.
*/
AnalyzePrototypeProperties(AbstractCompiler compiler,
JSModuleGraph moduleGraph, boolean canModifyExterns,
boolean anchorUnusedVars) {
this.compiler = compiler;
this.moduleGraph = moduleGraph;
this.canModifyExterns = canModifyExterns;
this.anchorUnusedVars = anchorUnusedVars;
if (moduleGraph != null) {
firstModule = moduleGraph.getRootModule();
} else {
firstModule = null;
}
globalNode.markReference(null);
externNode.markReference(null);
symbolGraph.createNode(globalNode);
symbolGraph.createNode(externNode);
for (String property : IMPLICITLY_USED_PROPERTIES) {
NameInfo nameInfo = getNameInfoForName(property, PROPERTY);
if (moduleGraph == null) {
symbolGraph.connect(externNode, null, nameInfo);
} else {
for (JSModule module : moduleGraph.getAllModules()) {
symbolGraph.connect(externNode, module, nameInfo);
}
}
}
}
@Override
public void process(Node externRoot, Node root) {
if (!canModifyExterns) {
NodeTraversal.traverseEs6(compiler, externRoot,
new ProcessExternProperties());
}
NodeTraversal.traverseEs6(compiler, root, new ProcessProperties());
FixedPointGraphTraversal<NameInfo, JSModule> t =
FixedPointGraphTraversal.newTraversal(new PropagateReferences());
t.computeFixedPoint(symbolGraph,
ImmutableSet.of(externNode, globalNode));
}
/**
* Returns information on all prototype properties.
*/
public Collection<NameInfo> getAllNameInfo() {
List<NameInfo> result = new ArrayList<>(propertyNameInfo.values());
result.addAll(varNameInfo.values());
return result;
}
/**
* Gets the name info for the property or variable of a given name,
* and creates a new one if necessary.
*
* @param name The name of the symbol.
* @param type The type of symbol.
*/
private NameInfo getNameInfoForName(String name, SymbolType type) {
Map<String, NameInfo> map = type == PROPERTY ?
propertyNameInfo : varNameInfo;
if (map.containsKey(name)) {
return map.get(name);
} else {
NameInfo nameInfo = new NameInfo(name);
map.put(name, nameInfo);
symbolGraph.createNode(nameInfo);
return nameInfo;
}
}
private class ProcessProperties implements NodeTraversal.ScopedCallback {
// There are two types of context information on this stack:
// 1) Every scope has a NameContext corresponding to its scope.
// Variables are given VAR contexts.
// Prototype properties are given PROPERTY contexts.
// The global scope is given the special [global] context.
// And function expressions that we aren't able to give a reasonable
// name are given a special [anonymous] context.
// 2) Every assignment of a prototype property of a non-function is
// given a name context. These contexts do not have scopes.
private final Stack<NameContext> symbolStack = new Stack<>();
@Override
public void enterScope(NodeTraversal t) {
Node n = t.getCurrentNode();
Scope scope = t.getScope();
Node root = scope.getRootNode();
if (root.isFunction()) {
String propName = getPrototypePropertyNameFromRValue(n);
if (propName != null) {
symbolStack.push(
new NameContext(
getNameInfoForName(propName, PROPERTY),
scope));
} else if (isGlobalFunctionDeclaration(t, n)) {
Node parent = n.getParent();
String name = parent.isName() ?
parent.getString() /* VAR */ :
n.getFirstChild().getString() /* named function */;
symbolStack.push(
new NameContext(getNameInfoForName(name, VAR), scope.getClosestHoistScope()));
} else {
// NOTE(nicksantos): We use the same anonymous node for all
// functions that do not have reasonable names. I can't remember
// at the moment why we do this. I think it's because anonymous
// nodes can never have in-edges. They're just there as a placeholder
// for scope information, and do not matter in the edge propagation.
symbolStack.push(new NameContext(anonymousNode, scope));
}
} else if (t.inGlobalScope()) {
symbolStack.push(new NameContext(globalNode, scope));
} else {
// TODO(moz): It's not yet clear if we need another kind of NameContext for block scopes
// in ES6, use anonymous node for now and investigate later.
Preconditions.checkState(NodeUtil.createsBlockScope(root), scope);
symbolStack.push(new NameContext(anonymousNode, scope));
}
}
@Override
public void exitScope(NodeTraversal t) {
symbolStack.pop();
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
// Process prototype assignments to non-functions.
String propName = processNonFunctionPrototypeAssign(n, parent);
if (propName != null) {
symbolStack.push(
new NameContext(
getNameInfoForName(propName, PROPERTY), null));
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isGetProp()) {
String propName = n.getSecondChild().getString();
if (n.isQualifiedName()) {
if (propName.equals("prototype")) {
if (processPrototypeRef(t, n)) {
return;
}
} else if (compiler.getCodingConvention().isExported(propName)) {
addGlobalUseOfSymbol(propName, t.getModule(), PROPERTY);
return;
} else {
// Do not mark prototype prop assigns as a 'use' in the global scope.
if (n.getParent().isAssign() && n.getNext() != null) {
String rValueName = getPrototypePropertyNameFromRValue(n);
if (rValueName != null) {
return;
}
}
}
}
addSymbolUse(propName, t.getModule(), PROPERTY);
} else if (n.isObjectLit()) {
// Make sure that we're not handling object literals being
// assigned to a prototype, as in:
// Foo.prototype = {bar: 3, baz: 5};
String lValueName = NodeUtil.getBestLValueName(
NodeUtil.getBestLValue(n));
if (lValueName != null && lValueName.endsWith(".prototype")) {
return;
}
// var x = {a: 1, b: 2}
// should count as a use of property a and b.
for (Node propNameNode = n.getFirstChild(); propNameNode != null;
propNameNode = propNameNode.getNext()) {
// May be STRING, GET, or SET, but NUMBER isn't interesting.
if (!propNameNode.isQuotedString()) {
addSymbolUse(propNameNode.getString(), t.getModule(), PROPERTY);
}
}
} else if (n.isName()) {
String name = n.getString();
Var var = t.getScope().getVar(name);
if (var != null) {
// Only process global functions.
if (var.isGlobal()) {
if (var.getInitialValue() != null &&
var.getInitialValue().isFunction()) {
if (t.inGlobalHoistScope()) {
if (!processGlobalFunctionDeclaration(t, n, var)) {
addGlobalUseOfSymbol(name, t.getModule(), VAR);
}
} else {
addSymbolUse(name, t.getModule(), VAR);
}
}
// If it is not a global, it might be accessing a local of the outer
// scope. If that's the case the functions between the variable's
// declaring scope and the variable reference scope cannot be moved.
} else if (var.getScope() != t.getScope()) {
for (int i = symbolStack.size() - 1; i >= 0; i--) {
NameContext context = symbolStack.get(i);
if (context.scope == var.getScope()) {
break;
}
context.name.readClosureVariables = true;
}
}
}
}
// Process prototype assignments to non-functions.
if (processNonFunctionPrototypeAssign(n, parent) != null) {
symbolStack.pop();
}
}
private void addSymbolUse(String name, JSModule module, SymbolType type) {
NameInfo info = getNameInfoForName(name, type);
NameInfo def = null;
// Skip all anonymous nodes. We care only about symbols with names.
for (int i = symbolStack.size() - 1; i >= 0; i--) {
def = symbolStack.get(i).name;
if (def != anonymousNode) {
break;
}
}
if (!def.equals(info)) {
symbolGraph.connect(def, module, info);
}
}
/**
* If this is a non-function prototype assign, return the prop name.
* Otherwise, return null.
*/
private String processNonFunctionPrototypeAssign(Node n, Node parent) {
if (isAssignRValue(n, parent) && !n.isFunction()) {
return getPrototypePropertyNameFromRValue(n);
}
return null;
}
/**
* Determines whether {@code n} is the FUNCTION node in a global function
* declaration.
*/
private boolean isGlobalFunctionDeclaration(NodeTraversal t, Node n) {
// Make sure we're not in a function scope, or if we are then the function we're looking at
// is defined in the global scope.
if (!(t.inGlobalHoistScope()
|| n.isFunction() && t.getScopeRoot() == n
&& t.getScope().getParent().getClosestHoistScope().isGlobal())) {
return false;
}
return NodeUtil.isFunctionDeclaration(n)
|| n.isFunction() && n.getParent().isName();
}
/**
* Returns true if this is the r-value of an assignment.
*/
private boolean isAssignRValue(Node n, Node parent) {
return parent != null && parent.isAssign() && parent.getFirstChild() != n;
}
/**
* Returns the name of a prototype property being assigned to this r-value.
*
* Returns null if this is not the R-value of a prototype property, or if
* the R-value is used in multiple expressions (i.e., if there's
* a prototype property assignment in a more complex expression).
*/
private String getPrototypePropertyNameFromRValue(Node rValue) {
Node lValue = NodeUtil.getBestLValue(rValue);
if (lValue == null ||
lValue.getParent() == null ||
lValue.getGrandparent() == null ||
!((NodeUtil.isObjectLitKey(lValue) && !lValue.isQuotedString()) ||
NodeUtil.isExprAssign(lValue.getGrandparent()))) {
return null;
}
String lValueName =
NodeUtil.getBestLValueName(NodeUtil.getBestLValue(rValue));
if (lValueName == null) {
return null;
}
int lastDot = lValueName.lastIndexOf('.');
if (lastDot == -1) {
return null;
}
String firstPart = lValueName.substring(0, lastDot);
if (!firstPart.endsWith(".prototype")) {
return null;
}
return lValueName.substring(lastDot + 1);
}
/**
* Processes a NAME node to see if it's a global function declaration.
* If it is, record it and return true. Otherwise, return false.
*/
private boolean processGlobalFunctionDeclaration(NodeTraversal t,
Node nameNode, Var v) {
Node firstChild = nameNode.getFirstChild();
Node parent = nameNode.getParent();
if (// Check for a named FUNCTION.
isGlobalFunctionDeclaration(t, parent) ||
// Check for a VAR declaration.
firstChild != null &&
isGlobalFunctionDeclaration(t, firstChild)) {
String name = nameNode.getString();
getNameInfoForName(name, VAR).getDeclarations().add(
new GlobalFunction(nameNode, v, t.getModule()));
// If the function name is exported, we should create an edge here
// so that it's never removed.
if (compiler.getCodingConvention().isExported(name) ||
anchorUnusedVars) {
addGlobalUseOfSymbol(name, t.getModule(), VAR);
}
return true;
}
return false;
}
/**
* Processes the GETPROP of prototype, which can either be under
* another GETPROP (in the case of Foo.prototype.bar), or can be
* under an assignment (in the case of Foo.prototype = ...).
* @return True if a declaration was added.
*/
private boolean processPrototypeRef(NodeTraversal t, Node ref) {
Node root = NodeUtil.getRootOfQualifiedName(ref);
Node n = ref.getParent();
switch (n.getToken()) {
// Foo.prototype.getBar = function() { ... }
case GETPROP:
Node dest = n.getSecondChild();
Node parent = n.getParent();
Node grandParent = parent.getParent();
if (dest.isString() &&
NodeUtil.isExprAssign(grandParent) &&
NodeUtil.isVarOrSimpleAssignLhs(n, parent)) {
String name = dest.getString();
Property prop = new AssignmentProperty(
grandParent,
maybeGetVar(t, root),
t.getModule());
getNameInfoForName(name, PROPERTY).getDeclarations().add(prop);
return true;
}
break;
// Foo.prototype = { "getBar" : function() { ... } }
case ASSIGN:
Node map = n.getSecondChild();
if (map.isObjectLit()) {
for (Node key = map.getFirstChild();
key != null; key = key.getNext()) {
if (!key.isQuotedString()) {
// May be STRING, GETTER_DEF, or SETTER_DEF,
String name = key.getString();
Property prop = new LiteralProperty(
key, key.getFirstChild(), map, n,
maybeGetVar(t, root),
t.getModule());
getNameInfoForName(name, PROPERTY).getDeclarations().add(prop);
}
}
return true;
}
break;
default:
break;
}
return false;
}
private Var maybeGetVar(NodeTraversal t, Node maybeName) {
return maybeName.isName()
? t.getScope().getVar(maybeName.getString()) : null;
}
private void addGlobalUseOfSymbol(String name, JSModule module,
SymbolType type) {
symbolGraph.connect(globalNode, module, getNameInfoForName(name, type));
}
}
private class ProcessExternProperties extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isGetProp()) {
symbolGraph.connect(externNode, firstModule,
getNameInfoForName(n.getLastChild().getString(), PROPERTY));
}
}
}
private class PropagateReferences
implements EdgeCallback<NameInfo, JSModule> {
@Override
public boolean traverseEdge(NameInfo start, JSModule edge, NameInfo dest) {
if (start.isReferenced()) {
JSModule startModule = start.getDeepestCommonModuleRef();
if (startModule != null &&
moduleGraph.dependsOn(startModule, edge)) {
return dest.markReference(startModule);
} else {
return dest.markReference(edge);
}
}
return false;
}
}
// TODO(user): We can use DefinitionsRemover and UseSite here. Then all
// we need to do is call getDefinition() and we'll magically know everything
// about the definition.
/**
* The declaration of an abstract symbol.
*/
interface Symbol {
/**
* Remove the declaration from the AST.
*/
void remove(AbstractCompiler compiler);
/**
* The variable for the root of this symbol.
*/
Var getRootVar();
/**
* Returns the module where this appears.
*/
JSModule getModule();
}
private static enum SymbolType {
PROPERTY,
VAR
}
/**
* A function initialized as a VAR statement or a function declaration.
*/
static class GlobalFunction implements Symbol {
private final Node nameNode;
private final Var var;
private final JSModule module;
GlobalFunction(Node nameNode, Var var, JSModule module) {
Node parent = nameNode.getParent();
Preconditions.checkState(
parent.isVar() ||
NodeUtil.isFunctionDeclaration(parent));
this.nameNode = nameNode;
this.var = var;
this.module = module;
}
@Override
public Var getRootVar() {
return var;
}
@Override
public void remove(AbstractCompiler compiler) {
Node parent = nameNode.getParent();
compiler.reportChangeToEnclosingScope(parent);
if (parent.isFunction() || parent.hasOneChild()) {
NodeUtil.removeChild(parent.getParent(), parent);
} else {
Preconditions.checkState(parent.isVar());
parent.removeChild(nameNode);
}
}
@Override
public JSModule getModule() {
return module;
}
}
/**
* Since there are two ways of assigning properties to prototypes, we hide
* then behind this interface so they can both be removed regardless of type.
*/
interface Property extends Symbol {
/** Returns the GETPROP node that refers to the prototype. */
Node getPrototype();
/** Returns the value of this property. */
Node getValue();
}
/**
* Properties created via EXPR assignment:
*
* <pre>function Foo() { ... };
* Foo.prototype.bar = function() { ... };</pre>
*/
static class AssignmentProperty implements Property {
private final Node exprNode;
private final Var rootVar;
private final JSModule module;
/**
* @param node An EXPR node.
*/
AssignmentProperty(Node node, Var rootVar, JSModule module) {
this.exprNode = node;
this.rootVar = rootVar;
this.module = module;
}
@Override
public Var getRootVar() {
return rootVar;
}
@Override
public void remove(AbstractCompiler compiler) {
compiler.reportChangeToEnclosingScope(exprNode);
NodeUtil.removeChild(exprNode.getParent(), exprNode);
}
@Override
public Node getPrototype() {
return getAssignNode().getFirstFirstChild();
}
@Override
public Node getValue() {
return getAssignNode().getLastChild();
}
private Node getAssignNode() {
return exprNode.getFirstChild();
}
@Override
public JSModule getModule() {
return module;
}
}
/**
* Properties created via object literals:
*
* <pre>function Foo() { ... };
* Foo.prototype = {bar: function() { ... };</pre>
*/
static class LiteralProperty implements Property {
private final Node key;
private final Node value;
private final Node map;
private final Node assign;
private final Var rootVar;
private final JSModule module;
LiteralProperty(Node key, Node value, Node map, Node assign,
Var rootVar, JSModule module) {
this.key = key;
this.value = value;
this.map = map;
this.assign = assign;
this.rootVar = rootVar;
this.module = module;
}
@Override
public Var getRootVar() {
return rootVar;
}
@Override
public void remove(AbstractCompiler compiler) {
compiler.reportChangeToEnclosingScope(key);
map.removeChild(key);
}
@Override
public Node getPrototype() {
return assign.getFirstChild();
}
@Override
public Node getValue() {
return value;
}
@Override
public JSModule getModule() {
return module;
}
}
/**
* The context of the current name. This includes the NameInfo and the scope
* if it is a scope defining name (function).
*/
private static class NameContext {
final NameInfo name;
// If this is a function context, then scope will be the scope of the
// corresponding function. Otherwise, it will be null.
final Scope scope;
NameContext(NameInfo name, Scope scope) {
this.name = name;
this.scope = scope;
}
}
/**
* Information on all properties or global variables of a given name.
*/
class NameInfo {
final String name;
private boolean referenced = false;
private final Deque<Symbol> declarations = new ArrayDeque<>();
private JSModule deepestCommonModuleRef = null;
// True if this property is a function that reads a variable from an
// outer scope which isn't the global scope.
private boolean readClosureVariables = false;
/**
* Constructs a new NameInfo.
* @param name The name of the property that this represents. May be null
* to signify dummy nodes in the property graph.
*/
NameInfo(String name) {
this.name = name;
}
@Override public String toString() { return name; }
/** Determines whether we've marked a reference to this property name. */
boolean isReferenced() {
return referenced;
}
/** Determines whether it reads a closure variable. */
boolean readsClosureVariables() {
return readClosureVariables;
}
/**
* Mark a reference in a given module to this property name, and record
* the deepest common module reference.
* @param module The module where it was referenced.
* @return Whether the name info has changed.
*/
boolean markReference(JSModule module) {
boolean hasChanged = false;
if (!referenced) {
referenced = true;
hasChanged = true;
}
if (moduleGraph != null) {
JSModule originalDeepestCommon = deepestCommonModuleRef;
if (deepestCommonModuleRef == null) {
deepestCommonModuleRef = module;
} else {
deepestCommonModuleRef =
moduleGraph.getDeepestCommonDependencyInclusive(
deepestCommonModuleRef, module);
}
if (originalDeepestCommon != deepestCommonModuleRef) {
hasChanged = true;
}
}
return hasChanged;
}
/**
* Returns the deepest common module of all the references to this
* property.
*/
JSModule getDeepestCommonModuleRef() {
return deepestCommonModuleRef;
}
/**
* Returns a mutable collection of all the prototype property declarations
* of this property name.
*/
Deque<Symbol> getDeclarations() {
return declarations;
}
}
}
|
|
package io.joynr.messaging.service;
/*
* #%L
* joynr::java::messaging::channel-service
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static com.jayway.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.google.inject.servlet.ServletModule;
import com.jayway.restassured.response.Response;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
/**
* @author christina.strobel
*
*/
public class ChannelRecoveryTest extends AbstractChannelSetUpTest {
private String serverUrl;
@Mock
ChannelRecoveryService mock;
@Mock
ChannelErrorNotifier notifierMock;
@Override
protected ServletModule getServletTestModule() {
return new ServletModule() {
@Override
protected void configureServlets() {
bind(ChannelRecoveryService.class).toInstance(mock);
bind(ChannelErrorNotifier.class).toInstance(notifierMock);
bind(ChannelRecoveryServiceRestAdapter.class);
serve("/some-channel-service/*").with(GuiceContainer.class);
}
};
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
super.setUp();
serverUrl = String.format("%s/some-channel-service/channels", getServerUrlWithoutPath());
}
@Test
public void testErrorHandlingBpRejectingLongPollsButBpcDoesntKnowChannelId() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(null);
Mockito.when(mock.createChannel("channel-123", null)).thenReturn(createChannel("0.0",
"http://joyn-bp0.muc/bp",
"channel-123"));
Response response = //
given(). //
when()
.put(serverUrl + "/channel-123?bp=0.0&status=rejecting_long_polls");
assertEquals(201 /* Created */, response.getStatusCode());
assertEquals("http://joyn-bp0.muc/bp/channels/channel-123", response.getHeader("Location"));
assertEquals("0.0", response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verify(mock).createChannel("channel-123", null);
Mockito.verifyNoMoreInteractions(mock);
}
@Test
public void testErrorHandlingBpRejectingLongPollsBecauseItWasMigrated() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(createChannel("X.Y",
"http://joyn-bpX.muc/bp",
"channel-123"));
Response response = //
given(). //
when()
.put(serverUrl + "/channel-123?bp=A.B&status=rejecting_long_polls");
assertEquals(200 /* OK */, response.getStatusCode());
assertEquals("http://joyn-bpX.muc/bp/channels/channel-123", response.getHeader("Location"));
assertEquals("X.Y", response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verifyNoMoreInteractions(mock);
}
@Test
public void testErrorHandlingBpRejectingLongPollsBecauseItLostData() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(createChannel("A.B",
"http://joyn-bpA.muc/bp",
"channel-123"));
Mockito.when(mock.recoverChannel("channel-123", "trackingId-xyz"))
.thenReturn(createChannel("A.B", "http://joyn-bpA.muc/bp", "channel-123"));
Response response = //
given(). //
when()
. //
header(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID, "trackingId-xyz")
. //
put(serverUrl + "/channel-123?bp=A.B&status=rejecting_long_polls");
assertEquals(204 /* No Content */, response.getStatusCode());
assertNull(response.getHeader("Location"));
assertNull(response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verify(mock).recoverChannel("channel-123", "trackingId-xyz");
Mockito.verifyNoMoreInteractions(mock);
}
@Test
public void testErrorHandlingBpUnreachableAndBpcDoesntKnowTheChannel() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(null);
Mockito.when(mock.createChannel("channel-123", null)).thenReturn(createChannel("X.Y",
"http://joyn-bpX.muc/bp",
"channel-123"));
Response response = //
given(). //
when()
.put(serverUrl + "/channel-123?bp=X.Y&status=unreachable");
assertEquals(201 /* Created */, response.getStatusCode());
assertEquals("http://joyn-bpX.muc/bp/channels/channel-123", response.getHeader("Location"));
assertEquals("X.Y", response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verify(mock).createChannel("channel-123", null);
Mockito.verifyNoMoreInteractions(mock);
}
@Test
public void testErrorHandlingBpUnreachableBecauseItWasMigrated() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(createChannel("X.Y",
"http://joyn-bpX.muc/bp",
"channel-123"));
Response response = //
given(). //
when()
.put(serverUrl + "/channel-123?bp=A.B&status=unreachable");
assertEquals(200 /* OK */, response.getStatusCode());
assertEquals("http://joyn-bpX.muc/bp/channels/channel-123", response.getHeader("Location"));
assertEquals("X.Y", response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verifyNoMoreInteractions(mock);
}
@Test
public void testErrorHandlingBpUnreachableForClusterControllersOnly() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(createChannel("X.Y",
"http://joyn-bpX.muc/bp",
"channel-123"));
Mockito.when(mock.isBounceProxyForChannelResponding("channel-123")).thenReturn(true);
Response response = //
given(). //
queryParam("bp", "X.Y")
.and()
.queryParam("status", "unreachable")
.when()
.put(serverUrl + "/channel-123");
assertEquals(204 /* No Content */, response.getStatusCode());
assertNull(response.getHeader("Location"));
assertNull(response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verify(mock).isBounceProxyForChannelResponding("channel-123");
Mockito.verifyNoMoreInteractions(mock);
Mockito.verify(notifierMock).alertBounceProxyUnreachable("channel-123",
"X.Y",
"127.0.0.1",
"Bounce Proxy unreachable for Cluster Controller");
}
@Test
public void testErrorHandlingBpUnreachable() {
Mockito.when(mock.getChannel("channel-123")).thenReturn(createChannel("X.Y",
"http://joyn-bpX.muc/bp",
"channel-123"));
Mockito.when(mock.isBounceProxyForChannelResponding("channel-123")).thenReturn(false);
Mockito.when(mock.createChannel("channel-123", null)).thenReturn(createChannel("1.1",
"http://joyn-bp1.muc/bp",
"channel-123"));
Response response = //
given(). //
queryParam("bp", "X.Y")
.and()
.queryParam("status", "unreachable")
.when()
.put(serverUrl + "/channel-123");
assertEquals(201 /* Created */, response.getStatusCode());
assertEquals("http://joyn-bp1.muc/bp/channels/channel-123", response.getHeader("Location"));
assertEquals("1.1", response.getHeader("bp"));
Mockito.verify(mock).getChannel("channel-123");
Mockito.verify(mock).isBounceProxyForChannelResponding("channel-123");
Mockito.verify(mock).createChannel("channel-123", null);
Mockito.verifyNoMoreInteractions(mock);
Mockito.verify(notifierMock).alertBounceProxyUnreachable("channel-123",
"X.Y",
"127.0.0.1",
"Bounce Proxy unreachable for Channel Service");
}
}
|
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.remote.grpc;
import com.google.flatbuffers.FlatBufferBuilder;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.nd4j.autodiff.execution.conf.ExecutorConfiguration;
import org.nd4j.autodiff.execution.input.OperandsAdapter;
import org.nd4j.autodiff.execution.input.Operands;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.autodiff.samediff.serde.FlatBuffersMapper;
import org.nd4j.graph.FlatDropRequest;
import org.nd4j.graph.FlatInferenceRequest;
import org.nd4j.graph.FlatVariable;
import org.nd4j.graph.IntPair;
import org.nd4j.remote.grpc.grpc.GraphInferenceServerGrpc;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.common.primitives.Pair;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
/**
* This class is a wrapper over GraphServer gRPC complex
*
* @author [email protected]
*/
@Slf4j
public class GraphInferenceGrpcClient {
private final ManagedChannel channel;
private final GraphInferenceServerGrpc.GraphInferenceServerBlockingStub blockingStub;
/**
* This method creates new GraphInferenceGrpcClient, with plain text connection
* @param host
* @param port
*/
public GraphInferenceGrpcClient(@NonNull String host, int port) {
this(host, port, false);
}
/**
* This method creates new GraphInferenceGrpcClient, with optional TLS support
* @param host
* @param port
*/
public GraphInferenceGrpcClient(@NonNull String host, int port, boolean useTLS) {
this(useTLS ? ManagedChannelBuilder.forAddress(host, port).build()
: ManagedChannelBuilder.forAddress(host, port).usePlaintext().build());
}
/**
* This method creates new GraphInferenceGrpcClient over given ManagedChannel
* @param channel
*/
public GraphInferenceGrpcClient(@NonNull ManagedChannel channel) {
this.channel = channel;
this.blockingStub = GraphInferenceServerGrpc.newBlockingStub(this.channel);
}
/**
* This method shuts down gRPC connection
*
* @throws InterruptedException
*/
public void shutdown() throws InterruptedException {
this.channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
}
/**
* This method adds given graph to the GraphServer storage
* @param graph
*/
public void registerGraph(@NonNull SameDiff graph) {
blockingStub.registerGraph(graph.asFlatGraph(false));
}
/**
* This method adds given graph to the GraphServer storage
*
* PLEASE NOTE: You don't need to register graph more then once
* PLEASE NOTE: You don't need to register graph if GraphServer was used with -f argument
* @param graphId id of the graph, if not 0 - should be used in subsequent output() requests
* @param graph
*
*/
public void registerGraph(long graphId, @NonNull SameDiff graph, ExecutorConfiguration configuration) {
val g = graph.asFlatGraph(graphId, configuration, false);
val v = blockingStub.registerGraph(g);
if (v.status() != 0)
throw new ND4JIllegalStateException("registerGraph() gRPC call failed");
}
/**
* This method sends inference request to the GraphServer instance, and returns result as array of INDArrays
*
* PLEASE NOTE: This call will be routed to default graph with id 0
* @param inputs graph inputs with their string ides
* @return
*/
public INDArray[] output(Pair<String, INDArray>... inputs) {
return output(0, inputs);
}
/**
* This method is suited for use of custom OperandsAdapters
* @param adapter
* @param <T>
* @return
*/
public <T> T output(long graphId, T value, OperandsAdapter<T> adapter) {
return adapter.output(this.output(graphId, adapter.input(value)));
}
public Operands output(long graphId, @NonNull Operands operands) {
val result = new ArrayList<INDArray>();
val builder = new FlatBufferBuilder(1024);
val ins = new int[operands.size()];
val col = operands.asCollection();
int cnt = 0;
for (val input: col) {
val id = input.getFirst();
val array = input.getSecond();
val idPair = IntPair.createIntPair(builder, id.getId(), id.getIndex());
val nameOff = id.getName() != null ? builder.createString(id.getName()) : 0;
val arrOff = array.toFlatArray(builder);
byte variableType = 0; //TODO is this OK here?
val varOff = FlatVariable.createFlatVariable(builder, idPair, nameOff, FlatBuffersMapper.getDataTypeAsByte(array.dataType()),0, arrOff, -1, variableType, 0, 0, 0);
ins[cnt++] = varOff;
}
val varsOff = FlatInferenceRequest.createVariablesVector(builder, ins);
val off = FlatInferenceRequest.createFlatInferenceRequest(builder, graphId, varsOff, 0);
builder.finish(off);
val req = FlatInferenceRequest.getRootAsFlatInferenceRequest(builder.dataBuffer());
val fr = blockingStub.inferenceRequest(req);
val res = new Operands();
for (int e = 0; e < fr.variablesLength(); e++) {
val v = fr.variables(e);
val array = Nd4j.createFromFlatArray(v.ndarray());
res.addArgument(v.name(), array);
res.addArgument(v.id().first(), v.id().second(), array);
res.addArgument(v.name(), v.id().first(), v.id().second(), array);
}
return res;
}
/**
* This method sends inference request to the GraphServer instance, and returns result as array of INDArrays
* @param graphId id of the graph
* @param inputs graph inputs with their string ides
* @return
*/
public INDArray[] output(long graphId, Pair<String, INDArray>... inputs) {
val operands = new Operands();
for (val in:inputs)
operands.addArgument(in.getFirst(), in.getSecond());
return output(graphId, operands).asArray();
}
/**
* This method allows to remove graph from the GraphServer instance
* @param graphId
*/
public void dropGraph(long graphId) {
val builder = new FlatBufferBuilder(128);
val off = FlatDropRequest.createFlatDropRequest(builder, graphId);
builder.finish(off);
val req = FlatDropRequest.getRootAsFlatDropRequest(builder.dataBuffer());
val v = blockingStub.forgetGraph(req);
if (v.status() != 0)
throw new ND4JIllegalStateException("registerGraph() gRPC call failed");
}
}
|
|
/*******************************************************************************
* Copyright 2014 Sergey Tarasevich
*
* 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.nostra13.universalimageloader.cache.disc.impl.ext;
import android.graphics.Bitmap;
import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.utils.IoUtils;
import com.nostra13.universalimageloader.utils.L;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Disk cache based on "Least-Recently Used" principle. Adapter pattern, adapts
* {@link com.nostra13.universalimageloader.cache.disc.impl.ext.DiskLruCache DiskLruCache} to
* {@link com.nostra13.universalimageloader.cache.disc.DiskCache DiskCache}
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @see FileNameGenerator
* @since 1.9.2
*/
public class LruDiscCache implements DiskCache {
/** {@value */
public static final int DEFAULT_BUFFER_SIZE = 32 * 1024; // 32 Kb
/** {@value */
public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG;
/** {@value */
public static final int DEFAULT_COMPRESS_QUALITY = 100;
private static final String ERROR_ARG_NULL = " argument must be not null";
private static final String ERROR_ARG_NEGATIVE = " argument must be positive number";
protected DiskLruCache cache;
private File reserveCacheDir;
protected final FileNameGenerator fileNameGenerator;
protected int bufferSize = DEFAULT_BUFFER_SIZE;
protected Bitmap.CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
protected int compressQuality = DEFAULT_COMPRESS_QUALITY;
/**
* @param cacheDir Directory for file caching
* @param fileNameGenerator {@linkplain com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator
* Name generator} for cached files. Generated names must match the regex
* <strong>[a-z0-9_-]{1,64}</strong>
* @param cacheMaxSize Max cache size in bytes. <b>0</b> means cache size is unlimited.
* @throws IOException if cache can't be initialized (e.g. "No space left on device")
*/
public LruDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, long cacheMaxSize) throws IOException {
this(cacheDir, null, fileNameGenerator, cacheMaxSize, 0);
}
/**
* @param cacheDir Directory for file caching
* @param reserveCacheDir null-ok; Reserve directory for file caching. It's used when the primary directory isn't available.
* @param fileNameGenerator {@linkplain com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator
* Name generator} for cached files. Generated names must match the regex
* <strong>[a-z0-9_-]{1,64}</strong>
* @param cacheMaxSize Max cache size in bytes. <b>0</b> means cache size is unlimited.
* @param cacheMaxFileCount Max file count in cache. <b>0</b> means file count is unlimited.
* @throws IOException if cache can't be initialized (e.g. "No space left on device")
*/
public LruDiscCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator, long cacheMaxSize,
int cacheMaxFileCount) throws IOException {
if (cacheDir == null) {
throw new IllegalArgumentException("cacheDir" + ERROR_ARG_NULL);
}
if (cacheMaxSize < 0) {
throw new IllegalArgumentException("cacheMaxSize" + ERROR_ARG_NEGATIVE);
}
if (cacheMaxFileCount < 0) {
throw new IllegalArgumentException("cacheMaxFileCount" + ERROR_ARG_NEGATIVE);
}
if (fileNameGenerator == null) {
throw new IllegalArgumentException("fileNameGenerator" + ERROR_ARG_NULL);
}
if (cacheMaxSize == 0) {
cacheMaxSize = Long.MAX_VALUE;
}
if (cacheMaxFileCount == 0) {
cacheMaxFileCount = Integer.MAX_VALUE;
}
this.reserveCacheDir = reserveCacheDir;
this.fileNameGenerator = fileNameGenerator;
initCache(cacheDir, reserveCacheDir, cacheMaxSize, cacheMaxFileCount);
}
private void initCache(File cacheDir, File reserveCacheDir, long cacheMaxSize, int cacheMaxFileCount)
throws IOException {
try {
cache = DiskLruCache.open(cacheDir, 1, 1, cacheMaxSize, cacheMaxFileCount);
} catch (IOException e) {
L.e(e);
if (reserveCacheDir != null) {
initCache(reserveCacheDir, null, cacheMaxSize, cacheMaxFileCount);
}
if (cache == null) {
throw e; //new RuntimeException("Can't initialize disk cache", e);
}
}
}
@Override
public File getDirectory() {
return cache.getDirectory();
}
@Override
public File get(String imageUri) {
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = cache.get(getKey(imageUri));
return snapshot == null ? null : snapshot.getFile(0);
} catch (IOException e) {
L.e(e);
return null;
} finally {
if (snapshot != null) {
snapshot.close();
}
}
}
@Override
public boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException {
DiskLruCache.Editor editor = cache.edit(getKey(imageUri));
if (editor == null) {
return false;
}
OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), bufferSize);
boolean copied = false;
try {
copied = IoUtils.copyStream(imageStream, os, listener, bufferSize);
} finally {
IoUtils.closeSilently(os);
if (copied) {
editor.commit();
} else {
editor.abort();
}
}
return copied;
}
@Override
public boolean save(String imageUri, Bitmap bitmap) throws IOException {
DiskLruCache.Editor editor = cache.edit(getKey(imageUri));
if (editor == null) {
return false;
}
OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), bufferSize);
boolean savedSuccessfully = false;
try {
savedSuccessfully = bitmap.compress(compressFormat, compressQuality, os);
} finally {
IoUtils.closeSilently(os);
}
if (savedSuccessfully) {
editor.commit();
} else {
editor.abort();
}
return savedSuccessfully;
}
@Override
public boolean remove(String imageUri) {
try {
return cache.remove(getKey(imageUri));
} catch (IOException e) {
L.e(e);
return false;
}
}
@Override
public void close() {
try {
cache.close();
} catch (IOException e) {
L.e(e);
}
cache = null;
}
@Override
public void clear() {
try {
cache.delete();
} catch (IOException e) {
L.e(e);
}
try {
initCache(cache.getDirectory(), reserveCacheDir, cache.getMaxSize(), cache.getMaxFileCount());
} catch (IOException e) {
L.e(e);
}
}
private String getKey(String imageUri) {
return fileNameGenerator.generate(imageUri);
}
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public void setCompressFormat(Bitmap.CompressFormat compressFormat) {
this.compressFormat = compressFormat;
}
public void setCompressQuality(int compressQuality) {
this.compressQuality = compressQuality;
}
}
|
|
package com.ftfl.icare.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.ftfl.icare.R;
import com.ftfl.icare.helper.ICareProfileDataSource;
import com.ftfl.icare.helper.MedicalHistoryDataSource;
import com.ftfl.icare.model.ICareProfile;
import com.ftfl.icare.model.MedicalHistory;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class FragmentAddMedicalHistory extends Fragment {
static final int CAMERA_REQUEST = 1;
String mImagePath = null;
static final String IMAGE_DIRECTORY_NAME = "Icare Images";
File image = null;
ImageView ivPrescription;
Button btnImagePrescription;
EditText etDrName;
EditText etDate;
EditText etPurpose;
EditText etSuggestion;
Button btnSave;
Spinner spGender;
ArrayAdapter<CharSequence> adapter;
MedicalHistoryDataSource mMedicalHistoryDataSource;
MedicalHistory mMedicalHistory;
FragmentManager frgManager;
Fragment fragment;
Context thiscontext;
String mID = "1";
Bundle args = new Bundle();
private SetDateOnClickDialog datePickerObj;
private setTimeOnclickDialog timePickerObj;
List<MedicalHistory> mMedicalHistoryList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_layout_add_medical_history, container, false);
thiscontext = container.getContext();
// Create global configuration and initialize ImageLoader with this
// config
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
thiscontext).defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(config);
ivPrescription = (ImageView) view.findViewById(R.id.ivPrescription);
btnImagePrescription = (Button) view
.findViewById(R.id.btnImagePrescription);
etDrName = (EditText) view.findViewById(R.id.etDrName);
etDate = (EditText) view.findViewById(R.id.etDate);
etPurpose = (EditText) view.findViewById(R.id.etPurpose);
etSuggestion = (EditText) view.findViewById(R.id.etSuggestion);
btnSave = (Button) view.findViewById(R.id.btnSave);
datePickerObj = new SetDateOnClickDialog(etDate, thiscontext);
btnImagePrescription.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent(v);
}
});
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
createMedialHistory(v);
}
});
return view;
}
public void setSpinner() {
adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.genderarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spGender.setAdapter(adapter);
}
public void createMedialHistory(View view) {
String mDoctorName = etDrName.getText().toString();
String mDate = etDate.getText().toString();
String mPurpose = etPurpose.getText().toString();
String mSuggestion = etSuggestion.getText().toString();
SharedPreferences prfs = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String mProfileId = prfs.getString("profile_id", "");
mMedicalHistory = new MedicalHistory();
mMedicalHistory.setDoctorName(mDoctorName);
mMedicalHistory.setDate(mDate);
mMedicalHistory.setPurpose(mPurpose);
mMedicalHistory.setSuggestion(mSuggestion);
mMedicalHistory.setPrescription(mImagePath);
mMedicalHistory.setProfileId(mProfileId);
mMedicalHistoryDataSource = new MedicalHistoryDataSource(getActivity());
if (mMedicalHistoryDataSource.insert(mMedicalHistory) == true) {
Toast toast = Toast.makeText(getActivity(), "Successfully Saved.",
Toast.LENGTH_LONG);
toast.show();
fragment = new FragmentHome();
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
setTitle("Home");
} else {
Toast toast = Toast.makeText(getActivity(),
"Error, Couldn't inserted data to database",
Toast.LENGTH_LONG);
toast.show();
}
}
/**
* open camera method
*/
public void dispatchTakePictureIntent(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(thiscontext.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(thiscontext, ex.getMessage(), Toast.LENGTH_SHORT)
.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
}
}
private File createImageFile() throws IOException {
if (image == null) {
// External SD card location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
mediaStorageDir /* directory */
);
}
mImagePath = image.getAbsolutePath();
return image;
}
/**
* On activity result
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
if (mImagePath != null) {
// btnProfilePhoto.setText("Change Image");
Bitmap correctBmp = null;
try {
File f = new File(mImagePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = 8;
Bitmap bmp1 = BitmapFactory.decodeStream(
new FileInputStream(f), null, option);
correctBmp = Bitmap.createBitmap(bmp1, 0, 0,
bmp1.getWidth(), bmp1.getHeight(), mat, true);
} catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
} catch (OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
DisplayImageOptions options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(100))
.cacheInMemory(true).cacheOnDisk(true).build();
ImageLoader.getInstance().displayImage("file:///" + mImagePath,
ivPrescription, options);
// mIvPhotoView.setImageBitmap(correctBmp);
}
}
}
public void setTitle(CharSequence title) {
getActivity().getActionBar().setTitle(title);
}
}
|
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.xml.*;
import com.intellij.util.xml.events.DomEvent;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
/**
* @author peter
*/
public class TreeIncrementalUpdateTest extends DomTestCase {
public void testRenameCollectionTag() throws Throwable {
final MyElement rootElement = createPhysicalElement(
"<?xml version='1.0' encoding='UTF-8'?>\n" + "<a>\n" + " <boy>\n" + " </boy>\n" + " <girl/>\n" + "</a>");
myCallRegistry.clear();
assertEquals(1, rootElement.getBoys().size());
assertEquals(1, rootElement.getGirls().size());
final MyElement oldBoy = rootElement.getBoys().get(0);
final XmlTag tag = oldBoy.getXmlTag();
assertNotNull(tag);
final int offset = tag.getTextOffset();
final int endoffset = offset+tag.getTextLength();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
rootElement.getGirls().get(0).undefine();
final Document document = getDocument(DomUtil.getFile(rootElement));
PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(document);
document.replaceString(offset+1, offset+1+"boy".length(), "girl");
commitDocument(document);
}
}.execute();
assertFalse(oldBoy.isValid());
assertEquals(0, rootElement.getBoys().size());
assertEquals(1, rootElement.getGirls().size());
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final Document document = getDocument(DomUtil.getFile(rootElement));
document.replaceString(endoffset - "boy".length(), endoffset, "girl");
commitDocument(document);
}
}.execute();
assertEquals(0, rootElement.getBoys().size());
assertEquals(1, rootElement.getGirls().size());
}
private MyElement createPhysicalElement(final String text) throws IncorrectOperationException {
final XmlFile file = (XmlFile)createFile("file.xml", text);
final DomFileElementImpl<MyElement> fileElement = getDomManager().getFileElement(file, MyElement.class, "a");
final MyElement rootElement = fileElement.getRootElement();
return rootElement;
}
public void testRenameFixedTag() throws Throwable {
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<a>\n" +
" <aboy>\n" +
" </aboy>\n" +
" <agirl/>\n" +
"</a>");
final DomFileElementImpl<MyElement> fileElement = getDomManager().getFileElement(file, MyElement.class, "a");
myCallRegistry.clear();
final MyElement rootElement = fileElement.getRootElement();
assertNotNull(rootElement.getAboy().getXmlElement());
assertNotNull(rootElement.getAgirl().getXmlElement());
final MyElement oldBoy = rootElement.getAboy();
final XmlTag tag = oldBoy.getXmlTag();
assertNotNull(tag);
final int offset = tag.getTextOffset();
final int endoffset = offset+tag.getTextLength();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
rootElement.getAgirl().undefine();
final Document document = getDocument(file);
PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(document);
document.replaceString(offset+1, offset+1+"aboy".length(), "agirl");
commitDocument(document);
}
}.execute();
assertFalse(oldBoy.isValid());
assertNull(rootElement.getAboy().getXmlElement());
assertNotNull(rootElement.getAgirl().getXmlElement());
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final Document document = getDocument(file);
document.replaceString(endoffset - "aboy".length(), endoffset, "agirl");
commitDocument(document);
}
}.execute();
assertNull(rootElement.getAboy().getXmlElement());
assertNotNull(rootElement.getAgirl().getXmlElement());
}
public void testDocumentChange() throws Throwable {
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<a>\n" +
" <child>\n" +
" <child/>\n" +
" </child>\n" +
"</a>");
final DomFileElementImpl<MyElement> fileElement =
getDomManager().getFileElement(file, MyElement.class, "a");
myCallRegistry.clear();
final MyElement rootElement = fileElement.getRootElement();
final MyElement oldLeaf = rootElement.getChild().getChild();
final XmlTag oldLeafTag = oldLeaf.getXmlTag();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final Document document = getDocument(file);
document.replaceString(0, document.getText().length(), "<a/>");
commitDocument(document);
}
}.execute();
assertFalse(oldLeafTag.isValid());
putExpected(new DomEvent(fileElement, false));
assertResultsAndClear();
assertEquals(fileElement.getRootElement(), rootElement);
assertTrue(rootElement.isValid());
assertFalse(oldLeaf.isValid());
assertTrue(rootElement.getChild().isValid());
assertNull(rootElement.getChild().getXmlTag());
assertNull(rootElement.getChild().getChild().getXmlTag());
}
public void testDocumentChange2() throws Throwable {
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<!DOCTYPE ejb-jar PUBLIC \"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN\" \"http://java.sun.com/dtd/ejb-jar_2_0.dtd\">\n" +
"<a>\n" +
" <child>\n" +
" <child/>\n" +
" </child>\n" +
"</a>");
final DomFileElementImpl<MyElement> fileElement =
getDomManager().getFileElement(file, MyElement.class, "a");
myCallRegistry.clear();
final MyElement rootElement = fileElement.getRootElement();
final MyElement oldLeaf = rootElement.getChild().getChild();
final XmlTag oldLeafTag = oldLeaf.getXmlTag();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
file.getDocument().getProlog().delete();
final XmlTag tag = file.getDocument().getRootTag();
tag.setAttribute("xmlns", "something");
tag.setAttribute("xmlns:xsi", "something");
}
}.execute();
assertTrue(oldLeafTag.isValid());
putExpected(new DomEvent(fileElement, false));
putExpected(new DomEvent(rootElement, false));
putExpected(new DomEvent(rootElement, false));
assertResultsAndClear();
assertEquals(fileElement.getRootElement(), rootElement);
assertTrue(rootElement.isValid());
assertTrue(rootElement.getChild().isValid());
assertTrue(rootElement.getChild().getXmlTag().isValid());
assertTrue(rootElement.getChild().getChild().getXmlTag().isValid());
}
public void testMoveUp() throws Throwable {
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<a>\n" +
" <child>\n" +
" <aboy />\n" +
" <agirl/>\n" +
" </child>\n" +
"</a>");
final DomFileElementImpl<MyElement> fileElement = getDomManager().getFileElement(file, MyElement.class, "a");
myCallRegistry.clear();
final MyElement rootElement = fileElement.getRootElement();
rootElement.getChild().getAboy();
rootElement.getChild().getAgirl();
final Document document = getDocument(file);
final int len = "<agirl/>".length();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final int agirl = document.getText().indexOf("<agirl/>");
final int boy = document.getText().indexOf("<aboy />");
document.replaceString(agirl, agirl + len, "<aboy />");
document.replaceString(boy, boy + len, "<agirl/>");
commitDocument(document);
}
}.execute();
assertTrue(rootElement.isValid());
final XmlTag tag1 = rootElement.getXmlTag().getSubTags()[0];
assertEquals(getDomManager().getDomElement(tag1.findFirstSubTag("agirl")), rootElement.getChild().getAgirl());
assertEquals(getDomManager().getDomElement(tag1.findFirstSubTag("aboy")), rootElement.getChild().getAboy());
}
public void testRemoveAttributeParent() throws Throwable {
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<!DOCTYPE ejb-jar PUBLIC \"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN\" \"http://java.sun.com/dtd/ejb-jar_2_0.dtd\">\n" +
"<a>\n" +
" <child-element xxx=\"239\"/>\n" +
"</a>");
final DomFileElementImpl<MyElement> fileElement =
getDomManager().getFileElement(file, MyElement.class, "a");
myCallRegistry.clear();
final MyElement rootElement = fileElement.getRootElement();
final MyElement oldLeaf = rootElement.getChildElements().get(0);
final GenericAttributeValue<String> xxx = oldLeaf.getXxx();
final XmlTag oldLeafTag = oldLeaf.getXmlTag();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
oldLeafTag.delete();
}
}.execute();
assertFalse(oldLeaf.isValid());
assertFalse(xxx.isValid());
}
public void testTypeBeforeRootTag() throws Throwable {
getDomManager().registerFileDescription(new DomFileDescription<>(MyElement.class, "a"), getTestRootDisposable());
final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<a/>");
assertTrue(getDomManager().isDomFile(file));
final DomFileElementImpl<MyElement> fileElement = getDomManager().getFileElement(file, MyElement.class);
assertTrue(fileElement.isValid());
myCallRegistry.clear();
putExpected(new DomEvent(fileElement, false));
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final Document document = getDocument(file);
final int i = document.getText().indexOf("<a");
document.insertString(i, "a");
commitDocument(document);
}
}.execute();
assertFalse(getDomManager().isDomFile(file));
assertFalse(fileElement.isValid());
assertResultsAndClear();
}
private void assertNoCache(XmlTag tag) {
assertNull(tag.getText(), getCachedHandler(tag));
if (tag.isValid()) {
for (XmlTag xmlTag : tag.getSubTags()) {
assertNoCache(xmlTag);
}
}
}
private MyElement createElement(final String xml) throws IncorrectOperationException {
return createElement(xml, MyElement.class);
}
public void testAddCollectionElement() throws Throwable {
final MyElement element = createElement("<a><child/><child/><child-element/></a>");
final MyElement child = element.getChild();
final MyElement child2 = element.getChild2();
final MyElement firstChild = element.getChildElements().get(0);
element.getXmlTag().add(createTag("<child-element/>"));
final XmlTag[] subTags = element.getXmlTag().getSubTags();
assertEquals(2, element.getChildElements().size());
assertEquals(firstChild, element.getChildElements().get(0));
MyElement nextChild = element.getChildElements().get(1);
putExpected(new DomEvent(element, false));
assertResultsAndClear();
}
public void testAddFixedElement() throws Throwable {
final MyElement element = createPhysicalElement("<a>" +
"<child/>" +
"<child><child/></child>" +
"<child/></a>");
final MyElement child = element.getChild();
final MyElement child2 = element.getChild2();
final XmlTag leafTag = child2.getChild().getXmlTag();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
element.getXmlTag().addAfter(createTag("<child/>"), child.getXmlTag());
}
}.execute();
assertNoCache(leafTag);
final XmlTag[] subTags = element.getXmlTag().getSubTags();
assertFalse(child2.isValid());
assertEquals(child, element.getChild());
assertFalse(child2.equals(element.getChild2()));
assertCached(child, subTags[0]);
assertNoCache(subTags[2]);
assertNoCache(subTags[3]);
putExpected(new DomEvent(element, false));
putExpected(new DomEvent(element, false));
assertResultsAndClear();
}
public void testAddFixedElementCanDefineIt() throws Throwable {
final MyElement element = createElement("<a></a>");
final MyElement child = element.getChild();
element.getXmlTag().add(createTag("<child/>"));
final XmlTag[] subTags = element.getXmlTag().getSubTags();
assertTrue(child.equals(element.getChild()));
assertTrue(element.getChild().equals(child));
assertCached(element.getChild(), subTags[0]);
putExpected(new DomEvent(element, false));
assertResultsAndClear();
}
public void testActuallyRemoveCollectionElement() throws Throwable {
final MyElement element = createElement("<a><child-element><child/></child-element><child-element/></a>");
final MyElement child = element.getChild();
final MyElement child2 = element.getChild2();
final MyElement firstChild = element.getChildElements().get(0);
final MyElement lastChild = element.getChildElements().get(1);
final XmlTag tag = element.getXmlTag();
final XmlTag childTag = tag.getSubTags()[0];
WriteCommandAction.runWriteCommandAction(null, () -> childTag.delete());
putExpected(new DomEvent(element, false));
assertResultsAndClear();
assertEquals(child, element.getChild());
assertEquals(child2, element.getChild2());
assertEquals(Arrays.asList(lastChild), element.getChildElements());
assertCached(lastChild, tag.getSubTags()[0]);
}
public void testCustomChildrenEvents() throws Throwable {
final Sepulka element = createElement("<a><foo/><bar/></a>", Sepulka.class);
final List<MyElement> list = element.getCustomChildren();
final XmlTag tag = element.getXmlTag();
WriteCommandAction.runWriteCommandAction(null, () -> {
tag.getSubTags()[0].delete();
tag.getSubTags()[0].delete();
});
tag.add(createTag("<goo/>"));
putExpected(new DomEvent(element, false));
putExpected(new DomEvent(element, false));
putExpected(new DomEvent(element, false));
assertResultsAndClear();
assertEquals(1, element.getCustomChildren().size());
}
public void testRemoveFixedElement() throws Throwable {
final MyElement element = createElement("<a>" +
"<child/>" +
"<child><child/></child>" +
"<child><child/></child>" +
"</a>");
final MyElement child = element.getChild();
final MyElement child2 = element.getChild2();
final MyElement oldLeaf = child2.getChild();
final XmlTag tag = element.getXmlTag();
XmlTag leafTag = tag.getSubTags()[2].getSubTags()[0];
assertNoCache(leafTag);
ApplicationManager.getApplication().runWriteAction(() -> {
tag.getSubTags()[1].delete();
assertFalse(oldLeaf.isValid());
putExpected(new DomEvent(element, false));
assertResultsAndClear();
assertEquals(child, element.getChild());
assertFalse(child2.isValid());
tag.getSubTags()[1].delete();
});
putExpected(new DomEvent(element, false));
assertResultsAndClear();
}
public void testRootTagAppearsLater() throws Throwable {
final XmlFile file = createXmlFile("");
final DomFileElementImpl<MyElement> fileElement = getDomManager().getFileElement(file, MyElement.class, "root");
myCallRegistry.clear();
assertNull(fileElement.getRootElement().getXmlTag());
file.getDocument().replace(createXmlFile("<root/>").getDocument());
final XmlTag rootTag = fileElement.getRootTag();
assertEquals(rootTag, file.getDocument().getRootTag());
putExpected(new DomEvent(fileElement.getRootElement(), false));
assertResultsAndClear();
}
public void testAnotherChildren() throws Throwable {
final MyElement element = createElement("<a><child/></a>");
element.getXmlTag().add(createTag("<another-child/>"));
assertEquals(1, element.getAnotherChildren().size());
putExpected(new DomEvent(element, false));
assertResultsAndClear();
}
public void testInvalidateParent() throws Throwable {
final MyElement root = getDomManager().createMockElement(MyElement.class, null, true);
new WriteCommandAction<MyElement>(getProject()) {
@Override
protected void run(@NotNull Result<MyElement> result) throws Throwable {
root.getChild().ensureTagExists();
root.getChild2().ensureTagExists();
final MyElement element = root.addChildElement().getChild();
result.setResult(element);
element.ensureTagExists().getValue().setText("abc");
root.addChildElement();
root.addChildElement();
}
}.execute().getResultObject();
assertTrue(root.isValid());
final MyElement element = root.getChildElements().get(0).getChild();
assertTrue(element.isValid());
final MyElement child = element.getChild();
final MyElement genericValue = child.getChild();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
final Document document = getDocument(DomUtil.getFile(element));
final TextRange range = element.getXmlTag().getTextRange();
document.replaceString(range.getStartOffset(), range.getEndOffset(), "");
commitDocument(document);
}
}.execute();
assertFalse(genericValue.isValid());
assertFalse(child.isValid());
assertFalse(element.isValid());
}
public void testCollectionChildValidAfterFormattingReparse() throws Throwable {
final MyElement root = getDomManager().createMockElement(MyElement.class, null, true);
final MyElement element = new WriteCommandAction<MyElement>(getProject()) {
@Override
protected void run(@NotNull Result<MyElement> result) throws Throwable {
result.setResult(root.addChildElement());
}
}.execute().getResultObject();
assertTrue(root.isValid());
assertNotNull(element.getXmlElement());
}
public void testChangeImplementationClass() throws Throwable {
getTypeChooserManager().registerTypeChooser(MyElement.class, createClassChooser());
try {
final MyElement element = getDomManager().createMockElement(MyElement.class, getModule(), true);
final DomFileElement<MyElement> root = DomUtil.getFileElement(element);
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
element.addChildElement().addChildElement();
}
}.execute();
final MyElement child = element.getChildElements().get(0);
MyElement grandChild = child.getChildElements().get(0);
assertTrue(child instanceof BarInterface);
assertTrue(grandChild instanceof BarInterface);
grandChild = element.getChildElements().get(0).getChildElements().get(0);
final XmlTag tag = grandChild.getXmlTag();
assertTrue(grandChild.isValid());
assertEquals(grandChild, root.getRootElement().getChildElements().get(0).getChildElements().get(0));
assertNotNull(element.getXmlTag());
assertNotNull(child.getXmlTag());
assertNotNull(tag);
assertTrue(tag.isValid());
myCallRegistry.clear();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("<foo/>"));
}
}.execute();
assertTrue(root.isValid());
assertTrue(element.isValid());
assertTrue(grandChild.isValid());
final MyElement newChild = root.getRootElement().getChildElements().get(0);
assertTrue(newChild instanceof BarInterface);
final MyElement newGrandChild = newChild.getChildElements().get(0);
assertTrue(newGrandChild.isValid());
assertTrue(newGrandChild instanceof FooInterface);
putExpected(new DomEvent(child, false));
putExpected(new DomEvent(grandChild, false));
assertResultsAndClear();
} finally {
getTypeChooserManager().unregisterTypeChooser(MyElement.class);
}
}
public void testChangeImplementationClass_InCollection() throws Throwable {
getTypeChooserManager().registerTypeChooser(MyElement.class, createClassChooser());
try {
final MyElement element = getDomManager().createMockElement(MyElement.class, getModule(), true);
final DomFileElement<MyElement> root = DomUtil.getFileElement(element);
new WriteCommandAction<MyElement>(getProject()) {
@Override
protected void run(@NotNull Result<MyElement> result) throws Throwable {
element.addChildElement().addChildElement();
}
}.execute().getResultObject();
final MyElement child = element.getChildElements().get(0);
final MyElement grandChild = child.getChildElements().get(0);
assertTrue(child instanceof BarInterface);
assertTrue(grandChild instanceof BarInterface);
assertTrue(element.isValid());
assertTrue(child.isValid());
assertTrue(grandChild.isValid());
assertNotNull(element.getXmlTag());
assertNotNull(child.getXmlTag());
final XmlTag tag = grandChild.getXmlTag();
assertNotNull(tag);
myCallRegistry.clear();
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("<foo/>"));
}
}.execute();
assertTrue(root.isValid());
assertTrue(element.isValid());
assertTrue(child.isValid());
final MyElement newChild = element.getChildElements().get(0);
assertTrue(newChild.isValid());
assertTrue(newChild.getClass().toString(), newChild instanceof BarInterface);
assertTrue(grandChild.isValid());
final MyElement newGrandChild = newChild.getChildElements().get(0);
assertTrue(newGrandChild.isValid());
assertTrue(newGrandChild instanceof FooInterface);
putExpected(new DomEvent(child, false));
putExpected(new DomEvent(grandChild, false));
assertResultsAndClear();
} finally {
getTypeChooserManager().unregisterTypeChooser(MyElement.class);
}
}
/*
public void testCommentTag() throws Throwable {
final String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE application PUBLIC \"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN\" \"http://java.sun.com/dtd/application_1_3.dtd\">\n" +
"<application>\n" + " <display-name>MyAppa</display-name>\n" + " <description>ss</description>\n" +
" <module id=\"MyWebApp2\">\n" + " <web> a\n" + " <web-uri>MyWebApp2.war</web-uri>\n" +
" ";
final String infix = "<context-root>MyWebApp2</context-root>";
String suffix = "\n" + " </web>\n" + " </module>\n" +
" <module id=\"MyWebApp22\">\n" + " <web>\n" + " <web-uri>MyWebApp2.war</web-uri>\n" +
" <context-root>MyWebApp2</context-root>\n" + " </web>\n" + " </module>\n" +
" <module id=\"MyEjb32\">\n" + " <ejb>MyEjb32.jar</ejb>\n" + " </module>\n" +
" <module id=\"MyEjb4\">\n" + " <ejb>MyEjb4.jar</ejb>\n" + " </module>\n" + " <security-role>\n" +
" <description>asdf</description>\n" + " <role-name>nameasdf</role-name>\n" +
" </security-role>\n" + "\n" + "</application>";
final XmlFile file = (XmlFile)createFile("web.xml", prefix + infix + suffix);
final JavaeeApplication javaeeApplication = getDomManager().getFileElement(file, JavaeeApplication.class).getRootElement();
assertEquals("MyWebApp2", javaeeApplication.getModules().get(0).getWeb().getContextRoot().getValue());
new WriteCommandAction(getProject()) {
@Override
protected void run(Result result) throws Throwable {
final Document document = getDocument(file);
document.insertString(prefix.length() + infix.length(), "-->");
document.insertString(prefix.length(), "<!--");
commitDocument(document);
}
}.execute();
assertTrue(javaeeApplication.isValid());
assertTrue(javaeeApplication.getModules().get(0).getWeb().getContextRoot().isValid());
assertTrue(javaeeApplication.getModules().get(0).getWeb().isValid());
assertNull(javaeeApplication.getModules().get(0).getWeb().getContextRoot().getXmlElement());
}
*/
private static TypeChooser createClassChooser() {
return new TypeChooser() {
@Override
public Type chooseType(final XmlTag tag) {
return tag != null && tag.findFirstSubTag("foo") != null
? FooInterface.class
: BarInterface.class;
}
@Override
public void distinguishTag(final XmlTag tag, final Type aClass)
throws IncorrectOperationException {
if (FooInterface.class.equals(aClass) && tag.findFirstSubTag("foo") == null) {
tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("<foo/>"));
}
}
@Override
public Type[] getChooserTypes() {
return new Class[]{FooInterface.class,
BarInterface.class};
}
};
}
public interface MyElement extends DomElement{
MyElement getChild();
@SubTag(value="child",index=1) MyElement getChild2();
List<MyElement> getChildElements();
List<MyElement> getBoys();
List<MyElement> getGirls();
List<MyElement> getAnotherChildren();
MyElement addChildElement();
GenericAttributeValue<String> getXxx();
MyElement getAboy();
MyElement getAgirl();
}
public interface FooInterface extends MyElement {
}
public interface BarInterface extends MyElement {
}
public interface Sepulka extends DomElement{
@CustomChildren
List<MyElement> getCustomChildren();
}
}
|
|
// Copyright 2000-2019 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.updateSettings.impl;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.CollectionComboBoxModel;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.util.net.NetUtils;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.JBEmptyBorder;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
/**
* @author pti
*/
public class UpdateSettingsConfigurable implements SearchableConfigurable {
private final UpdateSettings mySettings;
private final boolean myCheckNowEnabled;
private UpdatesSettingsPanel myPanel;
@SuppressWarnings("unused")
public UpdateSettingsConfigurable() {
this(true);
}
public UpdateSettingsConfigurable(boolean checkNowEnabled) {
mySettings = UpdateSettings.getInstance();
myCheckNowEnabled = checkNowEnabled;
}
@Override
public JComponent createComponent() {
myPanel = new UpdatesSettingsPanel(myCheckNowEnabled);
return myPanel.myPanel;
}
@Override
public String getDisplayName() {
return IdeBundle.message("updates.settings.title");
}
@NotNull
@Override
public String getHelpTopic() {
return "preferences.updates";
}
@Override
@NotNull
public String getId() {
return getHelpTopic();
}
@Override
public void apply() throws ConfigurationException {
if (myPanel.myUseSecureConnection.isSelected() && !NetUtils.isSniEnabled()) {
throw new ConfigurationException(IdeBundle.message("update.sni.disabled.error"));
}
boolean wasEnabled = mySettings.isCheckNeeded();
mySettings.setCheckNeeded(myPanel.myCheckForUpdates.isSelected());
if (wasEnabled != mySettings.isCheckNeeded()) {
UpdateCheckerComponent checker = ApplicationManager.getApplication().getComponent(UpdateCheckerComponent.class);
if (checker != null) {
if (wasEnabled) {
checker.cancelChecks();
}
else {
checker.queueNextCheck();
}
}
}
mySettings.setSelectedChannelStatus(myPanel.getSelectedChannelType());
mySettings.setSecureConnection(myPanel.myUseSecureConnection.isSelected());
}
@Override
public void reset() {
myPanel.myCheckForUpdates.setSelected(mySettings.isCheckNeeded());
myPanel.myUseSecureConnection.setSelected(mySettings.isSecureConnection());
myPanel.updateLastCheckedLabel();
myPanel.setSelectedChannelType(mySettings.getSelectedActiveChannel());
}
@Override
public boolean isModified() {
if (myPanel == null) {
return false;
}
if (mySettings.isCheckNeeded() != myPanel.myCheckForUpdates.isSelected() ||
mySettings.isSecureConnection() != myPanel.myUseSecureConnection.isSelected()) {
return true;
}
Object channel = myPanel.myUpdateChannels.getSelectedItem();
return channel != null && !channel.equals(mySettings.getSelectedActiveChannel());
}
@Override
public void disposeUIResources() {
myPanel = null;
}
private static class UpdatesSettingsPanel {
private final UpdateSettings mySettings;
private JPanel myPanel;
private JCheckBox myCheckForUpdates;
private JComboBox<ChannelStatus> myUpdateChannels;
private JButton myCheckNow;
private JBLabel myChannelWarning;
private JCheckBox myUseSecureConnection;
private JLabel myBuildNumber;
private JLabel myVersionNumber;
private JLabel myLastCheckedDate;
@SuppressWarnings("unused") private ActionLink myIgnoredBuildsLink;
UpdatesSettingsPanel(boolean checkNowEnabled) {
mySettings = UpdateSettings.getInstance();
ChannelStatus current = mySettings.getSelectedActiveChannel();
myUpdateChannels.setModel(new CollectionComboBoxModel<>(mySettings.getActiveChannels(), current));
ExternalUpdateManager manager = ExternalUpdateManager.ACTUAL;
if (manager != null) {
myCheckForUpdates.setText(IdeBundle.message("updates.settings.checkbox.external"));
myUpdateChannels.setVisible(false);
myChannelWarning.setText(IdeBundle.message("updates.settings.external", manager.toolName));
myChannelWarning.setForeground(JBColor.GRAY);
myChannelWarning.setVisible(true);
myChannelWarning.setBorder(new JBEmptyBorder(0, 0, 10, 0));
}
else if (ApplicationInfoEx.getInstanceEx().isMajorEAP() && UpdateStrategyCustomization.getInstance().forceEapUpdateChannelForEapBuilds()) {
myUpdateChannels.setEnabled(false);
myUpdateChannels.setToolTipText(IdeBundle.message("updates.settings.channel.locked"));
}
else {
myUpdateChannels.addActionListener(e -> {
boolean lessStable = current.compareTo(getSelectedChannelType()) > 0;
myChannelWarning.setVisible(lessStable);
});
myChannelWarning.setForeground(JBColor.RED);
}
if (checkNowEnabled) {
myCheckNow.addActionListener(e -> {
Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myCheckNow));
UpdateSettings settings = new UpdateSettings();
settings.loadState(mySettings.getState());
settings.setSelectedChannelStatus(getSelectedChannelType());
settings.setSecureConnection(myUseSecureConnection.isSelected());
UpdateChecker.updateAndShowResult(project, settings);
updateLastCheckedLabel();
});
}
else {
myCheckNow.setVisible(false);
}
ApplicationInfo appInfo = ApplicationInfo.getInstance();
myVersionNumber.setText(ApplicationNamesInfo.getInstance().getFullProductName() + ' ' + appInfo.getFullVersion());
myBuildNumber.setText(appInfo.getBuild().asString());
}
private void createUIComponents() {
myIgnoredBuildsLink = new ActionLink(IdeBundle.message("updates.settings.ignored"), new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
List<String> buildNumbers = mySettings.getIgnoredBuildNumbers();
String text = StringUtil.join(buildNumbers, "\n");
String result = Messages.showMultilineInputDialog(null, null, IdeBundle.message("updates.settings.ignored.title"), text, null, null);
if (result != null) {
buildNumbers.clear();
buildNumbers.addAll(StringUtil.split(result, "\n"));
}
}
});
}
private void updateLastCheckedLabel() {
long time = mySettings.getLastTimeChecked();
if (time <= 0) {
myLastCheckedDate.setText(IdeBundle.message("updates.last.check.never"));
}
else {
myLastCheckedDate.setText(DateFormatUtil.formatPrettyDateTime(time));
myLastCheckedDate.setToolTipText(DateFormatUtil.formatDate(time) + ' ' + DateFormatUtil.formatTimeWithSeconds(time));
}
}
public ChannelStatus getSelectedChannelType() {
return (ChannelStatus)myUpdateChannels.getSelectedItem();
}
public void setSelectedChannelType(ChannelStatus channelType) {
myUpdateChannels.setSelectedItem(channelType != null ? channelType : ChannelStatus.RELEASE);
}
}
}
|
|
/*
* 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.shell;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import com.facebook.buck.core.filesystems.AbsPath;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.sha1.Sha1HashCode;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class GenruleIntegrationTest {
@Rule public TemporaryPaths temporaryFolder = new TemporaryPaths();
@Parameterized.Parameters(name = "{0}")
public static Collection<Object> data() {
return Arrays.asList(new Object[] {"", "_outs"});
}
@Parameterized.Parameter() public String targetSuffix;
// When these tests fail, the failures contain buck output that is easy to confuse with the output
// of the instance of buck that's running the test. This prepends each line with "> ".
private String quoteOutput(String output) {
output = output.trim();
output = "> " + output;
output = output.replace("\n", "\n> ");
return output;
}
@Test
public void testIfCommandExitsZeroThenGenruleFails() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_failing_command", temporaryFolder);
workspace.setUp();
ProcessResult buildResult =
workspace.runBuckCommand("build", targetWithSuffix("//:fail"), "--verbose", "10");
buildResult.assertFailure();
/* We want to make sure we failed for the right reason. The expected should contain something
* like the following:
*
* BUILD FAILED: //:fail failed with exit code 1:
* (cd /tmp/junit12345/buck-out/gen/fail__srcs && /bin/bash -e -c 'false; echo >&2 hi')
*
* We should match all that, except for the specific temp dir.
*/
// "(?s)" enables multiline matching for ".*". Parens have to be escaped.
String outputPattern;
if (Platform.detect() == Platform.WINDOWS) {
outputPattern =
"(?s).*Command failed with exit code 1\\..*"
+ "When running <\\(cd buck-out\\\\gen(\\\\[0-9a-zA-Z]+)?\\\\fail"
+ targetSuffix
+ "__srcs && .*\\\\buck-out\\\\tmp\\\\genrule-[0-9]*\\.cmd\\)>.*";
} else {
outputPattern =
"(?s).*Command failed with exit code 1\\.(?s).*"
+ "When running <\\(cd buck-out/gen(/[0-9a-zA-Z]+)?/fail"
+ targetSuffix
+ "__srcs && /bin/bash -e .*/buck-out/tmp/genrule-[0-9]*\\.sh\\)>(?s).*";
}
assertTrue(
"Unexpected output:\n" + quoteOutput(buildResult.getStderr()),
buildResult.getStderr().matches(outputPattern));
}
@Test
public void genruleWithEmptyOutParameterFails() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_empty_out", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:genrule");
ProcessResult processResult = workspace.runBuckCommand("build", targetName);
processResult.assertFailure();
assertThat(
processResult.getStderr(),
containsString(
"The output path must be relative, simple, non-empty and not cross package boundary"));
}
@Test
public void genruleWithAbsoluteOutParameterFails() throws IOException {
// Note: the path in this genrule is not absolute on Windows.
assumeThat(Platform.detect(), not(equalTo(Platform.WINDOWS)));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_absolute_out", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:genrule");
ProcessResult processResult = workspace.runBuckCommand("build", targetName);
processResult.assertFailure();
assertThat(
processResult.getStderr(),
containsString(
"The output path must be relative, simple, non-empty and not cross package boundary"));
}
@Test
public void genruleDirectoryOutput() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_directory_output", temporaryFolder);
workspace.setUp();
workspace.enableDirCache();
String targetName = targetWithSuffix("//:mkdir");
workspace.runBuckCommand("build", targetName).assertSuccess();
Path directoryPath = getOutputPath(workspace, targetName, "directory");
assertTrue(Files.isDirectory(directoryPath));
Path filePath = getOutputPath(workspace, targetName, "directory/file");
assertThat(workspace.getFileContents(filePath), equalTo("something" + System.lineSeparator()));
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
assertFalse(Files.isDirectory(workspace.resolve("buck-out/gen")));
// Retrieving the genrule output from the local cache should recreate the directory contents.
workspace.runBuckCommand("build", targetName).assertSuccess();
workspace.getBuildLog().assertTargetWasFetchedFromCache(targetName);
assertTrue(Files.isDirectory(workspace.resolve(directoryPath)));
assertThat(workspace.getFileContents(filePath), equalTo("something" + System.lineSeparator()));
}
@Test
public void genruleWithBigCommand() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_big_command", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:big");
workspace.runBuckCommand("build", targetName).assertSuccess();
Path outputPath = getOutputPath(workspace, targetName, "file");
assertTrue(Files.isRegularFile(outputPath));
int stringSize = 1000;
StringBuilder expectedOutput = new StringBuilder();
for (int i = 0; i < stringSize; ++i) {
expectedOutput.append("X");
}
expectedOutput.append(System.lineSeparator());
assertThat(workspace.getFileContents(outputPath), equalTo(expectedOutput.toString()));
}
@Test
public void genruleDirectoryOutputIsCleanedBeforeBuildAndCacheFetch() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_directory_output_cleaned", temporaryFolder);
workspace.setUp();
workspace.enableDirCache();
String mkDirAnotherTargetName = targetWithSuffix("//:mkdir_another");
workspace.copyFile("BUCK.1", "BUCK");
workspace.runBuckCommand("build", mkDirAnotherTargetName).assertSuccess();
workspace.getBuildLog().assertTargetBuiltLocally(mkDirAnotherTargetName);
assertTrue(
String.format("%s should be built", mkDirAnotherTargetName),
Files.isRegularFile(
getOutputPath(workspace, mkDirAnotherTargetName, "another_directory/file")));
String mkDirTargetName = targetWithSuffix("//:mkdir");
workspace.runBuckCommand("build", mkDirTargetName).assertSuccess();
workspace.getBuildLog().assertTargetBuiltLocally(mkDirTargetName);
assertTrue(
"BUCK.1 should create its output",
Files.isRegularFile(getOutputPath(workspace, mkDirTargetName, "directory/one")));
assertFalse(
"BUCK.1 should not touch the output of BUCK.2",
Files.isRegularFile(getOutputPath(workspace, mkDirTargetName, "directory/two")));
assertTrue(
"output of mkdir_another should still exist",
Files.isRegularFile(
getOutputPath(workspace, mkDirAnotherTargetName, "another_directory/file")));
workspace.copyFile("BUCK.2", "BUCK");
workspace.runBuckCommand("build", mkDirTargetName).assertSuccess();
workspace.getBuildLog().assertTargetBuiltLocally(mkDirTargetName);
assertFalse(
"Output of BUCK.1 should be deleted before output of BUCK.2 is built",
Files.isRegularFile(getOutputPath(workspace, mkDirTargetName, "directory/one")));
assertTrue(
"BUCK.2 should create its output",
Files.isRegularFile(getOutputPath(workspace, mkDirTargetName, "directory/two")));
assertTrue(
"output of mkdir_another should still exist",
Files.isRegularFile(
getOutputPath(workspace, mkDirAnotherTargetName, "another_directory/file")));
workspace.copyFile("BUCK.1", "BUCK");
workspace.runBuckCommand("build", mkDirTargetName).assertSuccess();
workspace.getBuildLog().assertTargetWasFetchedFromCache(mkDirTargetName);
assertTrue(
"Output of BUCK.1 should be fetched from the cache",
Files.isRegularFile(
getOutputPath(workspace, mkDirAnotherTargetName, "another_directory/file")));
assertFalse(
"Output of BUCK.2 should be deleted before output of BUCK.1 is fetched from cache",
Files.isRegularFile(getOutputPath(workspace, mkDirTargetName, "directory/two")));
assertTrue(
"output of mkdir_another should still exist",
Files.isRegularFile(
getOutputPath(workspace, mkDirAnotherTargetName, "another_directory/file")));
assertTrue(Files.isDirectory(getOutputPath(workspace, mkDirTargetName, "directory")));
}
@Test
public void genruleCleansEntireOutputDirectory() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_robust_cleaning", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:write");
workspace.copyFile("BUCK.1", "BUCK");
workspace.runBuckCommand("build", targetName).assertSuccess();
workspace.getBuildLog().assertTargetBuiltLocally(targetName);
assertTrue(
String.format("%s should be built", targetName),
Files.isRegularFile(getOutputPath(workspace, targetName, "one")));
workspace.copyFile("BUCK.2", "BUCK");
workspace.runBuckCommand("build", targetName).assertSuccess();
workspace.getBuildLog().assertTargetBuiltLocally(targetName);
assertFalse(
"Output of BUCK.1 should be deleted before output of BUCK.2 is built",
Files.isRegularFile(getOutputPath(workspace, targetName, "one")));
assertTrue(
"BUCK.2 should create its output",
Files.isRegularFile(getOutputPath(workspace, targetName, "two")));
}
@Test
public void genruleDirectorySourcePath() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_directory_source_path", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:cpdir");
workspace.runBuckBuild(targetName).assertSuccess();
assertTrue(Files.isDirectory(getOutputPath(workspace, targetName, "copy")));
assertTrue(Files.isRegularFile(getOutputPath(workspace, targetName, "copy/hello")));
}
@Test
public void twoGenrulesWithTheSameOutputFileShouldNotOverwriteOneAnother() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_overwrite", temporaryFolder);
workspace.setUp();
String targetNameOne = targetWithLabelIfNonEmptySuffix("//:genrule-one", "output");
String targetNameTwo = targetWithLabelIfNonEmptySuffix("//:genrule-two", "output");
// The two genrules run in this test have the same inputs and same output name
Path output = workspace.buildAndReturnOutput(targetNameOne);
String originalOutput = new String(Files.readAllBytes(output), UTF_8);
output = workspace.buildAndReturnOutput(targetNameTwo);
String updatedOutput = new String(Files.readAllBytes(output), UTF_8);
assertNotEquals(originalOutput, updatedOutput);
// Finally, reinvoke the first rule.
output = workspace.buildAndReturnOutput(targetNameOne);
String originalOutput2 = new String(Files.readAllBytes(output), UTF_8);
assertEquals(originalOutput, originalOutput2);
}
@Test
public void executableGenruleForSingleOutput() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_executable", temporaryFolder);
workspace.setUp();
ProcessResult buildResult = workspace.runBuckCommand("run", "//:binary");
buildResult.assertSuccess();
}
@Test
public void executableGenruleWithMultipleOutputs() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_executable", temporaryFolder);
workspace.setUp();
// Multiple outputs doesn't support buck run yet, so get the output directly and execute it
Path executable = workspace.buildAndReturnOutput("//:binary_outs[output]");
DefaultProcessExecutor processExecutor = new DefaultProcessExecutor(new TestConsole());
ProcessExecutor.Result processResult =
processExecutor.launchAndExecute(
ProcessExecutorParams.builder().addCommand(executable.toString()).build());
assertEquals(0, processResult.getExitCode());
}
@Test
public void genruleExeMacro() throws Exception {
assumeThat(Platform.detect(), not(Platform.WINDOWS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_exe_macro", temporaryFolder);
workspace.setUp();
Path result =
workspace.buildAndReturnOutput(targetWithLabelIfNonEmptySuffix("//:exe_macro", "output"));
assertTrue(result.endsWith("example_out.txt"));
assertEquals("hello\n", workspace.getFileContents(result));
}
@Test
public void exeMacroWorksWithDefaultOutput() throws Exception {
assumeThat(Platform.detect(), not(Platform.WINDOWS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_exe_macro", temporaryFolder);
workspace.setUp();
Path result = workspace.buildAndReturnOutput("//:exe_macro_with_default_output");
assertTrue(result.endsWith("example_out.txt"));
assertEquals("hello\n", workspace.getFileContents(result));
}
@Test
public void genruleZipOutputsAreScrubbed() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_zip_scrubber", temporaryFolder);
workspace.setUp();
Path outputOne =
workspace.buildAndReturnOutput(targetWithLabelIfNonEmptySuffix("//:genrule-one", "output"));
Path outputTwo =
workspace.buildAndReturnOutput(targetWithLabelIfNonEmptySuffix("//:genrule-two", "output"));
assertZipsAreEqual(outputOne, outputTwo);
}
@Test
public void genruleZipOutputsExtendedTimestampsAreScrubbed() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_zip_scrubber", temporaryFolder);
workspace.setUp();
Path outputOne =
workspace.buildAndReturnOutput(
targetWithLabelIfNonEmptySuffix("//:extended-time-one", "output"));
Path outputTwo =
workspace.buildAndReturnOutput(
targetWithLabelIfNonEmptySuffix("//:extended-time-two", "output"));
assertZipsAreEqual(outputOne, outputTwo);
}
@Test
public void genruleCanUseExportFileInReferenceMode() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_export_file", temporaryFolder);
workspace.setUp();
String targetName = targetWithSuffix("//:re-exported");
workspace.runBuckBuild(targetName).assertSuccess();
// rebuild with changed contents
String contents = "new contents";
workspace.writeContentsToPath(contents, "source.txt");
Path genruleOutput = workspace.buildAndReturnOutput(targetName);
assertEquals(contents, workspace.getFileContents(genruleOutput));
}
@Test
public void genruleWithSandboxFailsAccessingUndeclaredFile() throws IOException {
assumeThat(Platform.detect(), is(Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_with_sandbox", temporaryFolder);
workspace.setUp();
Path output =
workspace.buildAndReturnOutput(targetWithLabelIfNonEmptySuffix("//:cat_input", "output"));
String expected =
new String(Files.readAllBytes(workspace.getPath("undeclared_input.txt")), UTF_8);
String actual = new String(Files.readAllBytes(output), UTF_8);
assertEquals(expected, actual);
ProcessResult result = workspace.runBuckBuild(targetWithSuffix("//:cat_input_with_sandbox"));
assertTrue(result.getStderr().contains("undeclared_input.txt: Operation not permitted"));
}
@Test
public void disabledDarwinSandboxingNotBreakingViolators() throws IOException {
assumeThat(Platform.detect(), is(Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_with_sandbox", temporaryFolder);
workspace.setUp();
Path output =
workspace.buildAndReturnOutput(
"--config",
"sandbox.darwin_sandbox_enabled=False",
targetWithLabelIfNonEmptySuffix("//:cat_input", "output"));
String actual = new String(Files.readAllBytes(output), UTF_8);
String expected =
new String(Files.readAllBytes(workspace.getPath("undeclared_input.txt")), UTF_8);
assertEquals(expected, actual);
}
@Test
public void disabledGenruleSandboxingNotBreakingViolators() throws IOException {
assumeThat(Platform.detect(), is(Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_with_sandbox", temporaryFolder);
workspace.setUp();
Path output =
workspace.buildAndReturnOutput(
"--config",
"sandbox.genrule_sandbox_enabled=False",
targetWithLabelIfNonEmptySuffix("//:cat_input", "output"));
String actual = new String(Files.readAllBytes(output), UTF_8);
String expected =
new String(Files.readAllBytes(workspace.getPath("undeclared_input.txt")), UTF_8);
assertEquals(expected, actual);
}
@Test
public void testGenruleWithMacrosRuleKeyDoesNotDependOnAbsolutePath() throws IOException {
Sha1HashCode rulekey1 =
buildAndGetRuleKey(
"genrule_rulekey", temporaryFolder.newFolder(), targetWithSuffix("//:bar"));
Sha1HashCode rulekey2 =
buildAndGetRuleKey(
"genrule_rulekey", temporaryFolder.newFolder(), targetWithSuffix("//:bar"));
assertEquals(rulekey1, rulekey2);
}
/**
* Test scenario: If top level directory is in default outs, we do not emit warning on undeclared
* file created in the output path
*/
@Test
public void testGenruleWithUndeclaredOutputFileAndDeclaredOutputPath() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_undeclared_out", temporaryFolder);
workspace.setUp();
String targetName = "//:declared_top_level_outs[output]";
ProcessResult processResult = workspace.runBuckBuild(targetName);
processResult.assertSuccess();
assertFalse(
"Unexpected file identified as undeclared in: " + processResult.getStderr(),
Pattern.compile("Untracked artifact found: (\\S)*\\bundeclared\\b*")
.matcher(processResult.getStderr())
.find());
}
/**
* Test scenario: If top-level directory is not in default outs, and there's an empty directory in
* the output path, we emit warning
*/
@Test
public void testGenruleWithUndeclaredEmptySubDir() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_undeclared_out", temporaryFolder);
workspace.setUp();
String targetName = "//:undeclared_empty_dir_outs[output]";
ProcessResult processResult = workspace.runBuckBuild(targetName);
processResult.assertSuccess();
assertTrue(
"Undeclared directory not identified in: " + processResult.getStderr(),
Pattern.compile("Untracked artifact found: (\\S)*\\bempty\\b")
.matcher(processResult.getStderr())
.find());
}
/**
* Tests that we emit warning in the event bus when we find undeclared output files under the
* output root directory.
*/
@Test
public void testGenruleWithUndeclaredOutputFileUnderOutputPath() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_undeclared_out", temporaryFolder);
workspace.setUp();
String targetName = "//:undeclared_nested_file_outs[output]";
ProcessResult processResult = workspace.runBuckBuild(targetName);
processResult.assertSuccess();
Files.exists(getOutputPath(workspace, targetName, "hello"));
Files.exists(getOutputPath(workspace, targetName, "undeclared"));
assertFalse(
"Unexpected file identified as undeclared in: " + processResult.getStderr(),
Pattern.compile("Untracked artifact found: (\\S)*\\bhello\\b")
.matcher(processResult.getStderr())
.find());
assertTrue(
"Undeclared directory not identified in: " + processResult.getStderr(),
Pattern.compile("Untracked artifact found: (\\S)*\\btest\\b")
.matcher(processResult.getStderr())
.find());
assertTrue(
"Undeclared file not identified in: " + processResult.getStderr(),
Pattern.compile("Untracked artifact found: (\\S)*\\bundeclared\\b")
.matcher(processResult.getStderr())
.find());
}
/**
* Tests that we handle genrules whose $OUT is "." and wants to make $OUT a directory without
* crashing.
*/
@Test
public void testGenruleWithDotOutWorks() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "genrule_dot_out", temporaryFolder);
workspace.setUp();
Path output = workspace.buildAndReturnOutput(targetWithSuffix("//:mkdir"));
assertTrue(output.toFile().isDirectory());
assertTrue(Files.exists(output.resolve("hello")));
}
@Test
public void testGenruleWithChangingNestedDirectory() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_path_changes", temporaryFolder);
workspace.setUp();
workspace.runBuckBuild(targetWithSuffix("//:hello")).assertSuccess();
workspace.runBuckBuild(targetWithSuffix("//:hello_break")).assertSuccess();
}
@Test
public void srcsMap() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "genrule_srcs_map", temporaryFolder);
workspace.setUp();
workspace.runBuckBuild(targetWithSuffix("//:gen")).assertSuccess();
}
@Test
public void namedOutputsMapToCorrespondingOutputs() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_outputs_map", temporaryFolder);
workspace.setUp();
Path result = workspace.buildAndReturnOutput("//:outputs_map[output1]");
assertTrue(result.endsWith("out1.txt"));
assertEquals("something" + System.lineSeparator(), workspace.getFileContents(result));
result = workspace.buildAndReturnOutput("//:outputs_map[output2]");
assertTrue(result.endsWith("out2.txt"));
assertEquals("another" + System.lineSeparator(), workspace.getFileContents(result));
result = workspace.buildAndReturnOutput("//:outputs_map");
assertTrue(result.endsWith("default.txt"));
assertEquals("foo" + System.lineSeparator(), workspace.getFileContents(result));
}
@Test
public void namedOutputCanBeInMultipleGroups() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_named_output_groups", temporaryFolder);
workspace.setUp();
Path result = workspace.buildAndReturnOutput("//:named_output_groups[output1]");
assertTrue(result.endsWith("out.txt"));
assertEquals("something" + System.lineSeparator(), workspace.getFileContents(result));
result = workspace.buildAndReturnOutput("//:named_output_groups[output2]");
assertTrue(result.endsWith("out.txt"));
assertEquals("something" + System.lineSeparator(), workspace.getFileContents(result));
result = workspace.buildAndReturnOutput("//:named_output_groups");
assertTrue(result.endsWith("out.txt"));
assertEquals("something" + System.lineSeparator(), workspace.getFileContents(result));
}
@Test
public void defaultOutsMustBePresentIfNamedOutputsArePresent() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_default_outs", temporaryFolder);
workspace.setUp();
ProcessResult result =
workspace
.runBuckBuild("//:target_without_default_outs[output1]")
.assertExitCode(ExitCode.FATAL_GENERIC);
assertTrue(
result
.getStderr()
.contains(
"default_outs must be present if outs is present in genrule target //:target_without_default_outs"));
}
@Test
public void canUseGenruleOutputLabelInSrcs() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_output_label_used_in_srcs", temporaryFolder);
workspace.setUp();
Path result = workspace.buildAndReturnOutput("//:file_with_named_outputs");
assertEquals("something" + System.lineSeparator(), workspace.getFileContents(result));
}
@Test
public void cannotHaveBothOutAndOuts() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_incompatible_attrs", temporaryFolder);
workspace.setUp();
ProcessResult processResult = workspace.runBuckBuild("//:binary");
processResult.assertExitCode(ExitCode.BUILD_ERROR);
assertTrue(
processResult
.getStderr()
.contains("One and only one of 'out' or 'outs' must be present in genrule."));
}
@Test
public void writingInWorkingDirWritesInSrcsDir() throws IOException {
String targetName = targetWithSuffix("//:working_dir");
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_working_dir", temporaryFolder);
workspace.setUp();
workspace.runBuckBuild(targetName).assertSuccess();
assertTrue(
Files.exists(
workspace
.getGenPath(BuildTargetFactory.newInstance(targetName), "%s__srcs")
.resolve("hello.txt")));
}
@Test
public void genruleWithInvalidOutParameterFails() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "genrule_invalid_out", temporaryFolder);
workspace.setUp();
String[] targets = {
"//:genrule",
"//:genrule-double-dot",
"//:genrule-double-dot-middle",
"//:genrule-double-slash",
"//:genrule-middle-dot",
"//:genrule-slash-end",
};
for (String target : targets) {
String targetName = targetWithSuffix(target);
ProcessResult processResult = workspace.runBuckCommand("build", targetName);
processResult.assertFailure();
assertThat(
processResult.getStderr(),
containsString(
"The output path must be relative, simple, non-empty and not cross package boundary"));
}
}
private Sha1HashCode buildAndGetRuleKey(String scenario, AbsPath temporaryFolder, String target)
throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, scenario, temporaryFolder);
workspace.setUp();
workspace.runBuckBuild(target);
return workspace.getBuildLog().getRuleKey(target);
}
private void assertZipsAreEqual(Path zipPathOne, Path zipPathTwo) throws IOException {
try (ZipFile zipOne = new ZipFile(zipPathOne.toFile());
ZipFile zipTwo = new ZipFile(zipPathTwo.toFile())) {
Enumeration<? extends ZipEntry> entriesOne = zipOne.entries(), entriesTwo = zipTwo.entries();
while (entriesOne.hasMoreElements()) {
assertTrue(entriesTwo.hasMoreElements());
ZipEntry entryOne = entriesOne.nextElement(), entryTwo = entriesTwo.nextElement();
assertEquals(zipEntryDebugString(entryOne), zipEntryDebugString(entryTwo));
assertEquals(zipEntryData(zipOne, entryOne), zipEntryData(zipTwo, entryTwo));
}
assertFalse(entriesTwo.hasMoreElements());
}
assertEquals(
new String(Files.readAllBytes(zipPathOne)), new String(Files.readAllBytes(zipPathTwo)));
}
private String zipEntryDebugString(ZipEntry entryOne) {
return "<ZE name="
+ entryOne.getName()
+ " crc="
+ entryOne.getCrc()
+ " comment="
+ entryOne.getComment()
+ " size="
+ entryOne.getSize()
+ " atime="
+ entryOne.getLastAccessTime()
+ " mtime="
+ entryOne.getLastModifiedTime()
+ " ctime="
+ entryOne.getCreationTime();
}
private String zipEntryData(ZipFile zip, ZipEntry entry) throws IOException {
return CharStreams.toString(new InputStreamReader(zip.getInputStream(entry)));
}
private String targetWithSuffix(String targetName) {
return targetName + targetSuffix;
}
private String targetWithLabelIfNonEmptySuffix(String targetName, String label) {
return targetSuffix.isEmpty()
? targetName
: String.format("%s[%s]", targetWithSuffix(targetName), label);
}
private Path getOutputPath(ProjectWorkspace workspace, String targetName, String outputName)
throws IOException {
return workspace
.getGenPath(BuildTargetFactory.newInstance(targetName), "%s")
.resolve(outputName);
}
}
|
|
/*
* 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.shindig.gadgets.features;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import org.apache.shindig.common.Pair;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.common.uri.UriBuilder;
import org.apache.shindig.common.util.ResourceLoader;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.RenderingContext;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Mechanism for loading feature.xml files from a location keyed by a String.
* That String might be the location of a text file which in turn contains
* other feature file locations; a directory; or a feature.xml file itself.
*/
@Singleton
public class FeatureRegistry {
public static final char FILE_SEPARATOR = ',';
public static final String RESOURCE_SCHEME = "res";
public static final String FILE_SCHEME = "file";
private static final Logger logger
= Logger.getLogger("org.apache.shindig.gadgets");
// Map keyed by FeatureNode object created as a lookup for transitive feature deps.
private final Map<Collection<String>, List<FeatureResource>> cache = new MapMaker().makeMap();
private final Map<Collection<String>, List<FeatureResource>> cacheIgnoreUnsupported =
new MapMaker().makeMap();
private final FeatureParser parser;
private final FeatureResourceLoader resourceLoader;
private final Map<String, FeatureNode> featureMap;
@Inject
public FeatureRegistry(FeatureResourceLoader resourceLoader) {
this.parser = new FeatureParser();
this.resourceLoader = resourceLoader;
this.featureMap = Maps.newHashMap();
}
/**
* For compatibility with GadgetFeatureRegistry, and to provide a programmatic hook
* for adding feature files by config, @Inject the @Named featureFiles variable.
* @param featureFiles
* @throws GadgetException
*/
@Inject(optional = true)
public void addDefaultFeatures(
@Named("shindig.features.default") String featureFiles) throws GadgetException {
register(featureFiles);
}
/**
* Reads and registers all of the features in the directory, or the file, specified by
* the given resourceKey. Invalid features or invalid paths will yield a
* GadgetException.
*
* All features registered by this method must be valid (well-formed XML, resource
* references all return successfully), and each "batch" of registered features
* must be able to be assimilated into the current features tree in a valid fashion.
* That is, their dependencies must all be valid features as well, and the
* dependency tree must not contain circular dependencies.
*
* @param resourceKey The file or directory to load the feature from. If feature.xml
* is passed in directly, it will be loaded as a single feature. If a
* directory is passed, any features in that directory (recursively) will
* be loaded. If res://*.txt or res:*.txt is passed, we will look for named resources
* in the text file. If path is prefixed with res:// or res:, the file
* is treated as a resource, and all references are assumed to be
* resources as well. Multiple locations may be specified by separating
* them with a comma.
* @throws GadgetException If any of the files can't be read, are malformed, or invalid.
*/
public void register(String resourceKey) throws GadgetException {
try {
for (String location : StringUtils.split(resourceKey, FILE_SEPARATOR)) {
Uri uriLoc = getComponentUri(location);
if (uriLoc.getScheme() != null && uriLoc.getScheme().equals(RESOURCE_SCHEME)) {
List<String> resources = Lists.newArrayList();
// Load as resource using ResourceLoader.
location = uriLoc.getPath();
if (location.startsWith("/")) {
// Accommodate res:// URIs.
location = location.substring(1);
}
logger.info("Loading resources from: " + uriLoc.toString());
if (location.endsWith(".txt")) {
// Text file contains a list of other resource files to load
for (String resource : getResourceContent(location).split("[\r\n]+")) {
resource = resource.trim();
if (resource.length () > 0 && resource.charAt(0) != '#') {
// Skip blank/commented lines.
resource = getComponentUri(resource.trim()).getPath();
resources.add(resource);
}
}
} else {
resources.add(location);
}
loadResources(resources);
} else {
// Load files in directory structure.
logger.info("Loading files from: " + location);
loadFile(new File(uriLoc.getPath()));
}
}
// Connect the dependency graph made up of all features and validate there
// are no circular deps.
connectDependencyGraph();
} catch (IOException e) {
throw new GadgetException(GadgetException.Code.INVALID_PATH, e);
}
}
/**
* For the given list of needed features, retrieves all the FeatureResource objects that
* contain their content and, if requested, that of their transitive dependencies.
*
* Resources are returned in order of their place in the dependency tree, with "bottom"/
* depended-on resources returned before those that depend on them. Resource objects
* within a given feature are returned in the order specified in their corresponding
* feature.xml file. In the case of a dependency tree "tie" eg. A depends on [B, C], B and C
* depend on D - resources are returned in the dependency order specified in feature.xml.
*
* Fills the "unsupported" list, if provided, with unknown features in the needed list.
*
* @param ctx Context for the request.
* @param needed List of all needed features.
* @param unsupported If non-null, a List populated with unknown features from the needed list.
* @return List of FeatureResources that may be used to render the needed features.
* @throws GadgetException
*/
public List<FeatureResource> getFeatureResources(
GadgetContext ctx, Collection<String> needed, List<String> unsupported, boolean transitive) {
Map<Collection<String>, List<FeatureResource>> useCache = null;
if (transitive) {
useCache = (unsupported != null) ? cache : cacheIgnoreUnsupported;
}
List<FeatureResource> resources = Lists.newLinkedList();
if (useCache != null && useCache.containsKey(needed)) {
return useCache.get(needed);
}
List<FeatureNode> featureNodes = null;
if (transitive) {
featureNodes = getTransitiveDeps(needed, unsupported);
} else {
featureNodes = getRequestedNodes(needed, unsupported);
}
String targetBundleType =
ctx.getRenderingContext() == RenderingContext.CONTAINER ? "container" : "gadget";
for (FeatureNode entry : featureNodes) {
for (FeatureBundle bundle : entry.getBundles()) {
if (bundle.getType().equals(targetBundleType)) {
if (containerMatch(bundle.getAttribs().get("container"), ctx.getContainer())) {
resources.addAll(bundle.getResources());
}
}
}
}
if (useCache != null && (unsupported == null || unsupported.isEmpty())) {
useCache.put(needed, resources);
}
return resources;
}
/**
* Helper method retrieving feature resources, including transitive dependencies.
* @param ctx Context for the request.
* @param needed List of all needed features.
* @param unsupported If non-null, a List populated with unknown features from the needed list.
* @return List of FeatureResources that may be used to render the needed features.
*/
public List<FeatureResource> getFeatureResources(
GadgetContext ctx, Collection<String> needed, List<String> unsupported) {
return getFeatureResources(ctx, needed, unsupported, true);
}
/**
* Returns all known FeatureResources in dependency order, as described in getFeatureResources.
* Returns only GADGET-context resources. This is a convenience method largely for calculating
* JS checksum.
* @return List of all known (RenderingContext.GADGET) FeatureResources.
*/
public List<FeatureResource> getAllFeatures() {
return getFeatureResources(
new GadgetContext(), Lists.newArrayList(featureMap.keySet()), null);
}
/**
* Calculates and returns a dependency-ordered (as in getFeatureResources) list of features
* included directly or transitively from the specified list of needed features.
* This API ignores any unknown features among the needed list.
* @param needed List of features for which to obtain an ordered dep list.
* @return Ordered list of feature names, as described.
*/
public List<String> getFeatures(List<String> needed) {
List<FeatureNode> fullTree = getTransitiveDeps(needed, Lists.<String>newLinkedList());
List<String> allFeatures = Lists.newLinkedList();
for (FeatureNode node : fullTree) {
allFeatures.add(node.name);
}
return allFeatures;
}
/**
* Helper method, returns all known feature names.
* @return All known feature names.
*/
public List<String> getAllFeatureNames() {
return Lists.newArrayList(featureMap.keySet());
}
// Visible for testing.
String getResourceContent(String resource) throws IOException {
return ResourceLoader.getContent(resource);
}
// Provided for backward compatibility with existing feature loader configurations.
// res://-prefixed URIs are actually scheme = res, host = "", path = "/stuff". We want res:path.
// Package-private for use by FeatureParser as well.
static Uri getComponentUri(String str) {
Uri uri = null;
if (str.startsWith("res://")) {
uri = new UriBuilder().setScheme(RESOURCE_SCHEME).setPath(str.substring(6)).toUri();
} else {
uri = Uri.parse(str);
}
return uri;
}
private List<FeatureNode> getTransitiveDeps(Collection<String> needed, List<String> unsupported) {
final List<FeatureNode> requested = getRequestedNodes(needed, unsupported);
Comparator<FeatureNode> nodeDepthComparator = new Comparator<FeatureNode>() {
public int compare(FeatureNode one, FeatureNode two) {
if (one.nodeDepth > two.nodeDepth ||
(one.nodeDepth == two.nodeDepth &&
requested.indexOf(one) < requested.indexOf(two))) {
return -1;
}
return 1;
}
};
// Before getTransitiveDeps() is called, all nodes and their graphs have been validated
// to have no circular dependencies, with their tree depth calculated. The requested
// features here may overlap in the tree, so we need to be sure not to double-include
// deps. Consider case where feature A depends on B and C, which both depend on D.
// If the requested features list is [A, C], we want to include A's tree in the appropriate
// order, and avoid double-including C (and its dependency D). Thus we sort by node depth
// first - A's tree is deeper than that of C, so *if* A's tree contains C, traversing
// it first guarantees that C is eventually included.
Collections.sort(requested, nodeDepthComparator);
Set<String> alreadySeen = Sets.newHashSet();
List<FeatureNode> fullDeps = Lists.newLinkedList();
for (FeatureNode requestedFeature : requested) {
for (FeatureNode toAdd : requestedFeature.getTransitiveDeps()) {
if (!alreadySeen.contains(toAdd.name)) {
alreadySeen.add(toAdd.name);
fullDeps.add(toAdd);
}
}
}
return fullDeps;
}
private List<FeatureNode> getRequestedNodes(Collection<String> needed, List<String> unsupported) {
List<FeatureNode> requested = Lists.newArrayList();
for (String featureName : needed) {
if (featureMap.containsKey(featureName)) {
requested.add(featureMap.get(featureName));
} else {
if (unsupported != null) unsupported.add(featureName);
}
}
return requested;
}
private boolean containerMatch(String containerAttrib, String container) {
if (containerAttrib == null || containerAttrib.length() == 0) {
// Nothing specified = all match.
return true;
}
Set<String> containers = Sets.newHashSet();
for (String attr : containerAttrib.split(",")) {
containers.add(attr.trim());
}
return containers.contains(container);
}
private void connectDependencyGraph() throws GadgetException {
// Iterate through each raw dependency, adding the corresponding feature to the graph.
// Collect as many feature dep tree errors as possible before erroring out.
List<String> problems = Lists.newLinkedList();
List<FeatureNode> theFeatures = Lists.newLinkedList();
// First hook up all first-order dependencies.
for (Map.Entry<String, FeatureNode> featureEntry : featureMap.entrySet()) {
String name = featureEntry.getKey();
FeatureNode feature = featureEntry.getValue();
for (String rawDep : feature.getRawDeps()) {
if (!featureMap.containsKey(rawDep)) {
problems.add("Feature [" + name + "] has dependency on unknown feature: " + rawDep);
} else {
feature.addDep(featureMap.get(rawDep));
theFeatures.add(feature);
}
}
}
// Then hook up the transitive dependency graph to validate there are
// no loops present.
for (FeatureNode feature : theFeatures) {
try {
// Validates the dependency tree ensuring no circular dependencies,
// and calculates the depth of the dependency tree rooted at the node.
feature.completeNodeGraph();
} catch (GadgetException e) {
problems.add(e.getMessage());
}
}
if (problems.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append("Problems found processing features:\n");
for (String problem : problems) {
sb.append(problem).append("\n");
}
throw new GadgetException(GadgetException.Code.INVALID_CONFIG, sb.toString());
}
}
private void loadResources(List<String> resources) throws GadgetException {
try {
for (String resource : resources) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Processing resource: " + resource);
}
String content = getResourceContent(resource);
Uri parent = new UriBuilder().setScheme(RESOURCE_SCHEME).setPath(resource).toUri();
loadFeature(parent, content);
}
} catch (IOException e) {
throw new GadgetException(GadgetException.Code.INVALID_PATH, e);
}
}
private void loadFile(File file) throws GadgetException, IOException {
if (!file.exists() || !file.canRead()) {
throw new GadgetException(GadgetException.Code.INVALID_CONFIG,
"Feature file '" + file.getPath() + "' doesn't exist or can't be read");
}
File[] toLoad = null;
if (file.isDirectory()) {
toLoad = file.listFiles();
} else {
toLoad = new File[] { file };
}
for (File featureFile : toLoad) {
if (featureFile.isDirectory()) {
// Traverse into subdirectories.
loadFile(featureFile);
} else if (featureFile.getName().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
String content = ResourceLoader.getContent(featureFile);
Uri parent = Uri.fromJavaUri(featureFile.toURI());
loadFeature(parent, content);
} else {
if (logger.isLoggable(Level.FINEST)) {
logger.finest(featureFile.getAbsolutePath() + " doesn't seem to be an XML file.");
}
}
}
}
protected void loadFeature(Uri parent, String xml) throws GadgetException {
FeatureParser.ParsedFeature parsed = parser.parse(parent, xml);
// Duplicate feature = OK, just indicate it's being overridden.
if (featureMap.containsKey(parsed.getName())) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Overriding feature: " + parsed.getName() + " with def at: " + parent);
}
}
// Walk through all parsed bundles, pulling resources and creating FeatureBundles/Nodes.
List<FeatureBundle> bundles = Lists.newArrayList();
for (FeatureParser.ParsedFeature.Bundle parsedBundle : parsed.getBundles()) {
List<FeatureResource> resources = Lists.newArrayList();
for (FeatureParser.ParsedFeature.Resource parsedResource : parsedBundle.getResources()) {
if (parsedResource.getSource() == null) {
resources.add(new InlineFeatureResource(parsedResource.getContent()));
} else {
// Load using resourceLoader
resources.add(
resourceLoader.load(parsedResource.getSource(), parsedResource.getAttribs()));
}
}
bundles.add(new FeatureBundle(parsedBundle.getType(), parsedBundle.getAttribs(), resources));
}
// Add feature to the master Map. The dependency tree isn't connected/validated/linked yet.
featureMap.put(parsed.getName(), new FeatureNode(parsed.getName(), bundles, parsed.getDeps()));
}
private static class InlineFeatureResource extends FeatureResource.Default {
private final String content;
private InlineFeatureResource(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public String getDebugContent() {
return content;
}
}
private static class FeatureBundle {
private final String type;
private final Map<String, String> attribs;
private final List<FeatureResource> resources;
private FeatureBundle(String type, Map<String, String> attribs,
List<FeatureResource> resources) {
this.type = type;
this.attribs = Collections.unmodifiableMap(attribs);
this.resources = Collections.unmodifiableList(resources);
}
public String getType() {
return type;
}
public Map<String, String> getAttribs() {
return attribs;
}
public List<FeatureResource> getResources() {
return resources;
}
}
private static class FeatureNode {
private final String name;
private final List<FeatureBundle> bundles;
private final List<String> requestedDeps;
private final List<FeatureNode> depList;
private List<FeatureNode> transitiveDeps;
private boolean calculatedDepsStale;
private int nodeDepth = 0;
private FeatureNode(String name, List<FeatureBundle> bundles, List<String> rawDeps) {
this.name = name;
this.bundles = Collections.unmodifiableList(bundles);
this.requestedDeps = Collections.unmodifiableList(rawDeps);
this.depList = Lists.newLinkedList();
this.transitiveDeps = Lists.newArrayList(this);
this.calculatedDepsStale = false;
}
public List<FeatureBundle> getBundles() {
return bundles;
}
public List<String> getRawDeps() {
return requestedDeps;
}
public void addDep(FeatureNode dep) {
depList.add(dep);
calculatedDepsStale = true;
}
private List<FeatureNode> getDepList() {
List<FeatureNode> revOrderDeps = Lists.newArrayList(depList);
Collections.reverse(revOrderDeps);
return Collections.unmodifiableList(revOrderDeps);
}
public void completeNodeGraph() throws GadgetException {
if (!calculatedDepsStale) {
return;
}
this.nodeDepth = 0;
this.transitiveDeps = Lists.newLinkedList();
this.transitiveDeps.add(this);
Queue<Pair<FeatureNode, Pair<Integer, String>>> toTraverse = Lists.newLinkedList();
toTraverse.add(Pair.of(this, Pair.of(0, "")));
while (!toTraverse.isEmpty()) {
Pair<FeatureNode, Pair<Integer, String>> next = toTraverse.poll();
String debug = next.two.two + (next.two.one > 0 ? " -> " : "") + next.one.name;
if (next.one == this && next.two.one != 0) {
throw new GadgetException(GadgetException.Code.INVALID_CONFIG,
"Feature dep loop detected: " + debug);
}
// Breadth-first list of dependencies.
this.transitiveDeps.add(next.one);
this.nodeDepth = Math.max(this.nodeDepth, next.two.one);
for (FeatureNode nextDep : next.one.getDepList()) {
toTraverse.add(Pair.of(nextDep, Pair.of(next.two.one + 1, debug)));
}
}
Collections.reverse(this.transitiveDeps);
calculatedDepsStale = false;
}
public List<FeatureNode> getTransitiveDeps() {
return this.transitiveDeps;
}
}
}
|
|
/* $Id: IbiscComponent.java 14675 2012-04-25 09:34:26Z ceriel $ */
package nl.esciencecenter.aether.compile;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import nl.esciencecenter.aether.compile.util.RunJavac;
/**
* This abstract class must be implemented by all components that are to be part
* of the Ibis compiler framework, and is the only means through which the
* Ibis compiler framework communicates with the component.
*/
public abstract class IbiscComponent {
/** Verbose flag. */
protected boolean verbose;
/** Keep generated Java files around. */
protected boolean keep;
/** Set when instantiated from Ibisc. */
protected boolean fromIbisc = false;
/** Wrapper for specific bytecode rewriter implementation. */
protected ByteCodeWrapper wrapper;
private HashMap<String, IbiscEntry> allClasses;
private HashMap<String, IbiscEntry> newClasses
= new HashMap<String, IbiscEntry>();
private class ClassIterator implements Iterator<Object> {
Iterator<IbiscEntry> i;
ClassIterator() {
i = allClasses.values().iterator();
}
public boolean hasNext() {
return i.hasNext();
}
public Object next() {
IbiscEntry e = i.next();
return e.getClassInfo().getClassObject();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
protected IbiscComponent() {
super();
}
void setWrapper(ByteCodeWrapper w) {
wrapper = w;
}
/**
* This method accepts an array of program arguments, processes the
* arguments that are intended for this component, and removes these
* arguments from the list. The parameter array may/must be modified.
* @param args the array of program arguments.
* @return <code>true</code> when this component must be run,
* <code>false</code> otherwise.
* @exception IllegalArgumentException may be thrown when there was an error
* in the arguments.
*/
public abstract boolean processArgs(ArrayList<String> args);
/**
* This method returns a short string, usable for a "usage" message
* when the user passes wrong parameters to ibisc.
* @return a usage string.
*/
public abstract String getUsageString();
/**
* This method processes an iterator which delivers java classes.
* The values are classes as represented by the byte code rewriter used.
* The component processes these entries as it sees fit.
* It can add entries by means of the {@link #addEntry(ClassInfo cl, String fromClass)} method.
* @param classes the class iterator to process.
*/
public abstract void process(Iterator<?> classes);
/**
* Returns the rewriter implementation. ASM and BCEL are supported.
* @return the rewriter implementation needed/used by this
* <code>IbiscComponent</code>.
*/
public abstract String rewriterImpl();
void processClasses(HashMap<String, IbiscEntry> classes) {
allClasses = classes;
process(new ClassIterator());
for (IbiscEntry ie : newClasses.values()) {
allClasses.put(ie.getClassInfo().getClassName(), ie);
}
}
/**
* Returns the name of the directory in which the file was found from
* which the class indicated by the specified class name was read.
* Returns <code>null</code> if the class is not found or the file lived
* in the current directory.
* @param cl the classname.
* @return the directory name or <code>null</code>.
*/
protected String getDirectory(String cl) {
IbiscEntry ie = allClasses.get(cl);
if (ie == null) {
ie = newClasses.get(cl);
}
if (ie == null) {
return null;
}
File f;
JarInfo ji = ie.getJarInfo();
if (ji == null) {
f = new File(ie.fileName);
} else {
f = new File(ji.getName());
}
return f.getParent();
}
/**
* Set the verbose flag to the specified value.
* @param v the value.
*/
void setVerbose(boolean v) {
verbose = v;
}
/**
* Set the keep flag to the specified value.
* When set, this flag instructs the component not to remove Java
* files that it may generate while processing the classes.
* @param v the value.
*/
void setKeep(boolean v) {
keep = v;
}
/**
* Writes out all modified classes and jars.
*/
protected void writeAll() {
Ibisc.writeAll();
}
/**
* Notifies that the specified class has changed.
* @param cl the class that has changed.
*/
protected void setModified(ClassInfo cl) {
String className = cl.getClassName();
IbiscEntry e = allClasses.get(className);
if (e == null) {
e = newClasses.get(className);
}
if (e != null) {
e.setClassInfo(cl);
}
}
/**
* Adds a new entry to the class list. The new entry is derived from
* the specified class, and is ultimately written in the same directory,
* or the same jar file as the class from which it is derived.
* @param cl the new entry.
* @param fromClass the name of the class from which it is derived.
*/
protected void addEntry(ClassInfo cl, String fromClass) {
IbiscEntry from = allClasses.get(fromClass);
String fn = from.fileName;
String className = cl.getClassName();
String baseDir = (new File(fn)).getParent();
String newFilename;
int n = className.lastIndexOf(".");
String name = className;
if (n != -1) {
name = name.substring(n+1, name.length());
}
if (baseDir == null) {
newFilename = name + ".class";
} else {
newFilename = baseDir + File.separator + name + ".class";
}
JarInfo fromInfo = from.getJarInfo();
IbiscEntry newEntry = new IbiscEntry(cl, newFilename, fromInfo);
newEntry.setModified(true);
newClasses.put(className, newEntry);
if (fromInfo != null) {
fromInfo.addEntry(newEntry);
}
}
/**
* Compiles the specified list of arguments, which are all derived from
* the specified class. The resulting classes are ultimately written in
* the same directory or the same jar file as the class from which they
* are derived.
* @param args the list of Java files to compile.
* @param fromClass the name of the class from which they are derived.
*/
protected void compile(ArrayList<String> args, String fromClass) {
int sz = args.size();
String[] compilerArgs = new String[sz + 1];
compilerArgs[0] = "-g";
for (int i = 0; i < sz; i++) {
compilerArgs[i + 1] = args.get(i);
}
if (!RunJavac.runJavac(compilerArgs, verbose)) {
System.exit(1);
}
for (int i = 1; i <= sz; i++) {
if (!keep) { // remove generated files
File f = new File(compilerArgs[i]);
f.delete();
}
}
// When called from Ibisc, parse resulting class files and remove
// them.
if (fromIbisc) {
for (int i = 1; i <= sz; i++) {
File f = new File(compilerArgs[i]);
File base = f.getParentFile();
if (base == null) {
base = new File(".");
}
String fn = f.getName();
fn = fn.substring(0, fn.length()-5);
String[] list = base.list();
for (int j = 0; j < list.length; j++) {
if (list[j].startsWith(fn) && list[j].endsWith(".class")) {
String name = base.getPath() + File.separator + list[j];
try {
ClassInfo cl = wrapper.parseClassFile(name);
addEntry(cl, fromClass);
(new File(name)).delete();
} catch(Exception e) {
System.err.println("Could not read " + name);
System.exit(1);
}
}
}
}
}
}
}
|
|
package com.fsck.k9.ui.messageview;
import java.util.Collections;
import java.util.Locale;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.activity.K9ActivityCommon;
import com.fsck.k9.ui.R;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.MessageLoaderHelper;
import com.fsck.k9.activity.MessageLoaderHelper.MessageLoaderCallbacks;
import com.fsck.k9.controller.MessageReference;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.fragment.AttachmentDownloadDialogFragment;
import com.fsck.k9.fragment.ConfirmationDialogFragment;
import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
import com.fsck.k9.ui.helper.FileBrowserHelper;
import com.fsck.k9.ui.helper.FileBrowserHelper.FileBrowserFailOverCallback;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mailstore.AttachmentViewInfo;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.MessageViewInfo;
import com.fsck.k9.ui.messageview.CryptoInfoDialog.OnClickShowCryptoKeyListener;
import com.fsck.k9.ui.messageview.MessageCryptoPresenter.MessageCryptoMvpView;
import com.fsck.k9.ui.settings.account.AccountSettingsActivity;
import com.fsck.k9.view.MessageCryptoDisplayStatus;
import com.fsck.k9.view.MessageHeader;
import timber.log.Timber;
public class MessageViewFragment extends Fragment implements ConfirmationDialogFragmentListener,
AttachmentViewCallback, OnClickShowCryptoKeyListener {
private static final String ARG_REFERENCE = "reference";
private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
private static final int ACTIVITY_CHOOSE_DIRECTORY = 3;
public static final int REQUEST_MASK_LOADER_HELPER = (1 << 8);
public static final int REQUEST_MASK_CRYPTO_PRESENTER = (1 << 9);
public static final int PROGRESS_THRESHOLD_MILLIS = 500 * 1000;
public static MessageViewFragment newInstance(MessageReference reference) {
MessageViewFragment fragment = new MessageViewFragment();
Bundle args = new Bundle();
args.putString(ARG_REFERENCE, reference.toIdentityString());
fragment.setArguments(args);
return fragment;
}
private MessageTopView mMessageView;
private Account mAccount;
private MessageReference mMessageReference;
private LocalMessage mMessage;
private MessagingController mController;
private DownloadManager downloadManager;
private Handler handler = new Handler();
private MessageLoaderHelper messageLoaderHelper;
private MessageCryptoPresenter messageCryptoPresenter;
private Long showProgressThreshold;
/**
* Used to temporarily store the destination folder for refile operations if a confirmation
* dialog is shown.
*/
private String mDstFolder;
private MessageViewFragmentListener mFragmentListener;
/**
* {@code true} after {@link #onCreate(Bundle)} has been executed. This is used by
* {@code MessageList.configureMenu()} to make sure the fragment has been initialized before
* it is used.
*/
private boolean mInitialized = false;
private Context mContext;
private AttachmentViewInfo currentAttachmentViewInfo;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context.getApplicationContext();
try {
mFragmentListener = (MessageViewFragmentListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("This fragment must be attached to a MessageViewFragmentListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This fragments adds options to the action bar
setHasOptionsMenu(true);
Context context = getActivity().getApplicationContext();
mController = MessagingController.getInstance(context);
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
messageCryptoPresenter = new MessageCryptoPresenter(messageCryptoMvpView);
messageLoaderHelper = new MessageLoaderHelper(
context, getLoaderManager(), getFragmentManager(), messageLoaderCallbacks);
mInitialized = true;
}
@Override
public void onResume() {
super.onResume();
messageCryptoPresenter.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
Activity activity = getActivity();
boolean isChangingConfigurations = activity != null && activity.isChangingConfigurations();
if (isChangingConfigurations) {
messageLoaderHelper.onDestroyChangingConfigurations();
return;
}
messageLoaderHelper.onDestroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = new ContextThemeWrapper(inflater.getContext(),
K9ActivityCommon.getK9ThemeResourceId(K9.getK9MessageViewTheme()));
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.message, container, false);
mMessageView = view.findViewById(R.id.message_view);
mMessageView.setAttachmentCallback(this);
mMessageView.setMessageCryptoPresenter(messageCryptoPresenter);
mMessageView.setOnToggleFlagClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onToggleFlagged();
}
});
mMessageView.setOnDownloadButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mMessageView.disableDownloadButton();
messageLoaderHelper.downloadCompleteMessage();
}
});
mFragmentListener.messageHeaderViewAvailable(mMessageView.getMessageHeaderView());
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
String messageReferenceString = arguments.getString(ARG_REFERENCE);
MessageReference messageReference = MessageReference.parse(messageReferenceString);
displayMessage(messageReference);
}
private void displayMessage(MessageReference messageReference) {
mMessageReference = messageReference;
Timber.d("MessageView displaying message %s", mMessageReference);
mAccount = Preferences.getPreferences(getApplicationContext()).getAccount(mMessageReference.getAccountUuid());
messageLoaderHelper.asyncStartOrResumeLoadingMessage(messageReference, null);
mFragmentListener.updateMenu();
}
private void hideKeyboard() {
Activity activity = getActivity();
if (activity == null) {
return;
}
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
View decorView = activity.getWindow().getDecorView();
if (decorView != null) {
imm.hideSoftInputFromWindow(decorView.getApplicationWindowToken(), 0);
}
}
private void showUnableToDecodeError() {
Context context = getActivity().getApplicationContext();
Toast.makeText(context, R.string.message_view_toast_unable_to_display_message, Toast.LENGTH_SHORT).show();
}
private void showMessage(MessageViewInfo messageViewInfo) {
hideKeyboard();
boolean handledByCryptoPresenter = messageCryptoPresenter.maybeHandleShowMessage(
mMessageView, mAccount, messageViewInfo);
if (!handledByCryptoPresenter) {
mMessageView.showMessage(mAccount, messageViewInfo);
if (mAccount.isOpenPgpProviderConfigured()) {
mMessageView.getMessageHeaderView().setCryptoStatusDisabled();
} else {
mMessageView.getMessageHeaderView().hideCryptoStatus();
}
}
if (messageViewInfo.subject != null) {
displaySubject(messageViewInfo.subject);
}
}
private void displayHeaderForLoadingMessage(LocalMessage message) {
mMessageView.setHeaders(message, mAccount);
if (mAccount.isOpenPgpProviderConfigured()) {
mMessageView.getMessageHeaderView().setCryptoStatusLoading();
}
displaySubject(message.getSubject());
mFragmentListener.updateMenu();
}
private void displaySubject(String subject) {
if (TextUtils.isEmpty(subject)) {
subject = mContext.getString(R.string.general_no_subject);
}
mMessageView.setSubject(subject);
displayMessageSubject(subject);
}
/**
* Called from UI thread when user select Delete
*/
public void onDelete() {
if (K9.confirmDelete() || (K9.confirmDeleteStarred() && mMessage.isSet(Flag.FLAGGED))) {
showDialog(R.id.dialog_confirm_delete);
} else {
delete();
}
}
public void onToggleAllHeadersView() {
mMessageView.getMessageHeaderView().onShowAdditionalHeaders();
}
public boolean allHeadersVisible() {
return mMessageView.getMessageHeaderView().additionalHeadersVisible();
}
private void delete() {
if (mMessage != null) {
// Disable the delete button after it's tapped (to try to prevent
// accidental clicks)
mFragmentListener.disableDeleteAction();
LocalMessage messageToDelete = mMessage;
mFragmentListener.showNextMessageOrReturn();
mController.deleteMessage(mMessageReference, null);
}
}
public void onRefile(String dstFolder) {
if (!mController.isMoveCapable(mAccount)) {
return;
}
if (!mController.isMoveCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
if (K9.FOLDER_NONE.equals(dstFolder)) {
return;
}
if (mAccount.getSpamFolder().equals(dstFolder) && K9.confirmSpam()) {
mDstFolder = dstFolder;
showDialog(R.id.dialog_confirm_spam);
} else {
refileMessage(dstFolder);
}
}
private void refileMessage(String dstFolder) {
String srcFolder = mMessageReference.getFolderServerId();
MessageReference messageToMove = mMessageReference;
mFragmentListener.showNextMessageOrReturn();
mController.moveMessage(mAccount, srcFolder, messageToMove, dstFolder);
}
public void onReply() {
if (mMessage != null) {
mFragmentListener.onReply(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onReplyAll() {
if (mMessage != null) {
mFragmentListener.onReplyAll(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onForward() {
if (mMessage != null) {
mFragmentListener.onForward(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onForwardAsAttachment() {
if (mMessage != null) {
mFragmentListener.onForwardAsAttachment(mMessage.makeMessageReference(), messageCryptoPresenter.getDecryptionResultForReply());
}
}
public void onToggleFlagged() {
if (mMessage != null) {
boolean newState = !mMessage.isSet(Flag.FLAGGED);
mController.setFlag(mAccount, mMessage.getFolder().getServerId(),
Collections.singletonList(mMessage), Flag.FLAGGED, newState);
mMessageView.setHeaders(mMessage, mAccount);
}
}
public void onMove() {
if ((!mController.isMoveCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isMoveCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_MOVE);
}
public void onCopy() {
if ((!mController.isCopyCapable(mAccount))
|| (mMessage == null)) {
return;
}
if (!mController.isCopyCapable(mMessageReference)) {
Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
toast.show();
return;
}
startRefileActivity(ACTIVITY_CHOOSE_FOLDER_COPY);
}
public void onArchive() {
onRefile(mAccount.getArchiveFolder());
}
public void onSpam() {
onRefile(mAccount.getSpamFolder());
}
public void onSelectText() {
// FIXME
// mMessageView.beginSelectingText();
}
private void startRefileActivity(int activity) {
Intent intent = new Intent(getActivity(), ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.getFolderServerId());
intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, mAccount.getLastSelectedFolder());
intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference.toIdentityString());
startActivityForResult(intent, activity);
}
public void onPendingIntentResult(int requestCode, int resultCode, Intent data) {
if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) {
requestCode ^= REQUEST_MASK_LOADER_HELPER;
messageLoaderHelper.onActivityResult(requestCode, resultCode, data);
return;
}
if ((requestCode & REQUEST_MASK_CRYPTO_PRESENTER) == REQUEST_MASK_CRYPTO_PRESENTER) {
requestCode ^= REQUEST_MASK_CRYPTO_PRESENTER;
messageCryptoPresenter.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
// Note: because fragments do not have a startIntentSenderForResult method, pending intent activities are
// launched through the MessageList activity, and delivered back via onPendingIntentResult()
switch (requestCode) {
case ACTIVITY_CHOOSE_DIRECTORY: {
if (data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
getAttachmentController(currentAttachmentViewInfo).saveAttachmentTo(filePath);
}
}
}
break;
}
case ACTIVITY_CHOOSE_FOLDER_MOVE:
case ACTIVITY_CHOOSE_FOLDER_COPY: {
if (data == null) {
return;
}
String destFolder = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
String messageReferenceString = data.getStringExtra(ChooseFolder.EXTRA_MESSAGE);
MessageReference ref = MessageReference.parse(messageReferenceString);
if (mMessageReference.equals(ref)) {
mAccount.setLastSelectedFolder(destFolder);
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE: {
mFragmentListener.showNextMessageOrReturn();
moveMessage(ref, destFolder);
break;
}
case ACTIVITY_CHOOSE_FOLDER_COPY: {
copyMessage(ref, destFolder);
break;
}
}
}
break;
}
}
}
public void onSendAlternate() {
if (mMessage != null) {
mController.sendAlternate(getActivity(), mAccount, mMessage);
}
}
public void onToggleRead() {
if (mMessage != null) {
mController.setFlag(mAccount, mMessage.getFolder().getServerId(),
Collections.singletonList(mMessage), Flag.SEEN, !mMessage.isSet(Flag.SEEN));
mMessageView.setHeaders(mMessage, mAccount);
mFragmentListener.updateMenu();
}
}
private void setProgress(boolean enable) {
if (mFragmentListener != null) {
mFragmentListener.setProgress(enable);
}
}
private void displayMessageSubject(String subject) {
if (mFragmentListener != null) {
mFragmentListener.displayMessageSubject(subject);
}
}
public void moveMessage(MessageReference reference, String destFolderName) {
mController.moveMessage(mAccount, mMessageReference.getFolderServerId(), reference, destFolderName);
}
public void copyMessage(MessageReference reference, String destFolderName) {
mController.copyMessage(mAccount, mMessageReference.getFolderServerId(), reference, destFolderName);
}
private void showDialog(int dialogId) {
DialogFragment fragment;
if (dialogId == R.id.dialog_confirm_delete) {
String title = getString(R.string.dialog_confirm_delete_title);
String message = getString(R.string.dialog_confirm_delete_message);
String confirmText = getString(R.string.dialog_confirm_delete_confirm_button);
String cancelText = getString(R.string.dialog_confirm_delete_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
} else if (dialogId == R.id.dialog_confirm_spam) {
String title = getString(R.string.dialog_confirm_spam_title);
String message = getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, 1);
String confirmText = getString(R.string.dialog_confirm_spam_confirm_button);
String cancelText = getString(R.string.dialog_confirm_spam_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
} else if (dialogId == R.id.dialog_attachment_progress) {
String message = getString(R.string.dialog_attachment_progress_title);
long size = currentAttachmentViewInfo.size;
fragment = AttachmentDownloadDialogFragment.newInstance(size, message);
} else {
throw new RuntimeException("Called showDialog(int) with unknown dialog id.");
}
fragment.setTargetFragment(this, dialogId);
fragment.show(getFragmentManager(), getDialogTag(dialogId));
}
private void removeDialog(int dialogId) {
FragmentManager fm = getFragmentManager();
if (fm == null || isRemoving() || isDetached()) {
return;
}
// Make sure the "show dialog" transaction has been processed when we call
// findFragmentByTag() below. Otherwise the fragment won't be found and the dialog will
// never be dismissed.
fm.executePendingTransactions();
DialogFragment fragment = (DialogFragment) fm.findFragmentByTag(getDialogTag(dialogId));
if (fragment != null) {
fragment.dismissAllowingStateLoss();
}
}
private String getDialogTag(int dialogId) {
return String.format(Locale.US, "dialog-%d", dialogId);
}
public void zoom(KeyEvent event) {
// mMessageView.zoom(event);
}
@Override
public void doPositiveClick(int dialogId) {
if (dialogId == R.id.dialog_confirm_delete) {
delete();
} else if (dialogId == R.id.dialog_confirm_spam) {
refileMessage(mDstFolder);
mDstFolder = null;
}
}
@Override
public void doNegativeClick(int dialogId) {
/* do nothing */
}
@Override
public void dialogCancelled(int dialogId) {
/* do nothing */
}
/**
* Get the {@link MessageReference} of the currently displayed message.
*/
public MessageReference getMessageReference() {
return mMessageReference;
}
public boolean isMessageRead() {
return (mMessage != null) && mMessage.isSet(Flag.SEEN);
}
public boolean isCopyCapable() {
return mController.isCopyCapable(mAccount);
}
public boolean isMoveCapable() {
return mController.isMoveCapable(mAccount);
}
public boolean canMessageBeArchived() {
return (!mMessageReference.getFolderServerId().equals(mAccount.getArchiveFolder())
&& mAccount.hasArchiveFolder());
}
public boolean canMessageBeMovedToSpam() {
return (!mMessageReference.getFolderServerId().equals(mAccount.getSpamFolder())
&& mAccount.hasSpamFolder());
}
public void updateTitle() {
if (mMessage != null) {
displayMessageSubject(mMessage.getSubject());
}
}
public Context getApplicationContext() {
return mContext;
}
public void disableAttachmentButtons(AttachmentViewInfo attachment) {
// mMessageView.disableAttachmentButtons(attachment);
}
public void enableAttachmentButtons(AttachmentViewInfo attachment) {
// mMessageView.enableAttachmentButtons(attachment);
}
public void runOnMainThread(Runnable runnable) {
handler.post(runnable);
}
public void showAttachmentLoadingDialog() {
// mMessageView.disableAttachmentButtons();
showDialog(R.id.dialog_attachment_progress);
}
public void hideAttachmentLoadingDialogOnMainThread() {
handler.post(new Runnable() {
@Override
public void run() {
removeDialog(R.id.dialog_attachment_progress);
// mMessageView.enableAttachmentButtons();
}
});
}
public void refreshAttachmentThumbnail(AttachmentViewInfo attachment) {
// mMessageView.refreshAttachmentThumbnail(attachment);
}
private MessageCryptoMvpView messageCryptoMvpView = new MessageCryptoMvpView() {
@Override
public void redisplayMessage() {
messageLoaderHelper.asyncReloadMessage();
}
@Override
public void startPendingIntentForCryptoPresenter(IntentSender si, Integer requestCode, Intent fillIntent,
int flagsMask, int flagValues, int extraFlags) throws SendIntentException {
if (requestCode == null) {
getActivity().startIntentSender(si, fillIntent, flagsMask, flagValues, extraFlags);
return;
}
requestCode |= REQUEST_MASK_CRYPTO_PRESENTER;
getActivity().startIntentSenderForResult(
si, requestCode, fillIntent, flagsMask, flagValues, extraFlags);
}
@Override
public void showCryptoInfoDialog(MessageCryptoDisplayStatus displayStatus, boolean hasSecurityWarning) {
CryptoInfoDialog dialog = CryptoInfoDialog.newInstance(displayStatus, hasSecurityWarning);
dialog.setTargetFragment(MessageViewFragment.this, 0);
dialog.show(getFragmentManager(), "crypto_info_dialog");
}
@Override
public void restartMessageCryptoProcessing() {
mMessageView.setToLoadingState();
messageLoaderHelper.asyncRestartMessageCryptoProcessing();
}
@Override
public void showCryptoConfigDialog() {
AccountSettingsActivity.startCryptoSettings(getActivity(), mAccount.getUuid());
}
};
@Override
public void onClickShowSecurityWarning() {
messageCryptoPresenter.onClickShowCryptoWarningDetails();
}
@Override
public void onClickSearchKey() {
messageCryptoPresenter.onClickSearchKey();
}
@Override
public void onClickShowCryptoKey() {
messageCryptoPresenter.onClickShowCryptoKey();
}
public interface MessageViewFragmentListener {
void onForward(MessageReference messageReference, Parcelable decryptionResultForReply);
void onForwardAsAttachment(MessageReference messageReference, Parcelable decryptionResultForReply);
void disableDeleteAction();
void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply);
void onReply(MessageReference messageReference, Parcelable decryptionResultForReply);
void displayMessageSubject(String title);
void setProgress(boolean b);
void showNextMessageOrReturn();
void messageHeaderViewAvailable(MessageHeader messageHeaderView);
void updateMenu();
}
public boolean isInitialized() {
return mInitialized ;
}
private MessageLoaderCallbacks messageLoaderCallbacks = new MessageLoaderCallbacks() {
@Override
public void onMessageDataLoadFinished(LocalMessage message) {
mMessage = message;
displayHeaderForLoadingMessage(message);
mMessageView.setToLoadingState();
showProgressThreshold = null;
}
@Override
public void onMessageDataLoadFailed() {
Toast.makeText(getActivity(), R.string.status_loading_error, Toast.LENGTH_LONG).show();
showProgressThreshold = null;
}
@Override
public void onMessageViewInfoLoadFinished(MessageViewInfo messageViewInfo) {
showMessage(messageViewInfo);
showProgressThreshold = null;
}
@Override
public void onMessageViewInfoLoadFailed(MessageViewInfo messageViewInfo) {
showMessage(messageViewInfo);
showProgressThreshold = null;
}
@Override
public void setLoadingProgress(int current, int max) {
if (showProgressThreshold == null) {
showProgressThreshold = SystemClock.elapsedRealtime() + PROGRESS_THRESHOLD_MILLIS;
} else if (showProgressThreshold == 0L || SystemClock.elapsedRealtime() > showProgressThreshold) {
showProgressThreshold = 0L;
mMessageView.setLoadingProgress(current, max);
}
}
@Override
public void onDownloadErrorMessageNotFound() {
mMessageView.enableDownloadButton();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.status_invalid_id_error, Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onDownloadErrorNetworkError() {
mMessageView.enableDownloadButton();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.status_network_error, Toast.LENGTH_LONG).show();
}
});
}
@Override
public void startIntentSenderForMessageLoaderHelper(IntentSender si, int requestCode, Intent fillIntent,
int flagsMask, int flagValues, int extraFlags) {
showProgressThreshold = null;
try {
requestCode |= REQUEST_MASK_LOADER_HELPER;
getActivity().startIntentSenderForResult(
si, requestCode, fillIntent, flagsMask, flagValues, extraFlags);
} catch (SendIntentException e) {
Timber.e(e, "Irrecoverable error calling PendingIntent!");
}
}
};
@Override
public void onViewAttachment(AttachmentViewInfo attachment) {
currentAttachmentViewInfo = attachment;
getAttachmentController(attachment).viewAttachment();
}
@Override
public void onSaveAttachment(AttachmentViewInfo attachment) {
currentAttachmentViewInfo = attachment;
getAttachmentController(attachment).saveAttachment();
}
@Override
public void onSaveAttachmentToUserProvidedDirectory(final AttachmentViewInfo attachment) {
currentAttachmentViewInfo = attachment;
FileBrowserHelper.getInstance().showFileBrowserActivity(MessageViewFragment.this, null,
ACTIVITY_CHOOSE_DIRECTORY, new FileBrowserFailOverCallback() {
@Override
public void onPathEntered(String path) {
getAttachmentController(attachment).saveAttachmentTo(path);
}
@Override
public void onCancel() {
// Do nothing
}
});
}
private AttachmentController getAttachmentController(AttachmentViewInfo attachment) {
return new AttachmentController(mController, downloadManager, this, attachment);
}
}
|
|
/*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions 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.infinities.skyport.ui;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.ContextRequirements;
import org.dasein.cloud.ContextRequirements.Field;
import org.dasein.cloud.ContextRequirements.FieldType;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.admin.AdminServices;
import org.dasein.cloud.ci.CIServices;
import org.dasein.cloud.identity.IdentityServices;
import org.dasein.cloud.platform.PlatformServices;
import org.dasein.cloud.storage.StorageServices;
import org.dasein.cloud.util.NamingConstraints;
import org.dasein.cloud.util.ResourceNamespace;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import com.infinities.skyport.ServiceProvider;
import com.infinities.skyport.compute.SkyportComputeServices;
import com.infinities.skyport.dc.SkyportDataCenterServices;
import com.infinities.skyport.network.SkyportNetworkServices;
import com.infinities.skyport.storage.SkyportStorageServices;
public class WithExtraValueServiceProvider implements ServiceProvider {
protected Mockery context = new JUnit4Mockery() {
{
setThreadingPolicy(new Synchroniser());
}
};
private SkyportDataCenterServices dataCenterServices = null;
public WithExtraValueServiceProvider() {
dataCenterServices = context.mock(SkyportDataCenterServices.class);
}
@Override
public void initialize() {
}
@Override
public String testContext() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean hasAdminServices() {
return false;
}
@Override
public boolean hasCIServices() {
return false;
}
@Override
public boolean hasComputeServices() {
return false;
}
@Override
public boolean hasIdentityServices() {
return false;
}
@Override
public boolean hasNetworkServices() {
return false;
}
@Override
public boolean hasPlatformServices() {
return false;
}
@Override
public boolean hasStorageServices() {
return false;
}
@Override
public AdminServices getAdminServices() {
return null;
}
@Override
public CloudProvider getComputeCloud() {
return null;
}
@Override
public ProviderContext getContext() {
return null;
}
@Override
public ContextRequirements getContextRequirements() {
return new ContextRequirements(new Field("MyKey", "Mycloud keypair", FieldType.KEYPAIR));
}
@Override
public String getCloudName() {
return "mock";
}
@Override
public SkyportDataCenterServices getSkyportDataCenterServices() {
return dataCenterServices;
}
@Override
public CIServices getCIServices() {
return null;
}
@Override
public SkyportComputeServices getSkyportComputeServices() {
return null;
}
@Override
public IdentityServices getIdentityServices() {
return null;
}
public PlatformServices getPlatformServices() {
return null;
}
@Override
public String getProviderName() {
return "mock";
}
@Override
public String findUniqueName(String baseName, NamingConstraints constraints, ResourceNamespace namespace)
throws CloudException, InternalException {
return null;
}
@Override
public void close() {
}
@Override
public SkyportNetworkServices getSkyportNetworkServices() throws ConcurrentException {
return null;
}
@Override
public SkyportStorageServices getSkyportStorageServices() throws ConcurrentException {
return null;
}
}
|
|
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.runtime;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.AdditionalMatchers.find;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.test.TestProvider;
import com.google.devtools.build.lib.analysis.test.TestProvider.TestParams;
import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos.TestStatus;
import com.google.devtools.build.lib.buildeventstream.PathConverter;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.util.io.AnsiTerminalPrinter;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.devtools.build.lib.view.test.TestStatus.BlazeTestStatus;
import com.google.devtools.build.lib.view.test.TestStatus.FailedTestCasesStatus;
import com.google.devtools.build.lib.view.test.TestStatus.TestCase;
import com.google.devtools.build.lib.view.test.TestStatus.TestCase.Status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.InOrder;
import org.mockito.Mockito;
@RunWith(JUnit4.class)
public class TestSummaryTest {
private static final String ANY_STRING = ".*?";
private static final String PATH = "package";
private static final String TARGET_NAME = "name";
private ConfiguredTarget stubTarget;
private static final ImmutableList<Long> SMALL_TIMING = ImmutableList.of(1L, 2L, 3L, 4L);
private static final int CACHED = SMALL_TIMING.size();
private static final int NOT_CACHED = 0;
private FileSystem fs;
private TestSummary.Builder basicBuilder;
@Before
public final void createFileSystem() throws Exception {
fs = new InMemoryFileSystem(BlazeClock.instance());
stubTarget = stubTarget();
basicBuilder = getTemplateBuilder();
}
private TestSummary.Builder getTemplateBuilder() {
BuildConfiguration configuration = Mockito.mock(BuildConfiguration.class);
when(configuration.checksum()).thenReturn("abcdef");
return TestSummary.newBuilder()
.setTarget(stubTarget)
.setConfiguration(configuration)
.setStatus(BlazeTestStatus.PASSED)
.setNumCached(NOT_CACHED)
.setActionRan(true)
.setRanRemotely(false)
.setWasUnreportedWrongSize(false);
}
private List<Path> getPathList(String... names) {
List<Path> list = new ArrayList<>();
for (String name : names) {
list.add(fs.getPath(name));
}
return list;
}
@Test
public void testShouldProperlyTestLabels() throws Exception {
ConfiguredTarget target = target("somepath", "MyTarget");
String expectedString = ANY_STRING + "//somepath:MyTarget" + ANY_STRING;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summaryStatus = createTestSummary(target, BlazeTestStatus.PASSED, CACHED);
TestSummaryPrinter.print(summaryStatus, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testShouldPrintPassedStatus() throws Exception {
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED + ANY_STRING;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.PASSED, NOT_CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
verify(terminalPrinter).print(find(expectedString));
}
@Test
public void testShouldPrintFailedStatus() throws Exception {
String expectedString = ANY_STRING + "ERROR" + ANY_STRING + BlazeTestStatus.FAILED + ANY_STRING;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.FAILED, NOT_CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
private void assertShouldNotPrint(BlazeTestStatus status, boolean verboseSummary) {
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(
createTestSummary(stubTarget, status, NOT_CACHED),
terminalPrinter,
Path::getPathString,
verboseSummary,
false);
verify(terminalPrinter, never()).print(anyString());
}
@Test
public void testShouldPrintFailedToBuildStatus() {
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.FAILED_TO_BUILD;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(BlazeTestStatus.FAILED_TO_BUILD, NOT_CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testShouldNotPrintFailedToBuildStatus() {
assertShouldNotPrint(BlazeTestStatus.FAILED_TO_BUILD, false);
}
@Test
public void testShouldNotPrintHaltedStatus() {
assertShouldNotPrint(BlazeTestStatus.BLAZE_HALTED_BEFORE_TESTING, true);
}
@Test
public void testShouldPrintCachedStatus() throws Exception {
String expectedString = ANY_STRING + "\\(cached" + ANY_STRING;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.PASSED, CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testPartialCachedStatus() throws Exception {
String expectedString = ANY_STRING + "\\(3/4 cached" + ANY_STRING;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.PASSED, CACHED - 1);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testIncompleteCached() throws Exception {
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.INCOMPLETE, CACHED - 1);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
verify(terminalPrinter).print(not(contains("cached")));
}
@Test
public void testShouldPrintUncachedStatus() throws Exception {
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.PASSED, NOT_CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
verify(terminalPrinter).print(not(contains("cached")));
}
@Test
public void testNoTiming() throws Exception {
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED;
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = createTestSummary(stubTarget, BlazeTestStatus.PASSED, NOT_CACHED);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testBuilder() throws Exception {
// No need to copy if built twice in a row; no direct setters on the object.
TestSummary summary = basicBuilder.build();
TestSummary sameSummary = basicBuilder.build();
assertThat(sameSummary).isSameInstanceAs(summary);
basicBuilder.addTestTimes(ImmutableList.of(40L));
TestSummary summaryCopy = basicBuilder.build();
assertThat(summaryCopy.getTarget()).isEqualTo(summary.getTarget());
assertThat(summaryCopy.getStatus()).isEqualTo(summary.getStatus());
assertThat(summaryCopy.numCached()).isEqualTo(summary.numCached());
assertThat(summaryCopy).isNotSameInstanceAs(summary);
assertThat(summary.totalRuns()).isEqualTo(0);
assertThat(summaryCopy.totalRuns()).isEqualTo(1);
// Check that the builder can add a new warning to the copy,
// despite the immutability of the original.
basicBuilder.addTestTimes(ImmutableList.of(60L));
TestSummary fiftyCached = basicBuilder.setNumCached(50).build();
assertThat(fiftyCached.getStatus()).isEqualTo(summary.getStatus());
assertThat(fiftyCached.numCached()).isEqualTo(50);
assertThat(fiftyCached.totalRuns()).isEqualTo(2);
TestSummary sixtyCached = basicBuilder.setNumCached(60).build();
assertThat(sixtyCached.numCached()).isEqualTo(60);
assertThat(fiftyCached.numCached()).isEqualTo(50);
}
@Test
public void testAsStreamProto() throws Exception {
TestParams testParams = mock(TestParams.class);
when(testParams.getRuns()).thenReturn(2);
when(testParams.getShards()).thenReturn(3);
TestProvider testProvider = new TestProvider(testParams, ImmutableList.of());
when(stubTarget.getProvider(eq(TestProvider.class))).thenReturn(testProvider);
PathConverter pathConverter = mock(PathConverter.class);
when(pathConverter.apply(any(Path.class)))
.thenAnswer(
invocation -> "/path/to" + ((Path) invocation.getArguments()[0]).getPathString());
BuildEventContext converters = mock(BuildEventContext.class);
when(converters.pathConverter()).thenReturn(pathConverter);
TestSummary summary =
basicBuilder
.setStatus(BlazeTestStatus.FAILED)
.addPassedLogs(getPathList("/apple"))
.addFailedLogs(getPathList("/pear"))
.mergeTiming(1000, 300)
.build();
assertThat(summary.asStreamProto(converters).getTestSummary())
.isEqualTo(
BuildEventStreamProtos.TestSummary.newBuilder()
.setOverallStatus(TestStatus.FAILED)
.setFirstStartTimeMillis(1000)
.setLastStopTimeMillis(1300)
.setTotalRunDurationMillis(300)
.setRunCount(2)
.setShardCount(3)
.addPassed(BuildEventStreamProtos.File.newBuilder().setUri("/path/to/apple"))
.addFailed(BuildEventStreamProtos.File.newBuilder().setUri("/path/to/pear"))
.build());
}
@Test
public void testSingleTime() throws Exception {
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED + ANY_STRING +
"in 3.4s";
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = basicBuilder.addTestTimes(ImmutableList.of(3412L)).build();
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testNoTime() throws Exception {
// The last part matches anything not containing "in".
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED + "(?!in)*";
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = basicBuilder.addTestTimes(ImmutableList.of(3412L)).build();
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, false, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testMultipleTimes() throws Exception {
String expectedString = ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED + ANY_STRING +
"\n Stats over 3 runs: max = 3.0s, min = 1.0s, " +
"avg = 2.0s, dev = 0.8s";
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = basicBuilder
.addTestTimes(ImmutableList.of(1000L, 2000L, 3000L))
.build();
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testCoverageDataReferences() throws Exception {
List<Path> paths = getPathList("/cov1.dat", "/cov2.dat", "/cov3.dat", "/cov4.dat");
FileSystemUtils.writeContentAsLatin1(paths.get(1), "something");
FileSystemUtils.writeContentAsLatin1(paths.get(3), "");
FileSystemUtils.writeContentAsLatin1(paths.get(3), "something else");
TestSummary summary = basicBuilder.addCoverageFiles(paths).build();
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
verify(terminalPrinter).print(find(ANY_STRING + "INFO" + ANY_STRING + BlazeTestStatus.PASSED));
verify(terminalPrinter).print(find(" /cov2.dat"));
verify(terminalPrinter).print(find(" /cov4.dat"));
}
@Test
public void testFlakyAttempts() throws Exception {
String expectedString = ANY_STRING + "WARNING" + ANY_STRING + BlazeTestStatus.FLAKY +
ANY_STRING + ", failed in 2 out of 3";
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = basicBuilder
.setStatus(BlazeTestStatus.FLAKY)
.addPassedLogs(getPathList("/a"))
.addFailedLogs(getPathList("/b", "/c"))
.build();
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testNumberOfFailedRuns() throws Exception {
String expectedString = ANY_STRING + "ERROR" + ANY_STRING + BlazeTestStatus.FAILED +
ANY_STRING + "in 2 out of 3";
AnsiTerminalPrinter terminalPrinter = Mockito.mock(AnsiTerminalPrinter.class);
TestSummary summary = basicBuilder
.setStatus(BlazeTestStatus.FAILED)
.addPassedLogs(getPathList("/a"))
.addFailedLogs(getPathList("/b", "/c"))
.build();
TestSummaryPrinter.print(summary, terminalPrinter, Path::getPathString, true, false);
terminalPrinter.print(find(expectedString));
}
@Test
public void testFileNamesNotShown() throws Exception {
List<TestCase> emptyDetails = ImmutableList.of();
TestSummary summary = basicBuilder
.setStatus(BlazeTestStatus.FAILED)
.addPassedLogs(getPathList("/apple"))
.addFailedLogs(getPathList("/pear"))
.addCoverageFiles(getPathList("/maracuja"))
.addFailedTestCases(emptyDetails, FailedTestCasesStatus.FULL)
.build();
// Check that only //package:name is printed.
AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
verify(printer).print(contains("//package:name"));
}
@Test
public void testMessageShownWhenTestCasesMissing() throws Exception {
ImmutableList<TestCase> emptyList = ImmutableList.of();
TestSummary summary = createTestSummaryWithDetails(
BlazeTestStatus.FAILED, emptyList, FailedTestCasesStatus.NOT_AVAILABLE);
AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
verify(printer).print(contains("//package:name"));
verify(printer).print(contains("not available"));
}
@Test
public void testMessageShownForPartialResults() throws Exception {
ImmutableList<TestCase> testCases =
ImmutableList.of(newDetail("orange", TestCase.Status.FAILED, 1500L));
TestSummary summary = createTestSummaryWithDetails(BlazeTestStatus.FAILED, testCases,
FailedTestCasesStatus.PARTIAL);
AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
verify(printer).print(contains("//package:name"));
verify(printer).print(find("FAILED.*orange"));
verify(printer).print(contains("incomplete"));
}
private TestCase newDetail(String name, TestCase.Status status, long duration) {
return TestCase.newBuilder()
.setName(name)
.setStatus(status)
.setRunDurationMillis(duration)
.build();
}
@Test
public void testTestCaseNamesShownWhenNeeded() throws Exception {
TestCase detailPassed =
newDetail("strawberry", TestCase.Status.PASSED, 1000L);
TestCase detailFailed =
newDetail("orange", TestCase.Status.FAILED, 1500L);
TestSummary summaryPassed = createTestSummaryWithDetails(
BlazeTestStatus.PASSED, Arrays.asList(detailPassed));
TestSummary summaryFailed = createTestSummaryWithDetails(
BlazeTestStatus.FAILED, Arrays.asList(detailPassed, detailFailed));
assertThat(summaryFailed.getStatus()).isEqualTo(BlazeTestStatus.FAILED);
AnsiTerminalPrinter printerPassed = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summaryPassed, printerPassed, Path::getPathString, true, true);
verify(printerPassed).print(contains("//package:name"));
AnsiTerminalPrinter printerFailed = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summaryFailed, printerFailed, Path::getPathString, true, true);
verify(printerFailed).print(contains("//package:name"));
verify(printerFailed).print(find("FAILED.*orange *\\(1\\.5"));
}
@Test
public void testTestCaseNamesOrdered() throws Exception {
TestCase[] details = {
newDetail("apple", TestCase.Status.FAILED, 1000L),
newDetail("banana", TestCase.Status.FAILED, 1000L),
newDetail("cranberry", TestCase.Status.FAILED, 1000L)
};
// The exceedingly dumb approach: writing all the permutations down manually
// is simply easier than any way of generating them.
int[][] permutations = {
{ 0, 1, 2 },
{ 0, 2, 1 },
{ 1, 0, 2 },
{ 1, 2, 0 },
{ 2, 0, 1 },
{ 2, 1, 0 }
};
for (int[] permutation : permutations) {
List<TestCase> permutatedDetails = new ArrayList<>();
for (int element : permutation) {
permutatedDetails.add(details[element]);
}
TestSummary summary = createTestSummaryWithDetails(BlazeTestStatus.FAILED, permutatedDetails);
// A mock that checks the ordering of method calls
AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
InOrder order = Mockito.inOrder(printer);
order.verify(printer).print(contains("//package:name"));
order.verify(printer).print(find("FAILED.*apple"));
order.verify(printer).print(find("FAILED.*banana"));
order.verify(printer).print(find("FAILED.*cranberry"));
}
}
@Test
public void testCachedResultsFirstInSort() throws Exception {
TestSummary summaryFailedCached = createTestSummary(BlazeTestStatus.FAILED, CACHED);
TestSummary summaryFailedNotCached = createTestSummary(BlazeTestStatus.FAILED, NOT_CACHED);
TestSummary summaryPassedCached = createTestSummary(BlazeTestStatus.PASSED, CACHED);
TestSummary summaryPassedNotCached = createTestSummary(BlazeTestStatus.PASSED, NOT_CACHED);
// This way we can make the test independent from the sort order of FAILEd
// and PASSED.
assertThat(summaryFailedCached.compareTo(summaryPassedNotCached)).isLessThan(0);
assertThat(summaryPassedCached.compareTo(summaryFailedNotCached)).isLessThan(0);
}
@Test
public void testCollectingFailedDetails() throws Exception {
TestCase rootCase = TestCase.newBuilder()
.setName("tests")
.setRunDurationMillis(5000L)
.addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
.addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
.addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
.build();
TestSummary summary =
getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.FAILED).build();
AnsiTerminalPrinter printer = Mockito.mock(AnsiTerminalPrinter.class);
TestSummaryPrinter.print(summary, printer, Path::getPathString, true, true);
verify(printer).print(contains("//package:name"));
verify(printer).print(find("FAILED.*apple"));
verify(printer).print(find("ERROR.*cherry"));
}
@Test
public void countTotalTestCases() throws Exception {
TestCase rootCase =
TestCase.newBuilder()
.setName("tests")
.setRunDurationMillis(5000L)
.addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
.addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
.addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
.build();
TestSummary summary =
getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.FAILED).build();
assertThat(summary.getTotalTestCases()).isEqualTo(3);
}
@Test
public void countUnknownTestCases() throws Exception {
TestSummary summary =
getTemplateBuilder().collectTestCases(null).setStatus(BlazeTestStatus.FAILED).build();
assertThat(summary.getTotalTestCases()).isEqualTo(1);
assertThat(summary.getUnkownTestCases()).isEqualTo(1);
}
@Test
public void countNotRunTestCases() throws Exception {
TestCase a =
TestCase.newBuilder()
.addChild(
TestCase.newBuilder().setName("A").setStatus(Status.PASSED).setRun(true).build())
.addChild(
TestCase.newBuilder().setName("B").setStatus(Status.PASSED).setRun(true).build())
.addChild(
TestCase.newBuilder().setName("C").setStatus(Status.PASSED).setRun(false).build())
.build();
TestSummary summary =
getTemplateBuilder().collectTestCases(a).setStatus(BlazeTestStatus.FAILED).build();
assertThat(summary.getTotalTestCases()).isEqualTo(2);
assertThat(summary.getUnkownTestCases()).isEqualTo(0);
assertThat(summary.getFailedTestCases()).isEmpty();
}
@Test
public void countTotalTestCasesInNestedTree() throws Exception {
TestCase aCase =
TestCase.newBuilder()
.setName("tests-1")
.setRunDurationMillis(5000L)
.addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
.addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
.addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
.build();
TestCase anotherCase =
TestCase.newBuilder()
.setName("tests-2")
.setRunDurationMillis(5000L)
.addChild(newDetail("apple", TestCase.Status.FAILED, 1000L))
.addChild(newDetail("banana", TestCase.Status.PASSED, 1000L))
.addChild(newDetail("cherry", TestCase.Status.ERROR, 1000L))
.build();
TestCase rootCase =
TestCase.newBuilder().setName("tests").addChild(aCase).addChild(anotherCase).build();
TestSummary summary =
getTemplateBuilder().collectTestCases(rootCase).setStatus(BlazeTestStatus.FAILED).build();
assertThat(summary.getTotalTestCases()).isEqualTo(6);
}
private ConfiguredTarget target(String path, String targetName) throws Exception {
ConfiguredTarget target = Mockito.mock(ConfiguredTarget.class);
when(target.getLabel()).thenReturn(Label.create(path, targetName));
when(target.getConfigurationChecksum()).thenReturn("abcdef");
return target;
}
private ConfiguredTarget stubTarget() throws Exception {
return target(PATH, TARGET_NAME);
}
private TestSummary createTestSummaryWithDetails(BlazeTestStatus status,
List<TestCase> details) {
TestSummary summary = getTemplateBuilder()
.setStatus(status)
.addFailedTestCases(details, FailedTestCasesStatus.FULL)
.build();
return summary;
}
private TestSummary createTestSummaryWithDetails(
BlazeTestStatus status, List<TestCase> testCaseList,
FailedTestCasesStatus detailsStatus) {
TestSummary summary = getTemplateBuilder()
.setStatus(status)
.addFailedTestCases(testCaseList, detailsStatus)
.build();
return summary;
}
private static TestSummary createTestSummary(ConfiguredTarget target, BlazeTestStatus status,
int numCached) {
ImmutableList<TestCase> emptyList = ImmutableList.of();
TestSummary summary = TestSummary.newBuilder()
.setTarget(target)
.setStatus(status)
.setNumCached(numCached)
.setActionRan(true)
.setRanRemotely(false)
.setWasUnreportedWrongSize(false)
.addFailedTestCases(emptyList, FailedTestCasesStatus.FULL)
.addTestTimes(SMALL_TIMING)
.build();
return summary;
}
private TestSummary createTestSummary(BlazeTestStatus status, int numCached) {
TestSummary summary = getTemplateBuilder()
.setStatus(status)
.setNumCached(numCached)
.addTestTimes(SMALL_TIMING)
.build();
return summary;
}
}
|
|
/*
Copyright (c) 2013, Colorado State University
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 holder 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 mendel.serialize;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
/**
* This class provides convenience functions to make the Serialization and
* Deserialization process easier.
*
* In brief, the static methods in this class will initialize proper streams for
* reading or creating objects, do the work, and then close the streams.
*
* @author malensek
*/
public class Serializer {
/**
* Dumps a ByteSerializable object to a portable byte array.
*
* @param obj The ByteSerializable object to serialize.
*
* @return binary byte array representation of the object.
*/
public static byte[] serialize(ByteSerializable obj)
throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
BufferedOutputStream buffOut = new BufferedOutputStream(byteOut);
SerializationOutputStream serialOut =
new SerializationOutputStream(buffOut);
serialOut.writeSerializable(obj);
serialOut.close();
return byteOut.toByteArray();
}
/**
* Loads a ByteSerializable object's binary form and then instantiates a new
* object using the SerializationInputStream constructor.
*
* @param type The type of object to create (deserialize).
* For example, Something.class.
*
* @param bytes Binary form of the object being loaded.
*/
public static <T extends ByteSerializable> T
deserialize(Class<T> type, byte[] bytes)
throws IOException, SerializationException {
ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
BufferedInputStream buffIn = new BufferedInputStream(byteIn);
SerializationInputStream serialIn =
new SerializationInputStream(buffIn);
T obj = deserialize(type, serialIn);
serialIn.close();
return obj;
}
/**
* Loads a ByteSerializable object's binary form from an input stream and
* then instantiates a new object using the SerializationInputStream
* constructor. This method is private to enforce users of the
* Serialization framework to instantiate deserializable objects using a
* SerializationInputStream constructor.
*
* @param type The type of object to create (deserialize).
* For example, Something.class.
*
* @param in SerializationInputStream containing a serialized instance of
* the object being loaded.
*/
private static <T extends ByteSerializable> T deserialize(Class<T> type,
SerializationInputStream in)
throws IOException, SerializationException {
/* ABANDON HOPE, ALL YE WHO ENTER HERE... */
T obj = null;
try {
Constructor<T> constructor =
type.getConstructor(SerializationInputStream.class);
obj = constructor.newInstance(in);
} catch (Exception e) {
/* We compress the myriad of possible exceptions that could occur
* here down to a single exception (SerializationException) to
* simplify implementations. However, if the current log level
* permits, we also embed more information in the exception detail
* message. */
throw new SerializationException("Could not instantiate object "
+ "for deserialization.", e);
}
return obj;
}
/**
* Deserializes and instantiates a ByteSerializable class from a stream.
* This method should only be used in cases where the type of the
* ByteSerializable class is not known at compile time.
*
* @param type The type of object to create (deserialize).
* For example, Something.class.
*
* @param in SerializationInputStream containing a serialized instance of
* the object being loaded.
*/
public static <T extends ByteSerializable> T deserializeFromStream(
Class<T> type, SerializationInputStream in)
throws IOException, SerializationException {
return deserialize(type, in);
}
/**
* Dumps a ByteSerializable object to a portable byte array and stores it on
* disk.
*
* @param obj The ByteSerializable object to serialize.
* @param file File to write the ByteSerializable object to.
*/
public static void persist(ByteSerializable obj, File file)
throws IOException {
FileOutputStream fOs = new FileOutputStream(file);
BufferedOutputStream bOs = new BufferedOutputStream(fOs);
SerializationOutputStream sOs = new SerializationOutputStream(bOs);
sOs.writeSerializable(obj);
sOs.close();
}
/**
* Dumps a ByteSerializable object to a portable byte array and stores it on
* disk.
*
* @param obj The ByteSerializable object to serialize.
* @param fileName path the object should be written to.
*/
public static void persist(ByteSerializable obj, String fileName)
throws IOException {
persist(obj, new File(fileName));
}
/**
* Loads a ByteSerializable object's binary form from disk and
* then instantiates a new object using the SerializationInputStream
* constructor.
*
* @param type The type of object to create (deserialize).
* For example, Something.class.
*
* @param inFile File containing a serialized instance of the object being
* loaded.
*/
public static <T extends ByteSerializable> T restore(Class<T> type,
File inFile)
throws IOException, SerializationException {
FileInputStream fIn = new FileInputStream(inFile);
BufferedInputStream bIn = new BufferedInputStream(fIn);
SerializationInputStream sIn = new SerializationInputStream(bIn);
T obj = deserializeFromStream(type, sIn);
sIn.close();
return obj;
}
/**
* Loads a ByteSerializable object's binary form from disk and
* then instantiates a new object using the SerializationInputStream
* constructor.
*
* @param type The type of object to create (deserialize).
* For example, Something.class.
*
* @param fileName path the object should be read from.
*/
public static <T extends ByteSerializable> T restore(Class<T> type,
String fileName)
throws IOException, SerializationException {
File inFile = new File(fileName);
return restore(type, inFile);
}
}
|
|
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.d.common;
import java.io.Serializable;
/**
* A 2D column vector
*/
public class Vector2 implements Serializable {
private static final long serialVersionUID = 1L;
public double x, y;
public Vector2() {
this(0, 0);
}
public Vector2(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2(Vector2 toCopy) {
this(toCopy.x, toCopy.y);
}
/** Zero out this vector. */
public final void setZero() {
x = 0.0f;
y = 0.0f;
}
/** Set the vector component-wise. */
public final Vector2 set(double x, double y) {
this.x = x;
this.y = y;
return this;
}
/** Set this vector to another vector. */
public final Vector2 set(Vector2 v) {
this.x = v.x;
this.y = v.y;
return this;
}
/** Return the sum of this vector and another; does not alter either one. */
public final Vector2 add(Vector2 v) {
return new Vector2(x + v.x, y + v.y);
}
/**
* Return the difference of this vector and another; does not alter either
* one.
*/
public final Vector2 sub(Vector2 v) {
return new Vector2(x - v.x, y - v.y);
}
/** Return this vector multiplied by a scalar; does not alter this vector. */
public final Vector2 mul(double a) {
return new Vector2(x * a, y * a);
}
/** Return the negation of this vector; does not alter this vector. */
public final Vector2 negate() {
return new Vector2(-x, -y);
}
/** Flip the vector and return it - alters this vector. */
public final Vector2 negateLocal() {
x = -x;
y = -y;
return this;
}
/** Add another vector to this one and returns result - alters this vector. */
public final Vector2 addLocal(Vector2 v) {
x += v.x;
y += v.y;
return this;
}
/** Adds values to this vector and returns result - alters this vector. */
public final Vector2 addLocal(double x, double y) {
this.x += x;
this.y += y;
return this;
}
/**
* Subtract another vector from this one and return result - alters this
* vector.
*/
public final Vector2 subLocal(Vector2 v) {
x -= v.x;
y -= v.y;
return this;
}
/** Multiply this vector by a number and return result - alters this vector. */
public final Vector2 mulLocal(double a) {
x *= a;
y *= a;
return this;
}
/** Get the skew vector such that dot(skew_vec, other) == cross(vec, other) */
public final Vector2 skew() {
return new Vector2(-y, x);
}
/** Get the skew vector such that dot(skew_vec, other) == cross(vec, other) */
public final void skew(Vector2 out) {
out.x = -y;
out.y = x;
}
/** Return the length of this vector. */
public final double length() {
return MathUtils.sqrt(x * x + y * y);
}
/** Return the squared length of this vector. */
public final double lengthSquared() {
return (x * x + y * y);
}
/**
* Normalize this vector and return the length before normalization. Alters
* this vector.
*/
public final double normalize() {
double length = length();
if (length < Settings.EPSILON) {
return 0f;
}
double invLength = 1.0f / length;
x *= invLength;
y *= invLength;
return length;
}
/**
* True if the vector represents a pair of valid, non-infinite doubleing
* point numbers.
*/
public final boolean isValid() {
return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y)
&& !Double.isInfinite(y);
}
/** Return a new vector that has positive components. */
public final Vector2 abs() {
return new Vector2(MathUtils.abs(x), MathUtils.abs(y));
}
public final void absLocal() {
x = MathUtils.abs(x);
y = MathUtils.abs(y);
}
// @Override // annotation omitted for GWT-compatibility
/** Return a copy of this vector. */
public final Vector2 clone() {
return new Vector2(x, y);
}
@Override
public final String toString() {
return "(" + x + "," + y + ")";
}
/*
* Static
*/
public final static Vector2 abs(Vector2 a) {
return new Vector2(MathUtils.abs(a.x), MathUtils.abs(a.y));
}
public final static void absToOut(Vector2 a, Vector2 out) {
out.x = MathUtils.abs(a.x);
out.y = MathUtils.abs(a.y);
}
public final static double dot(final Vector2 a, final Vector2 b) {
return a.x * b.x + a.y * b.y;
}
public final static double cross(final Vector2 a, final Vector2 b) {
return a.x * b.y - a.y * b.x;
}
public final static Vector2 cross(Vector2 a, double s) {
return new Vector2(s * a.y, -s * a.x);
}
public final static void crossToOut(Vector2 a, double s, Vector2 out) {
final double tempy = -s * a.x;
out.x = s * a.y;
out.y = tempy;
}
public final static void crossToOutUnsafe(Vector2 a, double s, Vector2 out) {
assert (out != a);
out.x = s * a.y;
out.y = -s * a.x;
}
public final static Vector2 cross(double s, Vector2 a) {
return new Vector2(-s * a.y, s * a.x);
}
public final static void crossToOut(double s, Vector2 a, Vector2 out) {
final double tempY = s * a.x;
out.x = -s * a.y;
out.y = tempY;
}
public final static void crossToOutUnsafe(double s, Vector2 a, Vector2 out) {
assert (out != a);
out.x = -s * a.y;
out.y = s * a.x;
}
public final static void negateToOut(Vector2 a, Vector2 out) {
out.x = -a.x;
out.y = -a.y;
}
public final static Vector2 min(Vector2 a, Vector2 b) {
return new Vector2(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y);
}
public final static Vector2 max(Vector2 a, Vector2 b) {
return new Vector2(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y);
}
public final static void minToOut(Vector2 a, Vector2 b, Vector2 out) {
out.x = a.x < b.x ? a.x : b.x;
out.y = a.y < b.y ? a.y : b.y;
}
public final static void maxToOut(Vector2 a, Vector2 b, Vector2 out) {
out.x = a.x > b.x ? a.x : b.x;
out.y = a.y > b.y ? a.y : b.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2 other = (Vector2) obj;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
return false;
return true;
}
}
|
|
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver14;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnTlvBroadcastRateVer14 implements OFBsnTlvBroadcastRate {
private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvBroadcastRateVer14.class);
// version: 1.4
final static byte WIRE_VERSION = 5;
final static int LENGTH = 8;
private final static long DEFAULT_VALUE = 0x0L;
// OF message fields
private final long value;
//
// Immutable default instance
final static OFBsnTlvBroadcastRateVer14 DEFAULT = new OFBsnTlvBroadcastRateVer14(
DEFAULT_VALUE
);
// package private constructor - used by readers, builders, and factory
OFBsnTlvBroadcastRateVer14(long value) {
this.value = U32.normalize(value);
}
// Accessors for OF message fields
@Override
public int getType() {
return 0x5a;
}
@Override
public long getValue() {
return value;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
public OFBsnTlvBroadcastRate.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnTlvBroadcastRate.Builder {
final OFBsnTlvBroadcastRateVer14 parentMessage;
// OF message fields
private boolean valueSet;
private long value;
BuilderWithParent(OFBsnTlvBroadcastRateVer14 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public int getType() {
return 0x5a;
}
@Override
public long getValue() {
return value;
}
@Override
public OFBsnTlvBroadcastRate.Builder setValue(long value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
@Override
public OFBsnTlvBroadcastRate build() {
long value = this.valueSet ? this.value : parentMessage.value;
//
return new OFBsnTlvBroadcastRateVer14(
value
);
}
}
static class Builder implements OFBsnTlvBroadcastRate.Builder {
// OF message fields
private boolean valueSet;
private long value;
@Override
public int getType() {
return 0x5a;
}
@Override
public long getValue() {
return value;
}
@Override
public OFBsnTlvBroadcastRate.Builder setValue(long value) {
this.value = value;
this.valueSet = true;
return this;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_14;
}
//
@Override
public OFBsnTlvBroadcastRate build() {
long value = this.valueSet ? this.value : DEFAULT_VALUE;
return new OFBsnTlvBroadcastRateVer14(
value
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnTlvBroadcastRate> {
@Override
public OFBsnTlvBroadcastRate readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0x5a
short type = bb.readShort();
if(type != (short) 0x5a)
throw new OFParseError("Wrong type: Expected=0x5a(0x5a), got="+type);
int length = U16.f(bb.readShort());
if(length != 8)
throw new OFParseError("Wrong length: Expected=8(8), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long value = U32.f(bb.readInt());
OFBsnTlvBroadcastRateVer14 bsnTlvBroadcastRateVer14 = new OFBsnTlvBroadcastRateVer14(
value
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnTlvBroadcastRateVer14);
return bsnTlvBroadcastRateVer14;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnTlvBroadcastRateVer14Funnel FUNNEL = new OFBsnTlvBroadcastRateVer14Funnel();
static class OFBsnTlvBroadcastRateVer14Funnel implements Funnel<OFBsnTlvBroadcastRateVer14> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnTlvBroadcastRateVer14 message, PrimitiveSink sink) {
// fixed value property type = 0x5a
sink.putShort((short) 0x5a);
// fixed value property length = 8
sink.putShort((short) 0x8);
sink.putLong(message.value);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnTlvBroadcastRateVer14> {
@Override
public void write(ByteBuf bb, OFBsnTlvBroadcastRateVer14 message) {
// fixed value property type = 0x5a
bb.writeShort((short) 0x5a);
// fixed value property length = 8
bb.writeShort((short) 0x8);
bb.writeInt(U32.t(message.value));
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnTlvBroadcastRateVer14(");
b.append("value=").append(value);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnTlvBroadcastRateVer14 other = (OFBsnTlvBroadcastRateVer14) obj;
if( value != other.value)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (value ^ (value >>> 32));
return result;
}
}
|
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.todo;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.TreeExpander;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.fileTypes.FileTypeEvent;
import com.intellij.openapi.fileTypes.FileTypeListener;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.OptionTag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
@State(
name = "TodoView",
storages = @Storage(StoragePathMacros.WORKSPACE_FILE)
)
public class TodoView implements PersistentStateComponent<TodoView.State>, Disposable {
private final Project myProject;
private ContentManager myContentManager;
private TodoPanel myAllTodos;
private final List<TodoPanel> myPanels = new ArrayList<>();
private final List<Content> myNotAddedContent = new ArrayList<>();
private State state = new State();
private Content myChangeListTodosContent;
private final MyVcsListener myVcsListener = new MyVcsListener();
public TodoView(@NotNull Project project) {
myProject = project;
state.all.arePackagesShown = true;
state.all.isAutoScrollToSource = true;
state.current.isAutoScrollToSource = true;
TodoConfiguration.getInstance().addPropertyChangeListener(new MyPropertyChangeListener(), this);
MessageBusConnection connection = project.getMessageBus().connect(this);
connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());
connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, myVcsListener);
}
static class State {
@Attribute(value = "selected-index")
public int selectedIndex;
@OptionTag(value = "selected-file", nameAttribute = "id", tag = "todo-panel", valueAttribute = "")
public TodoPanelSettings current = new TodoPanelSettings();
@OptionTag(value = "all", nameAttribute = "id", tag = "todo-panel", valueAttribute = "")
public TodoPanelSettings all = new TodoPanelSettings();
@OptionTag(value = "default-changelist", nameAttribute = "id", tag = "todo-panel", valueAttribute = "")
public TodoPanelSettings changeList = new TodoPanelSettings();
}
@Override
public void loadState(@NotNull State state) {
this.state = state;
}
@Override
public State getState() {
if (myContentManager != null) {
// all panel were constructed
Content content = myContentManager.getSelectedContent();
state.selectedIndex = myContentManager.getIndexOfContent(content);
}
return state;
}
@Override
public void dispose() {
}
public void initToolWindow(@NotNull ToolWindow toolWindow) {
// Create panels
ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
Content allTodosContent = contentFactory.createContent(null, IdeBundle.message("title.project"), false);
toolWindow.setHelpId("find.todoList");
myAllTodos = new TodoPanel(myProject, state.all, false, allTodosContent) {
@Override
protected TodoTreeBuilder createTreeBuilder(JTree tree, DefaultTreeModel treeModel, Project project) {
AllTodosTreeBuilder builder = createAllTodoBuilder(tree, treeModel, project);
builder.init();
return builder;
}
};
allTodosContent.setComponent(myAllTodos);
Disposer.register(this, myAllTodos);
if (toolWindow instanceof ToolWindowEx) {
DefaultActionGroup group = new DefaultActionGroup() {
{
getTemplatePresentation().setText("View Options");
setPopup(true);
add(myAllTodos.createAutoScrollToSourceAction());
addSeparator();
addAll(myAllTodos.createGroupByActionGroup());
}
};
((ToolWindowEx)toolWindow).setAdditionalGearActions(group);
}
Content currentFileTodosContent = contentFactory.createContent(null, IdeBundle.message("title.todo.current.file"), false);
CurrentFileTodosPanel currentFileTodos = new CurrentFileTodosPanel(myProject, state.current, currentFileTodosContent) {
@Override
protected TodoTreeBuilder createTreeBuilder(JTree tree, DefaultTreeModel treeModel, Project project) {
CurrentFileTodosTreeBuilder builder = new CurrentFileTodosTreeBuilder(tree, treeModel, project);
builder.init();
return builder;
}
};
Disposer.register(this, currentFileTodos);
currentFileTodosContent.setComponent(currentFileTodos);
String tabName = getTabNameForChangeList(ChangeListManager.getInstance(myProject).getDefaultChangeList().getName());
myChangeListTodosContent = contentFactory.createContent(null, tabName, false);
ChangeListTodosPanel changeListTodos = new ChangeListTodosPanel(myProject, state.current, myChangeListTodosContent) {
@Override
protected TodoTreeBuilder createTreeBuilder(JTree tree, DefaultTreeModel treeModel, Project project) {
ChangeListTodosTreeBuilder builder = new ChangeListTodosTreeBuilder(tree, treeModel, project);
builder.init();
return builder;
}
};
Disposer.register(this, changeListTodos);
myChangeListTodosContent.setComponent(changeListTodos);
Content scopeBasedTodoContent = contentFactory.createContent(null, "Scope Based", false);
ScopeBasedTodosPanel scopeBasedTodos = new ScopeBasedTodosPanel(myProject, state.current, scopeBasedTodoContent);
Disposer.register(this, scopeBasedTodos);
scopeBasedTodoContent.setComponent(scopeBasedTodos);
myContentManager = toolWindow.getContentManager();
myContentManager.addContent(allTodosContent);
myContentManager.addContent(currentFileTodosContent);
myContentManager.addContent(scopeBasedTodoContent);
if (ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss()) {
myVcsListener.myIsVisible = true;
myContentManager.addContent(myChangeListTodosContent);
}
for (Content content : myNotAddedContent) {
myContentManager.addContent(content);
}
myChangeListTodosContent.setCloseable(false);
allTodosContent.setCloseable(false);
currentFileTodosContent.setCloseable(false);
scopeBasedTodoContent.setCloseable(false);
Content content = myContentManager.getContent(state.selectedIndex);
myContentManager.setSelectedContent(content == null ? allTodosContent : content);
myPanels.add(myAllTodos);
myPanels.add(changeListTodos);
myPanels.add(currentFileTodos);
myPanels.add(scopeBasedTodos);
TreeExpander proxyExpander = new TreeExpander() {
@Override
public boolean canExpand() {
TreeExpander expander = getExpander();
return expander != null && expander.canExpand();
}
@Override
public void expandAll() {
TreeExpander expander = getExpander();
if (expander != null) {
expander.expandAll();
}
}
@Nullable
private TreeExpander getExpander() {
Content selectedContent = myContentManager.getSelectedContent();
if (selectedContent != null && selectedContent.getComponent() instanceof TodoPanel) {
return ((TodoPanel)selectedContent.getComponent()).getTreeExpander();
}
return null;
}
@Override
public void collapseAll() {
TreeExpander expander = getExpander();
if (expander != null) {
expander.collapseAll();
}
}
@Override
public boolean canCollapse() {
TreeExpander expander = getExpander();
return expander != null && expander.canCollapse();
}
};
//CommonActionsManager.getInstance().createExpandAllAction(proxyExpander, toolWindow.getComponent());
//CommonActionsManager.getInstance().createCollapseAllAction(proxyExpander, toolWindow.getComponent());
//((ToolWindowEx)toolWindow)
// .setTitleActions(CommonActionsManager.getInstance().createExpandAllAction(proxyExpander, toolWindow.getComponent()),
// CommonActionsManager.getInstance().createCollapseAllAction(proxyExpander, toolWindow.getComponent()));
}
@NotNull
static String getTabNameForChangeList(@NotNull String changelistName) {
String suffix = "Changelist";
return StringUtil.endsWithIgnoreCase(changelistName, suffix) ? changelistName : changelistName + " " + suffix;
}
@NotNull
protected AllTodosTreeBuilder createAllTodoBuilder(JTree tree, DefaultTreeModel treeModel, Project project) {
return new AllTodosTreeBuilder(tree, treeModel, project);
}
private final class MyVcsListener implements VcsListener {
private boolean myIsVisible;
@Override
public void directoryMappingChanged() {
ApplicationManager.getApplication().invokeLater(() -> {
if (myContentManager == null || myProject.isDisposed()) {
// was not initialized yet
return;
}
boolean hasActiveVcss = ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss();
if (myIsVisible && !hasActiveVcss) {
myContentManager.removeContent(myChangeListTodosContent, false);
myIsVisible = false;
}
else if (!myIsVisible && hasActiveVcss) {
myContentManager.addContent(myChangeListTodosContent);
myIsVisible = true;
}
}, ModalityState.NON_MODAL);
}
}
private final class MyPropertyChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent e) {
if (TodoConfiguration.PROP_TODO_PATTERNS.equals(e.getPropertyName()) || TodoConfiguration.PROP_TODO_FILTERS.equals(e.getPropertyName())) {
_updateFilters();
}
}
private void _updateFilters() {
try {
if (!DumbService.isDumb(myProject)) {
updateFilters();
return;
}
}
catch (ProcessCanceledException ignore) { }
DumbService.getInstance(myProject).smartInvokeLater(this::_updateFilters);
}
private void updateFilters() {
for (TodoPanel panel : myPanels) {
panel.updateTodoFilter();
}
}
}
private final class MyFileTypeListener implements FileTypeListener {
@Override
public void fileTypesChanged(@NotNull FileTypeEvent e) {
// this invokeLater guaranties that this code will be invoked after
// PSI gets the same event.
DumbService.getInstance(myProject).smartInvokeLater(() -> ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
if (myAllTodos == null) {
return;
}
ApplicationManager.getApplication().runReadAction(() -> {
for (TodoPanel panel : myPanels) {
panel.rebuildCache();
}
}
);
ApplicationManager.getApplication().invokeLater(() -> {
for (TodoPanel panel : myPanels) {
panel.updateTree();
}
}, ModalityState.NON_MODAL);
}, IdeBundle.message("progress.looking.for.todos"), false, myProject));
}
}
public void refresh() {
ApplicationManager.getApplication().runReadAction(() -> {
for (TodoPanel panel : myPanels) {
panel.rebuildCache();
}
}
);
ApplicationManager.getApplication().invokeLater(() -> {
for (TodoPanel panel : myPanels) {
panel.updateTree();
}
}, ModalityState.NON_MODAL);
}
public void addCustomTodoView(final TodoTreeBuilderFactory factory, final String title, final TodoPanelSettings settings) {
Content content = ContentFactory.SERVICE.getInstance().createContent(null, title, true);
final ChangeListTodosPanel panel = new ChangeListTodosPanel(myProject, settings, content) {
@Override
protected TodoTreeBuilder createTreeBuilder(JTree tree, DefaultTreeModel treeModel, Project project) {
TodoTreeBuilder todoTreeBuilder = factory.createTreeBuilder(tree, treeModel, project);
todoTreeBuilder.init();
return todoTreeBuilder;
}
};
content.setComponent(panel);
Disposer.register(this, panel);
if (myContentManager == null) {
myNotAddedContent.add(content);
}
else {
myContentManager.addContent(content);
}
myPanels.add(panel);
content.setCloseable(true);
content.setDisposer(new Disposable() {
@Override
public void dispose() {
myPanels.remove(panel);
}
});
}
}
|
|
/*
* 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/>.
*/
/*
* Copyright (C) 2004
* & Matthias Schubert ([email protected])
* & Zhanna Melnikova-Albrecht ([email protected])
* & Rainer Holzmann ([email protected])
*/
package weka.clusterers.forOPTICSAndDBScan.DataObjects;
import java.io.Serializable;
import weka.clusterers.forOPTICSAndDBScan.Databases.Database;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* <p>
* EuclideanDataObject.java <br/>
* Authors: Rainer Holzmann, Zhanna Melnikova-Albrecht, Matthias Schubert <br/>
* Date: Aug 19, 2004 <br/>
* Time: 5:50:22 PM <br/>
* $ Revision 1.4 $ <br/>
* </p>
*
* @author Matthias Schubert ([email protected])
* @author Zhanna Melnikova-Albrecht ([email protected])
* @author Rainer Holzmann ([email protected])
* @version $Revision: 8108 $
*/
public class EuclideanDataObject implements DataObject, Serializable,
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -4408119914898291075L;
/**
* Holds the original instance
*/
private final Instance instance;
/**
* Holds the (unique) key that is associated with this DataObject
*/
private String key;
/**
* Holds the ID of the cluster, to which this DataObject is assigned
*/
private int clusterID;
/**
* Holds the status for this DataObject (true, if it has been processed, else
* false)
*/
private boolean processed;
/**
* Holds the coreDistance for this DataObject
*/
private double c_dist;
/**
* Holds the reachabilityDistance for this DataObject
*/
private double r_dist;
/**
* Holds the database, that is the keeper of this DataObject
*/
private final Database database;
// *****************************************************************************************************************
// constructors
// *****************************************************************************************************************
/**
* Constructs a new DataObject. The original instance is kept as
* instance-variable
*
* @param originalInstance the original instance
*/
public EuclideanDataObject(Instance originalInstance, String key,
Database database) {
this.database = database;
this.key = key;
instance = originalInstance;
clusterID = DataObject.UNCLASSIFIED;
processed = false;
c_dist = DataObject.UNDEFINED;
r_dist = DataObject.UNDEFINED;
}
// *****************************************************************************************************************
// methods
// *****************************************************************************************************************
/**
* Compares two DataObjects in respect to their attribute-values
*
* @param dataObject The DataObject, that is compared with this.dataObject;
* now assumed to be of the same type and with the same structure
* @return Returns true, if the DataObjects correspond in each value, else
* returns false
*/
public boolean equals(DataObject dataObject) {
if (this == dataObject)
return true;
for (int i = 0; i < getInstance().numValues(); i++) {
double i_value_Instance_1 = getInstance().valueSparse(i);
double i_value_Instance_2 = dataObject.getInstance().valueSparse(i);
if (i_value_Instance_1 != i_value_Instance_2)
return false;
}
return true;
}
/**
* Calculates the euclidian-distance between dataObject and this.dataObject
*
* @param dataObject The DataObject, that is used for distance-calculation
* with this.dataObject; now assumed to be of the same type and with
* the same structure
* @return double-value The euclidian-distance between dataObject and
* this.dataObject
*/
public double distance(DataObject dataObject) {
double dist = 0.0;
for (int i = 0; i < getInstance().numValues(); i++) {
double cDistance = computeDistance(getInstance().index(i), getInstance()
.valueSparse(i), dataObject.getInstance().valueSparse(i));
dist += cDistance * cDistance;
}
return Math.sqrt(dist);
}
/**
* Performs euclidian-distance-calculation between two given values
*
* @param index of the attribute within the DataObject's instance
* @param v value_1
* @param v1 value_2
* @return double norm-distance between value_1 and value_2
*/
private double computeDistance(int index, double v, double v1) {
switch (getInstance().attribute(index).type()) {
case Attribute.NOMINAL:
return (Instance.isMissingValue(v) || Instance.isMissingValue(v1) || ((int) v != (int) v1)) ? 1
: 0;
case Attribute.NUMERIC:
if (Instance.isMissingValue(v) || Instance.isMissingValue(v1)) {
if (Instance.isMissingValue(v) && Instance.isMissingValue(v1))
return 1;
else {
return (Instance.isMissingValue(v)) ? norm(v1, index)
: norm(v, index);
}
} else
return norm(v, index) - norm(v1, index);
default:
return 0;
}
}
/**
* Normalizes a given value of a numeric attribute.
*
* @param x the value to be normalized
* @param i the attribute's index
*/
private double norm(double x, int i) {
if (Double.isNaN(database.getAttributeMinValues()[i])
|| Utils.eq(database.getAttributeMaxValues()[i],
database.getAttributeMinValues()[i])) {
return 0;
} else {
return (x - database.getAttributeMinValues()[i])
/ (database.getAttributeMaxValues()[i] - database
.getAttributeMinValues()[i]);
}
}
/**
* Returns the original instance
*
* @return originalInstance
*/
public Instance getInstance() {
return instance;
}
/**
* Returns the key for this DataObject
*
* @return key
*/
public String getKey() {
return key;
}
/**
* Sets the key for this DataObject
*
* @param key The key is represented as string
*/
public void setKey(String key) {
this.key = key;
}
/**
* Sets the clusterID (cluster), to which this DataObject belongs to
*
* @param clusterID Number of the Cluster
*/
public void setClusterLabel(int clusterID) {
this.clusterID = clusterID;
}
/**
* Returns the clusterID, to which this DataObject belongs to
*
* @return clusterID
*/
public int getClusterLabel() {
return clusterID;
}
/**
* Marks this dataObject as processed
*
* @param processed True, if the DataObject has been already processed, false
* else
*/
public void setProcessed(boolean processed) {
this.processed = processed;
}
/**
* Gives information about the status of a dataObject
*
* @return True, if this dataObject has been processed, else false
*/
public boolean isProcessed() {
return processed;
}
/**
* Sets a new coreDistance for this dataObject
*
* @param c_dist coreDistance
*/
public void setCoreDistance(double c_dist) {
this.c_dist = c_dist;
}
/**
* Returns the coreDistance for this dataObject
*
* @return coreDistance
*/
public double getCoreDistance() {
return c_dist;
}
/**
* Sets a new reachability-distance for this dataObject
*/
public void setReachabilityDistance(double r_dist) {
this.r_dist = r_dist;
}
/**
* Returns the reachabilityDistance for this dataObject
*/
public double getReachabilityDistance() {
return r_dist;
}
@Override
public String toString() {
return instance.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 8108 $");
}
}
|
|
/**
* Copyright 2011 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.math.BigInteger;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A BlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that the
* chain follows the rules of the {@link NetworkParameters} for this chain.<p>
*
* A BlockChain requires a {@link Wallet} to receive transactions that it finds during the initial download. However,
* if you don't care about this, you can just pass in an empty wallet and nothing bad will happen.<p>
*
* A newly constructed BlockChain is empty. To fill it up, use a {@link Peer} object to download the chain from the
* network.<p>
*
* <b>Notes</b><p>
*
* The 'chain' can actually be a tree although in normal operation it can be thought of as a simple list. In such a
* situation there are multiple stories of the economy competing to become the one true consensus. This can happen
* naturally when two miners solve a block within a few seconds of each other, or it can happen when the chain is
* under attack.<p>
*
* A reference to the head block of every chain is stored. If you can reach the genesis block by repeatedly walking
* through the prevBlock pointers, then we say this is a full chain. If you cannot reach the genesis block we say it is
* an orphan chain.<p>
*
* Orphan chains can occur when blocks are solved and received during the initial block chain download,
* or if we connect to a peer that doesn't send us blocks in order.
*/
public class BlockChain {
private static final Logger log = LoggerFactory.getLogger(BlockChain.class);
/** Keeps a map of block hashes to StoredBlocks. */
protected BlockStore blockStore;
/**
* Tracks the top of the best known chain.<p>
*
* Following this one down to the genesis block produces the story of the economy from the creation of BitCoin
* until the present day. The chain head can change if a new set of blocks is received that results in a chain of
* greater work than the one obtained by following this one down. In that case a reorganize is triggered,
* potentially invalidating transactions in our wallet.
*/
protected StoredBlock chainHead;
protected final NetworkParameters params;
protected final Wallet wallet;
// Holds blocks that we have received but can't plug into the chain yet, eg because they were created whilst we
// were downloading the block chain.
private final ArrayList<Block> unconnectedBlocks = new ArrayList<Block>();
/**
* Constructs a BlockChain connected to the given wallet and store. To obtain a {@link Wallet} you can construct
* one from scratch, or you can deserialize a saved wallet from disk using {@link Wallet#loadFromFile(java.io.File)}
* <p>
*
* For the store you can use a {@link MemoryBlockStore} if you don't care about saving the downloaded data, or a
* {@link BoundedOverheadBlockStore} if you'd like to ensure fast startup the next time you run the program.
*/
public BlockChain(NetworkParameters params, Wallet wallet, BlockStore blockStore) {
try {
this.blockStore = blockStore;
chainHead = blockStore.getChainHead();
log.info("chain head is:\n{}", chainHead.getHeader());
} catch (BlockStoreException e) {
throw new RuntimeException(e);
}
this.params = params;
this.wallet = wallet;
}
/**
* Processes a received block and tries to add it to the chain. If there's something wrong with the block an
* exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false.
* If the block can be connected to the chain, returns true.
*/
public synchronized boolean add(Block block) throws VerificationException, ScriptException {
try {
return add(block, true);
} catch (BlockStoreException e) {
// TODO: Figure out a better way to propagate this exception to the user.
throw new RuntimeException(e);
}
}
// Stat counters.
private long statsLastTime = System.currentTimeMillis();
private long statsBlocksAdded;
private synchronized boolean add(Block block, boolean tryConnecting)
throws BlockStoreException, VerificationException, ScriptException {
if (System.currentTimeMillis() - statsLastTime > 1000) {
// More than a second passed since last stats logging.
log.info("{} blocks per second", statsBlocksAdded);
statsLastTime = System.currentTimeMillis();
statsBlocksAdded = 0;
}
// We check only the chain head for double adds here to avoid potentially expensive block chain misses.
if (block.equals(chainHead.getHeader())) {
// Duplicate add of the block at the top of the chain, can be a natural artifact of the download process.
return true;
}
// Prove the block is internally valid: hash is lower than target, merkle root is correct and so on.
try {
block.verify();
} catch (VerificationException e) {
log.error("Failed to verify block:", e);
log.error(block.toString());
throw e;
}
// Try linking it to a place in the currently known blocks.
StoredBlock storedPrev = blockStore.get(block.getPrevBlockHash());
if (storedPrev == null) {
// We can't find the previous block. Probably we are still in the process of downloading the chain and a
// block was solved whilst we were doing it. We put it to one side and try to connect it later when we
// have more blocks.
log.warn("Block does not connect: {}", block.getHashAsString());
unconnectedBlocks.add(block);
return false;
} else {
// It connects to somewhere on the chain. Not necessarily the top of the best known chain.
//
// Create a new StoredBlock from this block. It will throw away the transaction data so when block goes
// out of scope we will reclaim the used memory.
StoredBlock newStoredBlock = storedPrev.build(block);
checkDifficultyTransitions(storedPrev, newStoredBlock);
blockStore.put(newStoredBlock);
// block.transactions may be null here if we received only a header and not a full block. This does not
// happen currently but might in future if getheaders is implemented.
connectBlock(newStoredBlock, storedPrev, block.transactions);
}
if (tryConnecting)
tryConnectingUnconnected();
statsBlocksAdded++;
return true;
}
private void connectBlock(StoredBlock newStoredBlock, StoredBlock storedPrev, List<Transaction> newTransactions)
throws BlockStoreException, VerificationException {
if (storedPrev.equals(chainHead)) {
// This block connects to the best known block, it is a normal continuation of the system.
setChainHead(newStoredBlock);
log.trace("Chain is now {} blocks high", chainHead.getHeight());
if (newTransactions != null)
sendTransactionsToWallet(newStoredBlock, NewBlockType.BEST_CHAIN, newTransactions);
} else {
// This block connects to somewhere other than the top of the best known chain. We treat these differently.
//
// Note that we send the transactions to the wallet FIRST, even if we're about to re-organize this block
// to become the new best chain head. This simplifies handling of the re-org in the Wallet class.
boolean haveNewBestChain = newStoredBlock.moreWorkThan(chainHead);
if (haveNewBestChain) {
log.info("Block is causing a re-organize");
} else {
StoredBlock splitPoint = findSplit(newStoredBlock, chainHead);
String splitPointHash =
splitPoint != null ? splitPoint.getHeader().getHashAsString() : "?";
log.info("Block forks the chain at {}, but it did not cause a reorganize:\n{}",
splitPointHash, newStoredBlock);
}
// We may not have any transactions if we received only a header. That never happens today but will in
// future when getheaders is used as an optimization.
if (newTransactions != null) {
sendTransactionsToWallet(newStoredBlock, NewBlockType.SIDE_CHAIN, newTransactions);
}
if (haveNewBestChain)
handleNewBestChain(newStoredBlock);
}
}
/**
* Called as part of connecting a block when the new block results in a different chain having higher total work.
*/
private void handleNewBestChain(StoredBlock newChainHead) throws BlockStoreException, VerificationException {
// This chain has overtaken the one we currently believe is best. Reorganize is required.
//
// Firstly, calculate the block at which the chain diverged. We only need to examine the
// chain from beyond this block to find differences.
StoredBlock splitPoint = findSplit(newChainHead, chainHead);
log.info("Re-organize after split at height {}", splitPoint.getHeight());
log.info("Old chain head: {}", chainHead.getHeader().getHashAsString());
log.info("New chain head: {}", newChainHead.getHeader().getHashAsString());
log.info("Split at block: {}", splitPoint.getHeader().getHashAsString());
// Then build a list of all blocks in the old part of the chain and the new part.
List<StoredBlock> oldBlocks = getPartialChain(chainHead, splitPoint);
List<StoredBlock> newBlocks = getPartialChain(newChainHead, splitPoint);
// Now inform the wallet. This is necessary so the set of currently active transactions (that we can spend)
// can be updated to take into account the re-organize. We might also have received new coins we didn't have
// before and our previous spends might have been undone.
wallet.reorganize(oldBlocks, newBlocks);
// Update the pointer to the best known block.
setChainHead(newChainHead);
}
/**
* Returns the set of contiguous blocks between 'higher' and 'lower'. Higher is included, lower is not.
*/
private List<StoredBlock> getPartialChain(StoredBlock higher, StoredBlock lower) throws BlockStoreException {
assert higher.getHeight() > lower.getHeight();
LinkedList<StoredBlock> results = new LinkedList<StoredBlock>();
StoredBlock cursor = higher;
while (true) {
results.add(cursor);
cursor = cursor.getPrev(blockStore);
assert cursor != null : "Ran off the end of the chain";
if (cursor.equals(lower)) break;
}
return results;
}
/**
* Locates the point in the chain at which newStoredBlock and chainHead diverge. Returns null if no split point was
* found (ie they are part of the same chain).
*/
private StoredBlock findSplit(StoredBlock newChainHead, StoredBlock chainHead) throws BlockStoreException {
StoredBlock currentChainCursor = chainHead;
StoredBlock newChainCursor = newChainHead;
// Loop until we find the block both chains have in common. Example:
//
// A -> B -> C -> D
// \--> E -> F -> G
//
// findSplit will return block B. chainHead = D and newChainHead = G.
while (!currentChainCursor.equals(newChainCursor)) {
if (currentChainCursor.getHeight() > newChainCursor.getHeight()) {
currentChainCursor = currentChainCursor.getPrev(blockStore);
assert currentChainCursor != null : "Attempt to follow an orphan chain";
} else {
newChainCursor = newChainCursor.getPrev(blockStore);
assert newChainCursor != null : "Attempt to follow an orphan chain";
}
}
return currentChainCursor;
}
enum NewBlockType {
BEST_CHAIN,
SIDE_CHAIN
}
private void sendTransactionsToWallet(StoredBlock block, NewBlockType blockType,
List<Transaction> newTransactions) throws VerificationException {
// Scan the transactions to find out if any mention addresses we own.
for (Transaction tx : newTransactions) {
try {
scanTransaction(block, tx, blockType);
} catch (ScriptException e) {
// We don't want scripts we don't understand to break the block chain,
// so just note that this tx was not scanned here and continue.
log.warn("Failed to parse a script: " + e.toString());
}
}
}
private void setChainHead(StoredBlock chainHead) {
this.chainHead = chainHead;
try {
blockStore.setChainHead(chainHead);
} catch (BlockStoreException e) {
throw new RuntimeException(e);
}
}
/**
* For each block in unconnectedBlocks, see if we can now fit it on top of the chain and if so, do so.
*/
private void tryConnectingUnconnected() throws VerificationException, ScriptException, BlockStoreException {
// For each block in our unconnected list, try and fit it onto the head of the chain. If we succeed remove it
// from the list and keep going. If we changed the head of the list at the end of the round try again until
// we can't fit anything else on the top.
int blocksConnectedThisRound;
do {
blocksConnectedThisRound = 0;
Iterator<Block> iter = unconnectedBlocks.iterator();
while (iter.hasNext()) {
Block block = iter.next();
// Look up the blocks previous.
StoredBlock prev = blockStore.get(block.getPrevBlockHash());
if (prev == null) {
// This is still an unconnected/orphan block.
continue;
}
// Otherwise we can connect it now.
// False here ensures we don't recurse infinitely downwards when connecting huge chains.
add(block, false);
iter.remove();
blocksConnectedThisRound++;
}
if (blocksConnectedThisRound > 0) {
log.info("Connected {} floating blocks.", blocksConnectedThisRound);
}
} while (blocksConnectedThisRound > 0);
}
/**
* Throws an exception if the blocks difficulty is not correct.
*/
private void checkDifficultyTransitions(StoredBlock storedPrev, StoredBlock storedNext)
throws BlockStoreException, VerificationException {
Block prev = storedPrev.getHeader();
Block next = storedNext.getHeader();
// Is this supposed to be a difficulty transition point?
if ((storedPrev.getHeight() + 1) % params.interval != 0) {
// No ... so check the difficulty didn't actually change.
if (next.getDifficultyTarget() != prev.getDifficultyTarget())
throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() +
": " + Long.toHexString(next.getDifficultyTarget()) + " vs " +
Long.toHexString(prev.getDifficultyTarget()));
return;
}
// We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
// two weeks after the initial block chain download.
long now = System.currentTimeMillis();
StoredBlock cursor = blockStore.get(prev.getHash());
for (int i = 0; i < params.interval - 1; i++) {
if (cursor == null) {
// This should never happen. If it does, it means we are following an incorrect or busted chain.
throw new VerificationException(
"Difficulty transition point but we did not find a way back to the genesis block.");
}
cursor = blockStore.get(cursor.getHeader().getPrevBlockHash());
}
log.info("Difficulty transition traversal took {}msec", System.currentTimeMillis() - now);
Block blockIntervalAgo = cursor.getHeader();
int timespan = (int) (prev.getTime() - blockIntervalAgo.getTime());
// Limit the adjustment step.
if (timespan < params.targetTimespan / 4)
timespan = params.targetTimespan / 4;
if (timespan > params.targetTimespan * 4)
timespan = params.targetTimespan * 4;
BigInteger newDifficulty = Utils.decodeCompactBits(blockIntervalAgo.getDifficultyTarget());
newDifficulty = newDifficulty.multiply(BigInteger.valueOf(timespan));
newDifficulty = newDifficulty.divide(BigInteger.valueOf(params.targetTimespan));
if (newDifficulty.compareTo(params.proofOfWorkLimit) > 0) {
log.warn("Difficulty hit proof of work limit: {}", newDifficulty.toString(16));
newDifficulty = params.proofOfWorkLimit;
}
int accuracyBytes = (int) (next.getDifficultyTarget() >>> 24) - 3;
BigInteger receivedDifficulty = next.getDifficultyTargetAsInteger();
// The calculated difficulty is to a higher precision than received, so reduce here.
BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
newDifficulty = newDifficulty.and(mask);
if (newDifficulty.compareTo(receivedDifficulty) != 0)
throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
receivedDifficulty.toString(16) + " vs " + newDifficulty.toString(16));
}
private void scanTransaction(StoredBlock block, Transaction tx, NewBlockType blockType) throws ScriptException, VerificationException {
// Coinbase transactions don't have anything useful in their inputs (as they create coins out of thin air).
if (tx.isMine(wallet) && !tx.isCoinBase()) {
System.out.println("======> RECEIVING"+tx.toString());
wallet.receive(tx, block, blockType);
}
}
/**
* Returns the block at the head of the current best chain. This is the block which represents the greatest
* amount of cumulative work done.
*/
public synchronized StoredBlock getChainHead() {
return chainHead;
}
/**
* Returns the most recent unconnected block or null if there are none. This will all have to change.
*/
public synchronized Block getUnconnectedBlock() {
if (unconnectedBlocks.size() == 0)
return null;
return unconnectedBlocks.get(unconnectedBlocks.size() - 1);
}
}
|
|
// Copyright 2015 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.net.urlconnection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.chromium.net.CronetTestRule.getContext;
import android.support.test.runner.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.Feature;
import org.chromium.net.CronetEngine;
import org.chromium.net.CronetTestRule;
import org.chromium.net.CronetTestRule.CompareDefaultWithCronet;
import org.chromium.net.CronetTestRule.OnlyRunCronetHttpURLConnection;
import org.chromium.net.NativeTestServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Tests the CronetBufferedOutputStream implementation.
*/
@RunWith(AndroidJUnit4.class)
public class CronetBufferedOutputStreamTest {
@Rule
public final CronetTestRule mTestRule = new CronetTestRule();
@Before
public void setUp() throws Exception {
mTestRule.setStreamHandlerFactory(new CronetEngine.Builder(getContext()).build());
assertTrue(NativeTestServer.startNativeTestServer(getContext()));
}
@After
public void tearDown() throws Exception {
NativeTestServer.shutdownNativeTestServer();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testGetOutputStreamAfterConnectionMade() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
assertEquals(200, connection.getResponseCode());
try {
connection.getOutputStream();
fail();
} catch (java.net.ProtocolException e) {
// Expected.
}
}
/**
* Tests write after connect. Strangely, the default implementation allows
* writing after being connected, so this test only runs against Cronet's
* implementation.
*/
@Test
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
public void testWriteAfterConnect() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
out.write(TestUtil.UPLOAD_DATA);
connection.connect();
try {
// Attemp to write some more.
out.write(TestUtil.UPLOAD_DATA);
fail();
} catch (IllegalStateException e) {
assertEquals("Use setFixedLengthStreamingMode() or "
+ "setChunkedStreamingMode() for writing after connect",
e.getMessage());
}
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteAfterReadingResponse() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
assertEquals(200, connection.getResponseCode());
try {
out.write(TestUtil.UPLOAD_DATA);
fail();
} catch (Exception e) {
// Default implementation gives an IOException and says that the
// stream is closed. Cronet gives an IllegalStateException and
// complains about write after connected.
}
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithContentLength() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
byte[] largeData = TestUtil.getLargeData();
connection.setRequestProperty("Content-Length",
Integer.toString(largeData.length));
OutputStream out = connection.getOutputStream();
int totalBytesWritten = 0;
// Number of bytes to write each time. It is doubled each time
// to make sure that the buffer grows.
int bytesToWrite = 683;
while (totalBytesWritten < largeData.length) {
if (bytesToWrite > largeData.length - totalBytesWritten) {
// Do not write out of bound.
bytesToWrite = largeData.length - totalBytesWritten;
}
out.write(largeData, totalBytesWritten, bytesToWrite);
totalBytesWritten += bytesToWrite;
bytesToWrite *= 2;
}
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithContentLengthOneMassiveWrite() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
byte[] largeData = TestUtil.getLargeData();
connection.setRequestProperty("Content-Length",
Integer.toString(largeData.length));
OutputStream out = connection.getOutputStream();
out.write(largeData);
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithContentLengthWriteOneByte() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
byte[] largeData = TestUtil.getLargeData();
connection.setRequestProperty("Content-Length",
Integer.toString(largeData.length));
OutputStream out = connection.getOutputStream();
for (int i = 0; i < largeData.length; i++) {
out.write(largeData[i]);
}
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithZeroContentLength() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "0");
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
assertEquals("", TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostZeroByteWithoutContentLength() throws Exception {
// Make sure both implementation sets the Content-Length header to 0.
URL url = new URL(NativeTestServer.getEchoHeaderURL("Content-Length"));
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
assertEquals("0", TestUtil.getResponseAsString(connection));
connection.disconnect();
// Make sure the server echoes back empty body for both implementation.
URL echoBody = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection2 =
(HttpURLConnection) echoBody.openConnection();
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
assertEquals(200, connection2.getResponseCode());
assertEquals("OK", connection2.getResponseMessage());
assertEquals("", TestUtil.getResponseAsString(connection2));
connection2.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithoutContentLengthSmall() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
out.write(TestUtil.UPLOAD_DATA);
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithoutContentLength() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
byte[] largeData = TestUtil.getLargeData();
OutputStream out = connection.getOutputStream();
int totalBytesWritten = 0;
// Number of bytes to write each time. It is doubled each time
// to make sure that the buffer grows.
int bytesToWrite = 683;
while (totalBytesWritten < largeData.length) {
if (bytesToWrite > largeData.length - totalBytesWritten) {
// Do not write out of bound.
bytesToWrite = largeData.length - totalBytesWritten;
}
out.write(largeData, totalBytesWritten, bytesToWrite);
totalBytesWritten += bytesToWrite;
bytesToWrite *= 2;
}
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithoutContentLengthOneMassiveWrite() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
byte[] largeData = TestUtil.getLargeData();
out.write(largeData);
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testPostWithoutContentLengthWriteOneByte() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
byte[] largeData = TestUtil.getLargeData();
for (int i = 0; i < largeData.length; i++) {
out.write(largeData[i]);
}
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsString(connection));
connection.disconnect();
}
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteLessThanContentLength() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// Set a content length that's 1 byte more.
connection.setRequestProperty(
"Content-Length", Integer.toString(TestUtil.UPLOAD_DATA.length + 1));
OutputStream out = connection.getOutputStream();
out.write(TestUtil.UPLOAD_DATA);
try {
connection.getResponseCode();
fail();
} catch (IOException e) {
// Expected.
}
connection.disconnect();
}
/**
* Tests that if caller writes more than the content length provided,
* an exception should occur.
*/
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteMoreThanContentLength() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// Use a content length that is 1 byte shorter than actual data.
connection.setRequestProperty(
"Content-Length", Integer.toString(TestUtil.UPLOAD_DATA.length - 1));
OutputStream out = connection.getOutputStream();
// Write a few bytes first.
out.write(TestUtil.UPLOAD_DATA, 0, 3);
try {
// Write remaining bytes.
out.write(TestUtil.UPLOAD_DATA, 3, TestUtil.UPLOAD_DATA.length - 3);
// On Lollipop, default implementation only triggers the error when reading response.
connection.getInputStream();
fail();
} catch (IOException e) {
assertEquals("exceeded content-length limit of " + (TestUtil.UPLOAD_DATA.length - 1)
+ " bytes",
e.getMessage());
}
connection.disconnect();
}
/**
* Same as {@code testWriteMoreThanContentLength()}, but it only writes one byte
* at a time.
*/
@Test
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteMoreThanContentLengthWriteOneByte() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// Use a content length that is 1 byte shorter than actual data.
connection.setRequestProperty(
"Content-Length", Integer.toString(TestUtil.UPLOAD_DATA.length - 1));
OutputStream out = connection.getOutputStream();
try {
for (int i = 0; i < TestUtil.UPLOAD_DATA.length; i++) {
out.write(TestUtil.UPLOAD_DATA[i]);
}
// On Lollipop, default implementation only triggers the error when reading response.
connection.getInputStream();
fail();
} catch (IOException e) {
assertEquals("exceeded content-length limit of " + (TestUtil.UPLOAD_DATA.length - 1)
+ " bytes",
e.getMessage());
}
connection.disconnect();
}
/**
* Tests that {@link CronetBufferedOutputStream} supports rewind in a
* POST preserving redirect.
* Use {@code OnlyRunCronetHttpURLConnection} as the default implementation
* does not pass this test.
*/
@Test
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
public void testRewind() throws Exception {
URL url = new URL(NativeTestServer.getRedirectToEchoBody());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty(
"Content-Length", Integer.toString(TestUtil.UPLOAD_DATA.length));
OutputStream out = connection.getOutputStream();
out.write(TestUtil.UPLOAD_DATA);
assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
connection.disconnect();
}
/**
* Like {@link #testRewind} but does not set Content-Length header.
*/
@Test
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
public void testRewindWithoutContentLength() throws Exception {
URL url = new URL(NativeTestServer.getRedirectToEchoBody());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
out.write(TestUtil.UPLOAD_DATA);
assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
connection.disconnect();
}
}
|
|
package com.projectchanged.client.userInterface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class DiffWindow extends JFrame {
private static final Color DELETE_BG = new Color(0xFF, 0x45, 0x33); // Asumming different from TextPane.background
private static final Color INSERT_BG = new Color(0xFF, 0xA5, 0x33); // Asumming different from TextPane.background
private JLabel lbFile1, lbFile2;
private StyleContext context1, context2;
private StyledDocument styledDoc1, styledDoc2;
private JTextPane tpFile1, tpFile2;
private diff_match_patch diff_util;
public DiffWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(false);
context1 = new StyleContext();
context2 = new StyleContext();
final JPanel pnDummy1 = new JPanel(), pnDummy2 = new JPanel(); // To disable line wrap of JTextPane
pnDummy1.setLayout(new BorderLayout());
pnDummy2.setLayout(new BorderLayout());
pnDummy1.add(tpFile1 = new JTextPane(styledDoc1 = new DefaultStyledDocument(context1)), BorderLayout.CENTER);
pnDummy2.add(tpFile2 = new JTextPane(styledDoc2 = new DefaultStyledDocument(context2)), BorderLayout.CENTER);
final JScrollPane spText1 = new JScrollPane(pnDummy1), spText2 = new JScrollPane(pnDummy2);
final JScrollBar sbText1Ver = spText1.getVerticalScrollBar(), sbText1Hor = spText1.getHorizontalScrollBar(), sbText2Ver = spText2.getVerticalScrollBar(), sbText2Hor = spText2.getHorizontalScrollBar();
sbText1Ver.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
sbText2Ver.setValue(e.getValue());
}
});
sbText2Ver.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
sbText1Ver.setValue(e.getValue());
}
});
sbText1Hor.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
sbText2Hor.setValue(e.getValue());
}
});
sbText2Hor.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
sbText1Hor.setValue(e.getValue());
}
});
final JPanel pnDummy3 = new JPanel(), pnDummy4 = new JPanel();
pnDummy3.setLayout(new BorderLayout());
pnDummy4.setLayout(new BorderLayout());
pnDummy3.add(lbFile1 = new JLabel(), BorderLayout.PAGE_START);
pnDummy3.add(spText1, BorderLayout.CENTER);
pnDummy4.add(lbFile2 = new JLabel(), BorderLayout.PAGE_START);
pnDummy4.add(spText2, BorderLayout.CENTER);
JSplitPane spMain = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pnDummy3, pnDummy4);
spMain.setResizeWeight(0.5);
tpFile1.setEditable(false);
tpFile2.setEditable(false);
setContentPane(spMain);
diff_util = new diff_match_patch();
}
private String readTextFromFile(File file) throws Exception {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(file));
int ord;
while ((ord = reader.read()) >= 0) {
builder.append((char) ord);
}
}
catch (Exception e) {
throw e;
}
finally {
try {
reader.close();
}
catch (Exception e) {
}
}
return builder.toString();
}
public static int countMatches(String str, String sub) {
int count = 0, idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
public void showDiff(File file1, File file2) {
lbFile1.setText(file1.getName());
lbFile2.setText(file2.getName());
LinkedList<diff_match_patch.Diff> diffs = null;
try {
diffs = diff_util.diff_main(readTextFromFile(file1), readTextFromFile(file2));
}
catch (Exception e) {
e.printStackTrace();
return;
}
diff_util.diff_cleanupSemantic(diffs);
int idx1 = 0, idx2 = 0, len, cnt;
boolean endedInNewLine = true, skipNewLineTest = false;
LinkedList<Integer> positions1 = new LinkedList<Integer>(), positions2 = new LinkedList<Integer>();
LinkedList<Integer> signsText1 = new LinkedList<Integer>(), signsText2 = new LinkedList<Integer>();
StringBuilder text1 = new StringBuilder(), text2 = new StringBuilder();
for (diff_match_patch.Diff diff : diffs) {
String text = diff.text;
len = text.length();
if (!endedInNewLine) {
endedInNewLine = (text.charAt(0) == '\n');
}
switch (diff.operation) {
case INSERT:
if ((cnt = DiffWindow.countMatches(text, "\n")) > 0) {
skipNewLineTest = true;
}
idx1 += cnt;
for (int i = cnt; --i >= 0;) {
text1.append("\n");
}
if (!endedInNewLine) {
--cnt;
}
for (int i = 0; i < len; ++i) {
if (endedInNewLine && (cnt-- > 0)) {
signsText2.addFirst(idx2 + i);
}
char ch = text.charAt(i);
text2.append(ch);
endedInNewLine = (ch == '\n');
}
positions2.add(idx2);
positions2.add(len);
idx2 += len;
break;
case DELETE:
if ((cnt = DiffWindow.countMatches(text, "\n")) > 0) {
skipNewLineTest = true;
}
idx2 += cnt;
for (int i = cnt; --i >= 0;) {
text2.append("\n");
}
if (!endedInNewLine) {
--cnt;
}
for (int i = 0; i < len; ++i) {
if (endedInNewLine && (cnt-- > 0)) {
signsText1.addFirst(idx1 + i);
}
char ch = text.charAt(i);
text1.append(ch);
endedInNewLine = (ch == '\n');
}
positions1.add(idx1);
positions1.add(len);
idx1 += len;
break;
case EQUAL:
text1.append(text);
text2.append(text);
idx1 += len;
idx2 += len;
break;
}
if (skipNewLineTest) {
endedInNewLine = true;
skipNewLineTest = false;
}
else {
endedInNewLine = (text.charAt(len - 1) == '\n');
}
}
String content1 = text1.toString(), content2 = text2.toString();
tpFile1.setText(content1);
tpFile2.setText(content2);
MutableAttributeSet attrs1 = new SimpleAttributeSet(), attrs2 = new SimpleAttributeSet();
StyleConstants.setBackground(attrs1, DiffWindow.DELETE_BG);
StyleConstants.setBackground(attrs2, DiffWindow.INSERT_BG);
Iterator<Integer> iter1 = positions1.iterator(), iter2 = positions2.iterator();
while (iter1.hasNext()) {
styledDoc1.setCharacterAttributes(iter1.next(), iter1.next(), attrs1, false);
}
while (iter2.hasNext()) {
styledDoc2.setCharacterAttributes(iter2.next(), iter2.next(), attrs2, false);
}
try {
iter1 = signsText1.iterator();
iter2 = signsText2.iterator();
content1 = styledDoc1.getText(0, styledDoc1.getLength());
content2 = styledDoc2.getText(0, styledDoc2.getLength());
Style signStyle = context1.getStyle(StyleContext.DEFAULT_STYLE);
int nextSignAt = iter1.hasNext() ? iter1.next() : -1;
int i = content1.length();
while ((nextSignAt > -1) && (i - nextSignAt == 1)) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/minus.png")));
styledDoc1.insertString(i--, " ", signStyle);
nextSignAt = iter1.hasNext() ? iter1.next() : -1;
}
for (; i > 0; --i) {
char ch = content1.charAt(i - 1);
if (ch != '\n') {
continue;
}
if (i == nextSignAt) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/minus.png")));
nextSignAt = iter1.hasNext() ? iter1.next() : -1;
}
else {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/white.png")));
}
styledDoc1.insertString(i, " ", signStyle);
}
if (nextSignAt == 0) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/minus.png")));
}
else {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/white.png")));
}
styledDoc1.insertString(0, " ", signStyle);
signStyle = context2.getStyle(StyleContext.DEFAULT_STYLE);
nextSignAt = iter2.hasNext() ? iter2.next() : -1;
i = content2.length();
while ((nextSignAt > -1) && (i - nextSignAt == 1)) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/plus.png")));
styledDoc2.insertString(i--, " ", signStyle);
nextSignAt = iter2.hasNext() ? iter2.next() : -1;
}
for (; i > 0; --i) {
char ch = content2.charAt(i - 1);
if (ch != '\n') {
continue;
}
if (i == nextSignAt) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/plus.png")));
nextSignAt = iter2.hasNext() ? iter2.next() : -1;
}
else {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/white.png")));
}
styledDoc2.insertString(i, " ", signStyle);
}
if (nextSignAt == 0) {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/plus.png")));
}
else {
StyleConstants.setComponent(signStyle, new JLabel(new ImageIcon("src/com/projectchanged/client/userInterface/resource/white.png")));
}
styledDoc2.insertString(0, " ", signStyle);
}
catch (Exception e) {
e.printStackTrace();
}
setSize(500, 300);
setVisible(true);
}
}
|
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.interestrate.payments.derivative;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
/**
* Class describing an average Ibor-like floating coupon.
*/
public class CouponIborAverage extends CouponFloating {
/**
* The first Ibor-like index on which the coupon fixes. The index currency should be the same as the index currency.
*/
private final IborIndex _index1;
/**
* The second Ibor-like index on which the coupon fixes. The index currency should be the same as the index currency.
*/
private final IborIndex _index2;
/**
* The weight for the first index.
*/
private final double _weight1;
/**
* The weight of the second index.
*/
private final double _weight2;
/**
* The fixing period start time (in years) of the first index.
*/
private final double _fixingPeriodStartTime1;
/**
* The fixing period end time (in years) of the first index.
*/
private final double _fixingPeriodEndTime1;
/**
* The fixing period year fraction (or accrual factor) of the first index in the fixing convention.
*/
private final double _fixingAccrualFactor1;
/**
* The fixing period start time (in years) of the second index.
*/
private final double _fixingPeriodStartTime2;
/**
* The fixing period end time (in years) of the second index.
*/
private final double _fixingPeriodEndTime2;
/**
* The fixing period year fraction (or accrual factor) of the second index in the fixing convention.
*/
private final double _fixingAccrualFactor2;
/**
* Constructor from all details.
* @param currency The payment currency.
* @param paymentTime Time (in years) up to the payment.
* @param paymentYearFraction The year fraction (or accrual factor) for the coupon payment.
* @param notional Coupon notional.
* @param fixingTime Time (in years) up to fixing.
* @param index1 The first Ibor-like index on which the coupon fixes.
* @param fixingPeriodStartTime1 The fixing period start time (in years) of the first index.
* @param fixingPeriodEndTime1 The fixing period end time (in years) of the first index.
* @param fixingYearFraction1 The year fraction (or accrual factor) for the fixing period of the first index.
* @param index2 The second Ibor-like index on which the coupon fixes.
* @param fixingPeriodStartTime2 The fixing period start time (in years) of the second index.
* @param fixingPeriodEndTime2 The fixing period end time (in years) of the second index.
* @param fixingYearFraction2 The year fraction (or accrual factor) for the fixing period of the second index.
* @param weight1 The weight of the first index.
* @param weight2 The weight of the second index.
*/
public CouponIborAverage(final Currency currency, final double paymentTime, final double paymentYearFraction, final double notional, final double fixingTime,
final IborIndex index1, final double fixingPeriodStartTime1, final double fixingPeriodEndTime1, final double fixingYearFraction1,
final IborIndex index2, final double fixingPeriodStartTime2, final double fixingPeriodEndTime2, final double fixingYearFraction2,
final double weight1, final double weight2) {
super(currency, paymentTime, paymentYearFraction, notional, fixingTime);
ArgumentChecker.isTrue(fixingPeriodStartTime1 >= fixingTime, "fixing period start < fixing time");
_fixingPeriodStartTime1 = fixingPeriodStartTime1;
ArgumentChecker.isTrue(fixingPeriodEndTime1 >= fixingPeriodStartTime1, "fixing period end < fixing period start");
_fixingPeriodEndTime1 = fixingPeriodEndTime1;
ArgumentChecker.isTrue(fixingYearFraction1 >= 0, "forward year fraction < 0");
_fixingAccrualFactor1 = fixingYearFraction1;
ArgumentChecker.notNull(index1, "Index");
ArgumentChecker.isTrue(currency.equals(index1.getCurrency()), "Index currency incompatible with coupon currency");
_index1 = index1;
_weight1 = weight1;
ArgumentChecker.isTrue(fixingPeriodStartTime2 >= fixingTime, "fixing period start < fixing time");
_fixingPeriodStartTime2 = fixingPeriodStartTime2;
ArgumentChecker.isTrue(fixingPeriodEndTime2 >= fixingPeriodStartTime2, "fixing period end < fixing period start");
_fixingPeriodEndTime2 = fixingPeriodEndTime2;
ArgumentChecker.isTrue(fixingYearFraction2 >= 0, "forward year fraction < 0");
_fixingAccrualFactor2 = fixingYearFraction2;
ArgumentChecker.notNull(index2, "Index");
ArgumentChecker.isTrue(currency.equals(index2.getCurrency()), "Index currency incompatible with coupon currency");
_index2 = index2;
_weight2 = weight2;
}
/**
* Gets the first Ibor index of the instrument.
* @return The first index.
*/
public IborIndex getIndex1() {
return _index1;
}
/**
* Gets the second Ibor index of the instrument.
* @return The second index.
*/
public IborIndex getIndex2() {
return _index2;
}
/**
* Gets the weight of the first index.
* @return The first weight.
*/
public double getWeight1() {
return _weight1;
}
/**
* Gets the weight of the second index.
* @return The second weight.
*/
public double getWeight2() {
return _weight2;
}
/**
* Gets the fixing period start time (in years) of the first index.
* @return The fixing period start time of the first index.
*/
public double getFixingPeriodStartTime1() {
return _fixingPeriodStartTime1;
}
/**
* Gets the fixing period end time (in years) of the first index.
* @return The fixing period end time of the first index.
*/
public double getFixingPeriodEndTime1() {
return _fixingPeriodEndTime1;
}
/**
* Gets the accrual factor for the fixing period of the first index.
* @return The accrual factor of the first index.
*/
public double getFixingAccrualFactor1() {
return _fixingAccrualFactor1;
}
/**
* Gets the fixing period start time (in years) of the second index.
* @return The fixing period start time of the second index.
*/
public double getFixingPeriodStartTime2() {
return _fixingPeriodStartTime2;
}
/**
* Gets the fixing period end time (in years )of the second index.
* @return The fixing period end time of the second index.
*/
public double getFixingPeriodEndTime2() {
return _fixingPeriodEndTime2;
}
/**
* Gets the accrual factor for the fixing period of the second index.
* @return The accrual factor of the second index.
*/
public double getFixingAccrualFactor2() {
return _fixingAccrualFactor2;
}
@Override
public CouponIborAverage withNotional(final double notional) {
return new CouponIborAverage(getCurrency(), getPaymentTime(), getPaymentYearFraction(), notional, getFixingTime(), _index1, getFixingPeriodStartTime1(),
getFixingPeriodEndTime1(),
getFixingAccrualFactor1(), _index2, getFixingPeriodStartTime2(),
getFixingPeriodEndTime2(),
getFixingAccrualFactor2(), getWeight1(), getWeight2());
}
@Override
public String toString() {
return "CouponIborAverage [_fixingPeriodStartTime1=" + _fixingPeriodStartTime1 + ", _fixingPeriodEndTime1=" + _fixingPeriodEndTime1 + ", _fixingAccrualFactor1=" + _fixingAccrualFactor1 +
", _fixingPeriodStartTime2=" + _fixingPeriodStartTime2 + ", _fixingPeriodEndTime2=" + _fixingPeriodEndTime2 + ", _fixingAccrualFactor2=" + _fixingAccrualFactor2 + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
long temp;
temp = Double.doubleToLongBits(_fixingAccrualFactor1);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_fixingAccrualFactor2);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_fixingPeriodEndTime1);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_fixingPeriodEndTime2);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_fixingPeriodStartTime1);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_fixingPeriodStartTime2);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((_index1 == null) ? 0 : _index1.hashCode());
result = prime * result + ((_index2 == null) ? 0 : _index2.hashCode());
temp = Double.doubleToLongBits(_weight1);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_weight2);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CouponIborAverage other = (CouponIborAverage) obj;
if (Double.doubleToLongBits(_fixingAccrualFactor1) != Double.doubleToLongBits(other._fixingAccrualFactor1)) {
return false;
}
if (Double.doubleToLongBits(_fixingAccrualFactor2) != Double.doubleToLongBits(other._fixingAccrualFactor2)) {
return false;
}
if (Double.doubleToLongBits(_fixingPeriodEndTime1) != Double.doubleToLongBits(other._fixingPeriodEndTime1)) {
return false;
}
if (Double.doubleToLongBits(_fixingPeriodEndTime2) != Double.doubleToLongBits(other._fixingPeriodEndTime2)) {
return false;
}
if (Double.doubleToLongBits(_fixingPeriodStartTime1) != Double.doubleToLongBits(other._fixingPeriodStartTime1)) {
return false;
}
if (Double.doubleToLongBits(_fixingPeriodStartTime2) != Double.doubleToLongBits(other._fixingPeriodStartTime2)) {
return false;
}
if (_index1 == null) {
if (other._index1 != null) {
return false;
}
} else if (!_index1.equals(other._index1)) {
return false;
}
if (_index2 == null) {
if (other._index2 != null) {
return false;
}
} else if (!_index2.equals(other._index2)) {
return false;
}
if (Double.doubleToLongBits(_weight1) != Double.doubleToLongBits(other._weight1)) {
return false;
}
if (Double.doubleToLongBits(_weight2) != Double.doubleToLongBits(other._weight2)) {
return false;
}
return true;
}
@Override
public <S, T> T accept(final InstrumentDerivativeVisitor<S, T> visitor, final S data) {
return visitor.visitCouponIborAverage(this, data);
}
@Override
public <T> T accept(final InstrumentDerivativeVisitor<?, T> visitor) {
return visitor.visitCouponIborAverage(this);
}
}
|
|
package com.selventa.belframework.api.examples;
import static com.selventa.belframework.common.BELUtilities.hasLength;
import static java.lang.String.format;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;
import com.selventa.belframework.api.examples.XGMMLObjects.Edge;
import com.selventa.belframework.api.examples.XGMMLObjects.Node;
import com.selventa.belframework.common.enums.FunctionEnum;
import com.selventa.belframework.common.enums.RelationshipType;
import com.selventa.belframework.kamstore.data.jdbc.KAMStoreDaoImpl.BelTerm;
/**
* XGMMLUtility provides utility methods for writing graph, node, and edge
* sections of an XGMML xml document.
*
* @author Anthony Bargnesi <[email protected]>
*/
public class XGMMLUtility {
/**
* Format: {@code %s %s %d %d}. In order, graphics type, fill color, x-pos,
* and y-pos.
*/
private static String NODE_GRAPHICS;
/**
* Format: {@code %d %s %d %s}. In order, line width, fill color, target
* arrow indicator, and edge label.
*/
private static String EDGE_GRAPHICS;
/**
* Format: {@code %s %s %s}.
*/
private static String EDGE_LABEL;
private static String DFLT_NODE_SHAPE;
private static String DFLT_EDGE_COLOR;
private static String DFLT_NODE_COLOR;
static {
NODE_GRAPHICS = " <graphics type='%s' fill='%s' ";
NODE_GRAPHICS += "x='%d' y='%d' h='20.0' w='80.0' ";
NODE_GRAPHICS += "cy:nodeLabel='%s'/>\n";
EDGE_GRAPHICS = " <graphics width='%d' fill='%s' ";
EDGE_GRAPHICS += "cy:targetArrow='%d' cy:edgeLabel='%s'/>\n";
EDGE_LABEL = "%s (%s) %s";
DFLT_NODE_SHAPE = "rectangle";
DFLT_EDGE_COLOR = "0,0,0";
DFLT_NODE_COLOR = "150,150,150";
}
/**
* Returns a shape for the supplied {@link FunctionEnum}.
*
* @param fe {@link FunctionEnum}
* @return Non-null {@link String}
* @see #DFLT_NODE_SHAPE
*/
public static String type(FunctionEnum fe) {
if (fe == null) {
return DFLT_NODE_SHAPE;
}
switch (fe) {
case ABUNDANCE:
return "ver_ellipsis";
case BIOLOGICAL_PROCESS:
return "rhombus";
case CATALYTIC_ACTIVITY:
return "hexagon";
case CELL_SECRETION:
return "arc";
case CELL_SURFACE_EXPRESSION:
return "arc";
case CHAPERONE_ACTIVITY:
return "hexagon";
case COMPLEX_ABUNDANCE:
return "hor_ellipsis";
case COMPOSITE_ABUNDANCE:
return "hor_ellipsis";
case DEGRADATION:
return "hor_ellipsis";
case GENE_ABUNDANCE:
return "hor_ellipsis";
case GTP_BOUND_ACTIVITY:
return "hexagon";
case KINASE_ACTIVITY:
return "hexagon";
case MICRORNA_ABUNDANCE:
return "hor_ellipsis";
case MOLECULAR_ACTIVITY:
return "hexagon";
case PATHOLOGY:
return "rhombus";
case PEPTIDASE_ACTIVITY:
return "hexagon";
case PHOSPHATASE_ACTIVITY:
return "hexagon";
case PRODUCTS:
case PROTEIN_ABUNDANCE:
return "hor_ellipsis";
case REACTANTS:
case RIBOSYLATION_ACTIVITY:
return "hexagon";
case RNA_ABUNDANCE:
return "hor_ellipsis";
case TRANSCRIPTIONAL_ACTIVITY:
return "hexagon";
case TRANSPORT_ACTIVITY:
return "hexagon";
}
return DFLT_NODE_SHAPE;
}
/**
* Returns an RGB tuple of the form {@code "x,x,x"} for the supplied
* {@link FunctionEnum}. Defaults to gray; RGB {@code "150,150,150"}.
*
* @param fe {@link FunctionEnum}
* @return Non-null {@link String}
*/
public static String color(FunctionEnum fe) {
if (fe == null) {
return DFLT_NODE_COLOR;
}
switch (fe) {
case ABUNDANCE:
return "40,255,85";
case BIOLOGICAL_PROCESS:
return "255,51,102";
case CATALYTIC_ACTIVITY:
return "100,100,255";
case CELL_SECRETION:
return "204,204,255";
case CELL_SURFACE_EXPRESSION:
return "204,204,255";
case CHAPERONE_ACTIVITY:
return "100,100,255";
case COMPLEX_ABUNDANCE:
return "102,153,255";
case COMPOSITE_ABUNDANCE:
return "222,255,255";
case DEGRADATION:
return "255,51,102";
case GENE_ABUNDANCE:
return "204,255,204";
case GTP_BOUND_ACTIVITY:
return "100,100,255";
case KINASE_ACTIVITY:
return "100,100,255";
case MICRORNA_ABUNDANCE:
return "0,255,150";
case MOLECULAR_ACTIVITY:
return "100,100,255";
case PATHOLOGY:
return "255,51,102";
case PEPTIDASE_ACTIVITY:
return "100,100,255";
case PHOSPHATASE_ACTIVITY:
return "100,100,255";
case PROTEIN_ABUNDANCE:
return "85,255,255";
case REACTION:
return "255,51,102";
case RIBOSYLATION_ACTIVITY:
return "100,100,255";
case RNA_ABUNDANCE:
return "40,255,85";
case TRANSCRIPTIONAL_ACTIVITY:
return "100,100,255";
case TRANSPORT_ACTIVITY:
return "100,100,255";
}
return DFLT_NODE_COLOR;
}
/**
* Returns an RGB tuple of the form {@code "x,x,x"} for the supplied
* {@link RelationshipType}. Defaults to black; RGB {@code "0,0,0"}.
*
* @param fe {@link RelationshipType}
* @return Non-null {@link String}
*/
public static String color(RelationshipType rel) {
if (rel == null) {
return DFLT_EDGE_COLOR;
}
switch (rel) {
case ACTS_IN:
return "153,153,153";
case HAS_COMPONENT:
return "153,153,153";
case HAS_MEMBER:
return "153,153,153";
case HAS_MODIFICATION:
return "153,153,153";
case HAS_PRODUCT:
return "153,153,153";
case HAS_VARIANT:
return "153,153,153";
case INCLUDES:
return "153,153,153";
case IS_A:
return "153,153,153";
case REACTANT_IN:
return "153,153,153";
case SUB_PROCESS_OF:
return "153,153,153";
case TRANSCRIBED_TO:
return "153,153,153";
case TRANSLATED_TO:
return "153,153,153";
case TRANSLOCATES:
return "153,153,153";
}
return DFLT_EDGE_COLOR;
}
/**
* Write the XGMML start using the {@code graphName} as the label.
*
* @param name {@link String}, the name of the XGMML graph
* @param writer {@link PrintWriter}, the writer
*/
public static void writeStart(String name, PrintWriter writer) {
StringBuilder sb = new StringBuilder();
sb.append("<graph xmlns='http://www.cs.rpi.edu/XGMML' ")
.append("xmlns:ns2='http://www.w3.org/1999/xlink' ")
.append("xmlns:cy='http://www.cytoscape.org' ")
.append("Graphic='1' label='").append(name)
.append("' directed='1'>\n");
writer.write(sb.toString());
}
/**
* Write an XGMML {@code <node>} from {@code node} properties.
*
* @param node {@link Node}, the node to write
* @param writer {@link PrintWriter}, the writer
*/
public static void writeNode(Node node, List<BelTerm> supportingTerms,
PrintWriter writer) {
int x = new Random().nextInt(200);
int y = new Random().nextInt(200);
StringBuilder sb = new StringBuilder();
sb.append(" <node label='");
sb.append(node.label);
sb.append("' id='");
sb.append(node.id.toString());
sb.append("'>\n");
sb.append(" <att name='function type'");
sb.append(" value='");
sb.append(node.function.getDisplayValue());
sb.append("' />\n");
sb.append(" <att name='parameters'");
sb.append(" value='");
String params = "";
for (BelTerm t : supportingTerms) {
if (hasLength(params)) {
params = params.concat(" ");
}
String label = t.getLabel();
label = label.replaceAll("&", "&");
label = label.replaceAll("'", """);
params = params.concat(label);
}
sb.append(params);
sb.append("' />\n");
// Graphics type and fill color
String graphics = format(NODE_GRAPHICS, type(node.function),
color(node.function), x, y, params);
sb.append(graphics);
sb.append(" </node>\n");
writer.write(sb.toString());
}
/**
* Write an XGMML <edge> from {@code edge} properties.
*
* @param edge {@link Edge}, the edge to write
* @param writer {@link PrintWriter}, the writer
*/
public static void writeEdge(Node src, Node tgt, Edge edge, PrintWriter writer) {
StringBuilder sb = new StringBuilder();
RelationshipType rel = edge.rel;
String reldispval = rel.getDisplayValue();
sb.append(" <edge label='");
String dispval = format(EDGE_LABEL, src.label, rel, tgt.label);
sb.append(dispval);
sb.append("' source='");
sb.append(edge.source.toString());
sb.append("' target='");
sb.append(edge.target.toString());
sb.append("'>\n");
sb.append(" <att name='relationship type'");
sb.append(" value='");
sb.append(reldispval);
sb.append("' />\n");
// Edge graphics
String color = color(rel);
String graphics = format(EDGE_GRAPHICS, 1, color, 1, reldispval);
sb.append(graphics);
sb.append(" </edge>\n");
writer.write(sb.toString());
}
/**
* Write the XGMML end.
*
* @param writer {@link PrintWriter}, the writer
*/
public static void writeEnd(PrintWriter writer) {
writer.write("</graph>");
}
}
|
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.inspections.PyNewStyleStringFormatParser;
import com.jetbrains.python.inspections.PyNewStyleStringFormatParser.Field;
import com.jetbrains.python.inspections.PyNewStyleStringFormatParser.ParseResult;
import junit.framework.TestCase;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.intellij.testFramework.UsefulTestCase.*;
import static com.jetbrains.python.inspections.PyStringFormatParser.*;
/**
* @author yole
*/
public class PyStringFormatParserTest extends TestCase {
public void testSimple() {
List<FormatStringChunk> chunks = parsePercentFormat("abc");
assertEquals(1, chunks.size());
assertConstant(chunks.get(0), 0, 3);
}
private static void assertConstant(FormatStringChunk aChunk, final int start, final int end) {
ConstantChunk chunk = (ConstantChunk)aChunk;
assertEquals(start, chunk.getStartIndex());
assertEquals(end, chunk.getEndIndex());
}
public void testDoublePercent() {
List<FormatStringChunk> chunks = parsePercentFormat("abc%%def");
assertEquals(1, chunks.size());
assertConstant(chunks.get(0), 0, 8);
}
public void testFormat() {
List<FormatStringChunk> chunks = parsePercentFormat("%s");
assertEquals(1, chunks.size());
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals(0, chunk.getStartIndex());
assertEquals(2, chunk.getEndIndex());
assertEquals('s', chunk.getConversionType());
}
public void testSubstitutionAfterFormat() {
List<FormatStringChunk> chunks = parsePercentFormat("Hello, %s");
assertEquals(2, chunks.size());
assertConstant(chunks.get(0), 0, 7);
}
public void testMappingKey() {
List<FormatStringChunk> chunks = parsePercentFormat("%(language)s");
assertEquals(1, chunks.size());
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals("language", chunk.getMappingKey());
assertEquals('s', chunk.getConversionType());
}
public void testConversionFlags() {
List<FormatStringChunk> chunks = parsePercentFormat("%#0d");
assertEquals(1, chunks.size());
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals("#0", chunk.getConversionFlags());
}
public void testWidth() {
List<FormatStringChunk> chunks = parsePercentFormat("%345d");
assertEquals(1, chunks.size());
SubstitutionChunk chunk = (SubstitutionChunk)chunks.get(0);
assertEquals("345", chunk.getWidth());
}
public void testPrecision() {
List<FormatStringChunk> chunks = parsePercentFormat("%.2d");
assertEquals(1, chunks.size());
SubstitutionChunk chunk = (SubstitutionChunk)chunks.get(0);
assertEquals("2", chunk.getPrecision());
}
public void testLengthModifier() {
List<FormatStringChunk> chunks = parsePercentFormat("%ld");
assertEquals(1, chunks.size());
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals('l', chunk.getLengthModifier());
}
public void testDoubleAsterisk() {
List<FormatStringChunk> chunks = parsePercentFormat("%**d");
assertEquals(2, chunks.size());
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals(2, chunk.getEndIndex());
assertEquals('\0', chunk.getConversionType());
}
public void testUnclosedMapping() {
List<FormatStringChunk> chunks = parsePercentFormat("%(name1s");
PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals("name1s", chunk.getMappingKey());
assertTrue(chunk.isUnclosedMapping());
}
// PY-8372
public void testNewStyleAutomaticNumbering() {
final List<SubstitutionChunk> chunks = filterSubstitutions(parseNewStyleFormat("{}, {}"));
assertEquals(2, chunks.size());
assertEquals(TextRange.create(0, 2), chunks.get(0).getTextRange());
assertEquals(TextRange.create(4, 6), chunks.get(1).getTextRange());
}
// PY-8372
public void testNewStylePositionalArgs() {
final List<SubstitutionChunk> chunks = filterSubstitutions(parseNewStyleFormat("{1}, {0}"));
assertEquals(2, chunks.size());
assertEquals(TextRange.create(0, 3), chunks.get(0).getTextRange());
assertEquals(TextRange.create(5, 8), chunks.get(1).getTextRange());
}
// PY-8372
public void testNewStyleKeywordArgs() {
final List<SubstitutionChunk> chunks = filterSubstitutions(parseNewStyleFormat("a{foo}{bar}bc"));
assertEquals(2, chunks.size());
assertEquals(TextRange.create(1, 6), chunks.get(0).getTextRange());
assertEquals(TextRange.create(6, 11), chunks.get(1).getTextRange());
}
// PY-8372
public void testBracesEscaping() {
final List<SubstitutionChunk> chunks = filterSubstitutions(parseNewStyleFormat("\\{\\}, {{}}"));
assertEquals(1, chunks.size());
assertEquals(TextRange.create(1, 4), chunks.get(0).getTextRange());
}
public void testAutoPosition() {
final List<SubstitutionChunk> oldStyleChunks = filterSubstitutions(parsePercentFormat("%s %(foo)s %(bar)s %*.*d"));
assertOrderedEquals(ContainerUtil.map(oldStyleChunks, SubstitutionChunk::getAutoPosition), 0, null, null, 1);
final List<SubstitutionChunk> newStyleChunks = filterSubstitutions(parseNewStyleFormat("'{foo} {} {bar} {0} {}'"));
assertOrderedEquals(ContainerUtil.map(newStyleChunks, SubstitutionChunk::getAutoPosition), null, 0, null, null, 1);
}
public void testNewStyleConstant() {
List<FormatStringChunk> chunks = parseNewStyleFormat("a");
assertEquals(1, chunks.size());
assertConstant(chunks.get(0), 0, 1);
}
public void testNewStyleUnbalanced() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{{{foo}}");
assertEquals(2, chunks.size());
}
public void testNewStyleEscapingAndValue() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{{{foo}}}");
assertEquals(3, chunks.size());
assertEquals(TextRange.create(0, 2), chunks.get(0).getTextRange());
assertEquals(TextRange.create(2, 7), chunks.get(1).getTextRange());
assertEquals(TextRange.create(7, 9), chunks.get(2).getTextRange());
}
public void testNewStyleSign() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:+}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertTrue(((NewStyleSubstitutionChunk)chunks.get(0)).hasSignOption());
}
public void testNewStyleAlternateForm() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:#}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertTrue(((NewStyleSubstitutionChunk)chunks.get(0)).useAlternateForm());
}
public void testNewStyleZeroPadded() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:0}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertTrue(((NewStyleSubstitutionChunk)chunks.get(0)).hasZeroPadding());
}
public void testNewStyleWidth() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:10}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 5), chunks.get(0).getTextRange());
assertEquals("10", ((NewStyleSubstitutionChunk)chunks.get(0)).getWidth());
}
public void testNewStyleZeroPaddingWidth() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:010}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 6), chunks.get(0).getTextRange());
assertTrue(((NewStyleSubstitutionChunk)chunks.get(0)).hasZeroPadding());
assertEquals("10", ((NewStyleSubstitutionChunk)chunks.get(0)).getWidth());
}
public void testNewStyleThousandSeparator() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:,}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertTrue(((NewStyleSubstitutionChunk)chunks.get(0)).hasThousandsSeparator());
}
public void testNewStylePrecision() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:.2}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 5), chunks.get(0).getTextRange());
assertEquals("2", ((NewStyleSubstitutionChunk)chunks.get(0)).getPrecision());
}
public void testNewStyleConversionType() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{:d}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertEquals('d', ((NewStyleSubstitutionChunk)chunks.get(0)).getConversionType());
}
public void testNewStyleConversion() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{!s}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 4), chunks.get(0).getTextRange());
assertEquals("s", ((NewStyleSubstitutionChunk)chunks.get(0)).getConversion());
}
public void testNewStyleUnicodeEscaping() {
List<SubstitutionChunk> chunks = filterSubstitutions(parseNewStyleFormat("u\"\\N{LATIN SMALL LETTER B}{:s}\\N{NUMBER SIGN}\\\n" +
" {:s}\\N{LATIN SMALL LETTER B}\""));
assertEquals(2, chunks.size());
assertEquals('s', chunks.get(0).getConversionType());
assertEquals('s', chunks.get(1).getConversionType());
}
public void testNewStyleNestedFields() {
final Field field = doParseAndGetFirstField("u'{foo:{bar} {baz}}'");
assertEquals("foo", field.getFirstName());
final List<Field> nestedFields = field.getNestedFields();
assertSize(2, nestedFields);
assertEquals("bar", nestedFields.get(0).getFirstName());
assertEquals("baz", nestedFields.get(1).getFirstName());
}
public void testNewStyleTooNestedFields() {
final ParseResult result = PyNewStyleStringFormatParser.parse("'{:{:{:{}}}} {}'");
final List<Field> topLevelFields = result.getFields();
assertSize(2, topLevelFields);
assertSize(5, result.getAllFields());
assertOrderedEquals(result.getAllFields().stream().map(Field::getDepth).toArray(), 1, 2, 3, 4, 1);
assertOrderedEquals(result.getAllFields().stream().map(SubstitutionChunk::getAutoPosition).toArray(), 0, 1, 2, 3, 4);
}
public void testNewStyleAttrAndLookups() {
Field field;
field = doParseAndGetFirstField("u'{foo'");
assertEquals("foo", field.getFirstName());
assertEmpty(field.getAttributesAndLookups());
field = doParseAndGetFirstField("u'{foo}'");
assertEquals("foo", field.getFirstName());
assertEmpty(field.getAttributesAndLookups());
field = doParseAndGetFirstField("u'{foo.bar.baz}'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), ".bar", ".baz");
field = doParseAndGetFirstField("u'{foo[bar][baz]}'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), "[bar]", "[baz]");
field = doParseAndGetFirstField("u'{foo.bar[baz]}'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), ".bar", "[baz]");
field = doParseAndGetFirstField("u'{foo.bar[baz}'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), ".bar");
field = doParseAndGetFirstField("u'{foo[{bar[baz]}'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), "[{bar[baz]");
field = doParseAndGetFirstField("u'{foo[{} {0} {bar.baz}]'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), "[{} {0} {bar.baz}]");
field = doParseAndGetFirstField("u'{foo[bar]baz'");
assertEquals("foo", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), "[bar]");
field = doParseAndGetFirstField("'{0[foo][.!:][}]}'");
assertEquals("0", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", "[.!:]", "[}]");
field = doParseAndGetFirstField("'{.foo.bar}'");
assertEmpty(field.getFirstName());
assertEquals(TextRange.create(2, 2), field.getFirstNameRange());
assertOrderedEquals(field.getAttributesAndLookups(), ".foo", ".bar");
field = doParseAndGetFirstField("'{}'");
assertEmpty(field.getFirstName());
assertEquals(TextRange.create(2, 2), field.getFirstNameRange());
field = doParseAndGetFirstField("'{:foo}'");
assertEmpty(field.getFirstName());
assertEquals(TextRange.create(2, 2), field.getFirstNameRange());
field = doParseAndGetFirstField("'{!r:foo}'");
assertEmpty(field.getFirstName());
assertEquals(TextRange.create(2, 2), field.getFirstNameRange());
}
public void testNewStyleIncompleteAttrAndLookups() {
Field field;
field = doParseAndGetFirstField("'{foo}'");
assertEquals("foo", field.getFirstName());
assertEmpty(field.getAttributesAndLookups());
// recover the first name
field = doParseAndGetFirstField("'{foo'");
assertEquals("foo", field.getFirstName());
assertEmpty(field.getAttributesAndLookups());
field = doParseAndGetFirstField("'{foo");
assertEquals("foo", field.getFirstName());
assertEmpty(field.getAttributesAndLookups());
field = doParseAndGetFirstField("'{0[foo].bar[baz]}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
// do not recover unfinished lookups
field = doParseAndGetFirstField("'{0[foo].bar[ba}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar[ba!}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar[ba:}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar[ba'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar[ba");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
// do not recover illegal attributes
field = doParseAndGetFirstField("'{0[foo].bar[baz]quux}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]quux!}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]quux:}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]quux'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0[foo].bar[baz]quux");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar", "[baz]");
field = doParseAndGetFirstField("'{0..}'");
assertEquals("0", field.getFirstName());
assertOrderedEquals(field.getAttributesAndLookups(), ".", ".");
// recover attributes
field = doParseAndGetFirstField("'{0[foo].}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".");
field = doParseAndGetFirstField("'{0[foo].'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".");
field = doParseAndGetFirstField("'{0[foo].");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".");
field = doParseAndGetFirstField("'{0[foo].bar}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar'");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
field = doParseAndGetFirstField("'{0[foo].bar");
assertOrderedEquals(field.getAttributesAndLookups(), "[foo]", ".bar");
}
public void testNewStyleAutoPosition() {
final ParseResult result = PyNewStyleStringFormatParser.parse("'{foo} {} {bar} {0} {}'");
final List<Field> topLevelFields = result.getFields();
assertSize(5, topLevelFields);
assertEquals("foo", topLevelFields.get(0).getMappingKey());
assertNull(topLevelFields.get(0).getManualPosition());
assertNull(topLevelFields.get(0).getAutoPosition());
assertNull(topLevelFields.get(1).getMappingKey());
assertNull(topLevelFields.get(1).getManualPosition());
assertEquals(0, (int)topLevelFields.get(1).getAutoPosition());
assertEquals("bar", topLevelFields.get(2).getMappingKey());
assertNull(topLevelFields.get(2).getManualPosition());
assertNull(topLevelFields.get(2).getAutoPosition());
assertNull(topLevelFields.get(3).getMappingKey());
assertEquals(0, (int)topLevelFields.get(3).getManualPosition());
assertNull(topLevelFields.get(3).getAutoPosition());
assertNull(topLevelFields.get(4).getMappingKey());
assertNull(topLevelFields.get(4).getManualPosition());
assertEquals(1, (int)topLevelFields.get(4).getAutoPosition());
}
public void testNewStyleNamedUnicodeEscapes() {
final List<Field> fields = doParseAndGetTopLevelFields("u\"\\N{LATIN SMALL LETTER B}{:s}\\N{NUMBER SIGN}\\\n" +
" {:s}\\N{LATIN SMALL LETTER B}\"");
assertSize(2, fields);
assertEquals(":s", fields.get(0).getFormatSpec());
assertEquals(":s", fields.get(1).getFormatSpec());
}
public void testNewStyleNamedUnicodeEscapeInLookup() {
final Field field = doParseAndGetFirstField("'{foo[\\N{ESCAPE WITH ]}]}'");
assertOrderedEquals(field.getAttributesAndLookups(), "[\\N{ESCAPE WITH ]}]");
}
public void testNewStyleNamedUnicodeEscapeInAttribute() {
final Field field = doParseAndGetFirstField("'{foo.b\\N{ESCAPE WITH [}.b\\N{ESCAPE WITH .}}'");
assertOrderedEquals(field.getAttributesAndLookups(), ".b\\N{ESCAPE WITH [}", ".b\\N{ESCAPE WITH .}");
}
public void testNewStyleUnclosedLookupEndsWithRightBrace() {
final Field field = doParseAndGetFirstField("u'{0[}'");
assertEquals(-1, field.getRightBraceOffset());
assertEquals(6, field.getFieldEnd());
assertEmpty(field.getAttributesAndLookups());
}
@NotNull
private static List<Field> doParseAndGetTopLevelFields(@NotNull String nodeText) {
final ParseResult result = PyNewStyleStringFormatParser.parse(nodeText);
return result.getFields();
}
@NotNull
private static Field doParseAndGetFirstField(@NotNull String nodeText) {
final ParseResult result = PyNewStyleStringFormatParser.parse(nodeText);
final List<Field> topLevelFields = result.getFields();
assertSize(1, topLevelFields);
return topLevelFields.get(0);
}
public void testNewStyleMappingKeyFormatSpec() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{a:d}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 5), chunks.get(0).getTextRange());
assertEquals("a", ((NewStyleSubstitutionChunk)chunks.get(0)).getMappingKey());
assertEquals('d', ((NewStyleSubstitutionChunk)chunks.get(0)).getConversionType());
}
public void testNewStyleMappingKeyConversionFormatSpec() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{a!s:.2d}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 9), chunks.get(0).getTextRange());
assertEquals("a", ((NewStyleSubstitutionChunk)chunks.get(0)).getMappingKey());
assertEquals("s", ((NewStyleSubstitutionChunk)chunks.get(0)).getConversion());
assertEquals("2", ((NewStyleSubstitutionChunk)chunks.get(0)).getPrecision());
assertEquals('d', ((NewStyleSubstitutionChunk)chunks.get(0)).getConversionType());
}
public void testSkipAlign() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{a:*^d}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 7), chunks.get(0).getTextRange());
assertEquals("a", ((NewStyleSubstitutionChunk)chunks.get(0)).getMappingKey());
assertEquals('d', ((NewStyleSubstitutionChunk)chunks.get(0)).getConversionType());
}
public void testNewStyleAllPossibleSpecs() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{a!s:#010,.2d}");
assertEquals(1, chunks.size());
assertEquals(TextRange.create(0, 14), chunks.get(0).getTextRange());
assertEquals("a", ((NewStyleSubstitutionChunk)chunks.get(0)).getMappingKey());
assertEquals("s", ((NewStyleSubstitutionChunk)chunks.get(0)).getConversion());
assertEquals("2", ((NewStyleSubstitutionChunk)chunks.get(0)).getPrecision());
assertEquals('d', ((NewStyleSubstitutionChunk)chunks.get(0)).getConversionType());
}
public void testNewStyleFiledNameWithAttribute() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{foo.a}");
assertEquals(1, chunks.size());
final NewStyleSubstitutionChunk chunk = (NewStyleSubstitutionChunk)chunks.get(0);
assertEquals(TextRange.create(0, 7), chunk.getTextRange());
assertEquals("foo", chunk.getMappingKey());
assertNotNull(chunk.getMappingKeyAttributeName());
assertEquals("a", chunk.getMappingKeyAttributeName());
}
public void testNewStyleFiledNameWithElementIndex() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{foo[a]}");
assertEquals(1, chunks.size());
final NewStyleSubstitutionChunk chunk = (NewStyleSubstitutionChunk)chunks.get(0);
assertEquals(TextRange.create(0, 8), chunk.getTextRange());
assertEquals("foo", chunk.getMappingKey());
assertNotNull(chunk.getMappingKeyElementIndex());
assertEquals("a", chunk.getMappingKeyElementIndex());
}
public void testNewStyleFiledNameWithAttributeWithFormatSpec() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{foo.a:d}");
assertEquals(1, chunks.size());
final NewStyleSubstitutionChunk chunk = (NewStyleSubstitutionChunk)chunks.get(0);
assertEquals(TextRange.create(0, 9), chunk.getTextRange());
assertEquals("foo", chunk.getMappingKey());
assertNotNull(chunk.getMappingKeyAttributeName());
assertEquals("a", chunk.getMappingKeyAttributeName());
assertEquals('d', chunk.getConversionType());
}
public void testNewStyleFiledNameWithElementIndexWithFormatSpec() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{foo[a]:d}");
assertEquals(1, chunks.size());
final NewStyleSubstitutionChunk chunk = (NewStyleSubstitutionChunk)chunks.get(0);
assertEquals(TextRange.create(0, 10), chunk.getTextRange());
assertEquals("foo", chunk.getMappingKey());
assertNotNull(chunk.getMappingKeyElementIndex());
assertEquals("a", chunk.getMappingKeyElementIndex());
assertEquals('d', chunk.getConversionType());
}
public void testNewStyleFieldNameWithNestedElementIndex() {
final List<FormatStringChunk> chunks = parseNewStyleFormat("{foo[a][1].a[1]:d}");
assertEquals(1, chunks.size());
final NewStyleSubstitutionChunk chunk = (NewStyleSubstitutionChunk)chunks.get(0);
assertEquals(TextRange.create(0, 18), chunk.getTextRange());
assertEquals("foo", chunk.getMappingKey());
assertNotNull(chunk.getMappingKeyElementIndex());
assertEquals("a", chunk.getMappingKeyElementIndex());
assertEquals('d', chunk.getConversionType());
}
public void testAsciiFormatSpecifierOldStyleFormat() {
final List<FormatStringChunk> chunks = parsePercentFormat("%a");
assertEquals(1, chunks.size());
final PercentSubstitutionChunk chunk = (PercentSubstitutionChunk)chunks.get(0);
assertEquals('a', chunk.getConversionType());
}
}
|
|
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.signup.tool.jsf.attachment;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.signup.logic.SakaiFacade;
import org.sakaiproject.signup.logic.SignupMeetingService;
import org.sakaiproject.signup.model.SignupAttachment;
import org.sakaiproject.signup.model.SignupMeeting;
import org.sakaiproject.signup.model.SignupSite;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
/*
* <p> This class will provides add/remove attachment functionality for sign-up tool.
* </P>
*/
public class AttachmentHandler implements Serializable {
private static Logger log = LoggerFactory.getLogger(AttachmentHandler.class);
private List<SignupAttachment> attachments;
private SakaiFacade sakaiFacade;
private SignupMeetingService signupMeetingService;
/**
* default constructor
*/
public AttachmentHandler() {
}
/**
* Constructor
*
* @param sakaiFacade
* -SakaiFacade object
* @param signupMeetingService
* -SignupMeetingService object
*/
public AttachmentHandler(SakaiFacade sakaiFacade, SignupMeetingService signupMeetingService) {
this.sakaiFacade = sakaiFacade;
this.signupMeetingService = signupMeetingService;
}
public void clear() {
this.attachments = null;
}
/**
* Redirect the add/remove attachment to Sakai's help page.
*
* @param attachList -
* a list of attachment objects
* @param sMeeting -
* SignupMeeting object
* @param isOrganizer -
* a boolean value
* @return null value
*/
public String processAddAttachRedirect(List attachList, SignupMeeting sMeeting,
boolean isOrganizer) {
this.attachments = attachList;
try {
List filePickerList = prepareReferenceList(attachments, sMeeting, isOrganizer);
ToolSession currentToolSession = SessionManager.getCurrentToolSession();
currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS,
filePickerList);
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.redirect("sakai.filepicker.helper/tool");
} catch (Exception e) {
log.error("fail to redirect to attachment page: " + e.getMessage());
}
return null;
}
private List prepareReferenceList(List attachmentList, SignupMeeting sMeeting,
boolean isOrganizer) {
List list = new ArrayList();
if (attachmentList == null) {
return list;
}
for (int i = 0; i < attachmentList.size(); i++) {
ContentResource cr = null;
SignupAttachment attach = (SignupAttachment) attachmentList.get(i);
try {
cr = getSakaiFacade().getContentHostingService()
.getResource(attach.getResourceId());
} catch (PermissionException e) {
log.warn("ContentHostingService.getResource() throws PermissionException="
+ e.getMessage());
} catch (IdUnusedException e) {
log.warn("ContentHostingService.getResource() throws IdUnusedException="
+ e.getMessage());
/*
* If the attachment somehow get removed from CHS and it's a
* broken link
*/
RemoveAttachment removeAttach = new RemoveAttachment(signupMeetingService,
sakaiFacade.getCurrentUserId(), sakaiFacade.getCurrentLocationId(),
isOrganizer);
removeAttach.removeAttachment(sMeeting, attach);
} catch (TypeException e) {
log.warn("ContentHostingService.getResource() throws TypeException="
+ e.getMessage());
} catch (Exception e) {
log.warn("Exception: " + e.getMessage());
}
if (cr != null) {
Reference ref = EntityManager.newReference(cr.getReference());
if (ref != null)
list.add(ref);
}
}
return list;
}
/**
* Called by SamigoJsfTool.java on exit from file picker
*/
public void setAttachmentItems() {
/*
* they share the same attachments pointer with JSF bean and via this to
* pass updated list
*/
processItemAttachment();
}
private void processItemAttachment() {
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
HashMap map = getResourceIdHash(this.attachments);
ArrayList newAttachmentList = new ArrayList();
String protocol = getSakaiFacade().getServerConfigurationService().getServerUrl();
List refs = (List) session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if (refs != null && refs.size() > 0) {
Reference ref;
for (int i = 0; i < refs.size(); i++) {
ref = (Reference) refs.get(i);
String resourceId = ref.getId();
if (map.get(resourceId) == null) {
// new attachment, add
SignupAttachment newAttach = createSignupAttachment(ref.getId(), ref
.getProperties().getProperty(
ref.getProperties().getNamePropDisplayName()), protocol);
newAttachmentList.add(newAttach);
} else {
// attachment already exist, let's add it to new list
// and
// check it off from map
newAttachmentList.add((SignupAttachment) map.get(resourceId));
map.remove(resourceId);
}
}
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
this.attachments.clear();
this.attachments.addAll(newAttachmentList);
}
}
private HashMap<String, SignupAttachment> getResourceIdHash(List<SignupAttachment> attachList) {
HashMap<String, SignupAttachment> map = new HashMap<String, SignupAttachment>();
if (attachList != null) {
for (SignupAttachment attach : attachList) {
map.put(attach.getResourceId(), attach);
}
}
return map;
}
/**
* Create a new copy of the attachment
*
* @param sMeeting
* -SignupMeeting object
* @param isOrganizer -
* a boolean value
* @param attach
* -SignupAttachment object
* @param folderId -
* a foldId string object
* @return - a SignupAttachment object
*/
public SignupAttachment copySignupAttachment(SignupMeeting sMeeting, boolean isOrganizer,
SignupAttachment attach, String folderId) {
SignupAttachment newAttach = null;
ContentResource cr = null;
ContentResource newCr = null;
if (attach == null || attach.getResourceId().trim().length() < 1)
return null;
String newResourceId = attach.getResourceId();
int index = attach.getResourceId().lastIndexOf("/");
if (index > -1) {
newResourceId = newResourceId.substring(0, index + 1) + folderId + "/"
+ newResourceId.substring(index + 1, newResourceId.length());
}
try {
cr = getSakaiFacade().getContentHostingService().getResource(attach.getResourceId());
if (cr != null) {
String protocol = getSakaiFacade().getServerConfigurationService().getServerUrl();
newResourceId = getSakaiFacade().getContentHostingService().copy(
attach.getResourceId(), newResourceId);
newCr = getSakaiFacade().getContentHostingService().getResource(newResourceId);
Reference ref = EntityManager.newReference(newCr.getReference());
if (ref != null) {
newAttach = createSignupAttachment(ref.getId(), ref.getProperties()
.getProperty(ref.getProperties().getNamePropDisplayName()), protocol);
/* Case: for cross-sites, make it to public view */
determineAndAssignPublicView(sMeeting, newAttach);
}
}
} catch (PermissionException e) {
log.warn("ContentHostingService.getResource() throws PermissionException="
+ e.getMessage());
} catch (IdUnusedException e) {
log.warn("ContentHostingService.getResource() throws IdUnusedException="
+ e.getMessage());
/*
* If the attachment somehow get removed from CHS and it's a broken
* link
*/
RemoveAttachment removeAttach = new RemoveAttachment(signupMeetingService, sakaiFacade
.getCurrentUserId(), sakaiFacade.getCurrentLocationId(), isOrganizer);
removeAttach.removeAttachment(sMeeting, attach);
} catch (TypeException e) {
log.warn("ContentHostingService.getResource() throws TypeException=" + e.getMessage());
} catch (Exception e) {
log.warn("ContentHostingService.getResource() throws Exception=" + e.getMessage());
}
return newAttach;
}
public void removeAttachmentInContentHost(SignupAttachment attach) {
if (attach == null || attach.getResourceId() == null)
return;
try {
getSakaiFacade().getContentHostingService().removeResource(attach.getResourceId());
} catch (PermissionException e) {
log.warn("ContentHostingService.getResource() throws PermissionException="
+ e.getMessage());
} catch (IdUnusedException e) {
log.warn("ContentHostingService.getResource() throws IdUnusedException="
+ e.getMessage());
} catch (TypeException e) {
log.warn("ContentHostingService.getResource() throws TypeException=" + e.getMessage());
} catch (InUseException e) {
log.warn("ContentHostingService.getResource() throws InUseException=" + e.getMessage());
} catch (Exception e) {
log.warn("ContentHostingService.getResource() throws Exception=" + e.getMessage());
}
}
public SakaiFacade getSakaiFacade() {
return sakaiFacade;
}
public void setSakaiFacade(SakaiFacade sakaiFacade) {
this.sakaiFacade = sakaiFacade;
}
public SignupMeetingService getSignupMeetingService() {
return signupMeetingService;
}
public void setSignupMeetingService(SignupMeetingService signupMeetingService) {
this.signupMeetingService = signupMeetingService;
}
public List<SignupAttachment> getAttachments() {
return this.attachments;
}
public void setAttachments(List<SignupAttachment> attachments) {
this.attachments = attachments;
}
protected SignupAttachment createSignupAttachment(String resourceId, String filename,
String protocol) {
SignupAttachment attach = new SignupAttachment();
Boolean isLink = Boolean.FALSE;
try {
ContentResource cr = getSakaiFacade().getContentHostingService()
.getResource(resourceId);
if (cr != null) {
ResourceProperties p = cr.getProperties();
attach = new SignupAttachment();
attach.setResourceId(resourceId);
attach.setMimeType(cr.getContentType());
// we want to display kb, so divide by 1000 and round the result
attach.setFileSize(new Long("" + fileSizeInKB((int)cr.getContentLength())));//2Gb??
if (cr.getContentType().lastIndexOf("url") > -1) {
isLink = Boolean.TRUE;
if (!filename.toLowerCase().startsWith("http")) {
String adjustedFilename = "http://" + filename;
attach.setFilename(adjustedFilename);
} else {
attach.setFilename(filename);
}
} else {
attach.setFilename(filename);
}
attach.setIsLink(isLink);
attach.setCreatedBy(p.getProperty(p.getNamePropCreator()));
attach.setCreatedDate(new Date());
attach.setLastModifiedBy(p.getProperty(p.getNamePropModifiedBy()));
attach.setLastModifiedDate(new Date());
attach.setLocation(getRelativePath(cr.getUrl(), protocol));
}
} catch (PermissionException pe) {
log.warn("PermissionException: " + pe.getMessage());
} catch (IdUnusedException ie) {
log.warn("IdUnusedException: " + ie.getMessage());
} catch (TypeException te) {
log.warn("TypeException: " + te.getMessage());
}
return attach;
}
private String fileSizeInKB(int fileSize) {
String fileSizeString = "1";
int size = Math.round((float) fileSize / 1024.0f);
if (size > 0) {
fileSizeString = size + "";
}
return fileSizeString;
}
public String getRelativePath(String url, String protocol) {
// replace whitespace with %20
url = replaceSpace(url);
int index = url.lastIndexOf(protocol);
if (index == 0) {
url = url.substring(protocol.length());
}
return url;
}
public void setPublicView(String resourceId, boolean pubview) {
getSakaiFacade().getContentHostingService().setPubView(resourceId, pubview);
}
private String replaceSpace(String tempString) {
String newString = "";
char[] oneChar = new char[1];
for (int i = 0; i < tempString.length(); i++) {
if (tempString.charAt(i) != ' ') {
oneChar[0] = tempString.charAt(i);
String concatString = new String(oneChar);
newString = newString.concat(concatString);
} else {
newString = newString.concat("%20");
}
}
return newString;
}
/**
* If it's a cross sites or for other site, the attachment will be set to
* public view in ContentHostingService
*
* @param sMeeting -
* a SignupMeeting object
* @param attach -
* a SignupAttachment object
*/
public void determineAndAssignPublicView(SignupMeeting sMeeting, SignupAttachment attach) {
if (attach == null)
return;
/* Case 1: multiple sites - set to public view */
if (sMeeting.getSignupSites() != null && sMeeting.getSignupSites().size() > 1) {
getSakaiFacade().getContentHostingService().setPubView(attach.getResourceId(), true);
return;
}
Site site = null;
if (sMeeting.getSignupSites() == null || sMeeting.getSignupSites().isEmpty())
return;
SignupSite signupSite = sMeeting.getSignupSites().get(0);
try {
site = getSakaiFacade().getSiteService().getSite(signupSite.getSiteId());
} catch (IdUnusedException e) {
log.error(e.getMessage(), e);
}
if (site == null)
return;
/* Case 2: publish the event for other site only - set to public view */
if (!site.getId().equals(sakaiFacade.getCurrentLocationId())) {
getSakaiFacade().getContentHostingService().setPubView(attach.getResourceId(), true);
return;
}
/*
* case 3: If site has roleId '.auth', any logged-in user should see it -
* set to public view
*/
Set siteRoles = site.getRoles();
if (siteRoles != null) {
for (Iterator iter = siteRoles.iterator(); iter.hasNext();) {
Role role = (Role) iter.next();
/* '.auth' roleId */
if (SakaiFacade.REALM_ID_FOR_LOGIN_REQUIRED_ONLY.equals(role.getId())) {
getSakaiFacade().getContentHostingService().setPubView(attach.getResourceId(),
true);
break;
}
}
}
}
}
|
|
/*
* 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.rave.portal.model;
import org.apache.rave.persistence.BasicEntity;
import org.codehaus.jackson.annotate.JsonManagedReference;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.List;
/**
* A page, which consists of regions, and which may be owned by a {@link User} (note the ownership will likely need to
* become more flexible to enable things like group ownership in the future).
*
* TODO RAVE-231: not all database providers will be able to support deferrable constraints
* so for the time being I'm commenting out the owner/render sequence since it
* will get updated in batches and blow up
* @UniqueConstraint(columnNames={"owner_id","render_sequence"}
*
*/
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@Table(name="page", uniqueConstraints={@UniqueConstraint(columnNames={"owner_id","name","page_type"})})
@NamedQueries({
@NamedQuery(name = Page.GET_BY_USER_ID_AND_PAGE_TYPE, query="SELECT p FROM Page p WHERE p.owner.entityId = :userId and p.pageType = :pageType ORDER BY p.renderSequence"),
@NamedQuery(name = Page.DELETE_BY_USER_ID_AND_PAGE_TYPE, query="DELETE FROM Page p WHERE p.owner.entityId = :userId and p.pageType = :pageType"),
@NamedQuery(name = Page.USER_HAS_PERSON_PAGE, query="SELECT count(p) FROM Page p WHERE p.owner.entityId = :userId and p.pageType = :pageType")
})
@Access(AccessType.FIELD)
public class Page implements BasicEntity, Serializable {
private static final long serialVersionUID = 1L;
public static final String GET_BY_USER_ID_AND_PAGE_TYPE = "Page.getByUserIdAndPageType";
public static final String DELETE_BY_USER_ID_AND_PAGE_TYPE = "Page.deleteByUserIdAndPageType";
public static final String USER_HAS_PERSON_PAGE = "Page.hasPersonPage";
@XmlAttribute(name="id")
@Id @Column(name="entity_id")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "pageIdGenerator")
@TableGenerator(name = "pageIdGenerator", table = "RAVE_PORTAL_SEQUENCES", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "page", allocationSize = 1, initialValue = 1)
private Long entityId;
@XmlElement
@Basic(optional=false) @Column(name="name")
private String name;
@ManyToOne
@JoinColumn(name = "owner_id")
private User owner;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="parent_page_id")
private Page parentPage;
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="parentPage")
@OrderBy("renderSequence")
private List<Page> subPages;
@Basic(optional=false) @Column(name="render_sequence")
private Long renderSequence;
@ManyToOne
@JoinColumn(name="page_layout_id")
private PageLayout pageLayout;
@XmlElement(name="region")
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("renderOrder")
@JoinColumn(name="page_id")
private List<Region> regions;
@Basic
@Column(name = "page_type")
@Enumerated(EnumType.STRING)
private PageType pageType;
public Page() {
}
public Page(Long entityId) {
this.entityId = entityId;
}
public Page(Long entityId, User owner) {
this.entityId = entityId;
this.owner = owner;
}
/**
* Gets the persistence unique identifier
*
* @return id The ID of persisted object; null if not persisted
*/
@Override
public Long getEntityId() {
return entityId;
}
@Override
public void setEntityId(Long entityId) {
this.entityId = entityId;
}
/**
* Gets the user defined name of the page
*
* @return Valid name
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Gets the {@link User} that owns the page
*
* @return Valid {@link User}
*/
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
/**
* Gets the order of the page instance relative to all pages for the owner (useful when presenting pages in an
* ordered layout like tabs or an accordion container)
*
* @return Valid, unique render sequence
*/
public Long getRenderSequence() {
return renderSequence;
}
public void setRenderSequence(Long renderSequence) {
this.renderSequence = renderSequence;
}
/**
* Gets the {@link PageLayout}
*
* @return Valid {@link PageLayout}
*/
public PageLayout getPageLayout() {
return pageLayout;
}
public void setPageLayout(PageLayout pageLayout) {
this.pageLayout = pageLayout;
}
/**
* Gets the widget containing {@link Region}s of the page
*
* @return Valid list of {@link Region}s
*/
@JsonManagedReference
public List<Region> getRegions() {
return regions;
}
public void setRegions(List<Region> regions) {
this.regions = regions;
}
public PageType getPageType() {
return pageType;
}
public void setPageType(PageType pageType) {
this.pageType = pageType;
}
public Page getParentPage() {
return parentPage;
}
public void setParentPage(Page parentPage) {
this.parentPage = parentPage;
}
public List<Page> getSubPages() {
return subPages;
}
public void setSubPages(List<Page> subPages) {
this.subPages = subPages;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Page other = (Page) obj;
if (this.entityId != other.entityId && (this.entityId == null || !this.entityId.equals(other.entityId))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + (this.entityId != null ? this.entityId.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return "Page{" + "entityId=" + entityId + ", name=" + name + ", owner=" + owner + ", renderSequence=" + renderSequence + ", pageLayout=" + pageLayout + ", pageType=" + pageType + "}";
}
}
|
|
/**
* The Game
*
* @author Lars Harmsen Jake Overton <OvertonMobile>
* Copyright (c) <2014> <Lars Harmsen - Quchen>
*/
package com.overtonmobile.saucertrek;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.example.games.basegameutils.BaseGameActivity;
import com.google.android.gms.ads.*;
import com.google.android.gms.games.Games;
import com.google.android.gms.common.api.GoogleApiClient;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class Game extends BaseGameActivity{
/** Name of the SharedPreference that saves the medals */
public static final String coin_save = "coin_save";
/** Key that saves the medal */
public static final String coin_key = "coin_key";
/** Will play things like mooing */
public static SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
private static final int GAMES_PER_AD = 3;
/** Counts number of played games */
private static int gameOverCounter = 1;
private InterstitialAd interstitial;
/**
* Will play songs like:
* nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan
* nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan
* nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan
* nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan nyan
* Does someone know the second verse ???
*/
public static MediaPlayer musicPlayer = null;
/**
* Whether the music should play or not
*/
public boolean musicShouldPlay = false;
/** Time interval (ms) you have to press the backbutton twice in to exit */
private static final long DOUBLE_BACK_TIME = 1000;
/** Saves the time of the last backbutton press*/
private long backPressed;
/** To do UI things from different threads */
public MyHandler handler;
/** Hold all accomplishments */
AccomplishmentBox accomplishmentBox;
/** The view that handles all kind of stuff */
GameView view;
/** The amount of collected coins */
int coins;
/** This will increase the revive price */
public int numberOfRevive = 1;
/** The dialog displayed when the game is over*/
GameOverDialog gameOverDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accomplishmentBox = new AccomplishmentBox();
view = new GameView(this);
gameOverDialog = new GameOverDialog(this);
handler = new MyHandler(this);
setContentView(view);
initMusicPlayer();
loadCoins();
if(gameOverCounter % GAMES_PER_AD == 0) {
setupAd();
}
}
/**
* Initializes the player with the nyan cat song
* and sets the position to 0.
*/
public void initMusicPlayer(){
if(musicPlayer == null){
// to avoid unnecessary reinitialisation
musicPlayer = MediaPlayer.create(this, R.raw.nyan_cat_theme);
musicPlayer.setLooping(true);
musicPlayer.setVolume(MainActivity.volume, MainActivity.volume);
}
musicPlayer.seekTo(0); // Reset song to position 0
}
private void loadCoins(){
SharedPreferences saves = this.getSharedPreferences(coin_save, 0);
this.coins = saves.getInt(coin_key, 0);
}
/**
* Pauses the view and the music
*/
@Override
protected void onPause() {
view.pause();
if(musicPlayer.isPlaying()){
musicPlayer.pause();
}
super.onPause();
}
/**
* Resumes the view (but waits the view waits for a tap)
* and starts the music if it should be running.
* Also checks whether the Google Play Services are available.
*/
@Override
protected void onResume() {
view.drawOnce();
if(musicShouldPlay){
musicPlayer.start();
}
if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS){
Toast.makeText(this, "Please check your Google Services", Toast.LENGTH_LONG).show();
}
super.onResume();
}
/**
* Prevent accidental exits by requiring a double press.
*/
@Override
public void onBackPressed() {
if(System.currentTimeMillis() - backPressed < DOUBLE_BACK_TIME){
super.onBackPressed();
}else{
backPressed = System.currentTimeMillis();
Toast.makeText(this, getResources().getString(R.string.on_back_press), Toast.LENGTH_LONG).show();
}
}
/**
* Sends the handler the command to show the GameOverDialog.
* Because it needs an UI thread.
*/
public void gameOver(){
if(gameOverCounter % GAMES_PER_AD == 0) {
handler.sendMessage(Message.obtain(handler, MyHandler.SHOW_AD));
} else {
handler.sendMessage(Message.obtain(handler, MyHandler.GAME_OVER_DIALOG));
}
}
public void increaseCoin(){
this.coins++;
if(coins >= 50 && !accomplishmentBox.achievement_50_coins){
accomplishmentBox.achievement_50_coins = true;
if(getApiClient().isConnected()){
Games.Achievements.unlock(getApiClient(), getResources().getString(R.string.achievement_50_coins));
}else{
handler.sendMessage(Message.obtain(handler,1,R.string.toast_achievement_50_coins, MyHandler.SHOW_TOAST));
}
}
}
/**
* What should happen, when an obstacle is passed?
*/
public void increasePoints(){
accomplishmentBox.points++;
this.view.getPlayer().upgradeBitmap(accomplishmentBox.points);
if(accomplishmentBox.points >= AccomplishmentBox.BRONZE_POINTS){
if(!accomplishmentBox.achievement_bronze){
accomplishmentBox.achievement_bronze = true;
if(getApiClient().isConnected()){
Games.Achievements.unlock(getApiClient(), getResources().getString(R.string.achievement_bronze));
}else{
handler.sendMessage(Message.obtain(handler, MyHandler.SHOW_TOAST, R.string.toast_achievement_bronze, MyHandler.SHOW_TOAST));
}
}
if(accomplishmentBox.points >= AccomplishmentBox.SILVER_POINTS){
if(!accomplishmentBox.achievement_silver){
accomplishmentBox.achievement_silver = true;
if(getApiClient().isConnected()){
Games.Achievements.unlock(getApiClient(), getResources().getString(R.string.achievement_silver));
}else{
handler.sendMessage(Message.obtain(handler, MyHandler.SHOW_TOAST, R.string.toast_achievement_silver, MyHandler.SHOW_TOAST));
}
}
if(accomplishmentBox.points >= AccomplishmentBox.GOLD_POINTS){
if(!accomplishmentBox.achievement_gold){
accomplishmentBox.achievement_gold = true;
if(getApiClient().isConnected()){
Games.Achievements.unlock(getApiClient(), getResources().getString(R.string.achievement_gold));
}else{
handler.sendMessage(Message.obtain(handler, MyHandler.SHOW_TOAST, R.string.toast_achievement_gold, MyHandler.SHOW_TOAST));
}
}
}
}
}
}
public GoogleApiClient getApiClient(){
return mHelper.getApiClient();
}
/**
* Shows the GameOverDialog when a message with code 0 is received.
*/
static class MyHandler extends Handler{
public static final int GAME_OVER_DIALOG = 0;
public static final int SHOW_TOAST = 1;
public static final int SHOW_AD = 2;
private Game game;
public MyHandler(Game game){
this.game = game;
}
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case GAME_OVER_DIALOG:
showGameOverDialog();
break;
case SHOW_TOAST:
Toast.makeText(game, msg.arg1, Toast.LENGTH_SHORT).show();
break;
case SHOW_AD:
showAd();
break;
}
}
private void showAd() {
if(game.interstitial == null) {
showGameOverDialog();
} else {
if(game.interstitial.isLoaded()) {
game.interstitial.show();
} else {
showGameOverDialog();
}
}
}
private void showGameOverDialog() {
++Game.gameOverCounter;
game.gameOverDialog.init();
game.gameOverDialog.show();
}
}
@Override
public void onSignInFailed() {}
@Override
public void onSignInSucceeded() {}
private void setupAd() {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.ad_unit_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new MyAdListener());
}
private class MyAdListener extends AdListener{
public void onAdClosed () {
handler.sendMessage(Message.obtain(handler, MyHandler.GAME_OVER_DIALOG));
}
}
}
|
|
package com.ctrip.platform.dal.dao.client;
import com.ctrip.platform.dal.dao.DalClientFactory;
import com.ctrip.platform.dal.dao.DalEventEnum;
import com.ctrip.platform.dal.dao.DalHints;
import com.ctrip.platform.dal.dao.base.MockConnectionAction;
import org.junit.*;
import com.ctrip.platform.dal.dao.task.SqlServerTestInitializer;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class DalConnectionManagerTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
SqlServerTestInitializer.setUpBeforeClass();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
SqlServerTestInitializer.tearDownAfterClass();
}
@Before
public void setUp() throws Exception {
SqlServerTestInitializer.setUp();
}
@After
public void tearDown() throws Exception {
SqlServerTestInitializer.tearDown();
}
private static final String noShardDb = "dao_test_sqlsvr";
private static final String shardDb = "dao_test_sqlsvr_dbShard";
static{
try {
DalClientFactory.initClientFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
private static DalConnectionManager getDalConnectionManager(String db) throws Exception {
return new DalConnectionManager(db, DalClientFactory.getDalConfigure());
}
@Test
public void testGetNewConnection() {
boolean useMaster = true;
DalHints hints = new DalHints();
try {
DalConnectionManager test = getDalConnectionManager(noShardDb);
DalConnection conn = test.getNewConnection(hints, useMaster, new MockConnectionAction(DalEventEnum.BATCH_CALL));
assertNotNull(conn);
assertNotNull(conn.getConn());
conn.getConn().close();
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testEvaluate() {
boolean useMaster = true;
DalHints hints = new DalHints();
try {
DalConnectionManager test = getDalConnectionManager(noShardDb);
String id = test.evaluateShard(hints);
assertNull(id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
try {
DalConnectionManager test = getDalConnectionManager(shardDb);
hints = new DalHints();
hints.inShard(1);
String id = test.evaluateShard(hints);
assertEquals("1", id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
try {
DalConnectionManager test = getDalConnectionManager(shardDb);
hints = new DalHints();
hints.inShard("1");
String id = test.evaluateShard(hints);
assertEquals("1", id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
try {
DalConnectionManager test = getDalConnectionManager(shardDb);
hints = new DalHints();
hints.setShardValue("3");
String id = test.evaluateShard(hints);
assertEquals("1", id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
try {
DalConnectionManager test = getDalConnectionManager(shardDb);
hints = new DalHints();
hints.setShardColValue("index", "3");
String id = test.evaluateShard(hints);
assertEquals("1", id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
try {
DalConnectionManager test = getDalConnectionManager(shardDb);
hints = new DalHints();
Map<String, String> shardColValues = new HashMap<>();
shardColValues.put("index", "3");
hints.setShardColValues(shardColValues);
String id = test.evaluateShard(hints);
assertEquals("1", id);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testDoInConnection() {
final boolean useMaster = true;
final DalHints hints = new DalHints();
try {
final DalConnectionManager test = getDalConnectionManager(noShardDb);
ConnectionAction<Object> action = new ConnectionAction<Object>() {
public Object execute() throws Exception {
connHolder = test.getNewConnection(hints, useMaster, new MockConnectionAction(DalEventEnum.BATCH_CALL));
statement = connHolder.getConn().createStatement();
rs = statement.executeQuery("select * from " + SqlServerTestInitializer.TABLE_NAME);
rs.next();
return null;
}
};
action.operation = DalEventEnum.EXECUTE;
test.doInConnection(action, hints);
assertTrue(action.conn == null);
assertTrue(action.statement == null);
assertTrue(action.rs == null);
assertTrue(action.connHolder == null);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testDoInConnectionException() {
final boolean useMaster = true;
final DalHints hints = new DalHints();
final String message = "testDoInConnectionException";
ConnectionAction<Object> action = null;
try {
final DalConnectionManager test = getDalConnectionManager(noShardDb);
action = new ConnectionAction<Object>() {
public Object execute() throws Exception {
connHolder = test.getNewConnection(hints, useMaster, new MockConnectionAction(DalEventEnum.BATCH_CALL));
statement = connHolder.getConn().createStatement();
rs = statement.executeQuery("select * from City");
rs.next();
throw new RuntimeException(message);
}
};
test.doInConnection(action, hints);
fail();
} catch (Exception e) {
e.printStackTrace();
assertNotNull(action);
assertTrue(action.conn == null);
assertTrue(action.statement == null);
assertTrue(action.rs == null);
assertTrue(action.connHolder == null);
}
}
}
|
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.sourcemap;
import com.google.gson.stream.JsonToken;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.util.PathUtil;
import com.intellij.util.SmartList;
import com.intellij.util.UriUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.JsonReaderEx;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static org.jetbrains.debugger.sourcemap.Base64VLQ.CharIterator;
// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US
public final class SourceMapDecoder {
public static final int UNMAPPED = -1;
private static final Comparator<MappingEntry> MAPPING_COMPARATOR_BY_SOURCE_POSITION = new Comparator<MappingEntry>() {
@Override
public int compare(@NotNull MappingEntry o1, @NotNull MappingEntry o2) {
if (o1.getSourceLine() == o2.getSourceLine()) {
return o1.getSourceColumn() - o2.getSourceColumn();
}
else {
return o1.getSourceLine() - o2.getSourceLine();
}
}
};
public static final Comparator<MappingEntry> MAPPING_COMPARATOR_BY_GENERATED_POSITION = new Comparator<MappingEntry>() {
@Override
public int compare(@NotNull MappingEntry o1, @NotNull MappingEntry o2) {
if (o1.getGeneratedLine() == o2.getGeneratedLine()) {
return o1.getGeneratedColumn() - o2.getGeneratedColumn();
}
else {
return o1.getGeneratedLine() - o2.getGeneratedLine();
}
}
};
public interface SourceResolverFactory {
@NotNull
SourceResolver create(@NotNull List<String> sourceUrls, @Nullable List<String> sourceContents);
}
@Nullable
public static SourceMap decode(@NotNull CharSequence in, @NotNull SourceResolverFactory sourceResolverFactory) throws IOException {
if (in.length() == 0) {
throw new IOException("source map contents cannot be empty");
}
JsonReaderEx reader = new JsonReaderEx(in);
reader.setLenient(true);
List<MappingEntry> mappings = new ArrayList<MappingEntry>();
return parseMap(reader, 0, 0, mappings, sourceResolverFactory);
}
@Nullable
private static SourceMap parseMap(@NotNull JsonReaderEx reader,
int line,
int column,
List<MappingEntry> mappings,
@NotNull SourceResolverFactory sourceResolverFactory) throws IOException {
reader.beginObject();
String sourceRoot = null;
JsonReaderEx sourcesReader = null;
List<String> names = null;
String encodedMappings = null;
String file = null;
int version = -1;
List<String> sourcesContent = null;
while (reader.hasNext()) {
String propertyName = reader.nextName();
if (propertyName.equals("sections")) {
throw new IOException("sections is not supported yet");
}
else if (propertyName.equals("version")) {
version = reader.nextInt();
}
else if (propertyName.equals("sourceRoot")) {
sourceRoot = readSourcePath(reader);
if (sourceRoot != null) {
sourceRoot = UriUtil.trimTrailingSlashes(sourceRoot);
}
}
else if (propertyName.equals("sources")) {
sourcesReader = reader.subReader();
reader.skipValue();
}
else if (propertyName.equals("names")) {
reader.beginArray();
if (reader.hasNext()) {
names = new ArrayList<String>();
do {
if (reader.peek() == JsonToken.BEGIN_OBJECT) {
// polymer map
reader.skipValue();
names.add("POLYMER UNKNOWN NAME");
}
else {
names.add(reader.nextString(true));
}
}
while (reader.hasNext());
}
else {
names = Collections.emptyList();
}
reader.endArray();
}
else if (propertyName.equals("mappings")) {
encodedMappings = reader.nextString();
}
else if (propertyName.equals("file")) {
file = reader.nextString();
}
else if (propertyName.equals("sourcesContent")) {
reader.beginArray();
if (reader.peek() != JsonToken.END_ARRAY) {
sourcesContent = new SmartList<String>();
do {
if (reader.peek() == JsonToken.STRING) {
sourcesContent.add(StringUtilRt.convertLineSeparators(reader.nextString()));
}
else {
reader.skipValue();
}
}
while (reader.hasNext());
}
reader.endArray();
}
else {
// skip file or extensions
reader.skipValue();
}
}
reader.close();
// check it before other checks, probably it is not sourcemap file
if (StringUtil.isEmpty(encodedMappings)) {
// empty map
return null;
}
if (version != 3) {
throw new IOException("Unsupported sourcemap version: " + version);
}
if (sourcesReader == null) {
throw new IOException("sources is not specified");
}
List<String> sources = readSources(sourcesReader, sourceRoot);
if (sources.isEmpty()) {
// empty map, meteor can report such ugly maps
return null;
}
@SuppressWarnings("unchecked")
List<MappingEntry>[] reverseMappingsBySourceUrl = new List[sources.size()];
readMappings(encodedMappings, line, column, mappings, reverseMappingsBySourceUrl, names);
MappingList[] sourceToEntries = new MappingList[reverseMappingsBySourceUrl.length];
for (int i = 0; i < reverseMappingsBySourceUrl.length; i++) {
List<MappingEntry> entries = reverseMappingsBySourceUrl[i];
if (entries != null) {
Collections.sort(entries, MAPPING_COMPARATOR_BY_SOURCE_POSITION);
sourceToEntries[i] = new SourceMappingList(entries);
}
}
return new SourceMap(file, new GeneratedMappingList(mappings), sourceToEntries, sourceResolverFactory.create(sources, sourcesContent), !ContainerUtil.isEmpty(names));
}
@Nullable
private static String readSourcePath(JsonReaderEx reader) {
return PathUtil.toSystemIndependentName(StringUtil.nullize(reader.nextString().trim()));
}
private static void readMappings(@NotNull String value,
int line,
int column,
@NotNull List<MappingEntry> mappings,
@NotNull List<MappingEntry>[] reverseMappingsBySourceUrl,
@Nullable List<String> names) {
if (StringUtil.isEmpty(value)) {
return;
}
CharSequenceIterator charIterator = new CharSequenceIterator(value);
int sourceIndex = 0;
List<MappingEntry> reverseMappings = getMapping(reverseMappingsBySourceUrl, sourceIndex);
int sourceLine = 0;
int sourceColumn = 0;
int nameIndex = 0;
while (charIterator.hasNext()) {
if (charIterator.peek() == ',') {
charIterator.next();
}
else {
while (charIterator.peek() == ';') {
line++;
column = 0;
charIterator.next();
if (!charIterator.hasNext()) {
return;
}
}
}
column += Base64VLQ.decode(charIterator);
if (isSeparator(charIterator)) {
mappings.add(new UnmappedEntry(line, column));
continue;
}
int sourceIndexDelta = Base64VLQ.decode(charIterator);
if (sourceIndexDelta != 0) {
sourceIndex += sourceIndexDelta;
reverseMappings = getMapping(reverseMappingsBySourceUrl, sourceIndex);
}
sourceLine += Base64VLQ.decode(charIterator);
sourceColumn += Base64VLQ.decode(charIterator);
MappingEntry entry;
if (isSeparator(charIterator)) {
entry = new UnnamedEntry(line, column, sourceIndex, sourceLine, sourceColumn);
}
else {
nameIndex += Base64VLQ.decode(charIterator);
assert names != null;
entry = new NamedEntry(names.get(nameIndex), line, column, sourceIndex, sourceLine, sourceColumn);
}
reverseMappings.add(entry);
mappings.add(entry);
}
}
private static List<String> readSources(@NotNull JsonReaderEx reader, @Nullable String sourceRootUrl) {
reader.beginArray();
List<String> sources;
if (reader.peek() == JsonToken.END_ARRAY) {
sources = Collections.emptyList();
}
else {
sources = new SmartList<String>();
do {
String sourceUrl = readSourcePath(reader);
sourceUrl = StringUtil.isEmpty(sourceRootUrl) ? sourceUrl : (sourceRootUrl + '/' + sourceUrl);
sources.add(sourceUrl);
}
while (reader.hasNext());
}
reader.endArray();
return sources;
}
private static List<MappingEntry> getMapping(@NotNull List<MappingEntry>[] reverseMappingsBySourceUrl, int sourceIndex) {
List<MappingEntry> reverseMappings = reverseMappingsBySourceUrl[sourceIndex];
if (reverseMappings == null) {
reverseMappings = new ArrayList<MappingEntry>();
reverseMappingsBySourceUrl[sourceIndex] = reverseMappings;
}
return reverseMappings;
}
private static boolean isSeparator(CharSequenceIterator charIterator) {
if (!charIterator.hasNext()) {
return true;
}
char current = charIterator.peek();
return current == ',' || current == ';';
}
/**
* Not mapped to a section in the original source.
*/
private static class UnmappedEntry extends MappingEntry {
private final int line;
private final int column;
UnmappedEntry(int line, int column) {
this.line = line;
this.column = column;
}
@Override
public int getGeneratedColumn() {
return column;
}
@Override
public int getGeneratedLine() {
return line;
}
@Override
public int getSourceLine() {
return UNMAPPED;
}
@Override
public int getSourceColumn() {
return UNMAPPED;
}
}
/**
* Mapped to a section in the original source.
*/
private static class UnnamedEntry extends UnmappedEntry {
private final int source;
private final int sourceLine;
private final int sourceColumn;
UnnamedEntry(int line, int column, int source, int sourceLine, int sourceColumn) {
super(line, column);
this.source = source;
this.sourceLine = sourceLine;
this.sourceColumn = sourceColumn;
}
@Override
public int getSource() {
return source;
}
@Override
public int getSourceLine() {
return sourceLine;
}
@Override
public int getSourceColumn() {
return sourceColumn;
}
}
/**
* Mapped to a section in the original source, and is associated with a name.
*/
private static class NamedEntry extends UnnamedEntry {
private final String name;
NamedEntry(String name, int line, int column, int source, int sourceLine, int sourceColumn) {
super(line, column, source, sourceLine, sourceColumn);
this.name = name;
}
@Override
public String getName() {
return name;
}
}
// java CharacterIterator is ugly, next() impl, so, we reinvent
private static class CharSequenceIterator implements CharIterator {
private final CharSequence content;
private final int length;
private int current = 0;
CharSequenceIterator(CharSequence content) {
this.content = content;
length = content.length();
}
@Override
public char next() {
return content.charAt(current++);
}
char peek() {
return content.charAt(current);
}
@Override
public boolean hasNext() {
return current < length;
}
}
private static final class SourceMappingList extends MappingList {
public SourceMappingList(@NotNull List<MappingEntry> mappings) {
super(mappings);
}
@Override
public int getLine(@NotNull MappingEntry mapping) {
return mapping.getSourceLine();
}
@Override
public int getColumn(@NotNull MappingEntry mapping) {
return mapping.getSourceColumn();
}
@Override
protected Comparator<MappingEntry> getComparator() {
return MAPPING_COMPARATOR_BY_SOURCE_POSITION;
}
}
private static final class GeneratedMappingList extends MappingList {
public GeneratedMappingList(@NotNull List<MappingEntry> mappings) {
super(mappings);
}
@Override
public int getLine(@NotNull MappingEntry mapping) {
return mapping.getGeneratedLine();
}
@Override
public int getColumn(@NotNull MappingEntry mapping) {
return mapping.getGeneratedColumn();
}
@Override
protected Comparator<MappingEntry> getComparator() {
return MAPPING_COMPARATOR_BY_GENERATED_POSITION;
}
}
}
|
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventgrid.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.core.management.SystemData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.eventgrid.models.DeadLetterDestination;
import com.azure.resourcemanager.eventgrid.models.DeadLetterWithResourceIdentity;
import com.azure.resourcemanager.eventgrid.models.DeliveryWithResourceIdentity;
import com.azure.resourcemanager.eventgrid.models.EventDeliverySchema;
import com.azure.resourcemanager.eventgrid.models.EventSubscriptionDestination;
import com.azure.resourcemanager.eventgrid.models.EventSubscriptionFilter;
import com.azure.resourcemanager.eventgrid.models.EventSubscriptionProvisioningState;
import com.azure.resourcemanager.eventgrid.models.RetryPolicy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.List;
/** Event Subscription. */
@Fluent
public final class EventSubscriptionInner extends ProxyResource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(EventSubscriptionInner.class);
/*
* Properties of the event subscription.
*/
@JsonProperty(value = "properties")
private EventSubscriptionProperties innerProperties;
/*
* The system metadata relating to Event Subscription resource.
*/
@JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY)
private SystemData systemData;
/**
* Get the innerProperties property: Properties of the event subscription.
*
* @return the innerProperties value.
*/
private EventSubscriptionProperties innerProperties() {
return this.innerProperties;
}
/**
* Get the systemData property: The system metadata relating to Event Subscription resource.
*
* @return the systemData value.
*/
public SystemData systemData() {
return this.systemData;
}
/**
* Get the topic property: Name of the topic of the event subscription.
*
* @return the topic value.
*/
public String topic() {
return this.innerProperties() == null ? null : this.innerProperties().topic();
}
/**
* Get the provisioningState property: Provisioning state of the event subscription.
*
* @return the provisioningState value.
*/
public EventSubscriptionProvisioningState provisioningState() {
return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
}
/**
* Get the destination property: Information about the destination where events have to be delivered for the event
* subscription.
*
* @return the destination value.
*/
public EventSubscriptionDestination destination() {
return this.innerProperties() == null ? null : this.innerProperties().destination();
}
/**
* Set the destination property: Information about the destination where events have to be delivered for the event
* subscription.
*
* @param destination the destination value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withDestination(EventSubscriptionDestination destination) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withDestination(destination);
return this;
}
/**
* Get the deliveryWithResourceIdentity property: Information about the destination where events have to be
* delivered for the event subscription. Uses the managed identity setup on the parent resource (namely, topic or
* domain) to acquire the authentication tokens being used during delivery / dead-lettering.
*
* @return the deliveryWithResourceIdentity value.
*/
public DeliveryWithResourceIdentity deliveryWithResourceIdentity() {
return this.innerProperties() == null ? null : this.innerProperties().deliveryWithResourceIdentity();
}
/**
* Set the deliveryWithResourceIdentity property: Information about the destination where events have to be
* delivered for the event subscription. Uses the managed identity setup on the parent resource (namely, topic or
* domain) to acquire the authentication tokens being used during delivery / dead-lettering.
*
* @param deliveryWithResourceIdentity the deliveryWithResourceIdentity value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withDeliveryWithResourceIdentity(
DeliveryWithResourceIdentity deliveryWithResourceIdentity) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withDeliveryWithResourceIdentity(deliveryWithResourceIdentity);
return this;
}
/**
* Get the filter property: Information about the filter for the event subscription.
*
* @return the filter value.
*/
public EventSubscriptionFilter filter() {
return this.innerProperties() == null ? null : this.innerProperties().filter();
}
/**
* Set the filter property: Information about the filter for the event subscription.
*
* @param filter the filter value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withFilter(EventSubscriptionFilter filter) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withFilter(filter);
return this;
}
/**
* Get the labels property: List of user defined labels.
*
* @return the labels value.
*/
public List<String> labels() {
return this.innerProperties() == null ? null : this.innerProperties().labels();
}
/**
* Set the labels property: List of user defined labels.
*
* @param labels the labels value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withLabels(List<String> labels) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withLabels(labels);
return this;
}
/**
* Get the expirationTimeUtc property: Expiration time of the event subscription.
*
* @return the expirationTimeUtc value.
*/
public OffsetDateTime expirationTimeUtc() {
return this.innerProperties() == null ? null : this.innerProperties().expirationTimeUtc();
}
/**
* Set the expirationTimeUtc property: Expiration time of the event subscription.
*
* @param expirationTimeUtc the expirationTimeUtc value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withExpirationTimeUtc(OffsetDateTime expirationTimeUtc) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withExpirationTimeUtc(expirationTimeUtc);
return this;
}
/**
* Get the eventDeliverySchema property: The event delivery schema for the event subscription.
*
* @return the eventDeliverySchema value.
*/
public EventDeliverySchema eventDeliverySchema() {
return this.innerProperties() == null ? null : this.innerProperties().eventDeliverySchema();
}
/**
* Set the eventDeliverySchema property: The event delivery schema for the event subscription.
*
* @param eventDeliverySchema the eventDeliverySchema value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withEventDeliverySchema(EventDeliverySchema eventDeliverySchema) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withEventDeliverySchema(eventDeliverySchema);
return this;
}
/**
* Get the retryPolicy property: The retry policy for events. This can be used to configure maximum number of
* delivery attempts and time to live for events.
*
* @return the retryPolicy value.
*/
public RetryPolicy retryPolicy() {
return this.innerProperties() == null ? null : this.innerProperties().retryPolicy();
}
/**
* Set the retryPolicy property: The retry policy for events. This can be used to configure maximum number of
* delivery attempts and time to live for events.
*
* @param retryPolicy the retryPolicy value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withRetryPolicy(RetryPolicy retryPolicy) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withRetryPolicy(retryPolicy);
return this;
}
/**
* Get the deadLetterDestination property: The DeadLetter destination of the event subscription.
*
* @return the deadLetterDestination value.
*/
public DeadLetterDestination deadLetterDestination() {
return this.innerProperties() == null ? null : this.innerProperties().deadLetterDestination();
}
/**
* Set the deadLetterDestination property: The DeadLetter destination of the event subscription.
*
* @param deadLetterDestination the deadLetterDestination value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withDeadLetterDestination(DeadLetterDestination deadLetterDestination) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withDeadLetterDestination(deadLetterDestination);
return this;
}
/**
* Get the deadLetterWithResourceIdentity property: The dead letter destination of the event subscription. Any event
* that cannot be delivered to its' destination is sent to the dead letter destination. Uses the managed identity
* setup on the parent resource (namely, topic or domain) to acquire the authentication tokens being used during
* delivery / dead-lettering.
*
* @return the deadLetterWithResourceIdentity value.
*/
public DeadLetterWithResourceIdentity deadLetterWithResourceIdentity() {
return this.innerProperties() == null ? null : this.innerProperties().deadLetterWithResourceIdentity();
}
/**
* Set the deadLetterWithResourceIdentity property: The dead letter destination of the event subscription. Any event
* that cannot be delivered to its' destination is sent to the dead letter destination. Uses the managed identity
* setup on the parent resource (namely, topic or domain) to acquire the authentication tokens being used during
* delivery / dead-lettering.
*
* @param deadLetterWithResourceIdentity the deadLetterWithResourceIdentity value to set.
* @return the EventSubscriptionInner object itself.
*/
public EventSubscriptionInner withDeadLetterWithResourceIdentity(
DeadLetterWithResourceIdentity deadLetterWithResourceIdentity) {
if (this.innerProperties() == null) {
this.innerProperties = new EventSubscriptionProperties();
}
this.innerProperties().withDeadLetterWithResourceIdentity(deadLetterWithResourceIdentity);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (innerProperties() != null) {
innerProperties().validate();
}
}
}
|
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.event.simulator.core.internal.generator.database.util;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import org.apache.log4j.Logger;
import org.wso2.carbon.event.simulator.core.exception.EventGenerationException;
import org.wso2.carbon.event.simulator.core.exception.SimulatorInitializationException;
import org.wso2.carbon.event.simulator.core.model.DBConnectionModel;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* DatabaseConnector is a utility class performs the following tasks
* 1. Load the driver
* 2. Connect to the database
* 3. Create and execute a SELECT query
* 4. Return a result set containing data required for database event simulation
* 5. Close database connection
*/
public class DatabaseConnector {
private static final Logger log = Logger.getLogger(DatabaseConnector.class);
private static final String query_attribute_OnlyStartTime = "SELECT %s,%s FROM %s WHERE %s >= %d ORDER BY ABS(%s);";
private static final String query_attribute_WithBothLimits = "SELECT %s,%s FROM %s WHERE %s >= %d AND %s <= %d " +
"ORDER BY ABS(%s);";
private static final String query_interval = "SELECT %s FROM %s;";
private HikariDataSource dataSource;
private Connection dbConnection;
private String dataSourceLocation;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public DatabaseConnector() {
}
/**
* getDatabaseEvenItems method is used to obtain data from a database
*
* @param tableName table from which data must be retrieved
* @param columnNames list of columns to be retrieved
* @param timestampAttribute column containing timestamp
* @param timestampStartTime least possible timestamp
* @param timestampEndTime maximum possible timestamp
* @return resultset containing data needed for event simulation
*/
public ResultSet getDatabaseEventItems(String tableName, List<String> columnNames, String timestampAttribute,
long timestampStartTime, long timestampEndTime) {
/*
* check whether,
* 1. database connection is established
* 2. table exists
* 3. column names are valid
*
* if successful, create an sql query and retrieve data for event generation
* else throw an exception
* */
try {
if (dbConnection != null && !dbConnection.isClosed()) {
if (checkTableExists(tableName) && validateColumns(tableName, columnNames)) {
prepareSQLstatement(tableName, columnNames, timestampAttribute, timestampStartTime,
timestampEndTime);
this.resultSet = preparedStatement.executeQuery();
}
} else {
throw new EventGenerationException("Unable to connect to source '" + dataSourceLocation + "' to " +
"retrieve data for the configuration, table name : '" + tableName + "', column names : '" +
columnNames + "', timestamp attribute : '" + timestampAttribute + "', timestamp start time : " +
"'" + timestampStartTime + "' and timestamp end time : '" + timestampEndTime + "'.");
}
} catch (SQLException e) {
log.error("Error occurred when retrieving resultset from source '" + dataSourceLocation + "' " +
"to retrieve data for the configuration table name : '" + tableName + "'," +
" column names : '" + columnNames + "', timestamp attribute : '" + timestampAttribute + "', " +
"timestamp start time : '" + timestampStartTime + "' and timestamp end time : '" +
timestampEndTime + "'. ", e);
closeConnection();
throw new EventGenerationException("Error occurred when retrieving resultset from source '" +
dataSourceLocation + "' to retrieve data for the configuration, table name : '" + tableName + "'," +
" column names : '" + columnNames + "', timestamp attribute : '" + timestampAttribute + "', " +
"timestamp start time : '" + timestampStartTime + "' and timestamp end time : '" +
timestampEndTime + "'. ", e);
}
return resultSet;
}
/**
* This method loads the JDBC driver and creates a database connection
*
* @param dataSourceLocation location of database to be used
* @param username username
* @param password password
*/
public void connectToDatabase(String driver, String dataSourceLocation, String username, String password) {
try {
DBConnectionModel connectionDetails = new DBConnectionModel();
connectionDetails.setDataSourceLocation(dataSourceLocation);
connectionDetails.setDriver(driver);
connectionDetails.setPassword(password);
connectionDetails.setUsername(username);
this.dataSource = DatabaseConnector.initializeDatasource(connectionDetails);
this.dataSourceLocation = dataSourceLocation;
dbConnection = dataSource.getConnection();
} catch (SQLException e) {
log.error("Error occurred while connecting to database for the configuration : driver : '"
+ driver + "', data source location : '" + dataSourceLocation + "' and username : '" + username +
"'. ", e);
closeConnection();
throw new SimulatorInitializationException(" Error occurred while connecting to database for the" +
" configuration : driver : '" + driver + "', data source location : '" + dataSourceLocation + "'," +
" and username : '" + username + "'. ", e);
}
if (log.isDebugEnabled()) {
log.debug("Create a database connection for for the configuration driver : '" + driver + "', data source " +
"location : '" + dataSourceLocation + "' and username : '" + username + "'. ");
}
}
/**
* checkTableExists methods checks whether the table specified exists in the specified database
*
* @param tableName name of table from which data must be retrieved
* @return true if table exists in the database
*/
private boolean checkTableExists(String tableName) {
try {
DatabaseMetaData metaData = dbConnection.getMetaData();
/*
* retrieve a resultset containing tables with name 'tableName'.
* if resultset has entries, table exists in data source
* else close resources and throw an exception indicating that the table is not available in the data source
* if an SQL exception occurs while checking whether the table exists close resources and throw an exception
* */
ResultSet tableResults = metaData.getTables(null, null, tableName, null);
if (tableResults.isBeforeFirst()) {
if (log.isDebugEnabled()) {
log.debug("Table '" + tableName + "' exists in data source '" + dataSourceLocation);
}
return true;
} else {
closeConnection();
throw new EventGenerationException(" Table '" + tableName + "' does not exist in data source '" +
dataSourceLocation + "'.");
}
} catch (SQLException e) {
log.error("Error occurred when validating whether table '" + tableName +
"' exists in '" + dataSourceLocation + "'. ", e);
closeConnection();
throw new EventGenerationException("Error occurred when validating whether table '" + tableName +
"' exists in '" + dataSourceLocation + "'. ", e);
}
}
/**
* validateColumns method checks whether the columns specified exists in the specified table in the
* specified database
*
* @param tableName table from which data must be retrieved
* @param columnNames list of columns to be retrieved
* @return true if columns exists
*/
private boolean validateColumns(String tableName, List<String> columnNames) {
try {
DatabaseMetaData metaData = dbConnection.getMetaData();
/*
* retrieve a resultset containing column details of table 'tableName'.
* check whether each column name specified by user exists in this list
* if yes, column names are valid.
* if not, close resources used and throw exception
* if an SQL exception occurs while validating column names, close resources and throw an exception
* */
ResultSet columnResults =
metaData.getColumns(null, null, tableName, null);
List<String> resulsetColumns = new ArrayList<>();
while (columnResults.next()) {
resulsetColumns.add(columnResults.getString("COLUMN_NAME"));
}
columnNames.forEach(columnName -> {
if (!resulsetColumns.contains(columnName)) {
closeConnection();
throw new EventGenerationException("Column '" + columnName + "' does not exist in table '" +
tableName + "' in data source '" + dataSourceLocation + "'.");
}
});
} catch (SQLException e) {
log.error("Error occurred when validating whether the columns ' " +
columnNames + "' exists in table '" + tableName + "' in the data source '" +
dataSourceLocation + "'. ", e);
closeConnection();
throw new EventGenerationException("Error occurred when validating whether the columns ' " +
columnNames + "' exists in table '" + tableName + "' in the data source '" +
dataSourceLocation + "'. ", e);
}
return true;
}
/**
* PrepareSQLstatement() method creates the prepared statement needed to retrieve resultset
*
* @param tableName table from which data must be retrieved
* @param columnNames list of columns to be retrieved
* @param timestampAttribute column containing timestamp
* @param timestampStartTime least possible value for timestamp
* @param timestampEndTime maximum possible value for timestamp
*/
@SuppressWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
private void prepareSQLstatement(String tableName, List<String> columnNames, String timestampAttribute,
long timestampStartTime, long timestampEndTime) {
/*
* create a prepared statement based on the timestamp start time and timestamp end time provided
* if an exception occurs while creating the prepared statement close resources and throw an exception
* */
String columns = String.join(",", columnNames);
try {
if (timestampAttribute == null) {
this.preparedStatement = dbConnection.prepareStatement(String.format(query_interval, columns,
tableName));
} else {
if (timestampEndTime == -1) {
this.preparedStatement = dbConnection.prepareStatement(String.format(query_attribute_OnlyStartTime,
timestampAttribute, columns, tableName, timestampAttribute, timestampStartTime,
timestampAttribute));
} else {
this.preparedStatement = dbConnection.prepareStatement(String.format(query_attribute_WithBothLimits,
timestampAttribute, columns, tableName, timestampAttribute, timestampStartTime,
timestampAttribute, timestampEndTime, timestampAttribute));
}
}
} catch (SQLException e) {
log.error("Error occurred when forming prepared statement for the configuration table name : '" +
tableName + "', columns : '" + columns + "', timestamp attribute : '" + timestampAttribute + "', " +
"timestamp start time : '" + timestampStartTime + "' and timestamp end time : '" +
timestampEndTime + "'. ", e);
closeConnection();
throw new EventGenerationException("Error occurred when forming prepared statement for the configuration" +
"table name : '" + tableName + "', columns : '" + columns + "', timestamp attribute : '" +
timestampAttribute + "', timestamp start time : '" + timestampStartTime + "' and timestamp end " +
"time : '" + timestampEndTime + "'. ", e);
}
}
public static HikariDataSource initializeDatasource(DBConnectionModel connectionDetails) {
Properties connectionProperties = new Properties();
String url = connectionDetails.getDataSourceLocation();
String username = connectionDetails.getUsername();
String password = connectionDetails.getPassword();
String driverClassName = connectionDetails.getDriver();
connectionProperties.setProperty("jdbcUrl", url);
connectionProperties.setProperty("dataSource.user", username);
connectionProperties.setProperty("dataSource.password", password);
connectionProperties.setProperty("driverClassName", driverClassName);
HikariConfig config = new HikariConfig(connectionProperties);
return new HikariDataSource(config);
}
public static List<String> retrieveTableNames(DBConnectionModel connectionDetails)
throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
HikariDataSource dataSource = initializeDatasource(connectionDetails);
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
List<String> tableNames = new ArrayList<>();
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved table names from datasource '" +
connectionDetails.getDataSourceLocation() + "'.");
}
return tableNames;
}
}
public static List<String> retrieveColumnNames(DBConnectionModel connectionDetails, String tableName)
throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
HikariDataSource dataSource = initializeDatasource(connectionDetails);
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getColumns(null, null, tableName, null);
List<String> columnNames = new ArrayList<>();
while (rs.next()) {
columnNames.add(rs.getString("COLUMN_NAME"));
}
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved column names of table '" + tableName + "' from datasource '" +
connectionDetails.getDataSourceLocation() + "'.");
}
return columnNames;
}
}
/**
* closeConnection method releases the database sources acquired.
* <p>
* It performs the following tasks
* 1. Close resultset obtained by querying the database
* 2. Close prepared statement used to query the database
* 3. Close the database connection established
*/
public void closeConnection() {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
dataSource.close();
}
} catch (SQLException e) {
log.error("Error occurred when terminating database resources used for data source '" +
dataSourceLocation + "'. ", e);
throw new EventGenerationException("Error occurred when terminating database resources used for " +
"data source '" + dataSourceLocation + "'. ", e);
}
if (log.isDebugEnabled()) {
log.debug("Close resources used for data source '" + dataSourceLocation + "'");
}
}
}
|
|
package org.apache.solr.schema;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.FlagsAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.document.Field;
import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.AttributeSource.State;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.schema.PreAnalyzedField.ParseResult;
import org.apache.solr.schema.PreAnalyzedField.PreAnalyzedParser;
/**
* Simple plain text format parser for {@link PreAnalyzedField}.
* <h2>Serialization format</h2>
* <p>The format of the serialization is as follows:
* <pre>
* content ::= version (stored)? tokens
* version ::= digit+ " "
* ; stored field value - any "=" inside must be escaped!
* stored ::= "=" text "="
* tokens ::= (token ((" ") + token)*)*
* token ::= text ("," attrib)*
* attrib ::= name '=' value
* name ::= text
* value ::= text
* </pre>
* <p>Special characters in "text" values can be escaped
* using the escape character \ . The following escape sequences are recognized:
* <pre>
* "\ " - literal space character
* "\," - literal , character
* "\=" - literal = character
* "\\" - literal \ character
* "\n" - newline
* "\r" - carriage return
* "\t" - horizontal tab
* </pre>
* Please note that Unicode sequences (e.g. \u0001) are not supported.
* <h2>Supported attribute names</h2>
* The following token attributes are supported, and identified with short
* symbolic names:
* <pre>
* i - position increment (integer)
* s - token offset, start position (integer)
* e - token offset, end position (integer)
* t - token type (string)
* f - token flags (hexadecimal integer)
* p - payload (bytes in hexadecimal format)
* </pre>
* Token positions are tracked and implicitly added to the token stream -
* the start and end offsets consider only the term text and whitespace,
* and exclude the space taken by token attributes.
* <h2>Example token streams</h2>
* <pre>
* 1 one two three
- version 1
- stored: 'null'
- tok: '(term=one,startOffset=0,endOffset=3)'
- tok: '(term=two,startOffset=4,endOffset=7)'
- tok: '(term=three,startOffset=8,endOffset=13)'
1 one two three
- version 1
- stored: 'null'
- tok: '(term=one,startOffset=1,endOffset=4)'
- tok: '(term=two,startOffset=6,endOffset=9)'
- tok: '(term=three,startOffset=12,endOffset=17)'
1 one,s=123,e=128,i=22 two three,s=20,e=22
- version 1
- stored: 'null'
- tok: '(term=one,positionIncrement=22,startOffset=123,endOffset=128)'
- tok: '(term=two,positionIncrement=1,startOffset=5,endOffset=8)'
- tok: '(term=three,positionIncrement=1,startOffset=20,endOffset=22)'
1 \ one\ \,,i=22,a=\, two\=
\n,\ =\ \
- version 1
- stored: 'null'
- tok: '(term= one ,,positionIncrement=22,startOffset=0,endOffset=6)'
- tok: '(term=two=
,positionIncrement=1,startOffset=7,endOffset=15)'
- tok: '(term=\,positionIncrement=1,startOffset=17,endOffset=18)'
1 ,i=22 ,i=33,s=2,e=20 ,
- version 1
- stored: 'null'
- tok: '(term=,positionIncrement=22,startOffset=0,endOffset=0)'
- tok: '(term=,positionIncrement=33,startOffset=2,endOffset=20)'
- tok: '(term=,positionIncrement=1,startOffset=2,endOffset=2)'
1 =This is the stored part with \=
\n \t escapes.=one two three
- version 1
- stored: 'This is the stored part with =
\n \t escapes.'
- tok: '(term=one,startOffset=0,endOffset=3)'
- tok: '(term=two,startOffset=4,endOffset=7)'
- tok: '(term=three,startOffset=8,endOffset=13)'
1 ==
- version 1
- stored: ''
- (no tokens)
1 =this is a test.=
- version 1
- stored: 'this is a test.'
- (no tokens)
* </pre>
*/
public final class SimplePreAnalyzedParser implements PreAnalyzedParser {
static final String VERSION = "1";
private static class Tok {
StringBuilder token = new StringBuilder();
Map<String, String> attr = new HashMap<String, String>();
public boolean isEmpty() {
return token.length() == 0 && attr.size() == 0;
}
public void reset() {
token.setLength(0);
attr.clear();
}
@Override
public String toString() {
return "tok='" + token + "',attr=" + attr;
}
}
// parser state
private static enum S {TOKEN, NAME, VALUE, UNDEF};
private static final byte[] EMPTY_BYTES = new byte[0];
/** Utility method to convert byte array to a hex string. */
static byte[] hexToBytes(String hex) {
if (hex == null) {
return EMPTY_BYTES;
}
hex = hex.replaceAll("\\s+", "");
if (hex.length() == 0) {
return EMPTY_BYTES;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(hex.length() / 2);
byte b;
for (int i = 0; i < hex.length(); i++) {
int high = charToNibble(hex.charAt(i));
int low = 0;
if (i < hex.length() - 1) {
i++;
low = charToNibble(hex.charAt(i));
}
b = (byte)(high << 4 | low);
baos.write(b);
}
return baos.toByteArray();
}
static final int charToNibble(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return 0xa + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return 0xA + (c - 'A');
} else {
throw new RuntimeException("Not a hex character: '" + c + "'");
}
}
static String bytesToHex(byte bytes[], int offset, int length) {
StringBuilder sb = new StringBuilder();
for (int i = offset; i < offset + length; ++i) {
sb.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF))
.substring(1));
}
return sb.toString();
}
public SimplePreAnalyzedParser() {
}
@Override
public ParseResult parse(Reader reader, AttributeSource parent) throws IOException {
ParseResult res = new ParseResult();
StringBuilder sb = new StringBuilder();
char[] buf = new char[128];
int cnt;
while ((cnt = reader.read(buf)) > 0) {
sb.append(buf, 0, cnt);
}
String val = sb.toString();
// empty string - accept even without version number
if (val.length() == 0) {
return res;
}
// first consume the version
int idx = val.indexOf(' ');
if (idx == -1) {
throw new IOException("Missing VERSION token");
}
String version = val.substring(0, idx);
if (!VERSION.equals(version)) {
throw new IOException("Unknown VERSION " + version);
}
val = val.substring(idx + 1);
// then consume the optional stored part
int tsStart = 0;
boolean hasStored = false;
StringBuilder storedBuf = new StringBuilder();
if (val.charAt(0) == '=') {
hasStored = true;
if (val.length() > 1) {
for (int i = 1; i < val.length(); i++) {
char c = val.charAt(i);
if (c == '\\') {
if (i < val.length() - 1) {
c = val.charAt(++i);
if (c == '=') { // we recognize only \= escape in the stored part
storedBuf.append('=');
} else {
storedBuf.append('\\');
storedBuf.append(c);
continue;
}
} else {
storedBuf.append(c);
continue;
}
} else if (c == '=') {
// end of stored text
tsStart = i + 1;
break;
} else {
storedBuf.append(c);
}
}
if (tsStart == 0) { // missing end-of-stored marker
throw new IOException("Missing end marker of stored part");
}
} else {
throw new IOException("Unexpected end of stored field");
}
}
if (hasStored) {
res.str = storedBuf.toString();
}
Tok tok = new Tok();
StringBuilder attName = new StringBuilder();
StringBuilder attVal = new StringBuilder();
// parser state
S s = S.UNDEF;
int lastPos = 0;
for (int i = tsStart; i < val.length(); i++) {
char c = val.charAt(i);
if (c == ' ') {
// collect leftovers
switch (s) {
case VALUE :
if (attVal.length() == 0) {
throw new IOException("Unexpected character '" + c + "' at position " + i + " - empty value of attribute.");
}
if (attName.length() > 0) {
tok.attr.put(attName.toString(), attVal.toString());
}
break;
case NAME: // attr name without a value ?
if (attName.length() > 0) {
throw new IOException("Unexpected character '" + c + "' at position " + i + " - missing attribute value.");
} else {
// accept missing att name and value
}
break;
case TOKEN:
case UNDEF:
// do nothing, advance to next token
}
attName.setLength(0);
attVal.setLength(0);
if (!tok.isEmpty() || s == S.NAME) {
AttributeSource.State state = createState(parent, tok, lastPos);
if (state != null) res.states.add(state.clone());
}
// reset tok
s = S.UNDEF;
tok.reset();
// skip
lastPos++;
continue;
}
StringBuilder tgt = null;
switch (s) {
case TOKEN:
tgt = tok.token;
break;
case NAME:
tgt = attName;
break;
case VALUE:
tgt = attVal;
break;
case UNDEF:
tgt = tok.token;
s = S.TOKEN;
}
if (c == '\\') {
if (s == S.TOKEN) lastPos++;
if (i >= val.length() - 1) { // end
tgt.append(c);
continue;
} else {
c = val.charAt(++i);
switch (c) {
case '\\' :
case '=' :
case ',' :
case ' ' :
tgt.append(c);
break;
case 'n':
tgt.append('\n');
break;
case 'r':
tgt.append('\r');
break;
case 't':
tgt.append('\t');
break;
default:
tgt.append('\\');
tgt.append(c);
lastPos++;
}
}
} else {
// state switch
if (c == ',') {
if (s == S.TOKEN) {
s = S.NAME;
} else if (s == S.VALUE) { // end of value, start of next attr
if (attVal.length() == 0) {
throw new IOException("Unexpected character '" + c + "' at position " + i + " - empty value of attribute.");
}
if (attName.length() > 0 && attVal.length() > 0) {
tok.attr.put(attName.toString(), attVal.toString());
}
// reset
attName.setLength(0);
attVal.setLength(0);
s = S.NAME;
} else {
throw new IOException("Unexpected character '" + c + "' at position " + i + " - missing attribute value.");
}
} else if (c == '=') {
if (s == S.NAME) {
s = S.VALUE;
} else {
throw new IOException("Unexpected character '" + c + "' at position " + i + " - empty value of attribute.");
}
} else {
tgt.append(c);
if (s == S.TOKEN) lastPos++;
}
}
}
// collect leftovers
if (!tok.isEmpty() || s == S.NAME || s == S.VALUE) {
// remaining attrib?
if (s == S.VALUE) {
if (attName.length() > 0 && attVal.length() > 0) {
tok.attr.put(attName.toString(), attVal.toString());
}
}
AttributeSource.State state = createState(parent, tok, lastPos);
if (state != null) res.states.add(state.clone());
}
return res;
}
private static AttributeSource.State createState(AttributeSource a, Tok state, int tokenEnd) {
a.clearAttributes();
CharTermAttribute termAtt = a.addAttribute(CharTermAttribute.class);
char[] tokChars = state.token.toString().toCharArray();
termAtt.copyBuffer(tokChars, 0, tokChars.length);
int tokenStart = tokenEnd - state.token.length();
for (Entry<String, String> e : state.attr.entrySet()) {
String k = e.getKey();
if (k.equals("i")) {
// position increment
int incr = Integer.parseInt(e.getValue());
PositionIncrementAttribute posIncr = a.addAttribute(PositionIncrementAttribute.class);
posIncr.setPositionIncrement(incr);
} else if (k.equals("s")) {
tokenStart = Integer.parseInt(e.getValue());
} else if (k.equals("e")) {
tokenEnd = Integer.parseInt(e.getValue());
} else if (k.equals("y")) {
TypeAttribute type = a.addAttribute(TypeAttribute.class);
type.setType(e.getValue());
} else if (k.equals("f")) {
FlagsAttribute flags = a.addAttribute(FlagsAttribute.class);
int f = Integer.parseInt(e.getValue(), 16);
flags.setFlags(f);
} else if (k.equals("p")) {
PayloadAttribute p = a.addAttribute(PayloadAttribute.class);
byte[] data = hexToBytes(e.getValue());
if (data != null && data.length > 0) {
p.setPayload(new BytesRef(data));
}
} else {
// unknown attribute
}
}
// handle offset attr
OffsetAttribute offset = a.addAttribute(OffsetAttribute.class);
offset.setOffset(tokenStart, tokenEnd);
State resState = a.captureState();
a.clearAttributes();
return resState;
}
@Override
public String toFormattedString(Field f) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(VERSION + " ");
if (f.fieldType().stored()) {
String s = f.stringValue();
if (s != null) {
// encode the equals sign
s = s.replaceAll("=", "\\=");
sb.append('=');
sb.append(s);
sb.append('=');
}
}
TokenStream ts = f.tokenStreamValue();
if (ts != null) {
StringBuilder tok = new StringBuilder();
boolean next = false;
while (ts.incrementToken()) {
if (next) {
sb.append(' ');
} else {
next = true;
}
tok.setLength(0);
Iterator<Class<? extends Attribute>> it = ts.getAttributeClassesIterator();
String cTerm = null;
String tTerm = null;
while (it.hasNext()) {
Class<? extends Attribute> cl = it.next();
if (!ts.hasAttribute(cl)) {
continue;
}
Attribute att = ts.getAttribute(cl);
if (cl.isAssignableFrom(CharTermAttribute.class)) {
CharTermAttribute catt = (CharTermAttribute)att;
cTerm = escape(catt.buffer(), catt.length());
} else if (cl.isAssignableFrom(TermToBytesRefAttribute.class)) {
TermToBytesRefAttribute tatt = (TermToBytesRefAttribute)att;
char[] tTermChars = tatt.getBytesRef().utf8ToString().toCharArray();
tTerm = escape(tTermChars, tTermChars.length);
} else {
if (tok.length() > 0) tok.append(',');
if (cl.isAssignableFrom(FlagsAttribute.class)) {
tok.append("f=" + Integer.toHexString(((FlagsAttribute)att).getFlags()));
} else if (cl.isAssignableFrom(OffsetAttribute.class)) {
tok.append("s=" + ((OffsetAttribute)att).startOffset() + ",e=" + ((OffsetAttribute)att).endOffset());
} else if (cl.isAssignableFrom(PayloadAttribute.class)) {
BytesRef p = ((PayloadAttribute)att).getPayload();
if (p != null && p.length > 0) {
tok.append("p=" + bytesToHex(p.bytes, p.offset, p.length));
} else if (tok.length() > 0) {
tok.setLength(tok.length() - 1); // remove the last comma
}
} else if (cl.isAssignableFrom(PositionIncrementAttribute.class)) {
tok.append("i=" + ((PositionIncrementAttribute)att).getPositionIncrement());
} else if (cl.isAssignableFrom(TypeAttribute.class)) {
tok.append("y=" + escape(((TypeAttribute)att).type()));
} else {
tok.append(cl.getName() + "=" + escape(att.toString()));
}
}
}
String term = null;
if (cTerm != null) {
term = cTerm;
} else {
term = tTerm;
}
if (term != null && term.length() > 0) {
if (tok.length() > 0) {
tok.insert(0, term + ",");
} else {
tok.insert(0, term);
}
}
sb.append(tok);
}
}
return sb.toString();
}
String escape(String val) {
return escape(val.toCharArray(), val.length());
}
String escape(char[] val, int len) {
if (val == null || len == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
switch (val[i]) {
case '\\' :
case '=' :
case ',' :
case ' ' :
sb.append('\\');
sb.append(val[i]);
break;
case '\n' :
sb.append('\\');
sb.append('n');
break;
case '\r' :
sb.append('\\');
sb.append('r');
break;
case '\t' :
sb.append('\\');
sb.append('t');
break;
default:
sb.append(val[i]);
}
}
return sb.toString();
}
}
|
|
/* */ package com.elcuk.jaxb;
/* */
/* */ import java.math.BigInteger;
/* */ import java.util.ArrayList;
/* */ import java.util.List;
/* */ import javax.xml.bind.annotation.XmlAccessType;
/* */ import javax.xml.bind.annotation.XmlAccessorType;
/* */ import javax.xml.bind.annotation.XmlElement;
/* */ import javax.xml.bind.annotation.XmlRootElement;
/* */ import javax.xml.bind.annotation.XmlSchemaType;
/* */ import javax.xml.bind.annotation.XmlType;
/* */ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
/* */ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/* */ import javax.xml.datatype.XMLGregorianCalendar;
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"sku", "standardProductID", "gtinExemptionReason", "relatedProductID", "productTaxCode", "launchDate", "discontinueDate", "releaseDate", "externalProductUrl", "offAmazonChannel", "onAmazonChannel", "condition", "rebate", "itemPackageQuantity", "numberOfItems", "liquidVolume", "descriptionData", "promoTag", "discoveryData", "productData", "shippedByFreight", "enhancedImageURL", "amazonVendorOnly", "amazonOnly", "registeredParameter"})
/* */ @XmlRootElement(name="Product")
/* */ public class Product
/* */ {
/* */
/* */ @XmlElement(name="SKU", required=true)
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String sku;
/* */
/* */ @XmlElement(name="StandardProductID")
/* */ protected StandardProductID standardProductID;
/* */
/* */ @XmlElement(name="GtinExemptionReason")
/* */ protected String gtinExemptionReason;
/* */
/* */ @XmlElement(name="RelatedProductID")
/* */ protected RelatedProductID relatedProductID;
/* */
/* */ @XmlElement(name="ProductTaxCode")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String productTaxCode;
/* */
/* */ @XmlElement(name="LaunchDate")
/* */ @XmlSchemaType(name="dateTime")
/* */ protected XMLGregorianCalendar launchDate;
/* */
/* */ @XmlElement(name="DiscontinueDate")
/* */ @XmlSchemaType(name="dateTime")
/* */ protected XMLGregorianCalendar discontinueDate;
/* */
/* */ @XmlElement(name="ReleaseDate")
/* */ @XmlSchemaType(name="dateTime")
/* */ protected XMLGregorianCalendar releaseDate;
/* */
/* */ @XmlElement(name="ExternalProductUrl")
/* */ @XmlSchemaType(name="anyURI")
/* */ protected String externalProductUrl;
/* */
/* */ @XmlElement(name="OffAmazonChannel")
/* */ protected String offAmazonChannel;
/* */
/* */ @XmlElement(name="OnAmazonChannel")
/* */ protected String onAmazonChannel;
/* */
/* */ @XmlElement(name="Condition")
/* */ protected ConditionInfo condition;
/* */
/* */ @XmlElement(name="Rebate")
/* */ protected List<RebateType> rebate;
/* */
/* */ @XmlElement(name="ItemPackageQuantity")
/* */ @XmlSchemaType(name="positiveInteger")
/* */ protected BigInteger itemPackageQuantity;
/* */
/* */ @XmlElement(name="NumberOfItems")
/* */ @XmlSchemaType(name="positiveInteger")
/* */ protected BigInteger numberOfItems;
/* */
/* */ @XmlElement(name="LiquidVolume")
/* */ protected VolumeDimension liquidVolume;
/* */
/* */ @XmlElement(name="DescriptionData")
/* */ protected DescriptionData descriptionData;
/* */
/* */ @XmlElement(name="PromoTag")
/* */ protected PromoTag promoTag;
/* */
/* */ @XmlElement(name="DiscoveryData")
/* */ protected DiscoveryData discoveryData;
/* */
/* */ @XmlElement(name="ProductData")
/* */ protected ProductData productData;
/* */
/* */ @XmlElement(name="ShippedByFreight")
/* */ protected Boolean shippedByFreight;
/* */
/* */ @XmlElement(name="EnhancedImageURL")
/* */ @XmlSchemaType(name="anyURI")
/* */ protected List<String> enhancedImageURL;
/* */
/* */ @XmlElement(name="Amazon-Vendor-Only")
/* */ protected AmazonVendorOnly amazonVendorOnly;
/* */
/* */ @XmlElement(name="Amazon-Only")
/* */ protected AmazonOnly amazonOnly;
/* */
/* */ @XmlElement(name="RegisteredParameter")
/* */ protected String registeredParameter;
/* */
/* */ public String getSKU()
/* */ {
/* 418 */ return this.sku;
/* */ }
/* */
/* */ public void setSKU(String value)
/* */ {
/* 430 */ this.sku = value;
/* */ }
/* */
/* */ public StandardProductID getStandardProductID()
/* */ {
/* 442 */ return this.standardProductID;
/* */ }
/* */
/* */ public void setStandardProductID(StandardProductID value)
/* */ {
/* 454 */ this.standardProductID = value;
/* */ }
/* */
/* */ public String getGtinExemptionReason()
/* */ {
/* 466 */ return this.gtinExemptionReason;
/* */ }
/* */
/* */ public void setGtinExemptionReason(String value)
/* */ {
/* 478 */ this.gtinExemptionReason = value;
/* */ }
/* */
/* */ public RelatedProductID getRelatedProductID()
/* */ {
/* 490 */ return this.relatedProductID;
/* */ }
/* */
/* */ public void setRelatedProductID(RelatedProductID value)
/* */ {
/* 502 */ this.relatedProductID = value;
/* */ }
/* */
/* */ public String getProductTaxCode()
/* */ {
/* 514 */ return this.productTaxCode;
/* */ }
/* */
/* */ public void setProductTaxCode(String value)
/* */ {
/* 526 */ this.productTaxCode = value;
/* */ }
/* */
/* */ public XMLGregorianCalendar getLaunchDate()
/* */ {
/* 538 */ return this.launchDate;
/* */ }
/* */
/* */ public void setLaunchDate(XMLGregorianCalendar value)
/* */ {
/* 550 */ this.launchDate = value;
/* */ }
/* */
/* */ public XMLGregorianCalendar getDiscontinueDate()
/* */ {
/* 562 */ return this.discontinueDate;
/* */ }
/* */
/* */ public void setDiscontinueDate(XMLGregorianCalendar value)
/* */ {
/* 574 */ this.discontinueDate = value;
/* */ }
/* */
/* */ public XMLGregorianCalendar getReleaseDate()
/* */ {
/* 586 */ return this.releaseDate;
/* */ }
/* */
/* */ public void setReleaseDate(XMLGregorianCalendar value)
/* */ {
/* 598 */ this.releaseDate = value;
/* */ }
/* */
/* */ public String getExternalProductUrl()
/* */ {
/* 610 */ return this.externalProductUrl;
/* */ }
/* */
/* */ public void setExternalProductUrl(String value)
/* */ {
/* 622 */ this.externalProductUrl = value;
/* */ }
/* */
/* */ public String getOffAmazonChannel()
/* */ {
/* 634 */ return this.offAmazonChannel;
/* */ }
/* */
/* */ public void setOffAmazonChannel(String value)
/* */ {
/* 646 */ this.offAmazonChannel = value;
/* */ }
/* */
/* */ public String getOnAmazonChannel()
/* */ {
/* 658 */ return this.onAmazonChannel;
/* */ }
/* */
/* */ public void setOnAmazonChannel(String value)
/* */ {
/* 670 */ this.onAmazonChannel = value;
/* */ }
/* */
/* */ public ConditionInfo getCondition()
/* */ {
/* 682 */ return this.condition;
/* */ }
/* */
/* */ public void setCondition(ConditionInfo value)
/* */ {
/* 694 */ this.condition = value;
/* */ }
/* */
/* */ public List<RebateType> getRebate()
/* */ {
/* 720 */ if (this.rebate == null) {
/* 721 */ this.rebate = new ArrayList();
/* */ }
/* 723 */ return this.rebate;
/* */ }
/* */
/* */ public BigInteger getItemPackageQuantity()
/* */ {
/* 735 */ return this.itemPackageQuantity;
/* */ }
/* */
/* */ public void setItemPackageQuantity(BigInteger value)
/* */ {
/* 747 */ this.itemPackageQuantity = value;
/* */ }
/* */
/* */ public BigInteger getNumberOfItems()
/* */ {
/* 759 */ return this.numberOfItems;
/* */ }
/* */
/* */ public void setNumberOfItems(BigInteger value)
/* */ {
/* 771 */ this.numberOfItems = value;
/* */ }
/* */
/* */ public VolumeDimension getLiquidVolume()
/* */ {
/* 783 */ return this.liquidVolume;
/* */ }
/* */
/* */ public void setLiquidVolume(VolumeDimension value)
/* */ {
/* 795 */ this.liquidVolume = value;
/* */ }
/* */
/* */ public DescriptionData getDescriptionData()
/* */ {
/* 807 */ return this.descriptionData;
/* */ }
/* */
/* */ public void setDescriptionData(DescriptionData value)
/* */ {
/* 819 */ this.descriptionData = value;
/* */ }
/* */
/* */ public PromoTag getPromoTag()
/* */ {
/* 831 */ return this.promoTag;
/* */ }
/* */
/* */ public void setPromoTag(PromoTag value)
/* */ {
/* 843 */ this.promoTag = value;
/* */ }
/* */
/* */ public DiscoveryData getDiscoveryData()
/* */ {
/* 855 */ return this.discoveryData;
/* */ }
/* */
/* */ public void setDiscoveryData(DiscoveryData value)
/* */ {
/* 867 */ this.discoveryData = value;
/* */ }
/* */
/* */ public ProductData getProductData()
/* */ {
/* 879 */ return this.productData;
/* */ }
/* */
/* */ public void setProductData(ProductData value)
/* */ {
/* 891 */ this.productData = value;
/* */ }
/* */
/* */ public Boolean isShippedByFreight()
/* */ {
/* 903 */ return this.shippedByFreight;
/* */ }
/* */
/* */ public void setShippedByFreight(Boolean value)
/* */ {
/* 915 */ this.shippedByFreight = value;
/* */ }
/* */
/* */ public List<String> getEnhancedImageURL()
/* */ {
/* 941 */ if (this.enhancedImageURL == null) {
/* 942 */ this.enhancedImageURL = new ArrayList();
/* */ }
/* 944 */ return this.enhancedImageURL;
/* */ }
/* */
/* */ public AmazonVendorOnly getAmazonVendorOnly()
/* */ {
/* 956 */ return this.amazonVendorOnly;
/* */ }
/* */
/* */ public void setAmazonVendorOnly(AmazonVendorOnly value)
/* */ {
/* 968 */ this.amazonVendorOnly = value;
/* */ }
/* */
/* */ public AmazonOnly getAmazonOnly()
/* */ {
/* 980 */ return this.amazonOnly;
/* */ }
/* */
/* */ public void setAmazonOnly(AmazonOnly value)
/* */ {
/* 992 */ this.amazonOnly = value;
/* */ }
/* */
/* */ public String getRegisteredParameter()
/* */ {
/* 1004 */ return this.registeredParameter;
/* */ }
/* */
/* */ public void setRegisteredParameter(String value)
/* */ {
/* 1016 */ this.registeredParameter = value;
/* */ }
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"promoTagType", "effectiveFromDate", "effectiveThroughDate"})
/* */ public static class PromoTag
/* */ {
/* */
/* */ @XmlElement(name="PromoTagType", required=true)
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String promoTagType;
/* */
/* */ @XmlElement(name="EffectiveFromDate", required=true)
/* */ @XmlSchemaType(name="date")
/* */ protected XMLGregorianCalendar effectiveFromDate;
/* */
/* */ @XmlElement(name="EffectiveThroughDate")
/* */ @XmlSchemaType(name="date")
/* */ protected XMLGregorianCalendar effectiveThroughDate;
/* */
/* */ public String getPromoTagType()
/* */ {
/* 3029 */ return this.promoTagType;
/* */ }
/* */
/* */ public void setPromoTagType(String value)
/* */ {
/* 3041 */ this.promoTagType = value;
/* */ }
/* */
/* */ public XMLGregorianCalendar getEffectiveFromDate()
/* */ {
/* 3053 */ return this.effectiveFromDate;
/* */ }
/* */
/* */ public void setEffectiveFromDate(XMLGregorianCalendar value)
/* */ {
/* 3065 */ this.effectiveFromDate = value;
/* */ }
/* */
/* */ public XMLGregorianCalendar getEffectiveThroughDate()
/* */ {
/* 3077 */ return this.effectiveThroughDate;
/* */ }
/* */
/* */ public void setEffectiveThroughDate(XMLGregorianCalendar value)
/* */ {
/* 3089 */ this.effectiveThroughDate = value;
/* */ }
/* */ }
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"home", "sports", "homeImprovement", "tools", "ce", "computers", "softwareVideoGames", "wireless", "lighting"})
/* */ public static class ProductData
/* */ {
/* */
/* */ @XmlElement(name="Home")
/* */ protected Home home;
/* */
/* */ @XmlElement(name="Sports")
/* */ protected Sports sports;
/* */
/* */ @XmlElement(name="HomeImprovement")
/* */ protected HomeImprovement homeImprovement;
/* */
/* */ @XmlElement(name="Tools")
/* */ protected Tools tools;
/* */
/* */ @XmlElement(name="CE")
/* */ protected CE ce;
/* */
/* */ @XmlElement(name="Computers")
/* */ protected Computers computers;
/* */
/* */ @XmlElement(name="SoftwareVideoGames")
/* */ protected SoftwareVideoGames softwareVideoGames;
/* */
/* */ @XmlElement(name="Wireless")
/* */ protected Wireless wireless;
/* */
/* */ @XmlElement(name="Lighting")
/* */ protected Lighting lighting;
/* */
/* */ public Home getHome()
/* */ {
/* 2757 */ return this.home;
/* */ }
/* */
/* */ public void setHome(Home value)
/* */ {
/* 2769 */ this.home = value;
/* */ }
/* */
/* */ public Sports getSports()
/* */ {
/* 2781 */ return this.sports;
/* */ }
/* */
/* */ public void setSports(Sports value)
/* */ {
/* 2793 */ this.sports = value;
/* */ }
/* */
/* */ public HomeImprovement getHomeImprovement()
/* */ {
/* 2805 */ return this.homeImprovement;
/* */ }
/* */
/* */ public void setHomeImprovement(HomeImprovement value)
/* */ {
/* 2817 */ this.homeImprovement = value;
/* */ }
/* */
/* */ public Tools getTools()
/* */ {
/* 2829 */ return this.tools;
/* */ }
/* */
/* */ public void setTools(Tools value)
/* */ {
/* 2841 */ this.tools = value;
/* */ }
/* */
/* */ public CE getCE()
/* */ {
/* 2853 */ return this.ce;
/* */ }
/* */
/* */ public void setCE(CE value)
/* */ {
/* 2865 */ this.ce = value;
/* */ }
/* */
/* */ public Computers getComputers()
/* */ {
/* 2877 */ return this.computers;
/* */ }
/* */
/* */ public void setComputers(Computers value)
/* */ {
/* 2889 */ this.computers = value;
/* */ }
/* */
/* */ public SoftwareVideoGames getSoftwareVideoGames()
/* */ {
/* 2901 */ return this.softwareVideoGames;
/* */ }
/* */
/* */ public void setSoftwareVideoGames(SoftwareVideoGames value)
/* */ {
/* 2913 */ this.softwareVideoGames = value;
/* */ }
/* */
/* */ public Wireless getWireless()
/* */ {
/* 2925 */ return this.wireless;
/* */ }
/* */
/* */ public void setWireless(Wireless value)
/* */ {
/* 2937 */ this.wireless = value;
/* */ }
/* */
/* */ public Lighting getLighting()
/* */ {
/* 2949 */ return this.lighting;
/* */ }
/* */
/* */ public void setLighting(Lighting value)
/* */ {
/* 2961 */ this.lighting = value;
/* */ }
/* */ }
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"priority", "browseExclusion", "recommendationExclusion"})
/* */ public static class DiscoveryData
/* */ {
/* */
/* */ @XmlElement(name="Priority")
/* */ protected Integer priority;
/* */
/* */ @XmlElement(name="BrowseExclusion")
/* */ protected Boolean browseExclusion;
/* */
/* */ @XmlElement(name="RecommendationExclusion")
/* */ protected Boolean recommendationExclusion;
/* */
/* */ public Integer getPriority()
/* */ {
/* 2622 */ return this.priority;
/* */ }
/* */
/* */ public void setPriority(Integer value)
/* */ {
/* 2634 */ this.priority = value;
/* */ }
/* */
/* */ public Boolean isBrowseExclusion()
/* */ {
/* 2646 */ return this.browseExclusion;
/* */ }
/* */
/* */ public void setBrowseExclusion(Boolean value)
/* */ {
/* 2658 */ this.browseExclusion = value;
/* */ }
/* */
/* */ public Boolean isRecommendationExclusion()
/* */ {
/* 2670 */ return this.recommendationExclusion;
/* */ }
/* */
/* */ public void setRecommendationExclusion(Boolean value)
/* */ {
/* 2682 */ this.recommendationExclusion = value;
/* */ }
/* */ }
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"title", "brand", "designer", "description", "bulletPoint", "itemDimensions", "packageDimensions", "packageWeight", "shippingWeight", "merchantCatalogNumber", "msrp", "msrpWithTax", "maxOrderQuantity", "serialNumberRequired", "prop65", "cpsiaWarning", "cpsiaWarningDescription", "legalDisclaimer", "manufacturer", "mfrPartNumber", "searchTerms", "platinumKeywords", "memorabilia", "autographed", "usedFor", "itemType", "otherItemAttributes", "targetAudience", "subjectContent", "isGiftWrapAvailable", "isGiftMessageAvailable", "promotionKeywords", "isDiscontinuedByManufacturer", "deliveryScheduleGroupID", "deliveryChannel", "purchasingChannel", "maxAggregateShipQuantity", "isCustomizable", "customizableTemplateName", "recommendedBrowseNode", "merchantShippingGroupName", "fedasid", "tsdAgeWarning", "tsdWarning", "tsdLanguage", "optionalPaymentTypeExclusion", "distributionDesignation"})
/* */ public static class DescriptionData
/* */ {
/* */
/* */ @XmlElement(name="Title", required=true)
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String title;
/* */
/* */ @XmlElement(name="Brand")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String brand;
/* */
/* */ @XmlElement(name="Designer")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String designer;
/* */
/* */ @XmlElement(name="Description")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String description;
/* */
/* */ @XmlElement(name="BulletPoint")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> bulletPoint;
/* */
/* */ @XmlElement(name="ItemDimensions")
/* */ protected Dimensions itemDimensions;
/* */
/* */ @XmlElement(name="PackageDimensions")
/* */ protected Dimensions packageDimensions;
/* */
/* */ @XmlElement(name="PackageWeight")
/* */ protected PositiveWeightDimension packageWeight;
/* */
/* */ @XmlElement(name="ShippingWeight")
/* */ protected PositiveWeightDimension shippingWeight;
/* */
/* */ @XmlElement(name="MerchantCatalogNumber")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String merchantCatalogNumber;
/* */
/* */ @XmlElement(name="MSRP")
/* */ protected CurrencyAmount msrp;
/* */
/* */ @XmlElement(name="MSRPWithTax")
/* */ protected CurrencyAmount msrpWithTax;
/* */
/* */ @XmlElement(name="MaxOrderQuantity")
/* */ @XmlSchemaType(name="positiveInteger")
/* */ protected BigInteger maxOrderQuantity;
/* */
/* */ @XmlElement(name="SerialNumberRequired")
/* */ protected Boolean serialNumberRequired;
/* */
/* */ @XmlElement(name="Prop65")
/* */ protected Boolean prop65;
/* */
/* */ @XmlElement(name="CPSIAWarning")
/* */ protected List<String> cpsiaWarning;
/* */
/* */ @XmlElement(name="CPSIAWarningDescription")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String cpsiaWarningDescription;
/* */
/* */ @XmlElement(name="LegalDisclaimer")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String legalDisclaimer;
/* */
/* */ @XmlElement(name="Manufacturer")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String manufacturer;
/* */
/* */ @XmlElement(name="MfrPartNumber")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String mfrPartNumber;
/* */
/* */ @XmlElement(name="SearchTerms")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> searchTerms;
/* */
/* */ @XmlElement(name="PlatinumKeywords")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> platinumKeywords;
/* */
/* */ @XmlElement(name="Memorabilia")
/* */ protected Boolean memorabilia;
/* */
/* */ @XmlElement(name="Autographed")
/* */ protected Boolean autographed;
/* */
/* */ @XmlElement(name="UsedFor")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> usedFor;
/* */
/* */ @XmlElement(name="ItemType")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String itemType;
/* */
/* */ @XmlElement(name="OtherItemAttributes")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> otherItemAttributes;
/* */
/* */ @XmlElement(name="TargetAudience")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> targetAudience;
/* */
/* */ @XmlElement(name="SubjectContent")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> subjectContent;
/* */
/* */ @XmlElement(name="IsGiftWrapAvailable")
/* */ protected Boolean isGiftWrapAvailable;
/* */
/* */ @XmlElement(name="IsGiftMessageAvailable")
/* */ protected Boolean isGiftMessageAvailable;
/* */
/* */ @XmlElement(name="PromotionKeywords")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected List<String> promotionKeywords;
/* */
/* */ @XmlElement(name="IsDiscontinuedByManufacturer")
/* */ protected Boolean isDiscontinuedByManufacturer;
/* */
/* */ @XmlElement(name="DeliveryScheduleGroupID")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String deliveryScheduleGroupID;
/* */
/* */ @XmlElement(name="DeliveryChannel")
/* */ protected List<String> deliveryChannel;
/* */
/* */ @XmlElement(name="PurchasingChannel")
/* */ protected List<String> purchasingChannel;
/* */
/* */ @XmlElement(name="MaxAggregateShipQuantity")
/* */ @XmlSchemaType(name="positiveInteger")
/* */ protected BigInteger maxAggregateShipQuantity;
/* */
/* */ @XmlElement(name="IsCustomizable")
/* */ protected Boolean isCustomizable;
/* */
/* */ @XmlElement(name="CustomizableTemplateName")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String customizableTemplateName;
/* */
/* */ @XmlElement(name="RecommendedBrowseNode")
/* */ @XmlSchemaType(name="positiveInteger")
/* */ protected List<BigInteger> recommendedBrowseNode;
/* */
/* */ @XmlElement(name="MerchantShippingGroupName")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String merchantShippingGroupName;
/* */
/* */ @XmlElement(name="FEDAS_ID")
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String fedasid;
/* */
/* */ @XmlElement(name="TSDAgeWarning")
/* */ protected String tsdAgeWarning;
/* */
/* */ @XmlElement(name="TSDWarning")
/* */ protected List<String> tsdWarning;
/* */
/* */ @XmlElement(name="TSDLanguage")
/* */ protected List<String> tsdLanguage;
/* */
/* */ @XmlElement(name="OptionalPaymentTypeExclusion")
/* */ protected List<String> optionalPaymentTypeExclusion;
/* */
/* */ @XmlElement(name="DistributionDesignation")
/* */ protected DistributionDesignationValues distributionDesignation;
/* */
/* */ public String getTitle()
/* */ {
/* 1373 */ return this.title;
/* */ }
/* */
/* */ public void setTitle(String value)
/* */ {
/* 1385 */ this.title = value;
/* */ }
/* */
/* */ public String getBrand()
/* */ {
/* 1397 */ return this.brand;
/* */ }
/* */
/* */ public void setBrand(String value)
/* */ {
/* 1409 */ this.brand = value;
/* */ }
/* */
/* */ public String getDesigner()
/* */ {
/* 1421 */ return this.designer;
/* */ }
/* */
/* */ public void setDesigner(String value)
/* */ {
/* 1433 */ this.designer = value;
/* */ }
/* */
/* */ public String getDescription()
/* */ {
/* 1445 */ return this.description;
/* */ }
/* */
/* */ public void setDescription(String value)
/* */ {
/* 1457 */ this.description = value;
/* */ }
/* */
/* */ public List<String> getBulletPoint()
/* */ {
/* 1483 */ if (this.bulletPoint == null) {
/* 1484 */ this.bulletPoint = new ArrayList();
/* */ }
/* 1486 */ return this.bulletPoint;
/* */ }
/* */
/* */ public Dimensions getItemDimensions()
/* */ {
/* 1498 */ return this.itemDimensions;
/* */ }
/* */
/* */ public void setItemDimensions(Dimensions value)
/* */ {
/* 1510 */ this.itemDimensions = value;
/* */ }
/* */
/* */ public Dimensions getPackageDimensions()
/* */ {
/* 1522 */ return this.packageDimensions;
/* */ }
/* */
/* */ public void setPackageDimensions(Dimensions value)
/* */ {
/* 1534 */ this.packageDimensions = value;
/* */ }
/* */
/* */ public PositiveWeightDimension getPackageWeight()
/* */ {
/* 1546 */ return this.packageWeight;
/* */ }
/* */
/* */ public void setPackageWeight(PositiveWeightDimension value)
/* */ {
/* 1558 */ this.packageWeight = value;
/* */ }
/* */
/* */ public PositiveWeightDimension getShippingWeight()
/* */ {
/* 1570 */ return this.shippingWeight;
/* */ }
/* */
/* */ public void setShippingWeight(PositiveWeightDimension value)
/* */ {
/* 1582 */ this.shippingWeight = value;
/* */ }
/* */
/* */ public String getMerchantCatalogNumber()
/* */ {
/* 1594 */ return this.merchantCatalogNumber;
/* */ }
/* */
/* */ public void setMerchantCatalogNumber(String value)
/* */ {
/* 1606 */ this.merchantCatalogNumber = value;
/* */ }
/* */
/* */ public CurrencyAmount getMSRP()
/* */ {
/* 1618 */ return this.msrp;
/* */ }
/* */
/* */ public void setMSRP(CurrencyAmount value)
/* */ {
/* 1630 */ this.msrp = value;
/* */ }
/* */
/* */ public CurrencyAmount getMSRPWithTax()
/* */ {
/* 1642 */ return this.msrpWithTax;
/* */ }
/* */
/* */ public void setMSRPWithTax(CurrencyAmount value)
/* */ {
/* 1654 */ this.msrpWithTax = value;
/* */ }
/* */
/* */ public BigInteger getMaxOrderQuantity()
/* */ {
/* 1666 */ return this.maxOrderQuantity;
/* */ }
/* */
/* */ public void setMaxOrderQuantity(BigInteger value)
/* */ {
/* 1678 */ this.maxOrderQuantity = value;
/* */ }
/* */
/* */ public Boolean isSerialNumberRequired()
/* */ {
/* 1690 */ return this.serialNumberRequired;
/* */ }
/* */
/* */ public void setSerialNumberRequired(Boolean value)
/* */ {
/* 1702 */ this.serialNumberRequired = value;
/* */ }
/* */
/* */ public Boolean isProp65()
/* */ {
/* 1714 */ return this.prop65;
/* */ }
/* */
/* */ public void setProp65(Boolean value)
/* */ {
/* 1726 */ this.prop65 = value;
/* */ }
/* */
/* */ public List<String> getCPSIAWarning()
/* */ {
/* 1752 */ if (this.cpsiaWarning == null) {
/* 1753 */ this.cpsiaWarning = new ArrayList();
/* */ }
/* 1755 */ return this.cpsiaWarning;
/* */ }
/* */
/* */ public String getCPSIAWarningDescription()
/* */ {
/* 1767 */ return this.cpsiaWarningDescription;
/* */ }
/* */
/* */ public void setCPSIAWarningDescription(String value)
/* */ {
/* 1779 */ this.cpsiaWarningDescription = value;
/* */ }
/* */
/* */ public String getLegalDisclaimer()
/* */ {
/* 1791 */ return this.legalDisclaimer;
/* */ }
/* */
/* */ public void setLegalDisclaimer(String value)
/* */ {
/* 1803 */ this.legalDisclaimer = value;
/* */ }
/* */
/* */ public String getManufacturer()
/* */ {
/* 1815 */ return this.manufacturer;
/* */ }
/* */
/* */ public void setManufacturer(String value)
/* */ {
/* 1827 */ this.manufacturer = value;
/* */ }
/* */
/* */ public String getMfrPartNumber()
/* */ {
/* 1839 */ return this.mfrPartNumber;
/* */ }
/* */
/* */ public void setMfrPartNumber(String value)
/* */ {
/* 1851 */ this.mfrPartNumber = value;
/* */ }
/* */
/* */ public List<String> getSearchTerms()
/* */ {
/* 1877 */ if (this.searchTerms == null) {
/* 1878 */ this.searchTerms = new ArrayList();
/* */ }
/* 1880 */ return this.searchTerms;
/* */ }
/* */
/* */ public List<String> getPlatinumKeywords()
/* */ {
/* 1906 */ if (this.platinumKeywords == null) {
/* 1907 */ this.platinumKeywords = new ArrayList();
/* */ }
/* 1909 */ return this.platinumKeywords;
/* */ }
/* */
/* */ public Boolean isMemorabilia()
/* */ {
/* 1921 */ return this.memorabilia;
/* */ }
/* */
/* */ public void setMemorabilia(Boolean value)
/* */ {
/* 1933 */ this.memorabilia = value;
/* */ }
/* */
/* */ public Boolean isAutographed()
/* */ {
/* 1945 */ return this.autographed;
/* */ }
/* */
/* */ public void setAutographed(Boolean value)
/* */ {
/* 1957 */ this.autographed = value;
/* */ }
/* */
/* */ public List<String> getUsedFor()
/* */ {
/* 1983 */ if (this.usedFor == null) {
/* 1984 */ this.usedFor = new ArrayList();
/* */ }
/* 1986 */ return this.usedFor;
/* */ }
/* */
/* */ public String getItemType()
/* */ {
/* 1998 */ return this.itemType;
/* */ }
/* */
/* */ public void setItemType(String value)
/* */ {
/* 2010 */ this.itemType = value;
/* */ }
/* */
/* */ public List<String> getOtherItemAttributes()
/* */ {
/* 2036 */ if (this.otherItemAttributes == null) {
/* 2037 */ this.otherItemAttributes = new ArrayList();
/* */ }
/* 2039 */ return this.otherItemAttributes;
/* */ }
/* */
/* */ public List<String> getTargetAudience()
/* */ {
/* 2065 */ if (this.targetAudience == null) {
/* 2066 */ this.targetAudience = new ArrayList();
/* */ }
/* 2068 */ return this.targetAudience;
/* */ }
/* */
/* */ public List<String> getSubjectContent()
/* */ {
/* 2094 */ if (this.subjectContent == null) {
/* 2095 */ this.subjectContent = new ArrayList();
/* */ }
/* 2097 */ return this.subjectContent;
/* */ }
/* */
/* */ public Boolean isIsGiftWrapAvailable()
/* */ {
/* 2109 */ return this.isGiftWrapAvailable;
/* */ }
/* */
/* */ public void setIsGiftWrapAvailable(Boolean value)
/* */ {
/* 2121 */ this.isGiftWrapAvailable = value;
/* */ }
/* */
/* */ public Boolean isIsGiftMessageAvailable()
/* */ {
/* 2133 */ return this.isGiftMessageAvailable;
/* */ }
/* */
/* */ public void setIsGiftMessageAvailable(Boolean value)
/* */ {
/* 2145 */ this.isGiftMessageAvailable = value;
/* */ }
/* */
/* */ public List<String> getPromotionKeywords()
/* */ {
/* 2171 */ if (this.promotionKeywords == null) {
/* 2172 */ this.promotionKeywords = new ArrayList();
/* */ }
/* 2174 */ return this.promotionKeywords;
/* */ }
/* */
/* */ public Boolean isIsDiscontinuedByManufacturer()
/* */ {
/* 2186 */ return this.isDiscontinuedByManufacturer;
/* */ }
/* */
/* */ public void setIsDiscontinuedByManufacturer(Boolean value)
/* */ {
/* 2198 */ this.isDiscontinuedByManufacturer = value;
/* */ }
/* */
/* */ public String getDeliveryScheduleGroupID()
/* */ {
/* 2210 */ return this.deliveryScheduleGroupID;
/* */ }
/* */
/* */ public void setDeliveryScheduleGroupID(String value)
/* */ {
/* 2222 */ this.deliveryScheduleGroupID = value;
/* */ }
/* */
/* */ public List<String> getDeliveryChannel()
/* */ {
/* 2248 */ if (this.deliveryChannel == null) {
/* 2249 */ this.deliveryChannel = new ArrayList();
/* */ }
/* 2251 */ return this.deliveryChannel;
/* */ }
/* */
/* */ public List<String> getPurchasingChannel()
/* */ {
/* 2277 */ if (this.purchasingChannel == null) {
/* 2278 */ this.purchasingChannel = new ArrayList();
/* */ }
/* 2280 */ return this.purchasingChannel;
/* */ }
/* */
/* */ public BigInteger getMaxAggregateShipQuantity()
/* */ {
/* 2292 */ return this.maxAggregateShipQuantity;
/* */ }
/* */
/* */ public void setMaxAggregateShipQuantity(BigInteger value)
/* */ {
/* 2304 */ this.maxAggregateShipQuantity = value;
/* */ }
/* */
/* */ public Boolean isIsCustomizable()
/* */ {
/* 2316 */ return this.isCustomizable;
/* */ }
/* */
/* */ public void setIsCustomizable(Boolean value)
/* */ {
/* 2328 */ this.isCustomizable = value;
/* */ }
/* */
/* */ public String getCustomizableTemplateName()
/* */ {
/* 2340 */ return this.customizableTemplateName;
/* */ }
/* */
/* */ public void setCustomizableTemplateName(String value)
/* */ {
/* 2352 */ this.customizableTemplateName = value;
/* */ }
/* */
/* */ public List<BigInteger> getRecommendedBrowseNode()
/* */ {
/* 2378 */ if (this.recommendedBrowseNode == null) {
/* 2379 */ this.recommendedBrowseNode = new ArrayList();
/* */ }
/* 2381 */ return this.recommendedBrowseNode;
/* */ }
/* */
/* */ public String getMerchantShippingGroupName()
/* */ {
/* 2393 */ return this.merchantShippingGroupName;
/* */ }
/* */
/* */ public void setMerchantShippingGroupName(String value)
/* */ {
/* 2405 */ this.merchantShippingGroupName = value;
/* */ }
/* */
/* */ public String getFEDASID()
/* */ {
/* 2417 */ return this.fedasid;
/* */ }
/* */
/* */ public void setFEDASID(String value)
/* */ {
/* 2429 */ this.fedasid = value;
/* */ }
/* */
/* */ public String getTSDAgeWarning()
/* */ {
/* 2441 */ return this.tsdAgeWarning;
/* */ }
/* */
/* */ public void setTSDAgeWarning(String value)
/* */ {
/* 2453 */ this.tsdAgeWarning = value;
/* */ }
/* */
/* */ public List<String> getTSDWarning()
/* */ {
/* 2479 */ if (this.tsdWarning == null) {
/* 2480 */ this.tsdWarning = new ArrayList();
/* */ }
/* 2482 */ return this.tsdWarning;
/* */ }
/* */
/* */ public List<String> getTSDLanguage()
/* */ {
/* 2508 */ if (this.tsdLanguage == null) {
/* 2509 */ this.tsdLanguage = new ArrayList();
/* */ }
/* 2511 */ return this.tsdLanguage;
/* */ }
/* */
/* */ public List<String> getOptionalPaymentTypeExclusion()
/* */ {
/* 2537 */ if (this.optionalPaymentTypeExclusion == null) {
/* 2538 */ this.optionalPaymentTypeExclusion = new ArrayList();
/* */ }
/* 2540 */ return this.optionalPaymentTypeExclusion;
/* */ }
/* */
/* */ public DistributionDesignationValues getDistributionDesignation()
/* */ {
/* 2552 */ return this.distributionDesignation;
/* */ }
/* */
/* */ public void setDistributionDesignation(DistributionDesignationValues value)
/* */ {
/* 2564 */ this.distributionDesignation = value;
/* */ }
/* */ }
/* */ }
/* Location: /Users/mac/Desktop/jaxb/
* Qualified Name: com.elcuk.jaxb.Product
* JD-Core Version: 0.6.2
*/
|
|
/**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;
// Start of user code for imports
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.context.impl.EObjectPropertiesEditionContext;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;
import org.eclipse.emf.eef.runtime.policies.PropertiesEditingPolicy;
import org.eclipse.emf.eef.runtime.providers.PropertiesEditingProvider;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable;
import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener;
import org.eclipse.emf.eef.runtime.ui.widgets.TabElementTreeSelectionDialog;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class BeanMediatorInputConnectorPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, BeanMediatorInputConnectorPropertiesEditionPart {
protected ReferencesTable incomingLinks;
protected List<ViewerFilter> incomingLinksBusinessFilters = new ArrayList<ViewerFilter>();
protected List<ViewerFilter> incomingLinksFilters = new ArrayList<ViewerFilter>();
/**
* For {@link ISection} use only.
*/
public BeanMediatorInputConnectorPropertiesEditionPartForm() { super(); }
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public BeanMediatorInputConnectorPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence beanMediatorInputConnectorStep = new BindingCompositionSequence(propertiesEditionComponent);
beanMediatorInputConnectorStep
.addStep(EsbViewsRepository.BeanMediatorInputConnector.Properties.class)
.addStep(EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks);
composer = new PartComposer(beanMediatorInputConnectorStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.BeanMediatorInputConnector.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks) {
return createIncomingLinksReferencesTable(widgetFactory, parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(EsbMessages.BeanMediatorInputConnectorPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
/**
*
*/
protected Composite createIncomingLinksReferencesTable(FormToolkit widgetFactory, Composite parent) {
this.incomingLinks = new ReferencesTable(getDescription(EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks, EsbMessages.BeanMediatorInputConnectorPropertiesEditionPart_IncomingLinksLabel), new ReferencesTableListener () {
public void handleAdd() { addIncomingLinks(); }
public void handleEdit(EObject element) { editIncomingLinks(element); }
public void handleMove(EObject element, int oldIndex, int newIndex) { moveIncomingLinks(element, oldIndex, newIndex); }
public void handleRemove(EObject element) { removeFromIncomingLinks(element); }
public void navigateTo(EObject element) { }
});
this.incomingLinks.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks, EsbViewsRepository.FORM_KIND));
this.incomingLinks.createControls(parent, widgetFactory);
this.incomingLinks.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (e.item != null && e.item.getData() instanceof EObject) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeanMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData()));
}
}
});
GridData incomingLinksData = new GridData(GridData.FILL_HORIZONTAL);
incomingLinksData.horizontalSpan = 3;
this.incomingLinks.setLayoutData(incomingLinksData);
this.incomingLinks.disableMove();
incomingLinks.setID(EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks);
incomingLinks.setEEFType("eef::AdvancedReferencesTable"); //$NON-NLS-1$
// Start of user code for createIncomingLinksReferencesTable
// End of user code
return parent;
}
/**
*
*/
protected void addIncomingLinks() {
TabElementTreeSelectionDialog dialog = new TabElementTreeSelectionDialog(incomingLinks.getInput(), incomingLinksFilters, incomingLinksBusinessFilters,
"incomingLinks", propertiesEditionComponent.getEditingContext().getAdapterFactory(), current.eResource()) {
@Override
public void process(IStructuredSelection selection) {
for (Iterator<?> iter = selection.iterator(); iter.hasNext();) {
EObject elem = (EObject) iter.next();
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeanMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, elem));
}
incomingLinks.refresh();
}
};
dialog.open();
}
/**
*
*/
protected void moveIncomingLinks(EObject element, int oldIndex, int newIndex) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeanMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex));
incomingLinks.refresh();
}
/**
*
*/
protected void removeFromIncomingLinks(EObject element) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeanMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element));
incomingLinks.refresh();
}
/**
*
*/
protected void editIncomingLinks(EObject element) {
EObjectPropertiesEditionContext context = new EObjectPropertiesEditionContext(propertiesEditionComponent.getEditingContext(), propertiesEditionComponent, element, adapterFactory);
PropertiesEditingProvider provider = (PropertiesEditingProvider)adapterFactory.adapt(element, PropertiesEditingProvider.class);
if (provider != null) {
PropertiesEditingPolicy policy = provider.getPolicy(context);
if (policy != null) {
policy.execute();
incomingLinks.refresh();
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart#initIncomingLinks(org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings)
*/
public void initIncomingLinks(ReferencesTableSettings settings) {
if (current.eResource() != null && current.eResource().getResourceSet() != null)
this.resourceSet = current.eResource().getResourceSet();
ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider();
incomingLinks.setContentProvider(contentProvider);
incomingLinks.setInput(settings);
incomingLinksBusinessFilters.clear();
incomingLinksFilters.clear();
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.BeanMediatorInputConnector.Properties.incomingLinks);
if (eefElementEditorReadOnlyState && incomingLinks.getTable().isEnabled()) {
incomingLinks.setEnabled(false);
incomingLinks.setToolTipText(EsbMessages.BeanMediatorInputConnector_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !incomingLinks.getTable().isEnabled()) {
incomingLinks.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart#updateIncomingLinks()
*
*/
public void updateIncomingLinks() {
incomingLinks.refresh();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart#addFilterIncomingLinks(ViewerFilter filter)
*
*/
public void addFilterToIncomingLinks(ViewerFilter filter) {
incomingLinksFilters.add(filter);
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart#addBusinessFilterIncomingLinks(ViewerFilter filter)
*
*/
public void addBusinessFilterToIncomingLinks(ViewerFilter filter) {
incomingLinksBusinessFilters.add(filter);
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.BeanMediatorInputConnectorPropertiesEditionPart#isContainedInIncomingLinksTable(EObject element)
*
*/
public boolean isContainedInIncomingLinksTable(EObject element) {
return ((ReferencesTableSettings)incomingLinks.getInput()).contains(element);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.BeanMediatorInputConnector_Part_Title;
}
// Start of user code additional methods
// End of user code
}
|
|
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.web.util.matcher;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Matcher which compares a pre-defined ant-style pattern against the URL (
* {@code servletPath + pathInfo}) of an {@code HttpServletRequest}. The query string of
* the URL is ignored and matching is case-insensitive or case-sensitive depending on the
* arguments passed into the constructor.
* <p>
* Using a pattern value of {@code /**} or {@code **} is treated as a universal match,
* which will match any request. Patterns which end with {@code /**} (and have no other
* wildcards) are optimized by using a substring match — a pattern of
* {@code /aaa/**} will match {@code /aaa}, {@code /aaa/} and any sub-directories, such as
* {@code /aaa/bbb/ccc}.
* </p>
* <p>
* For all other cases, Spring's {@link AntPathMatcher} is used to perform the match. See
* the Spring documentation for this class for comprehensive information on the syntax
* used.
* </p>
*
* @author Luke Taylor
* @author Rob Winch
* @since 3.1
*
* @see org.springframework.util.AntPathMatcher
*/
public final class AntPathRequestMatcher implements RequestMatcher {
private static final Log logger = LogFactory.getLog(AntPathRequestMatcher.class);
private static final String MATCH_ALL = "/**";
private final Matcher matcher;
private final String pattern;
private final HttpMethod httpMethod;
private final boolean caseSensitive;
/**
* Creates a matcher with the specific pattern which will match all HTTP methods in a
* case insensitive manner.
*
* @param pattern the ant pattern to use for matching
*/
public AntPathRequestMatcher(String pattern) {
this(pattern, null);
}
/**
* Creates a matcher with the supplied pattern and HTTP method in a case insensitive
* manner.
*
* @param pattern the ant pattern to use for matching
* @param httpMethod the HTTP method. The {@code matches} method will return false if
* the incoming request doesn't have the same method.
*/
public AntPathRequestMatcher(String pattern, String httpMethod) {
this(pattern, httpMethod, false);
}
/**
* Creates a matcher with the supplied pattern which will match the specified Http
* method
*
* @param pattern the ant pattern to use for matching
* @param httpMethod the HTTP method. The {@code matches} method will return false if
* the incoming request doesn't doesn't have the same method.
* @param caseSensitive true if the matcher should consider case, else false
*/
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive) {
Assert.hasText(pattern, "Pattern cannot be null or empty");
this.caseSensitive = caseSensitive;
if (pattern.equals(MATCH_ALL) || pattern.equals("**")) {
pattern = MATCH_ALL;
matcher = null;
}
else {
if (!caseSensitive) {
pattern = pattern.toLowerCase();
}
// If the pattern ends with {@code /**} and has no other wildcards or path
// variables, then optimize to a sub-path match
if (pattern.endsWith(MATCH_ALL)
&& (pattern.indexOf('?') == -1 && pattern.indexOf('{') == -1 && pattern
.indexOf('}') == -1)
&& pattern.indexOf("*") == pattern.length() - 2) {
matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3));
}
else {
matcher = new SpringAntMatcher(pattern);
}
}
this.pattern = pattern;
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod
.valueOf(httpMethod) : null;
}
/**
* Returns true if the configured pattern (and HTTP-Method) match those of the
* supplied request.
*
* @param request the request to match against. The ant pattern will be matched
* against the {@code servletPath} + {@code pathInfo} of the request.
*/
public boolean matches(HttpServletRequest request) {
if (httpMethod != null && StringUtils.hasText(request.getMethod())
&& httpMethod != valueOf(request.getMethod())) {
if (logger.isDebugEnabled()) {
logger.debug("Request '" + request.getMethod() + " "
+ getRequestPath(request) + "'" + " doesn't match '" + httpMethod
+ " " + pattern);
}
return false;
}
if (pattern.equals(MATCH_ALL)) {
if (logger.isDebugEnabled()) {
logger.debug("Request '" + getRequestPath(request)
+ "' matched by universal pattern '/**'");
}
return true;
}
String url = getRequestPath(request);
if (logger.isDebugEnabled()) {
logger.debug("Checking match of request : '" + url + "'; against '" + pattern
+ "'");
}
return matcher.matches(url);
}
private String getRequestPath(HttpServletRequest request) {
String url = request.getServletPath();
if (request.getPathInfo() != null) {
url += request.getPathInfo();
}
if (!caseSensitive) {
url = url.toLowerCase();
}
return url;
}
public String getPattern() {
return pattern;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AntPathRequestMatcher)) {
return false;
}
AntPathRequestMatcher other = (AntPathRequestMatcher) obj;
return this.pattern.equals(other.pattern) && this.httpMethod == other.httpMethod
&& this.caseSensitive == other.caseSensitive;
}
@Override
public int hashCode() {
int code = 31 ^ pattern.hashCode();
if (httpMethod != null) {
code ^= httpMethod.hashCode();
}
return code;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Ant [pattern='").append(pattern).append("'");
if (httpMethod != null) {
sb.append(", ").append(httpMethod);
}
sb.append("]");
return sb.toString();
}
/**
* Provides a save way of obtaining the HttpMethod from a String. If the method is
* invalid, returns null.
*
* @param method the HTTP method to use.
*
* @return the HttpMethod or null if method is invalid.
*/
private static HttpMethod valueOf(String method) {
try {
return HttpMethod.valueOf(method);
}
catch (IllegalArgumentException e) {
}
return null;
}
private static interface Matcher {
boolean matches(String path);
}
private static class SpringAntMatcher implements Matcher {
private static final AntPathMatcher antMatcher = new AntPathMatcher();
private final String pattern;
private SpringAntMatcher(String pattern) {
this.pattern = pattern;
}
public boolean matches(String path) {
return antMatcher.match(pattern, path);
}
}
/**
* Optimized matcher for trailing wildcards
*/
private static class SubpathMatcher implements Matcher {
private final String subpath;
private final int length;
private SubpathMatcher(String subpath) {
assert !subpath.contains("*");
this.subpath = subpath;
this.length = subpath.length();
}
public boolean matches(String path) {
return path.startsWith(subpath)
&& (path.length() == length || path.charAt(length) == '/');
}
}
}
|
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cloud.spanner.connection;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.gax.grpc.GrpcCallContext;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.connection.StatementExecutor.StatementTimeout;
import com.google.cloud.spanner.connection.StatementParser.ParsedStatement;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.Context;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/** Base for all {@link Connection}-based transactions and batches. */
abstract class AbstractBaseUnitOfWork implements UnitOfWork {
private final StatementExecutor statementExecutor;
private final StatementTimeout statementTimeout;
protected final String transactionTag;
/** Class for keeping track of the stacktrace of the caller of an async statement. */
static final class SpannerAsyncExecutionException extends RuntimeException {
final Statement statement;
SpannerAsyncExecutionException(Statement statement) {
this.statement = statement;
}
public String getMessage() {
// We only include the SQL of the statement and not the parameter values to prevent
// potentially sensitive data to escape into an error message.
return String.format("Execution failed for statement: %s", statement.getSql());
}
}
/**
* The {@link Future} that monitors the result of the statement currently being executed for this
* unit of work.
*/
@GuardedBy("this")
private volatile Future<?> currentlyRunningStatementFuture = null;
enum InterceptorsUsage {
INVOKE_INTERCEPTORS,
IGNORE_INTERCEPTORS
}
abstract static class Builder<B extends Builder<?, T>, T extends AbstractBaseUnitOfWork> {
private StatementExecutor statementExecutor;
private StatementTimeout statementTimeout = new StatementTimeout();
private String transactionTag;
Builder() {}
@SuppressWarnings("unchecked")
B self() {
return (B) this;
}
B withStatementExecutor(StatementExecutor executor) {
Preconditions.checkNotNull(executor);
this.statementExecutor = executor;
return self();
}
B setStatementTimeout(StatementTimeout timeout) {
Preconditions.checkNotNull(timeout);
this.statementTimeout = timeout;
return self();
}
B setTransactionTag(@Nullable String tag) {
this.transactionTag = tag;
return self();
}
abstract T build();
}
AbstractBaseUnitOfWork(Builder<?, ?> builder) {
Preconditions.checkState(builder.statementExecutor != null, "No statement executor specified");
this.statementExecutor = builder.statementExecutor;
this.statementTimeout = builder.statementTimeout;
this.transactionTag = builder.transactionTag;
}
StatementExecutor getStatementExecutor() {
return statementExecutor;
}
StatementTimeout getStatementTimeout() {
return statementTimeout;
}
@Override
public void cancel() {
synchronized (this) {
if (currentlyRunningStatementFuture != null
&& !currentlyRunningStatementFuture.isDone()
&& !currentlyRunningStatementFuture.isCancelled()) {
currentlyRunningStatementFuture.cancel(true);
}
}
}
<T> ApiFuture<T> executeStatementAsync(
ParsedStatement statement,
Callable<T> callable,
@Nullable MethodDescriptor<?, ?> applyStatementTimeoutToMethod) {
return executeStatementAsync(
statement,
callable,
InterceptorsUsage.INVOKE_INTERCEPTORS,
applyStatementTimeoutToMethod == null
? Collections.emptySet()
: ImmutableList.of(applyStatementTimeoutToMethod));
}
<T> ApiFuture<T> executeStatementAsync(
ParsedStatement statement,
Callable<T> callable,
Collection<MethodDescriptor<?, ?>> applyStatementTimeoutToMethods) {
return executeStatementAsync(
statement, callable, InterceptorsUsage.INVOKE_INTERCEPTORS, applyStatementTimeoutToMethods);
}
<ResponseT, MetadataT> ResponseT getWithStatementTimeout(
OperationFuture<ResponseT, MetadataT> operation, ParsedStatement statement) {
ResponseT res;
try {
if (statementTimeout.hasTimeout()) {
TimeUnit unit = statementTimeout.getAppropriateTimeUnit();
res = operation.get(statementTimeout.getTimeoutValue(unit), unit);
} else {
res = operation.get();
}
} catch (TimeoutException e) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.DEADLINE_EXCEEDED,
"Statement execution timeout occurred for " + statement.getSqlWithoutComments(),
e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
Set<Throwable> causes = new HashSet<>();
while (cause != null && !causes.contains(cause)) {
if (cause instanceof SpannerException) {
throw (SpannerException) cause;
}
causes.add(cause);
cause = cause.getCause();
}
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.fromGrpcStatus(Status.fromThrowable(e)),
"Statement execution failed for " + statement.getSqlWithoutComments(),
e);
} catch (InterruptedException e) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.CANCELLED, "Statement execution was interrupted", e);
} catch (CancellationException e) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.CANCELLED, "Statement execution was cancelled", e);
}
return res;
}
<T> ApiFuture<T> executeStatementAsync(
ParsedStatement statement,
Callable<T> callable,
InterceptorsUsage interceptorUsage,
final Collection<MethodDescriptor<?, ?>> applyStatementTimeoutToMethods) {
Preconditions.checkNotNull(statement);
Preconditions.checkNotNull(callable);
if (interceptorUsage == InterceptorsUsage.INVOKE_INTERCEPTORS) {
statementExecutor.invokeInterceptors(
statement, StatementExecutionStep.EXECUTE_STATEMENT, this);
}
Context context = Context.current();
if (statementTimeout.hasTimeout() && !applyStatementTimeoutToMethods.isEmpty()) {
context =
context.withValue(
SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY,
new SpannerOptions.CallContextConfigurator() {
@Override
public <ReqT, RespT> ApiCallContext configure(
ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) {
if (statementTimeout.hasTimeout()
&& applyStatementTimeoutToMethods.contains(method)) {
return GrpcCallContext.createDefault()
.withTimeout(statementTimeout.asDuration());
}
return null;
}
});
}
ApiFuture<T> f = statementExecutor.submit(context.wrap(callable));
final SpannerAsyncExecutionException caller =
new SpannerAsyncExecutionException(statement.getStatement());
final ApiFuture<T> future =
ApiFutures.catching(
f,
Throwable.class,
input -> {
input.addSuppressed(caller);
throw SpannerExceptionFactory.asSpannerException(input);
},
MoreExecutors.directExecutor());
synchronized (this) {
this.currentlyRunningStatementFuture = future;
}
future.addListener(
new Runnable() {
@Override
public void run() {
synchronized (this) {
if (currentlyRunningStatementFuture == future) {
currentlyRunningStatementFuture = null;
}
}
}
},
MoreExecutors.directExecutor());
return future;
}
}
|
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.StringInterner;
import com.intellij.util.io.URLUtil;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.text.CharSequenceReader;
import com.intellij.util.text.StringFactory;
import org.jdom.*;
import org.jdom.filter.Filter;
import org.jdom.input.SAXBuilder;
import org.jdom.input.SAXHandler;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.XMLConstants;
import java.io.*;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* @author mike
*/
@SuppressWarnings({"HardCodedStringLiteral"})
public class JDOMUtil {
private static final ThreadLocal<SoftReference<SAXBuilder>> ourSaxBuilder = new ThreadLocal<SoftReference<SAXBuilder>>();
public static final Condition<Attribute> NOT_EMPTY_VALUE_CONDITION = new Condition<Attribute>() {
@Override
public boolean value(Attribute attribute) {
return !StringUtil.isEmpty(attribute.getValue());
}
};
private JDOMUtil() { }
@NotNull
public static List<Element> getChildren(@Nullable Element parent) {
if (parent == null) {
return Collections.emptyList();
}
else {
return parent.getChildren();
}
}
@NotNull
public static List<Element> getChildren(@Nullable Element parent, @NotNull String name) {
if (parent != null) {
return parent.getChildren(name);
}
return Collections.emptyList();
}
@SuppressWarnings("UtilityClassWithoutPrivateConstructor")
private static class LoggerHolder {
private static final Logger ourLogger = Logger.getInstance("#com.intellij.openapi.util.JDOMUtil");
}
private static Logger getLogger() {
return LoggerHolder.ourLogger;
}
public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2) {
return areElementsEqual(e1, e2, false);
}
/**
*
* @param ignoreEmptyAttrValues defines if elements like <element foo="bar" skip_it=""/> and <element foo="bar"/> are 'equal'
* @return <code>true</code> if two elements are deep-equals by their content and attributes
*/
public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2, boolean ignoreEmptyAttrValues) {
if (e1 == null && e2 == null) return true;
if (e1 == null || e2 == null) return false;
return Comparing.equal(e1.getName(), e2.getName())
&& attListsEqual(e1.getAttributes(), e2.getAttributes(), ignoreEmptyAttrValues)
&& contentListsEqual(e1.getContent(CONTENT_FILTER), e2.getContent(CONTENT_FILTER), ignoreEmptyAttrValues);
}
private static final EmptyTextFilter CONTENT_FILTER = new EmptyTextFilter();
public static int getTreeHash(@NotNull Element root) {
return addToHash(0, root, true);
}
private static int addToHash(int i, @NotNull Element element, boolean skipEmptyText) {
i = addToHash(i, element.getName());
for (Attribute attribute : element.getAttributes()) {
i = addToHash(i, attribute.getName());
i = addToHash(i, attribute.getValue());
}
for (Content child : element.getContent()) {
if (child instanceof Element) {
i = addToHash(i, (Element)child, skipEmptyText);
}
else if (child instanceof Text) {
String text = ((Text)child).getText();
if (!skipEmptyText || !StringUtil.isEmptyOrSpaces(text)) {
i = addToHash(i, text);
}
}
}
return i;
}
private static int addToHash(int i, @NotNull String s) {
return i * 31 + s.hashCode();
}
/**
* @deprecated Use Element.getChildren() directly
*/
@NotNull
@Deprecated
public static Element[] getElements(@NotNull Element m) {
List<Element> list = m.getChildren();
return list.toArray(new Element[list.size()]);
}
public static void internElement(@NotNull Element element, @NotNull StringInterner interner) {
element.setName(interner.intern(element.getName()));
for (Attribute attr : element.getAttributes()) {
attr.setName(interner.intern(attr.getName()));
attr.setValue(interner.intern(attr.getValue()));
}
for (Content o : element.getContent()) {
if (o instanceof Element) {
internElement((Element)o, interner);
}
else if (o instanceof Text) {
((Text)o).setText(interner.intern(o.getValue()));
}
}
}
@NotNull
public static String legalizeText(@NotNull String str) {
return legalizeChars(str).toString();
}
@NotNull
public static CharSequence legalizeChars(@NotNull CharSequence str) {
StringBuilder result = new StringBuilder(str.length());
for (int i = 0, len = str.length(); i < len; i ++) {
appendLegalized(result, str.charAt(i));
}
return result;
}
private static void appendLegalized(@NotNull StringBuilder sb, char each) {
if (each == '<' || each == '>') {
sb.append(each == '<' ? "<" : ">");
}
else if (!Verifier.isXMLCharacter(each)) {
sb.append("0x").append(StringUtil.toUpperCase(Long.toHexString(each)));
}
else {
sb.append(each);
}
}
private static class EmptyTextFilter implements Filter {
@Override
public boolean matches(Object obj) {
return !(obj instanceof Text) || !CharArrayUtil.containsOnlyWhiteSpaces(((Text)obj).getText());
}
}
private static boolean contentListsEqual(final List c1, final List c2, boolean ignoreEmptyAttrValues) {
if (c1 == null && c2 == null) return true;
if (c1 == null || c2 == null) return false;
Iterator l1 = c1.listIterator();
Iterator l2 = c2.listIterator();
while (l1.hasNext() && l2.hasNext()) {
if (!contentsEqual((Content)l1.next(), (Content)l2.next(), ignoreEmptyAttrValues)) {
return false;
}
}
return l1.hasNext() == l2.hasNext();
}
private static boolean contentsEqual(Content c1, Content c2, boolean ignoreEmptyAttrValues) {
if (!(c1 instanceof Element) && !(c2 instanceof Element)) {
return c1.getValue().equals(c2.getValue());
}
return c1 instanceof Element && c2 instanceof Element && areElementsEqual((Element)c1, (Element)c2, ignoreEmptyAttrValues);
}
private static boolean attListsEqual(@NotNull List<Attribute> l1, @NotNull List<Attribute> l2, boolean ignoreEmptyAttrValues) {
if (ignoreEmptyAttrValues) {
l1 = ContainerUtil.filter(l1, NOT_EMPTY_VALUE_CONDITION);
l2 = ContainerUtil.filter(l2, NOT_EMPTY_VALUE_CONDITION);
}
if (l1.size() != l2.size()) return false;
for (int i = 0; i < l1.size(); i++) {
if (!attEqual(l1.get(i), l2.get(i))) return false;
}
return true;
}
private static boolean attEqual(@NotNull Attribute a1, @NotNull Attribute a2) {
return a1.getName().equals(a2.getName()) && a1.getValue().equals(a2.getValue());
}
private static SAXBuilder getSaxBuilder() {
SoftReference<SAXBuilder> reference = ourSaxBuilder.get();
SAXBuilder saxBuilder = com.intellij.reference.SoftReference.dereference(reference);
if (saxBuilder == null) {
saxBuilder = new SAXBuilder() {
@Override
protected void configureParser(XMLReader parser, SAXHandler contentHandler) throws JDOMException {
super.configureParser(parser, contentHandler);
try {
parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (Exception ignore) {
}
}
};
saxBuilder.setEntityResolver(new EntityResolver() {
@Override
@NotNull
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY));
}
});
ourSaxBuilder.set(new SoftReference<SAXBuilder>(saxBuilder));
}
return saxBuilder;
}
/**
* @deprecated Use {@link #load(CharSequence)}
*
* Direct usage of element allows to get rid of {@link Document#getRootElement()} because only Element is required in mostly all cases.
*/
@NotNull
@Deprecated
public static Document loadDocument(@NotNull CharSequence seq) throws IOException, JDOMException {
return loadDocument(new CharSequenceReader(seq));
}
public static Element load(@NotNull CharSequence seq) throws IOException, JDOMException {
return load(new CharSequenceReader(seq));
}
@NotNull
private static Document loadDocument(@NotNull Reader reader) throws IOException, JDOMException {
try {
return getSaxBuilder().build(reader);
}
finally {
reader.close();
}
}
@NotNull
public static Document loadDocument(File file) throws JDOMException, IOException {
return loadDocument(new BufferedInputStream(new FileInputStream(file)));
}
@NotNull
public static Element load(@NotNull File file) throws JDOMException, IOException {
return load(new BufferedInputStream(new FileInputStream(file)));
}
@NotNull
public static Document loadDocument(@NotNull InputStream stream) throws JDOMException, IOException {
return loadDocument(new InputStreamReader(stream, CharsetToolkit.UTF8_CHARSET));
}
public static Element load(Reader reader) throws JDOMException, IOException {
return reader == null ? null : loadDocument(reader).detachRootElement();
}
/**
* Consider to use `loadElement` (JdomKt.loadElement from java) due to more efficient whitespace handling (cannot be changed here due to backward compatibility).
*/
@Contract("null -> null; !null -> !null")
public static Element load(InputStream stream) throws JDOMException, IOException {
return stream == null ? null : loadDocument(stream).detachRootElement();
}
@NotNull
public static Document loadDocument(@NotNull Class clazz, String resource) throws JDOMException, IOException {
InputStream stream = clazz.getResourceAsStream(resource);
if (stream == null) {
throw new FileNotFoundException(resource);
}
return loadDocument(stream);
}
@NotNull
public static Document loadDocument(@NotNull URL url) throws JDOMException, IOException {
return loadDocument(URLUtil.openStream(url));
}
@NotNull
public static Document loadResourceDocument(URL url) throws JDOMException, IOException {
return loadDocument(URLUtil.openResourceStream(url));
}
public static void writeDocument(@NotNull Document document, @NotNull String filePath, String lineSeparator) throws IOException {
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filePath));
try {
writeDocument(document, stream, lineSeparator);
}
finally {
stream.close();
}
}
public static void writeDocument(@NotNull Document document, @NotNull File file, String lineSeparator) throws IOException {
write(document, file, lineSeparator);
}
public static void write(@NotNull Parent element, @NotNull File file) throws IOException {
write(element, file, "\n");
}
public static void write(@NotNull Parent element, @NotNull File file, @NotNull String lineSeparator) throws IOException {
FileUtil.createParentDirs(file);
OutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
try {
write(element, stream, lineSeparator);
}
finally {
stream.close();
}
}
public static void writeDocument(@NotNull Document document, @NotNull OutputStream stream, String lineSeparator) throws IOException {
write(document, stream, lineSeparator);
}
public static void write(@NotNull Parent element, @NotNull OutputStream stream, @NotNull String lineSeparator) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(stream, CharsetToolkit.UTF8_CHARSET);
try {
if (element instanceof Document) {
writeDocument((Document)element, writer, lineSeparator);
}
else {
writeElement((Element) element, writer, lineSeparator);
}
}
finally {
writer.close();
}
}
/**
* @deprecated Use {@link #writeDocument(Document, String)} or {@link #writeElement(Element)}}
*/
@NotNull
@Deprecated
public static byte[] printDocument(@NotNull Document document, String lineSeparator) throws IOException {
CharArrayWriter writer = new CharArrayWriter();
writeDocument(document, writer, lineSeparator);
return StringFactory.createShared(writer.toCharArray()).getBytes(CharsetToolkit.UTF8_CHARSET);
}
@NotNull
public static String writeDocument(@NotNull Document document, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
writeDocument(document, writer, lineSeparator);
return writer.toString();
}
catch (IOException ignored) {
// Can't be
return "";
}
}
@NotNull
public static String write(Parent element, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
write(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void write(Parent element, Writer writer, String lineSeparator) throws IOException {
if (element instanceof Element) {
writeElement((Element) element, writer, lineSeparator);
} else if (element instanceof Document) {
writeDocument((Document) element, writer, lineSeparator);
}
}
public static void writeElement(@NotNull Element element, Writer writer, String lineSeparator) throws IOException {
XMLOutputter xmlOutputter = createOutputter(lineSeparator);
try {
xmlOutputter.output(element, writer);
}
catch (NullPointerException ex) {
getLogger().error(ex);
printDiagnostics(element, "");
}
}
@NotNull
public static String writeElement(@NotNull Element element) {
return writeElement(element, "\n");
}
@NotNull
public static String writeElement(@NotNull Element element, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
writeElement(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@NotNull
public static String writeChildren(@NotNull final Element element, @NotNull final String lineSeparator) throws IOException {
final StringWriter writer = new StringWriter();
for (Element child : element.getChildren()) {
writeElement(child, writer, lineSeparator);
writer.append(lineSeparator);
}
return writer.toString();
}
public static void writeDocument(@NotNull Document document, @NotNull Writer writer, String lineSeparator) throws IOException {
XMLOutputter xmlOutputter = createOutputter(lineSeparator);
try {
xmlOutputter.output(document, writer);
}
catch (NullPointerException ex) {
getLogger().error(ex);
printDiagnostics(document.getRootElement(), "");
}
}
@NotNull
public static XMLOutputter createOutputter(String lineSeparator) {
XMLOutputter xmlOutputter = new MyXMLOutputter();
Format format = Format.getCompactFormat().
setIndent(" ").
setTextMode(Format.TextMode.TRIM).
setEncoding(CharsetToolkit.UTF8).
setOmitEncoding(false).
setOmitDeclaration(false).
setLineSeparator(lineSeparator);
xmlOutputter.setFormat(format);
return xmlOutputter;
}
/**
* Returns null if no escapement necessary.
*/
@Nullable
private static String escapeChar(char c, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) {
switch (c) {
case '\n': return escapeLineEnds ? " " : null;
case '\r': return escapeLineEnds ? " " : null;
case '\t': return escapeLineEnds ? "	" : null;
case ' ' : return escapeSpaces ? "" : null;
case '<': return "<";
case '>': return ">";
case '\"': return """;
case '\'': return escapeApostrophes ? "'": null;
case '&': return "&";
}
return null;
}
@NotNull
public static String escapeText(@NotNull String text) {
return escapeText(text, false, false);
}
@NotNull
public static String escapeText(@NotNull String text, boolean escapeSpaces, boolean escapeLineEnds) {
return escapeText(text, false, escapeSpaces, escapeLineEnds);
}
@NotNull
public static String escapeText(@NotNull String text, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) {
StringBuilder buffer = null;
for (int i = 0; i < text.length(); i++) {
final char ch = text.charAt(i);
final String quotation = escapeChar(ch, escapeApostrophes, escapeSpaces, escapeLineEnds);
if (buffer == null) {
if (quotation != null) {
// An quotation occurred, so we'll have to use StringBuffer
// (allocate room for it plus a few more entities).
buffer = new StringBuilder(text.length() + 20);
// Copy previous skipped characters and fall through
// to pickup current character
buffer.append(text, 0, i);
buffer.append(quotation);
}
}
else if (quotation == null) {
buffer.append(ch);
}
else {
buffer.append(quotation);
}
}
// If there were any entities, return the escaped characters
// that we put in the StringBuffer. Otherwise, just return
// the unmodified input string.
return buffer == null ? text : buffer.toString();
}
public static class MyXMLOutputter extends XMLOutputter {
@Override
@NotNull
public String escapeAttributeEntities(@NotNull String str) {
return escapeText(str, false, true);
}
@Override
@NotNull
public String escapeElementEntities(@NotNull String str) {
return escapeText(str, false, false);
}
}
private static void printDiagnostics(@NotNull Element element, String prefix) {
ElementInfo info = getElementInfo(element);
prefix += "/" + info.name;
if (info.hasNullAttributes) {
//noinspection UseOfSystemOutOrSystemErr
System.err.println(prefix);
}
for (final Element child : element.getChildren()) {
printDiagnostics(child, prefix);
}
}
@NotNull
private static ElementInfo getElementInfo(@NotNull Element element) {
ElementInfo info = new ElementInfo();
StringBuilder buf = new StringBuilder(element.getName());
List attributes = element.getAttributes();
if (attributes != null) {
int length = attributes.size();
if (length > 0) {
buf.append("[");
for (int idx = 0; idx < length; idx++) {
Attribute attr = (Attribute)attributes.get(idx);
if (idx != 0) {
buf.append(";");
}
buf.append(attr.getName());
buf.append("=");
buf.append(attr.getValue());
if (attr.getValue() == null) {
info.hasNullAttributes = true;
}
}
buf.append("]");
}
}
info.name = buf.toString();
return info;
}
public static void updateFileSet(@NotNull File[] oldFiles, @NotNull String[] newFilePaths, @NotNull Document[] newFileDocuments, String lineSeparator)
throws IOException {
getLogger().assertTrue(newFilePaths.length == newFileDocuments.length);
ArrayList<String> writtenFilesPaths = new ArrayList<String>();
// check if files are writable
for (String newFilePath : newFilePaths) {
File file = new File(newFilePath);
if (file.exists() && !file.canWrite()) {
throw new IOException("File \"" + newFilePath + "\" is not writeable");
}
}
for (File file : oldFiles) {
if (file.exists() && !file.canWrite()) {
throw new IOException("File \"" + file.getAbsolutePath() + "\" is not writeable");
}
}
for (int i = 0; i < newFilePaths.length; i++) {
String newFilePath = newFilePaths[i];
writeDocument(newFileDocuments[i], newFilePath, lineSeparator);
writtenFilesPaths.add(newFilePath);
}
// delete files if necessary
outer:
for (File oldFile : oldFiles) {
String oldFilePath = oldFile.getAbsolutePath();
for (final String writtenFilesPath : writtenFilesPaths) {
if (oldFilePath.equals(writtenFilesPath)) {
continue outer;
}
}
boolean result = oldFile.delete();
if (!result) {
throw new IOException("File \"" + oldFilePath + "\" was not deleted");
}
}
}
private static class ElementInfo {
@NotNull public String name = "";
public boolean hasNullAttributes = false;
}
public static String getValue(Object node) {
if (node instanceof Content) {
Content content = (Content)node;
return content.getValue();
}
else if (node instanceof Attribute) {
Attribute attribute = (Attribute)node;
return attribute.getValue();
}
else {
throw new IllegalArgumentException("Wrong node: " + node);
}
}
public static boolean isEmpty(@Nullable Element element) {
return element == null || (element.getAttributes().isEmpty() && element.getContent().isEmpty());
}
public static boolean isEmpty(@Nullable Element element, int attributeCount) {
return element == null || (element.getAttributes().size() == attributeCount && element.getContent().isEmpty());
}
}
|
|
// Copyright 2014 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.chrome.browser.omnibox;
import android.content.res.Resources;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.ssl.ConnectionSecurityHelperSecurityLevel;
import java.util.Locale;
/**
* A helper class that emphasizes the various components of a URL. Useful in the
* Omnibox and Origin Info dialog where different parts of the URL should appear
* in different colours depending on the scheme, host and connection.
*/
public class OmniboxUrlEmphasizer {
/**
* Describes the components of a URL that should be emphasized.
*/
public static class EmphasizeComponentsResponse {
/** The start index of the scheme. */
public final int schemeStart;
/** The length of the scheme. */
public final int schemeLength;
/** The start index of the host. */
public final int hostStart;
/** The length of the host. */
public final int hostLength;
EmphasizeComponentsResponse(
int schemeStart, int schemeLength, int hostStart, int hostLength) {
this.schemeStart = schemeStart;
this.schemeLength = schemeLength;
this.hostStart = hostStart;
this.hostLength = hostLength;
}
/**
* @return Whether the URL has a scheme to be emphasized.
*/
public boolean hasScheme() {
return schemeLength > 0;
}
/**
* @return Whether the URL has a host to be emphasized.
*/
public boolean hasHost() {
return hostLength > 0;
}
}
/**
* Parses the |text| passed in and determines the location of the scheme and
* host components to be emphasized.
*
* @param profile The profile to be used for parsing.
* @param text The text to be parsed for emphasis components.
* @return The response object containing the locations of the emphasis
* components.
*/
public static EmphasizeComponentsResponse parseForEmphasizeComponents(
Profile profile, String text) {
int[] emphasizeValues = nativeParseForEmphasizeComponents(profile, text);
assert emphasizeValues != null;
assert emphasizeValues.length == 4;
return new EmphasizeComponentsResponse(
emphasizeValues[0], emphasizeValues[1], emphasizeValues[2], emphasizeValues[3]);
}
/**
* Denotes that a span is used for emphasizing the URL.
*/
@VisibleForTesting
interface UrlEmphasisSpan {
}
/**
* Used for emphasizing the URL text by changing the text color.
*/
@VisibleForTesting
static class UrlEmphasisColorSpan extends ForegroundColorSpan
implements UrlEmphasisSpan {
/**
* @param color The color to set the text.
*/
public UrlEmphasisColorSpan(int color) {
super(color);
}
}
/**
* Used for emphasizing the URL text by striking through the https text.
*/
@VisibleForTesting
static class UrlEmphasisSecurityErrorSpan extends StrikethroughSpan
implements UrlEmphasisSpan {
}
/**
* Make the whole url greyed out (trailing url color).
*
* @param url The URL spannable to grey out. This variable is modified.
* @param resources Resources for the given application context.
* @param useDarkColors Whether the text colors should be dark (i.e.
* appropriate for use on a light background).
*/
public static void greyOutUrl(Spannable url, Resources resources, boolean useDarkColors) {
int nonEmphasizedColorId = R.color.url_emphasis_non_emphasized_text;
if (!useDarkColors) {
nonEmphasizedColorId = R.color.url_emphasis_light_non_emphasized_text;
}
UrlEmphasisColorSpan span = new UrlEmphasisColorSpan(
resources.getColor(nonEmphasizedColorId));
url.setSpan(span, 0, url.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
/**
* Modifies the given URL to emphasize the TLD and second domain.
* TODO(sashab): Make this take an EmphasizeComponentsResponse object to
* prevent calling parseForEmphasizeComponents() again.
*
* @param url The URL spannable to add emphasis to. This variable is
* modified.
* @param resources Resources for the given application context.
* @param profile The profile viewing the given URL.
* @param securityLevel A valid ConnectionSecurityHelperSecurityLevel for the specified
* web contents.
* @param isInternalPage Whether this page is an internal Chrome page.
* @param useDarkColors Whether the text colors should be dark (i.e.
* appropriate for use on a light background).
* @param emphasizeHttpsScheme Whether the https scheme should be emphasized.
*/
public static void emphasizeUrl(Spannable url, Resources resources, Profile profile,
int securityLevel, boolean isInternalPage,
boolean useDarkColors, boolean emphasizeHttpsScheme) {
assert (securityLevel == ConnectionSecurityHelperSecurityLevel.SECURITY_ERROR
|| securityLevel == ConnectionSecurityHelperSecurityLevel.SECURITY_WARNING)
? emphasizeHttpsScheme : true;
String urlString = url.toString();
EmphasizeComponentsResponse emphasizeResponse =
parseForEmphasizeComponents(profile, urlString);
int nonEmphasizedColorId = R.color.url_emphasis_non_emphasized_text;
if (!useDarkColors) {
nonEmphasizedColorId = R.color.url_emphasis_light_non_emphasized_text;
}
int startSchemeIndex = emphasizeResponse.schemeStart;
int endSchemeIndex = emphasizeResponse.schemeStart + emphasizeResponse.schemeLength;
int startHostIndex = emphasizeResponse.hostStart;
int endHostIndex = emphasizeResponse.hostStart + emphasizeResponse.hostLength;
// Add the https scheme highlight
ForegroundColorSpan span;
if (emphasizeResponse.hasScheme()) {
int colorId = nonEmphasizedColorId;
if (!isInternalPage && emphasizeHttpsScheme) {
switch (securityLevel) {
case ConnectionSecurityHelperSecurityLevel.NONE:
colorId = nonEmphasizedColorId;
break;
case ConnectionSecurityHelperSecurityLevel.SECURITY_WARNING:
colorId = R.color.url_emphasis_start_scheme_security_warning;
break;
case ConnectionSecurityHelperSecurityLevel.SECURITY_ERROR:
colorId = R.color.url_emphasis_start_scheme_security_error;
UrlEmphasisSecurityErrorSpan ss = new UrlEmphasisSecurityErrorSpan();
url.setSpan(ss, startSchemeIndex, endSchemeIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case ConnectionSecurityHelperSecurityLevel.EV_SECURE:
colorId = R.color.url_emphasis_start_scheme_ev_secure;
break;
case ConnectionSecurityHelperSecurityLevel.SECURE:
colorId = R.color.url_emphasis_start_scheme_secure;
break;
default:
assert false;
}
}
span = new UrlEmphasisColorSpan(resources.getColor(colorId));
url.setSpan(
span, startSchemeIndex, endSchemeIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Highlight the portion of the URL visible between the scheme and the host. For
// https, this will be ://. For normal pages, this will be empty as we trim off
// http://.
if (emphasizeResponse.hasHost()) {
span = new UrlEmphasisColorSpan(resources.getColor(nonEmphasizedColorId));
url.setSpan(span, endSchemeIndex, startHostIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (emphasizeResponse.hasHost()) {
// Highlight the complete host.
int hostColorId = R.color.url_emphasis_domain_and_registry;
if (!useDarkColors) {
hostColorId = R.color.url_emphasis_light_domain_and_registry;
}
span = new UrlEmphasisColorSpan(resources.getColor(hostColorId));
url.setSpan(span, startHostIndex, endHostIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Highlight the remainder of the URL.
if (endHostIndex < urlString.length()) {
span = new UrlEmphasisColorSpan(resources.getColor(nonEmphasizedColorId));
url.setSpan(span, endHostIndex, urlString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
/**
* Reset the modifications done to emphasize the TLD and second domain of the URL.
*
* @param url The URL spannable to remove emphasis from. This variable is
* modified.
*/
public static void deEmphasizeUrl(Spannable url) {
UrlEmphasisSpan[] emphasisSpans = getEmphasisSpans(url);
if (emphasisSpans.length == 0) return;
for (UrlEmphasisSpan span : emphasisSpans) {
url.removeSpan(span);
}
}
/**
* Returns whether the given URL has any emphasis spans applied.
*
* @param url The URL spannable to check emphasis on.
* @return True if the URL has emphasis spans, false if not.
*/
public static boolean hasEmphasisSpans(Spannable url) {
return getEmphasisSpans(url).length != 0;
}
/**
* Returns the emphasis spans applied to the URL.
*
* @param url The URL spannable to get spans for.
* @return The spans applied to the URL with emphasizeUrl().
*/
public static UrlEmphasisSpan[] getEmphasisSpans(Spannable url) {
return url.getSpans(0, url.length(), UrlEmphasisSpan.class);
}
/**
* Returns the index of the first character containing non-origin
* information, or 0 if the URL does not contain an origin.
*
* For "data" URLs, the URL is not considered to contain an origin.
* For non-http and https URLs, the whole URL is considered the origin.
*
* For example, HTTP and HTTPS urls return the index of the first character
* after the domain:
* http://www.google.com/?q=foo => 21 (up to the 'm' in google.com)
* https://www.google.com/?q=foo => 22
*
* Data urls always return 0, since they do not contain an origin:
* data:kf94hfJEj#N => 0
*
* Other URLs treat the whole URL as an origin:
* file://my/pc/somewhere/foo.html => 31
* about:blank => 11
* chrome://version => 18
* chrome-native://bookmarks => 25
* invalidurl => 10
*
* TODO(sashab): Make this take an EmphasizeComponentsResponse object to
* prevent calling parseForEmphasizeComponents() again.
*
* @param url The URL to find the last origin character in.
* @param profile The profile visiting this URL (used for parsing the URL).
* @return The index of the last character containing origin information.
*/
public static int getOriginEndIndex(String url, Profile profile) {
EmphasizeComponentsResponse emphasizeResponse =
parseForEmphasizeComponents(profile, url.toString());
if (!emphasizeResponse.hasScheme()) return url.length();
int startSchemeIndex = emphasizeResponse.schemeStart;
int endSchemeIndex = emphasizeResponse.schemeStart + emphasizeResponse.schemeLength;
String scheme = url.subSequence(startSchemeIndex, endSchemeIndex).toString().toLowerCase(
Locale.US);
if (scheme.equals("http") || scheme.equals("https")) {
return emphasizeResponse.hostStart + emphasizeResponse.hostLength;
} else if (scheme.equals("data")) {
return 0;
} else {
return url.length();
}
}
private static native int[] nativeParseForEmphasizeComponents(Profile profile, String text);
}
|
|
/*
Copyright (c) 2011, Sony Mobile Communications Inc.
Copyright (c) 2014, Sony Corporation
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 Sony Mobile Communications Inc.
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 HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sony.smarteyeglass.extension.util.ar;
import java.io.ByteArrayOutputStream;
import com.sony.smarteyeglass.SmartEyeglassControl;
import com.sonyericsson.extras.liveware.aef.control.Control;
import android.content.Intent;
import android.graphics.Bitmap;
/**
* Abstract render object. Every render object to be registered must be
* a member of
*/
public abstract class RenderObject {
/**
* Compression factor for conversion to PNG.
*/
static final int PNG_QUALITY = 100;
/**
* Occlusion order for rendering.
*/
private int order;
/**
* The image to display.
*/
private Bitmap bitmap;
/**
* The object ID.
*/
private final int objectId;
/**
* The object type.
*/
private final int objectType;
/**
* Creates a new instance of this class.
*
* @param objectId A unique ID for the render object, a positive integer.
* Give the object a unique ID that will allow you
* to identify it in the results of asynchronous operations.
* @param bitmap The bitmap image to be displayed with AR rendering.
* @param order The occlusion order for this object, a positive integer.
* Zero renders the object in the foreground.
* @param objectType Whether this object is static or animated. One of:
* <ul><li>{@link com.sony.smarteyeglass.extension.util.SmartEyeglassControl.Intents.AR_OBJECT_TYPE_STATIC_IMAGE}</li>
* <li>{@link com.sony.smarteyeglass.extension.util.SmartEyeglassControl.Intents.AR_OBJECT_TYPE_ANIMATED_IMAGE}</li></ul>
*
*/
public RenderObject(final int objectId, final Bitmap bitmap,
final int order, final int objectType) {
this.objectId = objectId;
this.bitmap = bitmap;
this.order = order;
this.objectType = objectType;
}
/**
* Retrieves the object ID.
* @return The object ID.
*/
public final int getObjectId() {
return objectId;
}
/**
* Sets the bitmap.
* @param bitmap The bitmap object.
*/
public final void setBitmap(final Bitmap bitmap) {
this.bitmap = bitmap;
}
/**
* Retrieves the bitmap.
* @return The bitmap object.
*/
public final Bitmap getBitmap() {
return bitmap;
}
/**
* Sets the occlusion order value.
* @param order The new order value, a positive integer.
*/
public final void setOrder(final int order) {
this.order = order;
}
/**
* Retrieves the occlusion order value.
* @return The order value.
*/
public final int getOrder() {
return this.order;
}
/**
* Set the intent to resist information.
* @param intent intent to set the extra.
*/
public void toRegisterExtras(final Intent intent) {
setObjectIdExtra(intent);
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_AR_ORDER,
this.order);
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_AR_OBJECT_TYPE,
objectType);
if (bitmap != null) {
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_IMAGE_WIDTH,
bitmap.getWidth());
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_IMAGE_HEIGHT,
bitmap.getHeight());
}
}
/**
* Set the intent to object response information.
* @param intent intent to set the extra.
*/
public final void toObjectResponseExtras(final Intent intent) {
setObjectIdExtra(intent);
if (bitmap != null) {
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, PNG_QUALITY,
byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
intent.putExtra(Control.Intents.EXTRA_DATA, imageByteArray);
}
}
/**
* Set the intent to move object information.
* @param intent intent to set the extra.
*/
public abstract void toMoveExtras(final Intent intent);
/**
* Set the intent to change order information.
* @param intent intent to set the extra.
*/
public final void toOrderExtras(final Intent intent) {
setObjectIdExtra(intent);
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_AR_ORDER, order);
}
/**
* Set the intent to object ID.
* @param intent intent intent to set the extra.
*/
protected final void setObjectIdExtra(final Intent intent) {
intent.putExtra(SmartEyeglassControl.Intents.EXTRA_AR_OBJECT_ID,
this.objectId);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (bitmap != null) {
b.append("objectId = ")
.append(getObjectId())
.append(", W = ")
.append(bitmap.getWidth())
.append(", H = ")
.append(bitmap.getHeight())
.append(", order = ")
.append(order);
}
return b.toString();
}
}
|
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library 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 library 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.
*/
package org.oep.dossiermgt.service;
import com.liferay.portal.service.InvokableLocalService;
/**
* @author trungdk
* @generated
*/
public class PaymentConfigLocalServiceClp implements PaymentConfigLocalService {
public PaymentConfigLocalServiceClp(
InvokableLocalService invokableLocalService) {
_invokableLocalService = invokableLocalService;
_methodName0 = "addPaymentConfig";
_methodParameterTypes0 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig"
};
_methodName1 = "createPaymentConfig";
_methodParameterTypes1 = new String[] { "long" };
_methodName2 = "deletePaymentConfig";
_methodParameterTypes2 = new String[] { "long" };
_methodName3 = "deletePaymentConfig";
_methodParameterTypes3 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig"
};
_methodName4 = "dynamicQuery";
_methodParameterTypes4 = new String[] { };
_methodName5 = "dynamicQuery";
_methodParameterTypes5 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName6 = "dynamicQuery";
_methodParameterTypes6 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
};
_methodName7 = "dynamicQuery";
_methodParameterTypes7 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
"com.liferay.portal.kernel.util.OrderByComparator"
};
_methodName8 = "dynamicQueryCount";
_methodParameterTypes8 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName9 = "dynamicQueryCount";
_methodParameterTypes9 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery",
"com.liferay.portal.kernel.dao.orm.Projection"
};
_methodName10 = "fetchPaymentConfig";
_methodParameterTypes10 = new String[] { "long" };
_methodName11 = "getPaymentConfig";
_methodParameterTypes11 = new String[] { "long" };
_methodName12 = "getPersistedModel";
_methodParameterTypes12 = new String[] { "java.io.Serializable" };
_methodName13 = "getPaymentConfigs";
_methodParameterTypes13 = new String[] { "int", "int" };
_methodName14 = "getPaymentConfigsCount";
_methodParameterTypes14 = new String[] { };
_methodName15 = "updatePaymentConfig";
_methodParameterTypes15 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig"
};
_methodName16 = "getBeanIdentifier";
_methodParameterTypes16 = new String[] { };
_methodName17 = "setBeanIdentifier";
_methodParameterTypes17 = new String[] { "java.lang.String" };
_methodName19 = "addPaymentConfig";
_methodParameterTypes19 = new String[] {
"java.lang.String", "java.lang.String", "java.lang.String",
"java.lang.String", "long",
"com.liferay.portal.service.ServiceContext"
};
_methodName20 = "updatePaymentConfig";
_methodParameterTypes20 = new String[] {
"long", "java.lang.String", "java.lang.String",
"java.lang.String", "java.lang.String", "long",
"com.liferay.portal.service.ServiceContext"
};
_methodName21 = "updatePaymentConfigResources";
_methodParameterTypes21 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig", "java.lang.String[][]",
"java.lang.String[][]",
"com.liferay.portal.service.ServiceContext"
};
_methodName22 = "removePaymentConfig";
_methodParameterTypes22 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig"
};
_methodName23 = "removePaymentConfig";
_methodParameterTypes23 = new String[] { "long" };
_methodName24 = "addPaymentConfigResources";
_methodParameterTypes24 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig", "boolean", "boolean",
"com.liferay.portal.service.ServiceContext"
};
_methodName25 = "addPaymentConfigResources";
_methodParameterTypes25 = new String[] {
"org.oep.dossiermgt.model.PaymentConfig", "java.lang.String[][]",
"java.lang.String[][]",
"com.liferay.portal.service.ServiceContext"
};
_methodName26 = "addPaymentConfigResources";
_methodParameterTypes26 = new String[] {
"long", "java.lang.String[][]", "java.lang.String[][]",
"com.liferay.portal.service.ServiceContext"
};
}
@Override
public org.oep.dossiermgt.model.PaymentConfig addPaymentConfig(
org.oep.dossiermgt.model.PaymentConfig paymentConfig)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName0,
_methodParameterTypes0,
new Object[] { ClpSerializer.translateInput(paymentConfig) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public org.oep.dossiermgt.model.PaymentConfig createPaymentConfig(
long paymentConfigId) {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName1,
_methodParameterTypes1, new Object[] { paymentConfigId });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public org.oep.dossiermgt.model.PaymentConfig deletePaymentConfig(
long paymentConfigId)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName2,
_methodParameterTypes2, new Object[] { paymentConfigId });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public org.oep.dossiermgt.model.PaymentConfig deletePaymentConfig(
org.oep.dossiermgt.model.PaymentConfig paymentConfig)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName3,
_methodParameterTypes3,
new Object[] { ClpSerializer.translateInput(paymentConfig) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName4,
_methodParameterTypes4, new Object[] { });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (com.liferay.portal.kernel.dao.orm.DynamicQuery)ClpSerializer.translateOutput(returnObj);
}
@Override
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName5,
_methodParameterTypes5,
new Object[] { ClpSerializer.translateInput(dynamicQuery) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.util.List)ClpSerializer.translateOutput(returnObj);
}
@Override
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
int end) throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName6,
_methodParameterTypes6,
new Object[] {
ClpSerializer.translateInput(dynamicQuery),
start,
end
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.util.List)ClpSerializer.translateOutput(returnObj);
}
@Override
@SuppressWarnings("rawtypes")
public java.util.List dynamicQuery(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName7,
_methodParameterTypes7,
new Object[] {
ClpSerializer.translateInput(dynamicQuery),
start,
end,
ClpSerializer.translateInput(orderByComparator)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.util.List)ClpSerializer.translateOutput(returnObj);
}
@Override
public long dynamicQueryCount(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName8,
_methodParameterTypes8,
new Object[] { ClpSerializer.translateInput(dynamicQuery) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return ((Long)returnObj).longValue();
}
@Override
public long dynamicQueryCount(
com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery,
com.liferay.portal.kernel.dao.orm.Projection projection)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName9,
_methodParameterTypes9,
new Object[] {
ClpSerializer.translateInput(dynamicQuery),
ClpSerializer.translateInput(projection)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return ((Long)returnObj).longValue();
}
@Override
public org.oep.dossiermgt.model.PaymentConfig fetchPaymentConfig(
long paymentConfigId)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName10,
_methodParameterTypes10, new Object[] { paymentConfigId });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public org.oep.dossiermgt.model.PaymentConfig getPaymentConfig(
long paymentConfigId)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName11,
_methodParameterTypes11, new Object[] { paymentConfigId });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public com.liferay.portal.model.PersistedModel getPersistedModel(
java.io.Serializable primaryKeyObj)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName12,
_methodParameterTypes12,
new Object[] { ClpSerializer.translateInput(primaryKeyObj) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (com.liferay.portal.model.PersistedModel)ClpSerializer.translateOutput(returnObj);
}
@Override
public java.util.List<org.oep.dossiermgt.model.PaymentConfig> getPaymentConfigs(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName13,
_methodParameterTypes13, new Object[] { start, end });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.util.List<org.oep.dossiermgt.model.PaymentConfig>)ClpSerializer.translateOutput(returnObj);
}
@Override
public int getPaymentConfigsCount()
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName14,
_methodParameterTypes14, new Object[] { });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return ((Integer)returnObj).intValue();
}
@Override
public org.oep.dossiermgt.model.PaymentConfig updatePaymentConfig(
org.oep.dossiermgt.model.PaymentConfig paymentConfig)
throws com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName15,
_methodParameterTypes15,
new Object[] { ClpSerializer.translateInput(paymentConfig) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public java.lang.String getBeanIdentifier() {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName16,
_methodParameterTypes16, new Object[] { });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (java.lang.String)ClpSerializer.translateOutput(returnObj);
}
@Override
public void setBeanIdentifier(java.lang.String beanIdentifier) {
try {
_invokableLocalService.invokeMethod(_methodName17,
_methodParameterTypes17,
new Object[] { ClpSerializer.translateInput(beanIdentifier) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
throw new UnsupportedOperationException();
}
@Override
public org.oep.dossiermgt.model.PaymentConfig addPaymentConfig(
java.lang.String govAgencyId, java.lang.String govAgencyName,
java.lang.String bankTransfer, java.lang.String keypay,
long ebPartnerShipId,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName19,
_methodParameterTypes19,
new Object[] {
ClpSerializer.translateInput(govAgencyId),
ClpSerializer.translateInput(govAgencyName),
ClpSerializer.translateInput(bankTransfer),
ClpSerializer.translateInput(keypay),
ebPartnerShipId,
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public org.oep.dossiermgt.model.PaymentConfig updatePaymentConfig(long id,
java.lang.String govAgencyId, java.lang.String govAgencyName,
java.lang.String bankTransfer, java.lang.String keypay,
long ebPartnerShipId,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
Object returnObj = null;
try {
returnObj = _invokableLocalService.invokeMethod(_methodName20,
_methodParameterTypes20,
new Object[] {
id,
ClpSerializer.translateInput(govAgencyId),
ClpSerializer.translateInput(govAgencyName),
ClpSerializer.translateInput(bankTransfer),
ClpSerializer.translateInput(keypay),
ebPartnerShipId,
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
return (org.oep.dossiermgt.model.PaymentConfig)ClpSerializer.translateOutput(returnObj);
}
@Override
public void updatePaymentConfigResources(
org.oep.dossiermgt.model.PaymentConfig paymentConfig,
java.lang.String[] groupPermissions,
java.lang.String[] guestPermissions,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName21,
_methodParameterTypes21,
new Object[] {
ClpSerializer.translateInput(paymentConfig),
ClpSerializer.translateInput(groupPermissions),
ClpSerializer.translateInput(guestPermissions),
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public void removePaymentConfig(
org.oep.dossiermgt.model.PaymentConfig paymentConfig)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName22,
_methodParameterTypes22,
new Object[] { ClpSerializer.translateInput(paymentConfig) });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public void removePaymentConfig(long id)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName23,
_methodParameterTypes23, new Object[] { id });
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public void addPaymentConfigResources(
org.oep.dossiermgt.model.PaymentConfig paymentConfig,
boolean addGroupPermission, boolean addGuestPermission,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName24,
_methodParameterTypes24,
new Object[] {
ClpSerializer.translateInput(paymentConfig),
addGroupPermission,
addGuestPermission,
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public void addPaymentConfigResources(
org.oep.dossiermgt.model.PaymentConfig paymentConfig,
java.lang.String[] groupPermissions,
java.lang.String[] guestPermissions,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName25,
_methodParameterTypes25,
new Object[] {
ClpSerializer.translateInput(paymentConfig),
ClpSerializer.translateInput(groupPermissions),
ClpSerializer.translateInput(guestPermissions),
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
@Override
public void addPaymentConfigResources(long id,
java.lang.String[] groupPermissions,
java.lang.String[] guestPermissions,
com.liferay.portal.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
try {
_invokableLocalService.invokeMethod(_methodName26,
_methodParameterTypes26,
new Object[] {
id,
ClpSerializer.translateInput(groupPermissions),
ClpSerializer.translateInput(guestPermissions),
ClpSerializer.translateInput(serviceContext)
});
}
catch (Throwable t) {
t = ClpSerializer.translateThrowable(t);
if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)t;
}
if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
throw (com.liferay.portal.kernel.exception.SystemException)t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
else {
throw new RuntimeException(t.getClass().getName() +
" is not a valid exception");
}
}
}
private InvokableLocalService _invokableLocalService;
private String _methodName0;
private String[] _methodParameterTypes0;
private String _methodName1;
private String[] _methodParameterTypes1;
private String _methodName2;
private String[] _methodParameterTypes2;
private String _methodName3;
private String[] _methodParameterTypes3;
private String _methodName4;
private String[] _methodParameterTypes4;
private String _methodName5;
private String[] _methodParameterTypes5;
private String _methodName6;
private String[] _methodParameterTypes6;
private String _methodName7;
private String[] _methodParameterTypes7;
private String _methodName8;
private String[] _methodParameterTypes8;
private String _methodName9;
private String[] _methodParameterTypes9;
private String _methodName10;
private String[] _methodParameterTypes10;
private String _methodName11;
private String[] _methodParameterTypes11;
private String _methodName12;
private String[] _methodParameterTypes12;
private String _methodName13;
private String[] _methodParameterTypes13;
private String _methodName14;
private String[] _methodParameterTypes14;
private String _methodName15;
private String[] _methodParameterTypes15;
private String _methodName16;
private String[] _methodParameterTypes16;
private String _methodName17;
private String[] _methodParameterTypes17;
private String _methodName19;
private String[] _methodParameterTypes19;
private String _methodName20;
private String[] _methodParameterTypes20;
private String _methodName21;
private String[] _methodParameterTypes21;
private String _methodName22;
private String[] _methodParameterTypes22;
private String _methodName23;
private String[] _methodParameterTypes23;
private String _methodName24;
private String[] _methodParameterTypes24;
private String _methodName25;
private String[] _methodParameterTypes25;
private String _methodName26;
private String[] _methodParameterTypes26;
}
|
|
package com.github.t3t5u.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
public final class ExtraIOUtils {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final Charset DEFAULT_CHARSET = Charsets.UTF_8;
private static final Logger LOGGER = LoggerFactory.getLogger(ExtraIOUtils.class);
private ExtraIOUtils() {
}
public static InputStream openInputStreamOrNull(final String pathName) {
return StringUtils.isBlank(pathName) ? null : openInputStreamOrNull(new File(pathName));
}
public static InputStream openInputStream(final String pathName) {
return openInputStream(new File(pathName));
}
public static InputStream openInputStreamOrNull(final File file) {
if (file == null) {
return null;
}
try {
return openInputStream(file);
} catch (final Throwable t) {
LOGGER.info("openInputStreamOrNull", t);
return null;
}
}
public static InputStream openInputStream(final File file) {
try {
return new FileInputStream(file);
} catch (final FileNotFoundException e) {
LOGGER.warn("openInputStream: " + ExtraFileUtils.getAbsolutePath(file), e);
throw new RuntimeException(e);
}
}
public static <R> R drainOrNull(final String pathName, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
return StringUtils.isBlank(pathName) || (function == null) ? null : drainOrNull(new File(pathName), function, init, buffer);
}
public static <R> R drain(final String pathName, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
return drain(new File(pathName), function, init, buffer);
}
public static <R> R drainOrNull(final File file, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
if ((file == null) || (function == null)) {
return null;
}
try {
return drain(file, function, init, buffer);
} catch (final Throwable t) {
LOGGER.info("drainOrNull", t);
return null;
}
}
public static <R> R drain(final File file, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
return drain(openInputStream(file), function, init, buffer);
}
public static <R> R drainOrNull(final InputStream is, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
if ((is == null) || (function == null)) {
IOUtils.closeQuietly(is);
return null;
}
try {
return drain(is, function, init, buffer);
} catch (final Throwable t) {
LOGGER.info("drainOrNull", t);
return null;
}
}
public static <R> R drain(final InputStream is, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) {
try {
return read(is, function, init, buffer);
} catch (final IOException e) {
LOGGER.warn("drain", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
private static <R> R read(final InputStream is, final Function<? super R, ? extends Function<byte[], ? extends R>> function, final R init, final byte[] buffer) throws IOException {
R result = init;
final byte[] bytes = buffer != null ? buffer : new byte[DEFAULT_BUFFER_SIZE];
while (true) {
final int read = is.read(bytes);
if (read < 0) {
break;
}
result = function.apply(result).apply(read == bytes.length ? bytes : Arrays.copyOf(bytes, read));
}
return result;
}
public static byte[] readOrNull(final String pathName) {
return StringUtils.isBlank(pathName) ? null : readOrNull(new File(pathName));
}
public static byte[] read(final String pathName) {
return read(new File(pathName));
}
public static byte[] readOrNull(final File file) {
if (file == null) {
return null;
}
try {
return read(file);
} catch (final Throwable t) {
LOGGER.info("readOrNull", t);
return null;
}
}
public static byte[] read(final File file) {
return read(openInputStream(file));
}
public static byte[] readOrNull(final InputStream is) {
if (is == null) {
IOUtils.closeQuietly(is);
return null;
}
try {
return read(is);
} catch (final Throwable t) {
LOGGER.info("readOrNull", t);
return null;
}
}
public static byte[] read(final InputStream is) {
byte[] bytes = null;
try {
bytes = IOUtils.toByteArray(is);
} catch (final IOException e) {
LOGGER.warn("read", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
return bytes;
}
public static String readAsStringOrNull(final String pathName) {
return StringUtils.isBlank(pathName) ? null : readAsStringOrNull(new File(pathName));
}
public static String readAsString(final String pathName) {
return readAsString(new File(pathName));
}
public static String readAsStringOrNull(final File file) {
if (file == null) {
return null;
}
try {
return readAsString(file);
} catch (final Throwable t) {
LOGGER.info("readAsStringOrNull", t);
return null;
}
}
public static String readAsString(final File file) {
return readAsString(openInputStream(file));
}
public static String readAsStringOrNull(final InputStream is) {
if (is == null) {
IOUtils.closeQuietly(is);
return null;
}
try {
return readAsString(is);
} catch (final Throwable t) {
LOGGER.info("readAsStringOrNull", t);
return null;
}
}
public static String readAsString(final InputStream is) {
return readAsString(is, DEFAULT_CHARSET);
}
public static String readAsStringOrNull(final String pathName, final Charset charset) {
return StringUtils.isBlank(pathName) ? null : readAsStringOrNull(new File(pathName), charset);
}
public static String readAsString(final String pathName, final Charset charset) {
return readAsString(new File(pathName), charset);
}
public static String readAsStringOrNull(final File file, final Charset charset) {
if ((file == null) || (charset == null)) {
return null;
}
try {
return readAsString(file, charset);
} catch (final Throwable t) {
LOGGER.info("readAsStringOrNull", t);
return null;
}
}
public static String readAsString(final File file, final Charset charset) {
return readAsString(openInputStream(file), charset);
}
public static String readAsStringOrNull(final InputStream is, final Charset charset) {
if ((is == null) || (charset == null)) {
IOUtils.closeQuietly(is);
return null;
}
try {
return readAsString(is, charset);
} catch (final Throwable t) {
LOGGER.info("readAsStringOrNull", t);
return null;
}
}
public static String readAsString(final InputStream is, final Charset charset) {
String s = null;
try {
s = IOUtils.toString(is, charset);
} catch (final IOException e) {
LOGGER.warn("readAsString", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("readAsString: " + s);
}
return s;
}
public static OutputStream openOutputStreamOrNull(final String pathName) {
return StringUtils.isBlank(pathName) ? null : openOutputStreamOrNull(new File(pathName));
}
public static OutputStream openOutputStream(final String pathName) {
return openOutputStream(new File(pathName));
}
public static OutputStream openOutputStreamOrNull(final File file) {
if (file == null) {
return null;
}
try {
return openOutputStream(file);
} catch (final Throwable t) {
LOGGER.info("openOutputStreamOrNull", t);
return null;
}
}
public static OutputStream openOutputStream(final File file) {
try {
return new FileOutputStream(file);
} catch (final FileNotFoundException e) {
LOGGER.warn("openOutputStream: " + ExtraFileUtils.getAbsolutePath(file), e);
throw new RuntimeException(e);
}
}
public static String writeOrNull(final byte[] bytes, final String pathName) {
final File file = StringUtils.isBlank(pathName) ? null : writeOrNull(bytes, new File(pathName));
return file != null ? file.getPath() : null;
}
public static String write(final byte[] bytes, final String pathName) {
final File file = write(bytes, new File(pathName));
return file != null ? file.getPath() : null;
}
public static File writeOrNull(final byte[] bytes, final File file) {
if ((bytes == null) || (file == null)) {
return null;
}
try {
return write(bytes, file);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static File write(final byte[] bytes, final File file) {
final OutputStream os = write(bytes, openOutputStream(file));
return os != null ? file : null;
}
public static <T extends OutputStream> T writeOrNull(final byte[] bytes, final T os) {
if ((bytes == null) || (os == null)) {
IOUtils.closeQuietly(os);
return null;
}
try {
return write(bytes, os);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static <T extends OutputStream> T write(final byte[] bytes, final T os) {
try {
IOUtils.write(bytes, os);
return os;
} catch (final IOException e) {
LOGGER.warn("write", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(os);
}
}
public static String writeOrNull(final String s, final String pathName) {
final File file = StringUtils.isBlank(pathName) ? null : writeOrNull(s, new File(pathName));
return file != null ? file.getPath() : null;
}
public static String write(final String s, final String pathName) {
final File file = write(s, new File(pathName));
return file != null ? file.getPath() : null;
}
public static File writeOrNull(final String s, final File file) {
if (StringUtils.isBlank(s) || (file == null)) {
return null;
}
try {
return write(s, file);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static File write(final String s, final File file) {
final OutputStream os = write(s, openOutputStream(file));
return os != null ? file : null;
}
public static <T extends OutputStream> T writeOrNull(final String s, final T os) {
if (StringUtils.isBlank(s) || (os == null)) {
IOUtils.closeQuietly(os);
return null;
}
try {
return write(s, os);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static <T extends OutputStream> T write(final String s, final T os) {
return write(s, os, DEFAULT_CHARSET);
}
public static String writeOrNull(final String s, final String pathName, final Charset charset) {
final File file = StringUtils.isBlank(pathName) ? null : writeOrNull(s, new File(pathName), charset);
return file != null ? file.getPath() : null;
}
public static String write(final String s, final String pathName, final Charset charset) {
final File file = write(s, new File(pathName), charset);
return file != null ? file.getPath() : null;
}
public static File writeOrNull(final String s, final File file, final Charset charset) {
if (StringUtils.isBlank(s) || (file == null) || (charset == null)) {
return null;
}
try {
return write(s, file, charset);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static File write(final String s, final File file, final Charset charset) {
final OutputStream os = write(s, openOutputStream(file), charset);
return os != null ? file : null;
}
public static <T extends OutputStream> T writeOrNull(final String s, final T os, final Charset charset) {
if (StringUtils.isBlank(s) || (os == null) || (charset == null)) {
IOUtils.closeQuietly(os);
return null;
}
try {
return write(s, os, charset);
} catch (final Throwable t) {
LOGGER.info("writeOrNull", t);
return null;
}
}
public static <T extends OutputStream> T write(final String s, final T os, final Charset charset) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("write: " + s);
}
try {
IOUtils.write(s, os, charset);
return os;
} catch (final IOException e) {
LOGGER.warn("write", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(os);
}
}
public static Long copyOrNull(final InputStream is, final OutputStream os) {
if ((is == null) || (os == null)) {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
return -1L;
}
try {
return copy(is, os);
} catch (final Throwable t) {
LOGGER.info("copyOrNull", t);
return -1L;
}
}
public static long copy(final InputStream is, final OutputStream os) {
try {
return IOUtils.copyLarge(is, os);
} catch (final IOException e) {
LOGGER.warn("copy", e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
public static Long copyOrNull(final InputStream is, final OutputStream os, final CopyProgressListener copyProgressListener, final long progress) {
if ((is == null) || (os == null)) {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
return -1L;
}
try {
return copy(is, os, copyProgressListener, progress);
} catch (final Throwable t) {
LOGGER.info("copyOrNull", t);
return -1L;
}
}
public static long copy(final InputStream is, final OutputStream os, final CopyProgressListener copyProgressListener, final long progress) {
try {
return copyProgressListener != null ? copyLarge(is, os, copyProgressListener, progress) : IOUtils.copyLarge(is, os);
} catch (final IOException e) {
LOGGER.warn("copy", e);
failed(copyProgressListener, e);
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
private static long copyLarge(final InputStream is, final OutputStream os, final CopyProgressListener copyProgressListener, final long progress) throws IOException {
long totalCopied = 0;
while (true) {
final long copied = progress > 0 ? IOUtils.copyLarge(is, os, 0, progress) : IOUtils.copyLarge(is, os);
totalCopied += copied;
final boolean finished = copied <= 0;
if (!copyProgressListener.onProgress(totalCopied, finished) || finished) {
break;
}
}
return totalCopied;
}
private static void failed(final CopyProgressListener copyProgressListener, final IOException e) {
if (copyProgressListener != null) {
copyProgressListener.onFailure(e);
}
}
}
|
|
package com.earthflare.android.ircradio;
import java.util.concurrent.atomic.AtomicBoolean;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.earthflare.android.cross.CrossView;
import com.earthflare.android.cross.OnCrossListener;
import com.earthflare.android.logmanager.LogEntry;
import com.earthflare.android.logmanager.LogManager;
import com.earthflare.android.logmanager.ServerLog;
public class ActChatLog extends TemplateChat implements OnCrossListener{
private ListChatAdapter adapter;
protected ListView listview;
private LinearLayout container;
private EditText et;
private NavBarListener listener;
private long uid;
private MenuData menuData;
@Override protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
// window features - must be set prior to calling setContentView...
setContentView(R.layout.chat);
initDrawer();
listview = (ListView)this.findViewById(R.id.ListViewServerLog);
Globo.handlerChatLog = myHandler;
//attempt to go to passed message
Intent intent = this.getIntent();
killNotification(intent);
uid = intent.getLongExtra("uid",-1);
Globo.chatlogActChannelName = intent.getStringExtra("channel");
Globo.chatlogActNetworkName = intent.getLongExtra("network",0);
Globo.chatlogActType = intent.getStringExtra("acttype");
Globo.chatlogActAccountName = intent.getStringExtra("accountname");
}
protected void killNotification(Intent intent) {
boolean linkedfromstatus = intent.getBooleanExtra("notificationlink", false);
if(linkedfromstatus){
NotificationManager nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(2);
}
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
uid = intent.getLongExtra("uid",-1);
killNotification(intent);
NavItem ni = new NavItem(intent.getLongExtra("network",0),intent.getStringExtra("accountname"),intent.getStringExtra("channel"),intent.getStringExtra("acttype"));
this.changeLog(ni);
scrollToUid();
}
public void initializeCrossing() {
CrossView cross = (CrossView) this.findViewById(R.id.crossview);
cross.addOnCrossListener(this);
LinearLayout navChanll;
navChanll = (LinearLayout)this.findViewById(R.id.navchanll);
if (Globo.chatlogChanNav.get()) {
navChanll.setVisibility(View.VISIBLE);
this.refreshNavBar();
}else{
navChanll.setVisibility(View.GONE);
}
if (Globo.chatlogActNav.get()) {
getSupportActionBar().show();
}else{
getSupportActionBar().hide();
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Globo.actChatlogVisisble = false;
}
private void setTitle() {
SpannableString ss;
boolean isChannelVoice;
boolean isServerVoice;
isChannelVoice = (Globo.voiceServer == Globo.chatlogActNetworkName && Globo.voiceChannel.equals(Globo.chatlogActChannelName) && Globo.voiceType.equals("channel") );
isServerVoice = (Globo.voiceServer == Globo.chatlogActNetworkName && Globo.voiceType.equals("server"));
int servercolor = this.getResources().getColor(Globo.botManager.getStatusColorServer(Globo.chatlogActNetworkName, false));
int appnamelength =0;
if ( Globo.chatlogActType.equals("server")) {
ss = new SpannableString ( Globo.chatlogActAccountName);
Globo.botManager.getStatusColorServer(Globo.chatlogActNetworkName, false);
ss.setSpan(new ForegroundColorSpan(servercolor), appnamelength, ss.length() , 0);
if (isServerVoice) {
ss.setSpan(new StyleSpan(Typeface.ITALIC), appnamelength, ss.length(), 0);
}
}else{
int channelcolor = this.getResources().getColor(Globo.botManager.getStatusColorChannel(Globo.chatlogActNetworkName, Globo.chatlogActChannelName, false));
ss = new SpannableString ( Globo.chatlogActAccountName + " " + Globo.chatlogActChannelName);
ss.setSpan(new ForegroundColorSpan(servercolor), appnamelength, appnamelength + Globo.chatlogActAccountName.length() , 0);
ss.setSpan(new ForegroundColorSpan(channelcolor), appnamelength + Globo.chatlogActAccountName.length() , ss.length() , 0);
if (isServerVoice) {
ss.setSpan(new StyleSpan(Typeface.ITALIC), appnamelength, appnamelength + Globo.chatlogActAccountName.length(), 0);
}else if(isChannelVoice) {
ss.setSpan(new StyleSpan(Typeface.ITALIC), appnamelength + Globo.chatlogActAccountName.length(), ss.length(), 0);
}
}
this.setTitle(ss);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
GloboUtil.globalizeChannelPrefs(this);
GloboUtil.claimaudiostream(this);
if (Globo.chatlogChanNav == null) {
Globo.chatlogChanNav = new AtomicBoolean();
Globo.chatlogChanNav.set(Globo.pref_chan_showchannav);
}
if (Globo.chatlogActNav == null) {
Globo.chatlogActNav = new AtomicBoolean();
Globo.chatlogActNav.set(Globo.pref_chan_showactnav);
}
//mark read and update notification
synchronized(LogManager.serverLogMap) {
updateChecked();
}
listener = new NavBarListener();
initialize();
initializeCrossing();
setTitle();
listview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
scrollToUid();
//if from notice go to position else go to end
}
protected void scrollToUid() {
if (uid > -1) {
int position = adapter.getPositionByUid(uid);
listview.post(new Runnable(){ public void run()
{ listview.setSelectionFromTop(adapter.getPositionByUid(uid), 10);
uid=-1;
ActChatLog.this.getIntent().putExtra("uid", -1); }});
}else{
listview.post(new Runnable(){ public void run() {
listview.setSelection(adapter.getCount()-1);
}});
}
}
protected void updateChecked() {
if (LogManager.serverLogMap.containsKey(Globo.chatlogActNetworkName)) {
ServerLog sl = LogManager.serverLogMap.get(Globo.chatlogActNetworkName);
if (Globo.chatlogActType.equals("server")) {
sl.checked = true;
}else{
if (sl.channelLogMap.containsKey(Globo.chatlogActChannelName)) {
if (!sl.channelLogMap.get(Globo.chatlogActChannelName).checked) {
//mark checked
sl.channelLogMap.get(Globo.chatlogActChannelName).checked = true;
if (!Globo.chatlogActChannelName.startsWith("#")) {
//refresh notification
Intent serviceIconUpdate = new Intent(this, IrcRadioService.class);
serviceIconUpdate.putExtra("action", "updateicon");
this.startService(serviceIconUpdate);
}
}
}
}
}
}
public void selectUser () {
DialogManagerChat dmc = new DialogManagerChat(this);
dmc.promptUser();
}
synchronized private void initialize() {
listview = (ListView)this.findViewById(R.id.ListViewServerLog);
//font style mono for server log.
Typeface typeface = Typeface.DEFAULT;
if (Globo.chatlogActType.equals("server") ) {
typeface = Typeface.MONOSPACE;
}
adapter = new ListChatAdapter(this, typeface, Globo.chatlogActAccountName );
listview.setAdapter(adapter);
this.registerForContextMenu(listview);
Globo.actChatlogVisisble = true;
//initialize textbox
et = (EditText)this.findViewById(R.id.textinput);
et.setOnKeyListener(new OnKeyListener()
{public boolean onKey(View v, int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
postmessage();
return true;
}
return true;
}
return false;
}
});
}
private void refreshNavBar() {
setTitle();
if (Globo.chatlogChanNav.get()){
LinearLayout navChanll;
View divider1;
navChanll = (LinearLayout)this.findViewById(R.id.navchanll);
synchronized(LogManager.serverLogMap) {
//NavBar.initialize(this, navChanll, listener);
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public Handler myHandler=new Handler() {
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
String action = msg.getData().getString("action");
String type = msg.getData().getString("type");
if (action == "addline") {
LogEntry logentry =(LogEntry) msg.getData().getSerializable("logentry");
adapter.addToList(logentry);
adapter.notifyDataSetChanged();
return;
}
if (action == "toast") {
ActChatLog.this.makeToast(msg.getData().getString("message"));
return;
}
if (action == "refresh") {
refreshNavBar();
}
}
};
private void postmessage() {
String input = et.getText().toString();
//check if server connected - parse command else warn not connected
if ( Globo.botManager.ircBots.containsKey(Globo.chatlogActNetworkName) ) {
if ( Globo.botManager.ircBots.get(Globo.chatlogActNetworkName).isConnected() ){
Globo.botManager.ircBots.get(Globo.chatlogActNetworkName).parseinput(input, Globo.chatlogActChannelName);
}else{
notConnectedError();
}
}else {
notConnectedError();
}
et.setText("");
}
private void notConnectedError() {
if(Globo.chatlogActType.equals("channel")){
//message notconnected
LogManager.writeChannelLog(MessageType.ERROR, "IRC Radio", getString(R.string.error_notconnectedtoserver), Globo.chatlogActNetworkName, Globo.chatlogActChannelName, Globo.chatlogActAccountName, this, true,"");
et.setText("");
}else{
LogManager.writeServerLog("error",getString(R.string.error_notconnectedtoserver),"",Globo.chatlogActNetworkName, Globo.chatlogActAccountName, this);
}
}
public void makeToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
@Override
public void onCross(boolean crossed) {
// TODO Auto-generated method stub
LinearLayout navChanll;
navChanll = (LinearLayout)this.findViewById(R.id.navchanll);
if (!crossed ) {
if (Globo.chatlogChanNav.get()) {
Globo.chatlogChanNav.set(false);
navChanll.setVisibility(View.GONE);
}else{
Globo.chatlogChanNav.set(true);
navChanll.setVisibility(View.VISIBLE);
this.refreshNavBar();
}
}else{
if (Globo.chatlogActNav.get()) {
Globo.chatlogActNav.set(false);
this.getSupportActionBar().hide();
}else{
Globo.chatlogActNav.set(true);
this.getSupportActionBar().show();
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
long network;
String account;
String channel;
String type;
boolean copysafe=false;
AdapterView.AdapterContextMenuInfo mi = (AdapterView.AdapterContextMenuInfo)menuInfo;
if (mi != null){
copysafe = true;
}
boolean navbutton = true;
if (v.getTag() == null) {
navbutton = false;
network = Globo.chatlogActNetworkName;
account = Globo.chatlogActAccountName;
channel = Globo.chatlogActChannelName;
type = Globo.chatlogActType;
}else{
NavItem ni = (NavItem)v.getTag();
network = ni.network;
account = ni.accountname;
channel = ni.channelname;
type = ni.acttype;
}
menuData = new MenuData(network,account,channel,type);
if (type.equals("server")) {
menu.setHeaderTitle(account);
if (!navbutton && copysafe){
menu.add(0, 5, 0, R.string.ctx_copy);
}
menu.add(0, 1, 0, R.string.ctx_clear);
menu.add(0, 2, 0, R.string.ctx_disconnect);
menu.add(0, 3, 0, R.string.ctx_close);
menu.add(0, 4, 0, R.string.ctx_activatespeech);
}else{
menu.setHeaderTitle(channel);
if (!navbutton && copysafe){
menu.add(0, 5, 0, R.string.ctx_copy);
}
menu.add(0, 0, 0, R.string.ctx_clear);
if (channel.startsWith("#")){
menu.add(0, 1, 0, R.string.ctx_part);
}
menu.add(0, 2, 0 , R.string.ctx_close);
menu.add(0, 3, 0, R.string.ctx_activatespeech);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
int clickeditem = item.getItemId();
if (menuData.type.equals("server")) {
switch(clickeditem) {
case 1:
LogManager.clearServer(menuData.network, menuData.account);
adapter.refresh();
this.adapter.notifyDataSetChanged();
this.refreshNavBar();
break;
case 2:
Globo.botManager.disconnectServer(menuData.network);
break;
case 3:
Globo.botManager.disconnectServer(menuData.network);
LogManager.closeServer(this, menuData.network);
nextLog();
break;
case 4:
promptLanguage("server",menuData.network,"");
break;
case 5:
AdapterView.AdapterContextMenuInfo mi = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
LogEntry logEntry = (LogEntry) adapter.getItem(mi.position);
clipboardCopy(logEntry);
break;
}
return true;
}
if (menuData.type.equals("channel")) {
switch(clickeditem) {
case 0:
LogManager.clearChannel(menuData.network, menuData.channel, menuData.account);
adapter.refresh();
this.adapter.notifyDataSetChanged();
this.refreshNavBar();
break;
case 1:
Globo.botManager.partChannel(menuData.network, menuData.channel, this);
break;
case 2:
Globo.botManager.partChannel(menuData.network, menuData.channel, this);
LogManager.closeChannel(this, menuData.network, menuData.channel , menuData.account);
nextLog();
break;
case 3:
promptLanguage("channel",menuData.network,menuData.channel);
this.refreshNavBar();
break;
case 5:
AdapterView.AdapterContextMenuInfo mi = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
LogEntry logEntry = (LogEntry) adapter.getItem(mi.position);
clipboardCopy(logEntry);
break;
}
return true;
}
return false;
}
protected void clipboardCopy(LogEntry logEntry) {
ClipboardManager cm = (ClipboardManager)this.getSystemService(CLIPBOARD_SERVICE);
cm.setText(logEntry.ss.toString());
}
protected void promptLanguage( String type, long network, String channel ) {
PromptVoiceLanguage dlg = new PromptVoiceLanguage(this, type, network, channel);
dlg.show();
}
class NavBarListener implements OnClickListener {
@Override
public void onClick(View v) {
NavItem ni = (NavItem)v.getTag();
changeLog(ni);
}
}
public void changeLog(NavItem ni) {
synchronized(LogManager.serverLogMap) {
Globo.chatlogActChannelName = ni.channelname;
Globo.chatlogActNetworkName = ni.network;
Globo.chatlogActType = ni.acttype;
Globo.chatlogActAccountName = ni.accountname;
Intent intent = new Intent(ActChatLog.this,ActChatLog.class);
intent.putExtra("channel", ni.channelname);
intent.putExtra("network", ni.network);
intent.putExtra("acttype", ni.acttype);
intent.putExtra("accountname", ni.accountname);
ActChatLog.this.setIntent(intent);
updateChecked();
//font style mono for server log.
Typeface typeface = Typeface.DEFAULT;
if (Globo.chatlogActType.equals("server") ) {
typeface = Typeface.MONOSPACE;
}
adapter = new ListChatAdapter(ActChatLog.this, typeface, Globo.chatlogActAccountName );
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
listview.setSelection(adapter.getCount());
setTitle();
LinearLayout navChanll;
navChanll = (LinearLayout)this.findViewById(R.id.navchanll);
//NavBar.initialize(ActChatLog.this, navChanll, listener);
}
}
public void nextLog() {
NavItem ni = new NavItem(Globo.chatlogActNetworkName,Globo.chatlogActAccountName);
ni = LogManager.getNextLog(ni);
if (ni.acttype.equals("none")) {
finish();
}else{
this.changeLog(ni);
}
}
private class MenuData {
public long network;
public String account;
public String channel;
public String type;
MenuData(long network, String account, String channel, String type) {
this.network = network;
this.account = account;
this.channel = channel;
this.type = type;
}
}
}
|
|
package extracells.tileentity;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridNode;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.crafting.ICraftingProvider;
import appeng.api.networking.crafting.ICraftingProviderHelper;
import appeng.api.networking.events.MENetworkCellArrayUpdate;
import appeng.api.networking.events.MENetworkCraftingPatternChange;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.networking.security.BaseActionSource;
import appeng.api.networking.security.IActionHost;
import appeng.api.networking.security.MachineSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.util.AECableType;
import appeng.api.util.DimensionalCoord;
import cpw.mods.fml.common.FMLCommonHandler;
import extracells.api.IECTileEntity;
import extracells.gridblock.ECFluidGridBlock;
import extracells.util.FluidUtil;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import org.apache.commons.lang3.tuple.MutablePair;
import java.util.ArrayList;
import java.util.List;
public class TileEntityFluidFiller extends TileBase implements IActionHost,
ICraftingProvider, IECTileEntity,
IMEMonitorHandlerReceiver<IAEFluidStack>, IListenerTile {
private ECFluidGridBlock gridBlock;
private IGridNode node = null;
List<Fluid> fluids = new ArrayList<Fluid>();
public ItemStack containerItem = new ItemStack(Items.bucket);
ItemStack returnStack = null;
int ticksToFinish = 0;
private boolean isFirstGetGridNode = true;
private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull();
public TileEntityFluidFiller() {
super();
this.gridBlock = new ECFluidGridBlock(this);
}
@MENetworkEventSubscribe
public void cellUpdate(MENetworkCellArrayUpdate event) {
IStorageGrid storage = getStorageGrid();
if (storage != null)
postChange(storage.getFluidInventory(), null, null);
}
@Override
public IGridNode getActionableNode() {
if (FMLCommonHandler.instance().getEffectiveSide().isClient())
return null;
if (this.node == null) {
this.node = AEApi.instance().createGridNode(this.gridBlock);
}
return this.node;
}
@Override
public AECableType getCableConnectionType(ForgeDirection dir) {
return AECableType.DENSE;
}
@Override
public Packet getDescriptionPacket() {
NBTTagCompound nbtTag = new NBTTagCompound();
writeToNBT(nbtTag);
return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord,
this.zCoord, 1, nbtTag);
}
@Override
public IGridNode getGridNode(ForgeDirection dir) {
if (FMLCommonHandler.instance().getSide().isClient()
&& (getWorldObj() == null || getWorldObj().isRemote))
return null;
if (this.isFirstGetGridNode) {
this.isFirstGetGridNode = false;
getActionableNode().updateState();
IStorageGrid storage = getStorageGrid();
storage.getFluidInventory().addListener(this, null);
}
return this.node;
}
@Override
public DimensionalCoord getLocation() {
return new DimensionalCoord(this);
}
private ItemStack getPattern(ItemStack emptyContainer,
ItemStack filledContainer) {
NBTTagList in = new NBTTagList();
NBTTagList out = new NBTTagList();
in.appendTag(emptyContainer.writeToNBT(new NBTTagCompound()));
out.appendTag(filledContainer.writeToNBT(new NBTTagCompound()));
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setTag("in", in);
itemTag.setTag("out", out);
itemTag.setBoolean("crafting", false);
ItemStack pattern = new ItemStack(this.encodedPattern);
pattern.setTagCompound(itemTag);
return pattern;
}
@Override
public double getPowerUsage() {
return 1.0D;
}
private IStorageGrid getStorageGrid() {
this.node = getGridNode(ForgeDirection.UNKNOWN);
if (this.node == null)
return null;
IGrid grid = this.node.getGrid();
if (grid == null)
return null;
return grid.getCache(IStorageGrid.class);
}
@Override
public boolean isBusy() {
return this.returnStack != null;
}
@Override
public boolean isValid(Object verificationToken) {
return true;
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.func_148857_g());
}
@Override
public void onListUpdate() {}
@Override
public void postChange(IBaseMonitor<IAEFluidStack> monitor,
Iterable<IAEFluidStack> change, BaseActionSource actionSource) {
List<Fluid> oldFluids = new ArrayList<Fluid>(this.fluids);
boolean mustUpdate = false;
this.fluids.clear();
for (IAEFluidStack fluid : ((IMEMonitor<IAEFluidStack>) monitor)
.getStorageList()) {
if (!oldFluids.contains(fluid.getFluid()))
mustUpdate = true;
else
oldFluids.remove(fluid.getFluid());
this.fluids.add(fluid.getFluid());
}
if (!(oldFluids.isEmpty() && !mustUpdate)) {
if (getGridNode(ForgeDirection.UNKNOWN) != null
&& getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) {
getGridNode(ForgeDirection.UNKNOWN).getGrid().postEvent(
new MENetworkCraftingPatternChange(this,
getGridNode(ForgeDirection.UNKNOWN)));
}
}
}
public void postUpdateEvent() {
if (getGridNode(ForgeDirection.UNKNOWN) != null
&& getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) {
getGridNode(ForgeDirection.UNKNOWN).getGrid().postEvent(
new MENetworkCraftingPatternChange(this,
getGridNode(ForgeDirection.UNKNOWN)));
}
}
@MENetworkEventSubscribe
public void powerUpdate(MENetworkPowerStatusChange event) {
IStorageGrid storage = getStorageGrid();
if (storage != null)
postChange(storage.getFluidInventory(), null, null);
}
@Override
public void provideCrafting(ICraftingProviderHelper craftingTracker) {
IStorageGrid storage = getStorageGrid();
if (storage == null)
return;
IMEMonitor<IAEFluidStack> fluidStorage = storage.getFluidInventory();
for (IAEFluidStack fluidStack : fluidStorage.getStorageList()) {
Fluid fluid = fluidStack.getFluid();
if (fluid == null)
continue;
int maxCapacity = FluidUtil.getCapacity(this.containerItem);
if (maxCapacity == 0)
continue;
MutablePair<Integer, ItemStack> filled = FluidUtil.fillStack(
this.containerItem.copy(), new FluidStack(fluid,
maxCapacity));
if (filled.right == null)
continue;
ItemStack pattern = getPattern(this.containerItem, filled.right);
ICraftingPatternItem patter = (ICraftingPatternItem) pattern
.getItem();
craftingTracker.addCraftingOption(this,
patter.getPatternForItem(pattern, getWorldObj()));
}
}
@Override
public boolean pushPattern(ICraftingPatternDetails patternDetails,
InventoryCrafting table) {
if (this.returnStack != null)
return false;
ItemStack filled = patternDetails.getCondensedOutputs()[0]
.getItemStack();
FluidStack fluid = FluidUtil.getFluidFromContainer(filled);
IStorageGrid storage = getStorageGrid();
if (storage == null)
return false;
IAEFluidStack fluidStack = AEApi
.instance()
.storage()
.createFluidStack(
new FluidStack(
fluid.getFluid(),
FluidUtil.getCapacity(patternDetails
.getCondensedInputs()[0].getItemStack())));
IAEFluidStack extracted = storage.getFluidInventory()
.extractItems(fluidStack.copy(), Actionable.SIMULATE,
new MachineSource(this));
if (extracted == null
|| extracted.getStackSize() != fluidStack.getStackSize())
return false;
storage.getFluidInventory().extractItems(fluidStack,
Actionable.MODULATE, new MachineSource(this));
this.returnStack = filled;
this.ticksToFinish = 40;
return true;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
if (tagCompound.hasKey("container"))
this.containerItem = ItemStack.loadItemStackFromNBT(tagCompound
.getCompoundTag("container"));
else if (tagCompound.hasKey("isContainerEmpty")
&& tagCompound.getBoolean("isContainerEmpty"))
this.containerItem = null;
if (tagCompound.hasKey("return"))
this.returnStack = ItemStack.loadItemStackFromNBT(tagCompound
.getCompoundTag("return"));
else if (tagCompound.hasKey("isReturnEmpty")
&& tagCompound.getBoolean("isReturnEmpty"))
this.returnStack = null;
if (tagCompound.hasKey("time"))
this.ticksToFinish = tagCompound.getInteger("time");
if (hasWorldObj()) {
IGridNode node = getGridNode(ForgeDirection.UNKNOWN);
if (tagCompound.hasKey("nodes") && node != null) {
node.loadFromNBT("node0", tagCompound.getCompoundTag("nodes"));
node.updateState();
}
}
}
@Override
public void registerListener() {
IStorageGrid storage = getStorageGrid();
if (storage == null)
return;
postChange(storage.getFluidInventory(), null, null);
storage.getFluidInventory().addListener(this, null);
}
@Override
public void removeListener() {
IStorageGrid storage = getStorageGrid();
if (storage == null)
return;
storage.getFluidInventory().removeListener(this);
}
@Override
public void securityBreak() {
if (this.getWorldObj() != null)
getWorldObj().func_147480_a(this.xCoord, this.yCoord, this.zCoord,
true);
}
@Override
public void updateEntity() {
if (getWorldObj() == null || getWorldObj().provider == null)
return;
if (this.ticksToFinish > 0)
this.ticksToFinish = this.ticksToFinish - 1;
if (this.ticksToFinish <= 0 && this.returnStack != null) {
IStorageGrid storage = getStorageGrid();
if (storage == null)
return;
IAEItemStack toInject = AEApi.instance().storage()
.createItemStack(this.returnStack);
if (storage.getItemInventory().canAccept(toInject.copy())) {
IAEItemStack nodAdded = storage.getItemInventory().injectItems(
toInject.copy(), Actionable.SIMULATE,
new MachineSource(this));
if (nodAdded == null) {
storage.getItemInventory().injectItems(toInject,
Actionable.MODULATE, new MachineSource(this));
this.returnStack = null;
}
}
}
}
@Override
public void updateGrid(IGrid oldGrid, IGrid newGrid) {
if (oldGrid != null) {
IStorageGrid storage = oldGrid.getCache(IStorageGrid.class);
if (storage != null)
storage.getFluidInventory().removeListener(this);
}
if (newGrid != null) {
IStorageGrid storage = newGrid.getCache(IStorageGrid.class);
if (storage != null)
storage.getFluidInventory().addListener(this, null);;
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
if (this.containerItem != null)
tagCompound.setTag("container", this.containerItem.writeToNBT(new NBTTagCompound()));
else
tagCompound.setBoolean("isContainerEmpty", true);
if (this.returnStack != null)
tagCompound.setTag("return", this.returnStack.writeToNBT(new NBTTagCompound()));
else
tagCompound.setBoolean("isReturnEmpty", true);
tagCompound.setInteger("time", this.ticksToFinish);
if (!hasWorldObj())
return;
IGridNode node = getGridNode(ForgeDirection.UNKNOWN);
if (node != null) {
NBTTagCompound nodeTag = new NBTTagCompound();
node.saveToNBT("node0", nodeTag);
tagCompound.setTag("nodes", nodeTag);
}
}
}
|
|
/*
* 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.data.provider;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.vaadin.shared.Range;
import com.vaadin.shared.data.HierarchicalDataCommunicatorConstants;
import com.vaadin.ui.ItemCollapseAllowedProvider;
import elemental.json.Json;
import elemental.json.JsonObject;
/**
* Mapper for hierarchical data.
* <p>
* Keeps track of the expanded nodes, and size of of the subtrees for each
* expanded node.
* <p>
* This class is framework internal implementation details, and can be changed /
* moved at any point. This means that you should not directly use this for
* anything.
*
* @author Vaadin Ltd
* @since 8.1
*
* @param <T>
* the data type
* @param <F>
* the filter type
*/
public class HierarchyMapper<T, F> implements DataGenerator<T> {
// childMap is only used for finding parents of items and clean up on
// removing children of expanded nodes.
private Map<T, Set<T>> childMap = new HashMap<>();
private Map<Object, T> parentIdMap = new HashMap<>();
private final HierarchicalDataProvider<T, F> provider;
private F filter;
private List<QuerySortOrder> backEndSorting;
private Comparator<T> inMemorySorting;
private ItemCollapseAllowedProvider<T> itemCollapseAllowedProvider = t -> true;
private Set<Object> expandedItemIds = new HashSet<>();
/**
* Constructs a new HierarchyMapper.
*
* @param provider
* the hierarchical data provider for this mapper
*/
public HierarchyMapper(HierarchicalDataProvider<T, F> provider) {
this.provider = provider;
}
/**
* Returns the size of the currently expanded hierarchy.
*
* @return the amount of available data
*/
public int getTreeSize() {
return (int) getHierarchy(null).count();
}
/**
* Finds the index of the parent of the item in given target index.
*
* @param item
* the item to get the parent of
* @return the parent index or a negative value if the parent is not found
*
*/
public Integer getParentIndex(T item) {
// TODO: This can be optimized.
List<T> flatHierarchy = getHierarchy(null).collect(Collectors.toList());
return flatHierarchy.indexOf(getParentOfItem(item));
}
/**
* Returns whether the given item is expanded.
*
* @param item
* the item to test
* @return {@code true} if item is expanded; {@code false} if not
*/
public boolean isExpanded(T item) {
if (item == null) {
// Root nodes are always visible.
return true;
}
return expandedItemIds.contains(getDataProvider().getId(item));
}
/**
* Expands the given item.
*
* @param item
* the item to expand
* @param position
* the index of item
* @return range of rows added by expanding the item
*/
public Range doExpand(T item, Optional<Integer> position) {
Range rows = Range.withLength(0, 0);
if (!isExpanded(item) && hasChildren(item)) {
Object id = getDataProvider().getId(item);
expandedItemIds.add(id);
if (position.isPresent()) {
rows = Range.withLength(position.get() + 1,
(int) getHierarchy(item, false).count());
}
}
return rows;
}
/**
* Collapses the given item.
*
* @param item
* the item to expand
* @param position
* the index of item
*
* @return range of rows removed by collapsing the item
*/
public Range doCollapse(T item, Optional<Integer> position) {
Range removedRows = Range.withLength(0, 0);
if (isExpanded(item)) {
Object id = getDataProvider().getId(item);
if (position.isPresent()) {
long childCount = getHierarchy(item, false).count();
removedRows = Range.withLength(position.get() + 1,
(int) childCount);
}
expandedItemIds.remove(id);
}
return removedRows;
}
@Override
public void generateData(T item, JsonObject jsonObject) {
JsonObject hierarchyData = Json.createObject();
int depth = getDepth(item);
if (depth >= 0) {
hierarchyData.put(HierarchicalDataCommunicatorConstants.ROW_DEPTH,
depth);
}
boolean isLeaf = !getDataProvider().hasChildren(item);
if (isLeaf) {
hierarchyData.put(HierarchicalDataCommunicatorConstants.ROW_LEAF,
true);
} else {
hierarchyData.put(
HierarchicalDataCommunicatorConstants.ROW_COLLAPSED,
!isExpanded(item));
hierarchyData.put(HierarchicalDataCommunicatorConstants.ROW_LEAF,
false);
hierarchyData.put(
HierarchicalDataCommunicatorConstants.ROW_COLLAPSE_ALLOWED,
getItemCollapseAllowedProvider().test(item));
}
// add hierarchy information to row as metadata
jsonObject.put(
HierarchicalDataCommunicatorConstants.ROW_HIERARCHY_DESCRIPTION,
hierarchyData);
}
/**
* Gets the current item collapse allowed provider.
*
* @return the item collapse allowed provider
*/
public ItemCollapseAllowedProvider<T> getItemCollapseAllowedProvider() {
return itemCollapseAllowedProvider;
}
/**
* Sets the current item collapse allowed provider.
*
* @param itemCollapseAllowedProvider
* the item collapse allowed provider
*/
public void setItemCollapseAllowedProvider(
ItemCollapseAllowedProvider<T> itemCollapseAllowedProvider) {
this.itemCollapseAllowedProvider = itemCollapseAllowedProvider;
}
/**
* Gets the current in-memory sorting.
*
* @return the in-memory sorting
*/
public Comparator<T> getInMemorySorting() {
return inMemorySorting;
}
/**
* Sets the current in-memory sorting. This will cause the hierarchy to be
* constructed again.
*
* @param inMemorySorting
* the in-memory sorting
*/
public void setInMemorySorting(Comparator<T> inMemorySorting) {
this.inMemorySorting = inMemorySorting;
}
/**
* Gets the current back-end sorting.
*
* @return the back-end sorting
*/
public List<QuerySortOrder> getBackEndSorting() {
return backEndSorting;
}
/**
* Sets the current back-end sorting. This will cause the hierarchy to be
* constructed again.
*
* @param backEndSorting
* the back-end sorting
*/
public void setBackEndSorting(List<QuerySortOrder> backEndSorting) {
this.backEndSorting = backEndSorting;
}
/**
* Gets the current filter.
*
* @return the filter
*/
public F getFilter() {
return filter;
}
/**
* Sets the current filter. This will cause the hierarchy to be constructed
* again.
*
* @param filter
* the filter
*/
public void setFilter(Object filter) {
this.filter = (F) filter;
}
/**
* Gets the {@code HierarchicalDataProvider} for this
* {@code HierarchyMapper}.
*
* @return the hierarchical data provider
*/
public HierarchicalDataProvider<T, F> getDataProvider() {
return provider;
}
/**
* Returns whether given item has children.
*
* @param item
* the node to test
* @return {@code true} if node has children; {@code false} if not
*/
public boolean hasChildren(T item) {
return getDataProvider().hasChildren(item);
}
/* Fetch methods. These are used to calculate what to request. */
/**
* Gets a stream of items in the form of a flattened hierarchy from the
* back-end and filter the wanted results from the list.
*
* @param range
* the requested item range
* @return the stream of items
*/
public Stream<T> fetchItems(Range range) {
return getHierarchy(null).skip(range.getStart()).limit(range.length());
}
/**
* Gets a stream of children for the given item in the form of a flattened
* hierarchy from the back-end and filter the wanted results from the list.
*
* @param parent
* the parent item for the fetch
* @param range
* the requested item range
* @return the stream of items
*/
public Stream<T> fetchItems(T parent, Range range) {
return getHierarchy(parent, false).skip(range.getStart())
.limit(range.length());
}
/* Methods for providing information on the hierarchy. */
/**
* Generic method for finding direct children of a given parent, limited by
* given range.
*
* @param parent
* the parent
* @param range
* the range of direct children to return
* @return the requested children of the given parent
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private Stream<T> doFetchDirectChildren(T parent, Range range) {
return getDataProvider().fetchChildren(new HierarchicalQuery(
range.getStart(), range.length(), getBackEndSorting(),
getInMemorySorting(), getFilter(), parent));
}
private int getDepth(T item) {
int depth = -1;
while (item != null) {
item = getParentOfItem(item);
++depth;
}
return depth;
}
/**
* Find parent for the given item among open folders.
* @param item the item
* @return parent item or {@code null} for root items or if the parent is closed
*/
protected T getParentOfItem(T item) {
Objects.requireNonNull(item, "Can not find the parent of null");
return parentIdMap.get(getDataProvider().getId(item));
}
/**
* Removes all children of an item identified by a given id. Items removed
* by this method as well as the original item are all marked to be
* collapsed.
* May be overridden in subclasses for removing obsolete data to avoid memory leaks.
*
* @param id
* the item id
*/
protected void removeChildren(Object id) {
// Clean up removed nodes from child map
Iterator<Entry<T, Set<T>>> iterator = childMap.entrySet().iterator();
Set<T> invalidatedChildren = new HashSet<>();
while (iterator.hasNext()) {
Entry<T, Set<T>> entry = iterator.next();
T key = entry.getKey();
if (key != null && getDataProvider().getId(key).equals(id)) {
invalidatedChildren.addAll(entry.getValue());
iterator.remove();
}
}
expandedItemIds.remove(id);
invalidatedChildren.stream().map(getDataProvider()::getId).forEach(x -> {
removeChildren(x);
parentIdMap.remove(x);
});
}
/**
* Finds the current index of given object. This is based on a search in
* flattened version of the hierarchy.
*
* @param target
* the target object to find
* @return optional index of given object
*/
public Optional<Integer> getIndexOf(T target) {
if (target == null) {
return Optional.empty();
}
final List<Object> collect = getHierarchy(null).map(provider::getId)
.collect(Collectors.toList());
int index = collect.indexOf(getDataProvider().getId(target));
return Optional.ofNullable(index < 0 ? null : index);
}
/**
* Gets the full hierarchy tree starting from given node.
*
* @param parent
* the parent node to start from
* @return the flattened hierarchy as a stream
*/
private Stream<T> getHierarchy(T parent) {
return getHierarchy(parent, true);
}
/**
* Getst hte full hierarchy tree starting from given node. The starting node
* can be omitted.
*
* @param parent
* the parent node to start from
* @param includeParent
* {@code true} to include the parent; {@code false} if not
* @return the flattened hierarchy as a stream
*/
private Stream<T> getHierarchy(T parent, boolean includeParent) {
return Stream.of(parent)
.flatMap(node -> getChildrenStream(node, includeParent));
}
/**
* Gets the stream of direct children for given node.
*
* @param parent
* the parent node
* @return the stream of direct children
*/
private Stream<T> getDirectChildren(T parent) {
return doFetchDirectChildren(parent, Range.between(0, getDataProvider()
.getChildCount(new HierarchicalQuery<>(filter, parent))));
}
/**
* The method to recursively fetch the children of given parent. Used with
* {@link Stream#flatMap} to expand a stream of parent nodes into a
* flattened hierarchy.
*
* @param parent
* the parent node
* @return the stream of all children under the parent, includes the parent
*/
private Stream<T> getChildrenStream(T parent) {
return getChildrenStream(parent, true);
}
/**
* The method to recursively fetch the children of given parent. Used with
* {@link Stream#flatMap} to expand a stream of parent nodes into a
* flattened hierarchy.
*
* @param parent
* the parent node
* @param includeParent
* {@code true} to include the parent in the stream;
* {@code false} if not
* @return the stream of all children under the parent
*/
private Stream<T> getChildrenStream(T parent, boolean includeParent) {
List<T> childList = Collections.emptyList();
if (isExpanded(parent)) {
childList = getDirectChildren(parent).collect(Collectors.toList());
if (childList.isEmpty()) {
removeChildren(parent == null ? null
: getDataProvider().getId(parent));
} else {
registerChildren(parent, childList);
}
}
return combineParentAndChildStreams(parent,
childList.stream().flatMap(this::getChildrenStream),
includeParent);
}
/**
* Register parent and children items into inner structures.
* May be overridden in subclasses.
*
* @param parent the parent item
* @param childList list of parents children to be registered.
*/
protected void registerChildren(T parent, List<T> childList) {
childMap.put(parent, new HashSet<>(childList));
childList.forEach(x -> parentIdMap.put(getDataProvider().getId(x), parent));
}
/**
* Helper method for combining parent and a stream of children into one
* stream. {@code null} item is never included, and parent can be skipped by
* providing the correct value for {@code includeParent}.
*
* @param parent
* the parent node
* @param children
* the stream of children
* @param includeParent
* {@code true} to include the parent in the stream;
* {@code false} if not
* @return the combined stream of parent and its children
*/
private Stream<T> combineParentAndChildStreams(T parent, Stream<T> children,
boolean includeParent) {
boolean parentIncluded = includeParent && parent != null;
Stream<T> parentStream = parentIncluded ? Stream.of(parent)
: Stream.empty();
return Stream.concat(parentStream, children);
}
@Override
public void destroyAllData() {
childMap.clear();
parentIdMap.clear();
}
}
|
|
/*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.service;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import edu.northwestern.bioinformatics.studycalendar.core.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.core.StudyCalendarTestCase;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.domain.BlackoutDate;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.SpecificDateBlackout;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Subject;
import edu.northwestern.bioinformatics.studycalendar.service.dataproviders.SiteConsumer;
import java.util.Arrays;
import java.util.List;
import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*;
import static org.easymock.classextension.EasyMock.expect;
/**
* @author Padmaja Vedula
*/
public class SiteServiceTest extends StudyCalendarTestCase {
private SiteDao siteDao;
private SiteService service;
private SiteConsumer siteConsumer;
private Site nu, mayo;
@Override
protected void setUp() throws Exception {
super.setUp();
siteDao = registerDaoMockFor(SiteDao.class);
siteConsumer = registerMockFor(SiteConsumer.class);
service = new SiteService();
service.setSiteDao(siteDao);
service.setSiteConsumer(siteConsumer);
nu = setId(1, Fixtures.createNamedInstance("Northwestern", Site.class));
mayo = setId(4, Fixtures.createNamedInstance("Mayo", Site.class));
}
public void testCreateSite() throws Exception {
siteDao.save(nu);
replayMocks();
Site siteCreated = service.createOrUpdateSite(nu);
verifyMocks();
assertNotNull("site not returned", siteCreated);
}
public void testRemoveRemovableSite() throws Exception {
Site site = new Site();
site.setId(1);
siteDao.delete(site);
replayMocks();
service.removeSite(site);
verifyMocks();
}
public void testRemoveSiteWhenSiteMayNotBeRemoved() throws Exception {
Site site = setId(4, new Site());
Fixtures.createAssignment(new Study(), site, new Subject());
replayMocks(); // expect nothing to happen
service.removeSite(site);
verifyMocks();
}
public void testCreateOrMergeSiteForCreateSite() throws Exception {
siteDao.save(nu);
replayMocks();
Site newSite = service.createOrMergeSites(null, nu);
assertEquals(newSite.getName(), nu.getName());
verifyMocks();
}
public void testCreateOrMergeSiteForMergeSite() throws Exception {
nu.setId(1);
Site newSite = new Site();
newSite.setName("new Name");
siteDao.save(nu);
expect(siteDao.getById(1)).andReturn(nu);
expect(siteConsumer.refresh(nu)).andReturn(nu);
replayMocks();
Site mergedSite = service.createOrMergeSites(nu, newSite);
verifyMocks();
assertEquals("new Name", mergedSite.getName());
assertEquals(mergedSite, nu);
}
public void testGetByIdRefreshesSite() throws Exception {
nu.setId(1);
expect(siteDao.getById(1)).andReturn(nu);
expect(siteConsumer.refresh(nu)).andReturn(nu);
replayMocks();
assertSame(nu, service.getById(1));
verifyMocks();
}
public void testGetByIdForUnknownReturnsNull() throws Exception {
expect(siteDao.getById(-1)).andReturn(null);
replayMocks();
assertNull(service.getById(-1));
verifyMocks();
}
public void testGetByAssignedIdentRefreshesSite() throws Exception {
expect(siteDao.getByAssignedIdentifier("NU")).andReturn(nu);
expect(siteConsumer.refresh(nu)).andReturn(nu);
replayMocks();
assertSame(nu, service.getByAssignedIdentifier("NU"));
verifyMocks();
}
public void testGetByAssignedIdentForUnknownReturnsNull() throws Exception {
expect(siteDao.getByAssignedIdentifier("elf")).andReturn(null);
replayMocks();
assertNull(service.getByAssignedIdentifier("elf"));
verifyMocks();
}
public void testGetByNameRefreshesSite() throws Exception {
expect(siteDao.getByName("Northwestern")).andReturn(nu);
expect(siteConsumer.refresh(nu)).andReturn(nu);
replayMocks();
assertSame(nu, service.getByName("Northwestern"));
verifyMocks();
}
public void testGetByNameForUnknownReturnsNull() throws Exception {
expect(siteDao.getByAssignedIdentifier("xyz")).andReturn(null);
replayMocks();
assertNull(service.getByAssignedIdentifier("xyz"));
verifyMocks();
}
public void testGetAllRefreshes() throws Exception {
List<Site> expected = Arrays.asList(nu, mayo);
expect(siteDao.getAll()).andReturn(expected);
expect(siteConsumer.refresh(expected)).andReturn(expected);
replayMocks();
List<Site> actual = service.getAll();
assertSame("Wrong 0", nu, actual.get(0));
assertSame("Wrong 1", mayo, actual.get(1));
verifyMocks();
}
public void testMergeSiteForProvidedSite() throws Exception {
nu.setId(1);
nu.setProvider("Provider");
Site newSite = new Site();
try {
service.createOrMergeSites(nu, newSite);
fail("Exception not thrown");
} catch (StudyCalendarSystemException e) {
assertEquals("The provided site Northwestern is not editable", e.getMessage());
}
}
public void testDeleteSiteWhenSiteHasStudySiteRelation() throws Exception {
Study study = createNamedInstance("Study A", Study.class);
Site site = createNamedInstance("Northwestern", Site.class);
site.setId(12);
createStudySite(study, site);
siteDao.delete(site);
replayMocks();
service.removeSite(site);
verifyMocks();
}
public void testResolveSiteForBlackoutDateWhenSiteFound() throws Exception {
SpecificDateBlackout blackOutDate = createBlackoutDate();
assertNull("Site is not from system", blackOutDate.getSite().getId());
expect(siteDao.getByAssignedIdentifier("Mayo")).andReturn(mayo);
replayMocks();
BlackoutDate actual = service.resolveSiteForBlackoutDate(blackOutDate);
verifyMocks();
assertNotNull("Site is new", actual.getSite().getId());
}
public void testResolveSiteForBlackoutDateWhenSiteNotFound() throws Exception {
SpecificDateBlackout blackOutDate = createBlackoutDate();
assertNull("Site is not from system", blackOutDate.getSite().getId());
expect(siteDao.getByAssignedIdentifier("Mayo")).andReturn(null);
replayMocks();
try {
service.resolveSiteForBlackoutDate(blackOutDate);
fail("Exception not thrown");
} catch (StudyCalendarValidationException scve) {
assertEquals("Site 'Mayo' not found. Please define a site that exists.", scve.getMessage());
}
}
//Helper Method
private SpecificDateBlackout createBlackoutDate() {
SpecificDateBlackout blackOutDate = new SpecificDateBlackout();
blackOutDate.setDay(2);
blackOutDate.setMonth(1);
blackOutDate.setYear(2008);
blackOutDate.setDescription("month day holiday");
Site site = new Site();
site.setAssignedIdentifier("Mayo");
blackOutDate.setSite(site);
blackOutDate.setGridId("3");
return blackOutDate;
}
}
|
|
package org.apache.maven.plugin.assembly.archive.task;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import junit.framework.TestCase;
import org.apache.maven.plugin.assembly.archive.ArchiveCreationException;
import org.apache.maven.plugin.assembly.testutils.MockManager;
import org.apache.maven.plugin.assembly.testutils.TestFileManager;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.ArchiverException;
import org.easymock.MockControl;
public class AddDirectoryTaskTest
extends TestCase
{
private MockManager mockManager;
private TestFileManager fileManager;
private Archiver archiver;
private MockControl archiverControl;
public void setUp()
{
fileManager = new TestFileManager( "ArchiveAssemblyUtils.test.", "" );
mockManager = new MockManager();
archiverControl = MockControl.createControl( Archiver.class );
mockManager.add( archiverControl );
archiver = (Archiver) archiverControl.getMock();
}
public void tearDown()
throws IOException
{
fileManager.cleanUp();
}
public void testAddDirectory_ShouldNotAddDirectoryIfNonExistent()
throws ArchiveCreationException
{
File dir = new File( System.getProperty( "java.io.tmpdir" ), "non-existent." + System.currentTimeMillis() );
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.execute( archiver, null );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectory()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( null );
archiverControl.setMatcher( MockControl.ALWAYS_MATCHER );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setOutputDirectory( "dir" );
task.execute( archiver, null );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectoryWithDirMode()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( null );
archiverControl.setMatcher( MockControl.ALWAYS_MATCHER );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
int dirMode = Integer.parseInt( "777", 8 );
int fileMode = Integer.parseInt( "777", 8 );
configureModeExpectations( -1, -1, dirMode, fileMode, true );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setDirectoryMode( dirMode );
task.setFileMode( fileMode );
task.setOutputDirectory( "dir" );
task.execute( archiver, null );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectoryWithIncludesAndExcludes()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( null );
archiverControl.setMatcher( MockControl.ALWAYS_MATCHER );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setIncludes( Collections.singletonList( "**/*.txt" ) );
task.setExcludes( Collections.singletonList( "**/README.txt" ) );
task.setOutputDirectory( "dir" );
task.execute( archiver, null );
mockManager.verifyAll();
}
private void configureModeExpectations( int defaultDirMode, int defaultFileMode, int dirMode, int fileMode,
boolean expectTwoSets )
{
archiver.getOverrideDirectoryMode();
archiverControl.setReturnValue( defaultDirMode );
archiver.getOverrideFileMode();
archiverControl.setReturnValue( defaultFileMode );
if ( expectTwoSets )
{
if ( dirMode > -1 )
{
archiver.setDirectoryMode( dirMode );
}
if ( fileMode > -1 )
{
archiver.setFileMode( fileMode );
}
}
if ( dirMode > -1 )
{
archiver.setDirectoryMode( defaultDirMode );
}
if ( fileMode > -1 )
{
archiver.setFileMode( defaultFileMode );
}
}
}
|
|
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.pkgcache;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ServerDirectories;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.util.AnalysisMock;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.BuildFileContainsErrorsException;
import com.google.devtools.build.lib.packages.NoSuchPackageException;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.PackageFactory;
import com.google.devtools.build.lib.packages.StarlarkSemanticsOptions;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction;
import com.google.devtools.build.lib.skyframe.BazelSkyframeExecutorConstants;
import com.google.devtools.build.lib.skyframe.PrecomputedValue;
import com.google.devtools.build.lib.skyframe.SkyframeExecutor;
import com.google.devtools.build.lib.syntax.StarlarkFile;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.testutil.SkyframeExecutorTestHelper;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for package loading. */
@RunWith(JUnit4.class)
public class PackageLoadingTest extends FoundationTestCase {
private AnalysisMock analysisMock;
private ConfiguredRuleClassProvider ruleClassProvider;
private SkyframeExecutor skyframeExecutor;
private final ActionKeyContext actionKeyContext = new ActionKeyContext();
@Before
public final void initializeSkyframeExecutor() throws Exception {
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ true);
}
/**
* @param doPackageLoadingChecks when true, a PackageLoader will be called after each package load
* this test performs, and the results compared to SkyFrame's result.
*/
private void initializeSkyframeExecutor(boolean doPackageLoadingChecks) throws Exception {
analysisMock = AnalysisMock.get();
ruleClassProvider = analysisMock.createRuleClassProvider();
BlazeDirectories directories =
new BlazeDirectories(
new ServerDirectories(outputBase, outputBase, outputBase),
rootDirectory,
/* defaultSystemJavabase= */ null,
analysisMock.getProductName());
PackageFactory.BuilderForTesting packageFactoryBuilder =
analysisMock.getPackageFactoryBuilderForTesting(directories);
if (!doPackageLoadingChecks) {
packageFactoryBuilder.disableChecks();
}
BuildOptions defaultBuildOptions;
try {
defaultBuildOptions = BuildOptions.of(ImmutableList.of());
} catch (OptionsParsingException e) {
throw new RuntimeException(e);
}
skyframeExecutor =
BazelSkyframeExecutorConstants.newBazelSkyframeExecutorBuilder()
.setPkgFactory(packageFactoryBuilder.build(ruleClassProvider, fileSystem))
.setFileSystem(fileSystem)
.setDirectories(directories)
.setActionKeyContext(actionKeyContext)
.setDefaultBuildOptions(defaultBuildOptions)
.setExtraSkyFunctions(analysisMock.getSkyFunctions(directories))
.build();
SkyframeExecutorTestHelper.process(skyframeExecutor);
setUpSkyframe(parsePackageOptions(), parseStarlarkSemanticsOptions());
}
private void setUpSkyframe(
PackageOptions packageOptions, StarlarkSemanticsOptions starlarkSemanticsOptions) {
PathPackageLocator pkgLocator =
PathPackageLocator.create(
null,
packageOptions.packagePath,
reporter,
rootDirectory,
rootDirectory,
BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY);
packageOptions.showLoadingProgress = true;
packageOptions.globbingThreads = 7;
skyframeExecutor.injectExtraPrecomputedValues(
ImmutableList.of(
PrecomputedValue.injected(
RepositoryDelegatorFunction.RESOLVED_FILE_INSTEAD_OF_WORKSPACE,
Optional.<RootedPath>absent())));
skyframeExecutor.preparePackageLoading(
pkgLocator,
packageOptions,
starlarkSemanticsOptions,
UUID.randomUUID(),
ImmutableMap.<String, String>of(),
new TimestampGranularityMonitor(BlazeClock.instance()));
skyframeExecutor.setActionEnv(ImmutableMap.<String, String>of());
skyframeExecutor.setDeletedPackages(ImmutableSet.copyOf(packageOptions.getDeletedPackages()));
}
private OptionsParser parse(String... options) throws Exception {
OptionsParser parser =
OptionsParser.builder()
.optionsClasses(PackageOptions.class, StarlarkSemanticsOptions.class)
.build();
parser.parse("--default_visibility=public");
parser.parse(options);
return parser;
}
private PackageOptions parsePackageOptions(String... options) throws Exception {
return parse(options).getOptions(PackageOptions.class);
}
private StarlarkSemanticsOptions parseStarlarkSemanticsOptions(String... options)
throws Exception {
return parse(options).getOptions(StarlarkSemanticsOptions.class);
}
protected void setOptions(String... options) throws Exception {
setUpSkyframe(parsePackageOptions(options), parseStarlarkSemanticsOptions(options));
}
private PackageManager getPackageManager() {
return skyframeExecutor.getPackageManager();
}
private void invalidatePackages() throws InterruptedException {
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
}
private Package getPackage(String packageName)
throws NoSuchPackageException, InterruptedException {
return getPackageManager()
.getPackage(reporter, PackageIdentifier.createInMainRepo(packageName));
}
private Target getTarget(Label label)
throws NoSuchPackageException, NoSuchTargetException, InterruptedException {
return getPackageManager().getTarget(reporter, label);
}
private Target getTarget(String label) throws Exception {
return getTarget(Label.parseAbsolute(label, ImmutableMap.of()));
}
private void createPkg1() throws IOException {
scratch.file("pkg1/BUILD", "cc_library(name = 'foo') # a BUILD file");
}
// Check that a substring is present in an error message.
private void checkGetPackageFails(String packageName, String expectedMessage) throws Exception {
NoSuchPackageException e =
assertThrows(NoSuchPackageException.class, () -> getPackage(packageName));
assertThat(e).hasMessageThat().contains(expectedMessage);
}
@Test
public void testGetPackage() throws Exception {
createPkg1();
Package pkg1 = getPackage("pkg1");
assertThat(pkg1.getName()).isEqualTo("pkg1");
assertThat(pkg1.getFilename().asPath().getPathString()).isEqualTo("/workspace/pkg1/BUILD");
assertThat(getPackageManager().getPackage(reporter, PackageIdentifier.createInMainRepo("pkg1")))
.isSameInstanceAs(pkg1);
}
@Test
public void testASTIsNotRetained() throws Exception {
createPkg1();
Package pkg1 = getPackage("pkg1");
MoreAsserts.assertInstanceOfNotReachable(pkg1, StarlarkFile.class);
}
@Test
public void testGetNonexistentPackage() throws Exception {
checkGetPackageFails("not-there", "no such package 'not-there': " + "BUILD file not found");
}
@Test
public void testGetPackageWithInvalidName() throws Exception {
scratch.file("invalidpackagename:42/BUILD", "cc_library(name = 'foo') # a BUILD file");
checkGetPackageFails(
"invalidpackagename:42",
"no such package 'invalidpackagename:42': Invalid package name 'invalidpackagename:42'");
}
@Test
public void testGetTarget() throws Exception {
createPkg1();
Label label = Label.parseAbsolute("//pkg1:foo", ImmutableMap.of());
Target target = getTarget(label);
assertThat(target.getLabel()).isEqualTo(label);
}
@Test
public void testGetNonexistentTarget() throws Exception {
createPkg1();
NoSuchTargetException e =
assertThrows(NoSuchTargetException.class, () -> getTarget("//pkg1:not-there"));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"no such target '//pkg1:not-there': target 'not-there' "
+ "not declared in package 'pkg1' defined by /workspace/pkg1/BUILD");
}
/**
* A missing package is one for which no BUILD file can be found. The PackageCache caches failures
* of this kind until the next sync.
*/
@Test
public void testRepeatedAttemptsToParseMissingPackage() throws Exception {
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
// Still missing:
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
// Update the BUILD file on disk so "missing" is no longer missing:
scratch.file("missing/BUILD", "# an ok build file");
// Still missing:
checkGetPackageFails("missing", "no such package 'missing': " + "BUILD file not found");
invalidatePackages();
// Found:
Package missing = getPackage("missing");
assertThat(missing.getName()).isEqualTo("missing");
}
/**
* A broken package is one that exists but contains lexer/parser/evaluator errors. The
* PackageCache only makes one attempt to parse each package once found.
*
* <p>Depending on the strictness of the PackageFactory, parsing a broken package may cause a
* Package object to be returned (possibly missing some rules) or an exception to be thrown. For
* this test we need that strict behavior.
*
* <p>Note: since the PackageCache.setStrictPackageCreation method was deleted (since it wasn't
* used by any significant clients) creating a "broken" build file got trickier--syntax errors are
* not enough. For now, we create an unreadable BUILD file, which will cause an IOException to be
* thrown. This test seems less valuable than it once did.
*/
@Test
public void testParseBrokenPackage() throws Exception {
reporter.removeHandler(failFastHandler);
Path brokenBuildFile = scratch.file("broken/BUILD");
brokenBuildFile.setReadable(false);
BuildFileContainsErrorsException e =
assertThrows(BuildFileContainsErrorsException.class, () -> getPackage("broken"));
assertThat(e).hasMessageThat().contains("/workspace/broken/BUILD (Permission denied)");
eventCollector.clear();
// Update the BUILD file on disk so "broken" is no longer broken:
scratch.overwriteFile("broken/BUILD", "# an ok build file");
invalidatePackages(); // resets cache of failures
Package broken = getPackage("broken");
assertThat(broken.getName()).isEqualTo("broken");
assertNoEvents();
}
@Test
public void testMovedBuildFileCausesReloadAfterSync() throws Exception {
// PackageLoader doesn't support --package_path.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
Path buildFile1 = scratch.file("pkg/BUILD", "cc_library(name = 'foo')");
Path buildFile2 = scratch.file("/otherroot/pkg/BUILD", "cc_library(name = 'bar')");
setOptions("--package_path=/workspace:/otherroot");
Package oldPkg = getPackage("pkg");
assertThat(getPackage("pkg")).isSameInstanceAs(oldPkg); // change not yet visible
assertThat(oldPkg.getFilename().asPath()).isEqualTo(buildFile1);
assertThat(oldPkg.getSourceRoot().get()).isEqualTo(Root.fromPath(rootDirectory));
buildFile1.delete();
invalidatePackages();
Package newPkg = getPackage("pkg");
assertThat(newPkg).isNotSameInstanceAs(oldPkg);
assertThat(newPkg.getFilename().asPath()).isEqualTo(buildFile2);
assertThat(newPkg.getSourceRoot().get()).isEqualTo(Root.fromPath(scratch.dir("/otherroot")));
// TODO(bazel-team): (2009) test BUILD file moves in the other direction too.
}
private Path rootDir1;
private Path rootDir2;
private void setUpCacheWithTwoRootLocator() throws Exception {
// Root 1:
// /a/BUILD
// /b/BUILD
// /c/d
// /c/e
//
// Root 2:
// /b/BUILD
// /c/BUILD
// /c/d/BUILD
// /f/BUILD
// /f/g
// /f/g/h/BUILD
rootDir1 = scratch.dir("/workspace");
rootDir2 = scratch.dir("/otherroot");
createBuildFile(rootDir1, "a", "foo.txt", "bar/foo.txt");
createBuildFile(rootDir1, "b", "foo.txt", "bar/foo.txt");
rootDir1.getRelative("c").createDirectory();
rootDir1.getRelative("c/d").createDirectory();
rootDir1.getRelative("c/e").createDirectory();
createBuildFile(rootDir2, "c", "d", "d/foo.txt", "foo.txt", "bar/foo.txt", "e", "e/foo.txt");
createBuildFile(rootDir2, "c/d", "foo.txt");
createBuildFile(rootDir2, "f", "g/foo.txt", "g/h", "g/h/foo.txt", "foo.txt");
createBuildFile(rootDir2, "f/g/h", "foo.txt");
setOptions("--package_path=/workspace:/otherroot");
}
protected Path createBuildFile(Path workspace, String packageName, String... targets)
throws IOException {
String[] lines = new String[targets.length];
for (int i = 0; i < targets.length; i++) {
lines[i] = "sh_library(name='" + targets[i] + "')";
}
return scratch.file(workspace + "/" + packageName + "/BUILD", lines);
}
private void assertLabelValidity(boolean expected, String labelString) throws Exception {
Label label = Label.parseAbsolute(labelString, ImmutableMap.of());
boolean actual = false;
String error = null;
try {
getTarget(label);
actual = true;
} catch (NoSuchPackageException | NoSuchTargetException e) {
error = e.getMessage();
}
if (actual != expected) {
fail(
"assertLabelValidity("
+ label
+ ") "
+ actual
+ ", not equal to expected value "
+ expected
+ " (error="
+ error
+ ")");
}
}
private void assertPackageLoadingFails(String pkgName, String expectedError) throws Exception {
Package pkg = getPackage(pkgName);
assertThat(pkg.containsErrors()).isTrue();
assertContainsEvent(expectedError);
}
@Test
public void testLocationForLabelCrossingSubpackage() throws Exception {
scratch.file("e/f/BUILD");
scratch.file("e/BUILD", "# Whatever", "filegroup(name='fg', srcs=['f/g'])");
reporter.removeHandler(failFastHandler);
List<Event> events = getPackage("e").getEvents();
assertThat(events).hasSize(1);
assertThat(events.get(0).getLocation().line()).isEqualTo(2);
}
/** Static tests (i.e. no changes to filesystem, nor calls to sync). */
@Test
public void testLabelValidity() throws Exception {
// PackageLoader doesn't support --package_path.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
reporter.removeHandler(failFastHandler);
setUpCacheWithTwoRootLocator();
scratch.file(rootDir2 + "/c/d/foo.txt");
assertLabelValidity(true, "//a:foo.txt");
assertLabelValidity(true, "//a:bar/foo.txt");
assertLabelValidity(false, "//a/bar:foo.txt"); // no such package a/bar
assertLabelValidity(true, "//b:foo.txt");
assertLabelValidity(true, "//b:bar/foo.txt");
assertLabelValidity(false, "//b/bar:foo.txt"); // no such package b/bar
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(true, "//c:bar/foo.txt");
assertLabelValidity(false, "//c/bar:foo.txt"); // no such package c/bar
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(false, "//c:d/foo.txt"); // crosses boundary of c/d
assertLabelValidity(true, "//c/d:foo.txt");
assertLabelValidity(true, "//c:foo.txt");
assertLabelValidity(true, "//c:e");
assertLabelValidity(true, "//c:e/foo.txt");
assertLabelValidity(false, "//c/e:foo.txt"); // no such package c/e
assertLabelValidity(true, "//f:foo.txt");
assertLabelValidity(true, "//f:g/foo.txt");
assertLabelValidity(false, "//f/g:foo.txt"); // no such package f/g
assertLabelValidity(false, "//f:g/h/foo.txt"); // crosses boundary of f/g/h
assertLabelValidity(false, "//f/g:h/foo.txt"); // no such package f/g
assertLabelValidity(true, "//f/g/h:foo.txt");
}
/** Dynamic tests of label validity. */
@Test
public void testAddedBuildFileCausesLabelToBecomeInvalid() throws Exception {
reporter.removeHandler(failFastHandler);
scratch.file("pkg/BUILD", "cc_library(name = 'foo', srcs = ['x/y.cc'])");
assertLabelValidity(true, "//pkg:x/y.cc");
// The existence of this file makes 'x/y.cc' an invalid reference.
scratch.file("pkg/x/BUILD");
// but not yet...
assertLabelValidity(true, "//pkg:x/y.cc");
invalidatePackages();
// now:
assertPackageLoadingFails(
"pkg", "Label '//pkg:x/y.cc' is invalid because 'pkg/x' is a subpackage");
}
@Test
public void testDeletedPackages() throws Exception {
// PackageLoader doesn't support --deleted_packages.
initializeSkyframeExecutor(/*doPackageLoadingChecks=*/ false);
reporter.removeHandler(failFastHandler);
setUpCacheWithTwoRootLocator();
createBuildFile(rootDir1, "c", "d/x");
// Now package c exists in both roots, and c/d exists in only in the second
// root. It's as if we've merged c and c/d in the first root.
// c/d is still a subpackage--found in the second root:
assertThat(getPackage("c/d").getFilename().asPath())
.isEqualTo(rootDir2.getRelative("c/d/BUILD"));
// Subpackage labels are still valid...
assertLabelValidity(true, "//c/d:foo.txt");
// ...and this crosses package boundaries:
assertLabelValidity(false, "//c:d/x");
assertPackageLoadingFails(
"c",
"Label '//c:d/x' is invalid because 'c/d' is a subpackage; have you deleted c/d/BUILD? "
+ "If so, use the --deleted_packages=c/d option");
assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d")))
.isTrue();
setOptions("--deleted_packages=c/d");
invalidatePackages();
assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d")))
.isFalse();
// c/d is no longer a subpackage--even though there's a BUILD file in the
// second root:
NoSuchPackageException e = assertThrows(NoSuchPackageException.class, () -> getPackage("c/d"));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"no such package 'c/d': Package is considered deleted due to --deleted_packages");
// Labels in the subpackage are no longer valid...
assertLabelValidity(false, "//c/d:x");
// ...and now d is just a subdirectory of c:
assertLabelValidity(true, "//c:d/x");
}
@Test
public void testPackageFeatures() throws Exception {
scratch.file(
"peach/BUILD",
"package(features = ['crosstool_default_false'])",
"cc_library(name = 'cc', srcs = ['cc.cc'])");
assertThat(getPackage("peach").getFeatures()).hasSize(1);
}
@Test
public void testBrokenPackageOnMultiplePackagePathEntries() throws Exception {
reporter.removeHandler(failFastHandler);
setOptions("--package_path=.:.");
scratch.file("x/y/BUILD");
scratch.file("x/BUILD", "genrule(name = 'x',", "srcs = [],", "outs = ['y/z.h'],", "cmd = '')");
Package p = getPackage("x");
assertThat(p.containsErrors()).isTrue();
}
}
|
|
package uk.ac.ebi.spot.goci.curation.model;
import org.springframework.format.annotation.DateTimeFormat;
import uk.ac.ebi.spot.goci.model.Curator;
import uk.ac.ebi.spot.goci.model.NoteSubject;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
/**
* Created by xinhe on 03/04/2017.
*/
public class StudyNoteForm {
private Long id;
@NotNull
@Size(min = 1)
//Thymeleaf will not return null for an text input, instead it returns an empty string of size 0.
private String textNote;
@NotNull
private NoteSubject noteSubject;
@NotNull
private Boolean status;
@NotNull
private Curator curator;
private Long genericId;
@DateTimeFormat(pattern = "YYYY-MM-dd HH:mm:ss")
private Date createdAt;
@DateTimeFormat(pattern = "YYYY-MM-dd HH:mm:ss")
private Date updatedAt;
private Boolean isSystemNote = Boolean.FALSE;
private Boolean canEdit = Boolean.TRUE;
private Boolean canRemove = Boolean.TRUE;
private Boolean canSave = Boolean.FALSE;
private Boolean canDiscard = Boolean.FALSE;
private Boolean editing = Boolean.FALSE;
public StudyNoteForm() {
}
public StudyNoteForm(Long id,
String textNote,
NoteSubject noteSubject,
Boolean status,
Curator curator,
Long genericId,
Date createdAt,
Date updatedAt) {
this.id = id;
this.textNote = textNote;
this.noteSubject = noteSubject;
this.status = status;
this.curator = curator;
this.genericId = genericId;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Boolean getSystemNote() {
return isSystemNote;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTextNote() {
return textNote;
}
public void setTextNote(String textNote) {
this.textNote = textNote;
}
public NoteSubject getNoteSubject() {
return noteSubject;
}
public void setNoteSubject(NoteSubject noteSubject) {
this.noteSubject = noteSubject;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Curator getCurator() {
return curator;
}
public void setCurator(Curator curator) {
this.curator = curator;
}
public Long getGenericId() {
return genericId;
}
public void setGenericId(Long genericId) {
this.genericId = genericId;
}
public Boolean getCanEdit() {
return canEdit;
}
public void setCanEdit(Boolean canEdit) {
this.canEdit = canEdit;
}
public Boolean getCanRemove() {
return canRemove;
}
public void setCanRemove(Boolean canRemove) {
this.canRemove = canRemove;
}
public Boolean getCanSave() {
return canSave;
}
public void setCanSave(Boolean canSave) {
this.canSave = canSave;
}
public Boolean getCanDiscard() {
return canDiscard;
}
public void setCanDiscard(Boolean canDiscard) {
this.canDiscard = canDiscard;
}
public Boolean getEditing() {
return editing;
}
public void setEditing(Boolean editing) {
this.editing = editing;
}
public void setSystemNote(Boolean systemNote) {
isSystemNote = systemNote;
}
public Boolean isSystemNoteFrom() {
return isSystemNote;
}
public void startEdit() {
this.setEditing(Boolean.TRUE);
this.setCanDiscard(Boolean.TRUE);
this.setCanSave(Boolean.TRUE);
this.setCanEdit(Boolean.FALSE);
this.setCanRemove(Boolean.FALSE);
}
public void finishEdit() {
makeEditable();
}
public void makeNotEditable() {
this.setCanEdit(Boolean.FALSE);
this.setCanRemove(Boolean.FALSE);
this.setCanSave(Boolean.FALSE);
this.setCanDiscard(Boolean.FALSE);
this.setEditing(Boolean.FALSE);
}
public void makeEditable() {
this.setCanEdit(Boolean.TRUE);
this.setCanRemove(Boolean.TRUE);
this.setCanSave(Boolean.FALSE);
this.setCanDiscard(Boolean.FALSE);
this.setEditing(Boolean.FALSE);
}
}
|
|
package ping.pong.net.server.io;
import java.net.SocketAddress;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ping.pong.net.connection.Connection;
import ping.pong.net.connection.ConnectionEvent;
import ping.pong.net.connection.config.ConnectionConfigFactory;
import ping.pong.net.connection.messaging.Envelope;
import ping.pong.net.connection.messaging.MessageListener;
import ping.pong.net.server.Server;
import ping.pong.net.server.ServerConnectionListener;
/**
*
* @author mfullen
*/
public class IoServerTest
{
private static final Logger logger = LoggerFactory.getLogger(IoServer.class);
Envelope<String> tcpMessage = new Envelope<String>()
{
@Override
public boolean isReliable()
{
return true;
}
@Override
public String getMessage()
{
return "Test";
}
};
Connection connection1 = new Connection<String>()
{
@Override
public void close()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isConnected()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getConnectionId()
{
return 1;
}
@Override
public void setConnectionId(int id)
{
assertTrue(id == 1);
}
@Override
public void sendMessage(Envelope<String> message)
{
assertTrue(message.isReliable());
assertEquals(message.getMessage(), "Test");
}
@Override
public void run()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void addConnectionEventListener(ConnectionEvent listener)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeConnectionEventListener(ConnectionEvent listener)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isUsingCustomSerialization()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isUdpEnabled()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SocketAddress getSocketAddress()
{
throw new UnsupportedOperationException("Not supported yet.");
}
};
public IoServerTest()
{
}
@BeforeClass
public static void setUpClass() throws Exception
{
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
/**
* Test of broadcast method, of class IoServer.
*/
@Test
public void testBroadcast()
{
IoServer instance = new IoServer();
assertNotNull(instance);
assertNotNull(connection1);
instance.addConnection(connection1);
instance.broadcast(tcpMessage);
}
/**
* Test of start method, of class IoServer.
*/
@Test
public void testStart()
{
IoServer instance = new IoServer();
instance.start();
assertTrue(instance.isListening());
}
@Test
public void testConnectionManager()
{
IoServer instance = new IoServer();
assertFalse(instance.isListening());
assertNull(instance.serverConnectionManager);
instance.serverConnectionManager = new ServerConnectionManager(ConnectionConfigFactory.createConnectionConfiguration(), instance);
assertNotNull(instance.serverConnectionManager);
//assertFalse(instance.isListening());
instance.start();
}
/**
* Test of shutdown method, of class IoServer.
*/
@Test
public void testShutdown()
{
IoServer instance = new IoServer();
instance.shutdown();
instance.start();
assertTrue(instance.isListening());
instance.shutdown();
assertFalse(instance.isListening());
}
/**
* Test of getConnection method, of class IoServer.
*/
@Test
public void testGetConnection()
{
IoServer instance = new IoServer();
assertNotNull(instance);
assertNotNull(connection1);
int id = connection1.getConnectionId();
assertNull(instance.getConnection(id));
instance.addConnection(connection1);
assertEquals(connection1, instance.getConnection(id));
}
/**
* Test of getConnections method, of class IoServer.
*/
@Test
public void testGetConnections()
{
IoServer instance = new IoServer();
assertTrue(instance.getConnections().isEmpty());
instance.addConnection(connection1);
assertEquals(instance.getConnections().size(), 1);
}
/**
* Test of hasConnections method, of class IoServer.
*/
@Test
public void testHasConnections()
{
IoServer instance = new IoServer();
assertFalse(instance.hasConnections());
instance.addConnection(connection1);
assertTrue(instance.hasConnections());
}
/**
* Test of isListening method, of class IoServer.
*/
@Test
public void testIsListening()
{
IoServer instance = new IoServer();
assertFalse(instance.isListening());
instance.start();
assertTrue(instance.isListening());
instance.shutdown();
assertFalse(instance.isListening());
}
@Test
public void testIsListening2()
{
IoServer instance = new IoServer();
assertFalse(instance.isListening());
instance.serverConnectionManager = new ServerConnectionManager(ConnectionConfigFactory.createConnectionConfiguration(), instance);
instance.serverConnectionManager.listening = false;
assertFalse(instance.isListening());
}
/**
* Test of addMessageListener method, of class IoServer.
*/
@Test
public void testAddMessageListener()
{
MessageListener<? super Connection, Envelope> listener = null;
IoServer instance = new IoServer();
instance.addMessageListener(listener);
assertEquals(0, instance.messageListeners.size());
listener = new MessageListener<Connection, Envelope>()
{
@Override
public void messageReceived(Connection source, Envelope message)
{
assertNotNull(source);
assertNotNull(message);
}
};
instance.addMessageListener(listener);
assertEquals(1, instance.messageListeners.size());
}
/**
* Test of removeMessageListener method, of class IoServer.
*/
@Test
public void testRemoveMessageListener()
{
MessageListener<? super Connection, Envelope> listener = null;
IoServer instance = new IoServer();
instance.removeMessageListener(listener);
assertEquals(0, instance.messageListeners.size());
listener = new MessageListener<Connection, Envelope>()
{
@Override
public void messageReceived(Connection source, Envelope message)
{
assertNotNull(source);
assertNotNull(message);
}
};
instance.addMessageListener(listener);
assertEquals(1, instance.messageListeners.size());
instance.removeMessageListener(listener);
assertEquals(0, instance.messageListeners.size());
}
/**
* Test of addConnectionListener method, of class IoServer.
*/
@Test
public void testAddConnectionListener()
{
ServerConnectionListener listener = null;
IoServer instance = new IoServer();
instance.addConnectionListener(listener);
assertEquals(0, instance.connectionListeners.size());
listener = new ServerConnectionListener()
{
@Override
public void connectionAdded(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
@Override
public void connectionRemoved(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
};
instance.addConnectionListener(listener);
assertEquals(1, instance.connectionListeners.size());
}
/**
* Test of removeConnectionListener method, of class IoServer.
*/
@Test
public void testRemoveConnectionListener()
{
ServerConnectionListener listener = null;
IoServer instance = new IoServer();
instance.removeConnectionListener(listener);
assertEquals(0, instance.connectionListeners.size());
listener = new ServerConnectionListener()
{
@Override
public void connectionAdded(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
@Override
public void connectionRemoved(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
};
instance.addConnectionListener(listener);
assertEquals(1, instance.connectionListeners.size());
instance.removeConnectionListener(listener);
assertEquals(0, instance.connectionListeners.size());
}
/**
* Test of getNextAvailableId method, of class IoServer.
*/
@Test
public void testGetNextAvailableId()
{
IoServer instance = new IoServer();
int result = instance.getNextAvailableId();
assertEquals(1, result);
instance.addConnection(connection1);
result = instance.getNextAvailableId();
result = instance.getNextAvailableId();
assertEquals(2, result);
}
@Test
public void testRemoveConnection()
{
IoServer instance = new IoServer();
ServerConnectionListener listener = new ServerConnectionListener()
{
@Override
public void connectionAdded(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
@Override
public void connectionRemoved(Server server, Connection conn)
{
assertNotNull(server);
assertNotNull(conn);
}
};
instance.addConnectionListener(listener);
instance.addConnection(connection1);
assertEquals(1, instance.getConnections().size());
assertNotNull(instance.getConnection(connection1.getConnectionId()));
instance.removeConnection(connection1);
assertEquals(0, instance.getConnections().size());
assertNull(instance.getConnection(connection1.getConnectionId()));
instance.removeConnectionListener(listener);
instance.addConnection(connection1);
assertEquals(1, instance.getConnections().size());
assertNotNull(instance.getConnection(connection1.getConnectionId()));
instance.removeConnection(connection1.getConnectionId());
assertEquals(0, instance.getConnections().size());
assertNull(instance.getConnection(connection1.getConnectionId()));
instance.removeConnection(null);
assertEquals(0, instance.getConnections().size());
assertNull(instance.getConnection(connection1.getConnectionId()));
}
}
|
|
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* 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.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm.tree.analysis;
import java.util.List;
import org.objectweb.asm.Type;
/**
* An extended {@link BasicVerifier} that performs more precise verifications.
* This verifier computes exact class types, instead of using a single "object
* reference" type (as done in the {@link BasicVerifier}).
*
* @author Eric Bruneton
* @author Bing Ran
*/
public class SimpleVerifier extends BasicVerifier {
/**
* The class that is verified.
*/
private final Type currentClass;
/**
* The super class of the class that is verified.
*/
private final Type currentSuperClass;
/**
* The interfaces implemented by the class that is verified.
*/
private final List<Type> currentClassInterfaces;
/**
* If the class that is verified is an interface.
*/
private final boolean isInterface;
/**
* The loader to use for referenced classes.
*/
private ClassLoader loader = getClass().getClassLoader();
/**
* Constructs a new {@link SimpleVerifier}.
*/
public SimpleVerifier() {
this(null, null, false);
}
/**
* Constructs a new {@link SimpleVerifier} to verify a specific class. This
* class will not be loaded into the JVM since it may be incorrect.
*
* @param currentClass the class that is verified.
* @param currentSuperClass the super class of the class that is verified.
* @param isInterface if the class that is verified is an interface.
*/
public SimpleVerifier(
final Type currentClass,
final Type currentSuperClass,
final boolean isInterface)
{
this(currentClass, currentSuperClass, null, isInterface);
}
/**
* Constructs a new {@link SimpleVerifier} to verify a specific class. This
* class will not be loaded into the JVM since it may be incorrect.
*
* @param currentClass the class that is verified.
* @param currentSuperClass the super class of the class that is verified.
* @param currentClassInterfaces the interfaces implemented by the class
* that is verified.
* @param isInterface if the class that is verified is an interface.
*/
public SimpleVerifier(
final Type currentClass,
final Type currentSuperClass,
final List<Type> currentClassInterfaces,
final boolean isInterface)
{
this(ASM4,
currentClass,
currentSuperClass,
currentClassInterfaces,
isInterface);
}
protected SimpleVerifier(
final int api,
final Type currentClass,
final Type currentSuperClass,
final List<Type> currentClassInterfaces,
final boolean isInterface)
{
super(api);
this.currentClass = currentClass;
this.currentSuperClass = currentSuperClass;
this.currentClassInterfaces = currentClassInterfaces;
this.isInterface = isInterface;
}
/**
* Set the <code>ClassLoader</code> which will be used to load referenced
* classes. This is useful if you are verifying multiple interdependent
* classes.
*
* @param loader a <code>ClassLoader</code> to use
*/
public void setClassLoader(final ClassLoader loader) {
this.loader = loader;
}
@Override
public BasicValue newValue(final Type type) {
if (type == null) {
return BasicValue.UNINITIALIZED_VALUE;
}
boolean isArray = type.getSort() == Type.ARRAY;
if (isArray) {
switch (type.getElementType().getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
return new BasicValue(type);
}
}
BasicValue v = super.newValue(type);
if (BasicValue.REFERENCE_VALUE.equals(v)) {
if (isArray) {
v = newValue(type.getElementType());
String desc = v.getType().getDescriptor();
for (int i = 0; i < type.getDimensions(); ++i) {
desc = '[' + desc;
}
v = new BasicValue(Type.getType(desc));
} else {
v = new BasicValue(type);
}
}
return v;
}
@Override
protected boolean isArrayValue(final BasicValue value) {
Type t = value.getType();
return t != null
&& ("Lnull;".equals(t.getDescriptor()) || t.getSort() == Type.ARRAY);
}
@Override
protected BasicValue getElementValue(final BasicValue objectArrayValue)
throws AnalyzerException
{
Type arrayType = objectArrayValue.getType();
if (arrayType != null) {
if (arrayType.getSort() == Type.ARRAY) {
return newValue(Type.getType(arrayType.getDescriptor()
.substring(1)));
} else if ("Lnull;".equals(arrayType.getDescriptor())) {
return objectArrayValue;
}
}
throw new Error("Internal error");
}
@Override
protected boolean isSubTypeOf(final BasicValue value, final BasicValue expected) {
Type expectedType = expected.getType();
Type type = value.getType();
switch (expectedType.getSort()) {
case Type.INT:
case Type.FLOAT:
case Type.LONG:
case Type.DOUBLE:
return type.equals(expectedType);
case Type.ARRAY:
case Type.OBJECT:
if ("Lnull;".equals(type.getDescriptor())) {
return true;
} else if (type.getSort() == Type.OBJECT
|| type.getSort() == Type.ARRAY)
{
return isAssignableFrom(expectedType, type);
} else {
return false;
}
default:
throw new Error("Internal error");
}
}
@Override
public BasicValue merge(final BasicValue v, final BasicValue w) {
if (!v.equals(w)) {
Type t = v.getType();
Type u = w.getType();
if (t != null
&& (t.getSort() == Type.OBJECT || t.getSort() == Type.ARRAY))
{
if (u != null
&& (u.getSort() == Type.OBJECT || u.getSort() == Type.ARRAY))
{
if ("Lnull;".equals(t.getDescriptor())) {
return w;
}
if ("Lnull;".equals(u.getDescriptor())) {
return v;
}
if (isAssignableFrom(t, u)) {
return v;
}
if (isAssignableFrom(u, t)) {
return w;
}
// TODO case of array classes of the same dimension
// TODO should we look also for a common super interface?
// problem: there may be several possible common super
// interfaces
do {
if (t == null || isInterface(t)) {
return BasicValue.REFERENCE_VALUE;
}
t = getSuperClass(t);
if (isAssignableFrom(t, u)) {
return newValue(t);
}
} while (true);
}
}
return BasicValue.UNINITIALIZED_VALUE;
}
return v;
}
protected boolean isInterface(final Type t) {
if (currentClass != null && t.equals(currentClass)) {
return isInterface;
}
return getClass(t).isInterface();
}
protected Type getSuperClass(final Type t) {
if (currentClass != null && t.equals(currentClass)) {
return currentSuperClass;
}
Class<?> c = getClass(t).getSuperclass();
return c == null ? null : Type.getType(c);
}
protected boolean isAssignableFrom(final Type t, final Type u) {
if (t.equals(u)) {
return true;
}
if (currentClass != null && t.equals(currentClass)) {
if (getSuperClass(u) == null) {
return false;
} else {
if (isInterface) {
return u.getSort() == Type.OBJECT || u.getSort() == Type.ARRAY;
}
return isAssignableFrom(t, getSuperClass(u));
}
}
if (currentClass != null && u.equals(currentClass)) {
if (isAssignableFrom(t, currentSuperClass)) {
return true;
}
if (currentClassInterfaces != null) {
for (int i = 0; i < currentClassInterfaces.size(); ++i) {
Type v = currentClassInterfaces.get(i);
if (isAssignableFrom(t, v)) {
return true;
}
}
}
return false;
}
Class<?> tc = getClass(t);
if (tc.isInterface()) {
tc = Object.class;
}
return tc.isAssignableFrom(getClass(u));
}
protected Class<?> getClass(final Type t) {
try {
if (t.getSort() == Type.ARRAY) {
return Class.forName(t.getDescriptor().replace('/', '.'),
false,
loader);
}
return Class.forName(t.getClassName(), false, loader);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.toString());
}
}
}
|
|
/*
* Copyright 2009 The Closure Compiler 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.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.DefinitionsRemover.Definition;
import com.google.javascript.jscomp.DefinitionsRemover.ExternalNameOnlyDefinition;
import com.google.javascript.jscomp.DefinitionsRemover.UnknownDefinition;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Simple name-based definition gatherer that implements
* {@link DefinitionProvider}.
*
* It treats all variable writes as happening in the global scope and
* treats all objects as capable of having the same set of properties.
* The current implementation only handles definitions whose right
* hand side is an immutable value or function expression. All
* complex definitions are treated as unknowns.
*
*/
class SimpleDefinitionFinder implements CompilerPass, DefinitionProvider {
private final AbstractCompiler compiler;
private final Map<Node, DefinitionSite> definitionSiteMap;
private final Multimap<String, Definition> nameDefinitionMultimap;
private final Multimap<String, UseSite> nameUseSiteMultimap;
public SimpleDefinitionFinder(AbstractCompiler compiler) {
this.compiler = compiler;
this.definitionSiteMap = Maps.newLinkedHashMap();
this.nameDefinitionMultimap = LinkedHashMultimap.create();
this.nameUseSiteMultimap = LinkedHashMultimap.create();
}
/**
* Returns the collection of definition sites found during traversal.
*
* @return definition site collection.
*/
public Collection<DefinitionSite> getDefinitionSites() {
return definitionSiteMap.values();
}
private DefinitionSite getDefinitionAt(Node node) {
return definitionSiteMap.get(node);
}
DefinitionSite getDefinitionForFunction(Node function) {
Preconditions.checkState(function.isFunction());
return getDefinitionAt(getNameNodeFromFunctionNode(function));
}
@Override
public Collection<Definition> getDefinitionsReferencedAt(Node useSite) {
if (definitionSiteMap.containsKey(useSite)) {
return null;
}
if (useSite.isGetProp()) {
String propName = useSite.getLastChild().getString();
if (propName.equals("apply") || propName.equals("call")) {
useSite = useSite.getFirstChild();
}
}
String name = getSimplifiedName(useSite);
if (name != null) {
Collection<Definition> defs = nameDefinitionMultimap.get(name);
if (!defs.isEmpty()) {
return defs;
} else {
return null;
}
} else {
return null;
}
}
@Override
public void process(Node externs, Node source) {
NodeTraversal.traverse(
compiler, externs, new DefinitionGatheringCallback(true));
NodeTraversal.traverse(
compiler, source, new DefinitionGatheringCallback(false));
NodeTraversal.traverse(
compiler, source, new UseSiteGatheringCallback());
}
/**
* Returns a collection of use sites that may refer to provided
* definition. Returns an empty collection if the definition is not
* used anywhere.
*
* @param definition Definition of interest.
* @return use site collection.
*/
Collection<UseSite> getUseSites(Definition definition) {
String name = getSimplifiedName(definition.getLValue());
return nameUseSiteMultimap.get(name);
}
/**
* Extract a name from a node. In the case of GETPROP nodes,
* replace the namespace or object expression with "this" for
* simplicity and correctness at the expense of inefficiencies due
* to higher chances of name collisions.
*
* TODO(user) revisit. it would be helpful to at least use fully
* qualified names in the case of namespaces. Might not matter as
* much if this pass runs after "collapsing properties".
*/
private static String getSimplifiedName(Node node) {
if (node.isName()) {
String name = node.getString();
if (name != null && !name.isEmpty()) {
return name;
} else {
return null;
}
} else if (node.isGetProp()) {
return "this." + node.getLastChild().getString();
}
return null;
}
private class DefinitionGatheringCallback implements Callback {
private boolean inExterns;
DefinitionGatheringCallback(boolean inExterns) {
this.inExterns = inExterns;
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (inExterns) {
if (n.isFunction() && !n.getFirstChild().isName()) {
// No need to crawl functions in JSDoc
return false;
}
if (parent != null
&& parent.isFunction() && n != parent.getFirstChild()) {
// Arguments of external functions should not count as name
// definitions. They are placeholder names for documentation
// purposes only which are not reachable from anywhere.
return false;
}
}
return true;
}
@Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
if (inExterns && node.getJSDocInfo() != null) {
for (Node typeRoot : node.getJSDocInfo().getTypeNodes()) {
traversal.traverse(typeRoot);
}
}
Definition def =
DefinitionsRemover.getDefinition(node, inExterns);
if (def != null) {
String name = getSimplifiedName(def.getLValue());
if (name != null) {
Node rValue = def.getRValue();
if ((rValue != null) &&
!NodeUtil.isImmutableValue(rValue) &&
!rValue.isFunction()) {
// Unhandled complex expression
Definition unknownDef =
new UnknownDefinition(def.getLValue(), inExterns);
def = unknownDef;
}
// TODO(johnlenz) : remove this stub dropping code if it becomes
// illegal to have untyped stubs in the externs definitions.
if (inExterns) {
// We need special handling of untyped externs stubs here:
// the stub should be dropped if the name is provided elsewhere.
List<Definition> stubsToRemove = Lists.newArrayList();
// If there is no qualified name for this, then there will be
// no stubs to remove. This will happen if node is an object
// literal key.
if (node.isQualifiedName()) {
for (Definition prevDef : nameDefinitionMultimap.get(name)) {
if (prevDef instanceof ExternalNameOnlyDefinition
&& !jsdocContainsDeclarations(node)) {
if (node.matchesQualifiedName(prevDef.getLValue())) {
// Drop this stub, there is a real definition.
stubsToRemove.add(prevDef);
}
}
}
for (Definition prevDef : stubsToRemove) {
nameDefinitionMultimap.remove(name, prevDef);
}
}
}
nameDefinitionMultimap.put(name, def);
definitionSiteMap.put(node,
new DefinitionSite(node,
def,
traversal.getModule(),
traversal.inGlobalScope(),
inExterns));
}
}
if (inExterns && (parent != null) && parent.isExprResult()) {
String name = getSimplifiedName(node);
if (name != null) {
// TODO(johnlenz) : remove this code if it becomes illegal to have
// stubs in the externs definitions.
// We need special handling of untyped externs stubs here:
// the stub should be dropped if the name is provided elsewhere.
// We can't just drop the stub now as it needs to be used as the
// externs definition if no other definition is provided.
boolean dropStub = false;
if (!jsdocContainsDeclarations(node)) {
if (node.isQualifiedName()) {
for (Definition prevDef : nameDefinitionMultimap.get(name)) {
if (node.matchesQualifiedName(prevDef.getLValue())) {
dropStub = true;
break;
}
}
}
}
if (!dropStub) {
// Incomplete definition
Definition definition = new ExternalNameOnlyDefinition(node);
nameDefinitionMultimap.put(name, definition);
definitionSiteMap.put(node,
new DefinitionSite(node,
definition,
traversal.getModule(),
traversal.inGlobalScope(),
inExterns));
}
}
}
}
/**
* @return Whether the node has a JSDoc that actually declares something.
*/
private boolean jsdocContainsDeclarations(Node node) {
JSDocInfo info = node.getJSDocInfo();
return (info != null && info.containsDeclaration());
}
}
private class UseSiteGatheringCallback extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
Collection<Definition> defs = getDefinitionsReferencedAt(node);
if (defs == null) {
return;
}
Definition first = defs.iterator().next();
String name = getSimplifiedName(first.getLValue());
Preconditions.checkNotNull(name);
nameUseSiteMultimap.put(
name,
new UseSite(node, traversal.getScope(), traversal.getModule()));
}
}
/**
* @param use A use site to check.
* @return Whether the use is a call or new.
*/
static boolean isCallOrNewSite(UseSite use) {
Node call = use.node.getParent();
if (call == null) {
// The node has been removed from the AST.
return false;
}
// We need to make sure we're dealing with a call to the function we're
// optimizing. If the the first child of the parent is not the site, this
// is a nested call and it's a call to another function.
return NodeUtil.isCallOrNew(call) && call.getFirstChild() == use.node;
}
boolean canModifyDefinition(Definition definition) {
if (isExported(definition)) {
return false;
}
// Don't modify unused definitions for two reasons:
// 1) It causes unnecessary churn
// 2) Other definitions might be used to reflect on this one using
// goog.reflect.object (the check for definitions with uses is below).
Collection<UseSite> useSites = getUseSites(definition);
if (useSites.isEmpty()) {
return false;
}
for (UseSite site : useSites) {
// This catches the case where an object literal in goog.reflect.object
// and a prototype method have the same property name.
// NOTE(nicksantos): Maps and trogedit both do this by different
// mechanisms.
Node nameNode = site.node;
Collection<Definition> singleSiteDefinitions =
getDefinitionsReferencedAt(nameNode);
if (singleSiteDefinitions.size() > 1) {
return false;
}
Preconditions.checkState(!singleSiteDefinitions.isEmpty());
Preconditions.checkState(singleSiteDefinitions.contains(definition));
}
return true;
}
/**
* @return Whether the definition is directly exported.
*/
private boolean isExported(Definition definition) {
// Assume an exported method result is used.
Node lValue = definition.getLValue();
if (lValue == null) {
return true;
}
String partialName;
if (lValue.isGetProp()) {
partialName = lValue.getLastChild().getString();
} else if (lValue.isName()) {
partialName = lValue.getString();
} else {
// GETELEM is assumed to be an export or other expression are unknown
// uses.
return true;
}
CodingConvention codingConvention = compiler.getCodingConvention();
if (codingConvention.isExported(partialName)) {
return true;
}
return false;
}
/**
* @return Whether the function is defined in a non-aliasing expression.
*/
static boolean isSimpleFunctionDeclaration(Node fn) {
Node parent = fn.getParent();
Node gramps = parent.getParent();
// Simple definition finder doesn't provide useful results in some
// cases, specifically:
// - functions with recursive definitions
// - functions defined in object literals
// - functions defined in array literals
// Here we defined a set of known function declaration that are 'ok'.
// Some projects seem to actually define "JSCompiler_renameProperty"
// rather than simply having an extern definition. Don't mess with it.
Node nameNode = SimpleDefinitionFinder.getNameNodeFromFunctionNode(fn);
if (nameNode != null
&& nameNode.isName()) {
String name = nameNode.getString();
if (name.equals(NodeUtil.JSC_PROPERTY_NAME_FN) ||
name.equals(
ObjectPropertyStringPreprocess.EXTERN_OBJECT_PROPERTY_STRING)) {
return false;
}
}
// example: function a(){};
if (NodeUtil.isFunctionDeclaration(fn)) {
return true;
}
// example: a = function(){};
// example: var a = function(){};
if (fn.getFirstChild().getString().isEmpty()
&& (NodeUtil.isExprAssign(gramps) || parent.isName())) {
return true;
}
return false;
}
/**
* @return the node defining the name for this function (if any).
*/
static Node getNameNodeFromFunctionNode(Node function) {
Preconditions.checkState(function.isFunction());
if (NodeUtil.isFunctionDeclaration(function)) {
return function.getFirstChild();
} else {
Node parent = function.getParent();
if (NodeUtil.isVarDeclaration(parent)) {
return parent;
} else if (parent.isAssign()) {
return parent.getFirstChild();
} else if (NodeUtil.isObjectLitKey(parent)) {
return parent;
}
}
return null;
}
/**
* Traverse a node and its children and remove any references to from
* the structures.
*/
void removeReferences(Node node) {
if (DefinitionsRemover.isDefinitionNode(node)) {
DefinitionSite defSite = definitionSiteMap.get(node);
if (defSite != null) {
Definition def = defSite.definition;
String name = getSimplifiedName(def.getLValue());
if (name != null) {
this.definitionSiteMap.remove(node);
this.nameDefinitionMultimap.remove(name, node);
}
}
} else {
Node useSite = node;
if (useSite.isGetProp()) {
String propName = useSite.getLastChild().getString();
if (propName.equals("apply") || propName.equals("call")) {
useSite = useSite.getFirstChild();
}
}
String name = getSimplifiedName(useSite);
if (name != null) {
this.nameUseSiteMultimap.remove(name, new UseSite(useSite, null, null));
}
}
for (Node child : node.children()) {
removeReferences(child);
}
}
}
|
|
/*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
package net.adamcin.granite.client.packman;
import net.adamcin.commons.testing.junit.TestBody;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static org.junit.Assert.*;
public abstract class AbstractPackageManagerClientTestBase {
public final Logger LOGGER = LoggerFactory.getLogger(getClass());
public final ResponseProgressListener LISTENER = new LoggingListener(LOGGER, LoggingListener.Level.DEBUG);
protected abstract AbstractPackageManagerClient getClientImplementation();
public void generateTestPackage(File packageFile) throws IOException {
InputStream testPack = null;
OutputStream identOs = null;
try {
testPack = getClass().getResourceAsStream("/test-packmgr-client-1.0.zip");
if (packageFile.getParentFile().isDirectory()
|| packageFile.getParentFile().mkdirs()) {
identOs = new FileOutputStream(packageFile);
IOUtils.copy(testPack, identOs);
} else {
LOGGER.error("[generateTestPackage] failed to generate test package: {}", packageFile);
}
} finally {
IOUtils.closeQuietly(testPack);
IOUtils.closeQuietly(identOs);
}
}
@Test
public void testIdentifyPackage() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
File nonExist = new File("target/non-exist-package.zip");
boolean ioExceptionThrown = false;
try {
client.identify(nonExist);
} catch (IOException e) {
ioExceptionThrown = true;
}
assertTrue("identify throws correct exception for non-existent file", ioExceptionThrown);
File identifiable = new File("target/identifiable-package.zip");
generateTestPackage(identifiable);
PackId id = client.identify(identifiable);
assertNotNull("id should not be null", id);
assertEquals("group should be test-packmgr", "test-packmgr", id.getGroup());
assertEquals("name should be test-packmgr-client", "test-packmgr-client", id.getName());
assertEquals("version should be 1.0", "1.0", id.getVersion());
assertEquals("installationPath should be /etc/packages/test-packmgr/test-packmgr-client-1.0", "/etc/packages/test-packmgr/test-packmgr-client-1.0", id.getInstallationPath());
}
});
}
@Test
public void testGetHtmlUrl() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
PackId goodId = PackId.createPackId("group", "name", "1.0");
assertEquals("packIds with no special chars should work",
client.getHtmlUrl() + "/etc/packages/group/name-1.0.zip",
client.getHtmlUrl(goodId));
// escape space ( %20) and percent (% %25)
PackId illegalId = PackId.createPackId("percents%", "and spaces", "1.0");
assertEquals("packIds with illegal path chars should work",
client.getHtmlUrl() + "/etc/packages/percents%25/and%20spaces-1.0.zip",
client.getHtmlUrl(illegalId));
// escape question mark (? %3F) and octothorpe (# %23), but not ampersand (& %26)
PackId reservedId = PackId.createPackId("amps&", "quests?octothorpes#", "1.0");
assertEquals("packIds with reserved URL chars should work",
client.getHtmlUrl() + "/etc/packages/amps&/quests%3Foctothorpes%23-1.0.zip",
client.getHtmlUrl(reservedId));
// escape non-ascii?
/*
PackId utf8Id = PackId.createPackId("eighty\u20ACs", "name", "1.0");
assertEquals("packIds with UTF-8 should have ascii-only urls",
client.getHtmlUrl() + "/etc/packages/eighty%E2%82%ACs/name.zip",
client.getHtmlUrl(utf8Id));
*/
}
});
}
@Test
public void testGetJsonUrl() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
PackId goodId = PackId.createPackId("group", "name", "1.0");
assertEquals("packIds with no special chars should work",
client.getJsonUrl() + "/etc/packages/group/name-1.0.zip",
client.getJsonUrl(goodId));
// escape space ( %20) and percent (% %25)
PackId illegalId = PackId.createPackId("percents%", "and spaces", "1.0");
assertEquals("packIds with illegal path chars should work",
client.getJsonUrl() + "/etc/packages/percents%25/and%20spaces-1.0.zip",
client.getJsonUrl(illegalId));
// escape question mark (? %3F) and octothorpe (# %23), but not ampersand (& %26)
PackId reservedId = PackId.createPackId("amps&", "quests?octothorpes#", "1.0");
assertEquals("packIds with reserved URL chars should work",
client.getJsonUrl() + "/etc/packages/amps&/quests%3Foctothorpes%23-1.0.zip",
client.getJsonUrl(reservedId));
}
});
}
@Test
public void testGetConsoleUiUrl() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
PackId goodId = PackId.createPackId("group", "name", "1.0");
assertEquals("packIds with no special chars should work",
client.getConsoleUiUrl() + "#/etc/packages/group/name-1.0.zip",
client.getConsoleUiUrl(goodId));
// escape space ( %20) and percent (% %25)
PackId illegalId = PackId.createPackId("percents%", "and spaces", "1.0");
assertEquals("packIds with illegal path chars should work",
client.getConsoleUiUrl() + "#/etc/packages/percents%25/and%20spaces-1.0.zip",
client.getConsoleUiUrl(illegalId));
// escape octothorpe (# %23), but do not escape question mark (? %3F) or ampersand (& %26)
PackId reservedId = PackId.createPackId("amps&", "quests?octothorpes#", "1.0");
assertEquals("packIds with reserved URL chars should work",
client.getConsoleUiUrl() + "#/etc/packages/amps&/quests?octothorpes%23-1.0.zip",
client.getConsoleUiUrl(reservedId));
}
});
}
@Test
public void testGetListUrl() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
String noSlash = "http://localhost:4502";
assertEquals("don't screw up the URL handling, you klutz. [default]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_LIST_PATH,
client.getListUrl());
client.setBaseUrl(noSlash);
assertEquals("don't screw up the URL handling, you klutz. [noSlash]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_LIST_PATH,
client.getListUrl());
String slash = noSlash + "/";
client.setBaseUrl(slash);
assertEquals("don't screw up the URL handling, you klutz. [slash]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_LIST_PATH,
client.getListUrl());
String withContextNoSlash = noSlash + "/context";
client.setBaseUrl(withContextNoSlash);
assertEquals("don't screw up the URL handling, you klutz. [withContextNoSlash]",
withContextNoSlash + AbstractPackageManagerClient.CONSOLE_UI_LIST_PATH,
client.getListUrl());
String withContextSlash = withContextNoSlash + "/";
client.setBaseUrl(withContextSlash);
assertEquals("don't screw up the URL handling, you klutz. [withContextSlash]",
withContextNoSlash + AbstractPackageManagerClient.CONSOLE_UI_LIST_PATH,
client.getListUrl());
}
});
}
@Test
public void testGetDownloadUrl() {
TestBody.test(new PackmgrClientTestBody() {
@Override protected void execute() throws Exception {
String noSlash = "http://localhost:4502";
assertEquals("don't screw up the URL handling, you klutz. [default]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_DOWNLOAD_PATH,
client.getDownloadUrl());
client.setBaseUrl(noSlash);
assertEquals("don't screw up the URL handling, you klutz. [noSlash]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_DOWNLOAD_PATH,
client.getDownloadUrl());
String slash = noSlash + "/";
client.setBaseUrl(slash);
assertEquals("don't screw up the URL handling, you klutz. [slash]",
noSlash + AbstractPackageManagerClient.CONSOLE_UI_DOWNLOAD_PATH,
client.getDownloadUrl());
String withContextNoSlash = noSlash + "/context";
client.setBaseUrl(withContextNoSlash);
assertEquals("don't screw up the URL handling, you klutz. [withContextNoSlash]",
withContextNoSlash + AbstractPackageManagerClient.CONSOLE_UI_DOWNLOAD_PATH,
client.getDownloadUrl());
String withContextSlash = withContextNoSlash + "/";
client.setBaseUrl(withContextSlash);
assertEquals("don't screw up the URL handling, you klutz. [withContextSlash]",
withContextNoSlash + AbstractPackageManagerClient.CONSOLE_UI_DOWNLOAD_PATH,
client.getDownloadUrl());
}
});
}
abstract class PackmgrClientTestBody extends TestBody {
AbstractPackageManagerClient client = getClientImplementation();
}
}
|
|
/*
* 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.tallison.cc.index.mappers;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang.StringUtils;
import org.tallison.cc.index.CCIndexRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class loads a tab-delimited file of mime\t<code>float</code>.
* It selects a record if a random float is at/below that threshold.
* <p>
* This allows the user to set different sampling rates per mime
* type to generate a new sub-index for downloading, e.g. I only
* want .001% of "text/html" but I want 50% of "application/pdf"
* <p>
* If a mime type does not exist in the sampling weights file, the index
* record is selected (or threshold value = 1.0f).
* <p>
* Alternatively, the tab delimited file can contain topleveldomain\tmime\t<code>float</code>
*/
public class DownSample extends AbstractRecordProcessor {
private enum WHICH_MIME {
HEADER_ONLY,
DETECTED_ONLY,
HEADER_OR_DETECTED
}
private static final String ANY_TLD = "ANY_TLD";
private static final String MIME_COL_HEADER = "mime";
private static Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.create();
private final Random random = new Random();
private Writer writer;
private boolean includesTLD = false;
private long selected = 0;
private long total = 0;
private WHICH_MIME headerOrDetected = WHICH_MIME.HEADER_OR_DETECTED;
private int i;
private final Map<String, MimeMatcher> tldMimes = new HashMap<>();
int multiline = 0;
public DownSample() {
}
@Override
public void init(String[] args) throws Exception {
super.init(args);
tldMimes.clear();
if (args.length > 2) {
if (args[2].contains("detected_only")) {
headerOrDetected = WHICH_MIME.DETECTED_ONLY;
} else if (args[2].contains("header_only")) {
headerOrDetected = WHICH_MIME.HEADER_ONLY;
} else {
throw new IllegalArgumentException("Expected 'detected_only' or 'header_only'."+
" I regret I don't understand: "+args[2]);
}
}
try (BufferedReader reader = Files.newBufferedReader(Paths.get(args[0]))) {
String line = reader.readLine();
int lastNumCols = -1;
while (line != null) {
String[] cols = line.split("\t");
if (cols.length == 2) {
if (lastNumCols > -1 && lastNumCols != 2) {
throw new IllegalArgumentException("Last row had" + lastNumCols +
"columns, but this row has 2. Every row must have the same number of columns");
}
lastNumCols = 2;
String mime = cols[0].trim();
if (mime.equalsIgnoreCase(MIME_COL_HEADER)) {
line = reader.readLine();
continue;
}
float f = -1.0f;
try {
f = Float.parseFloat(cols[1]);
MimeMatcher mimeMatcher = tldMimes.get(ANY_TLD);
if (mimeMatcher == null) {
mimeMatcher = new MimeMatcher();
tldMimes.put(ANY_TLD, mimeMatcher);
}
mimeMatcher.addMime(mime, f);
} catch (NumberFormatException e) {
System.err.println("couldn't parse " + cols[1] + " for: " + mime);
}
} else if (cols.length == 3) {
if (lastNumCols > -1 && lastNumCols != 2) {
throw new IllegalArgumentException("Last row had" + lastNumCols +
"columns, but this row has 3. Every row must have the same number of columns");
}
lastNumCols = 3;
includesTLD = true;
String tld = cols[0].trim();
String mime = cols[1].trim();
if (mime.equalsIgnoreCase(MIME_COL_HEADER)) {
line = reader.readLine();
continue;
}
float f = -1.0f;
try {
f = Float.parseFloat(cols[2]);
MimeMatcher mimeMatcher = tldMimes.get(tld);
if (mimeMatcher == null) {
mimeMatcher = new MimeMatcher();
tldMimes.put(tld, mimeMatcher);
}
mimeMatcher.addMime(mime, f);
} catch (NumberFormatException e) {
System.err.println("couldn't parse " + cols[1] + " for: " + mime);
}
} else {
System.err.println("row too short: " + line);
}
line = reader.readLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
Path targFile = Paths.get(args[1]).resolve("downsampled_rows_" + getThreadNumber() + ".txt");
Files.createDirectories(targFile.getParent());
writer = Files.newBufferedWriter(targFile,
StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void usage() {
System.out.println("DownSample <sample_rates_file> <output_directory> <optional>detected_only|header_only</optional>");
System.out.println("Sample rates file should be a UTF-8 tab delimited file (with no escaped tabs)");
System.out.println("and it should have at least 2 columns: mime\tfloat");
System.out.println("alternatively, it can have 3 columns: topleveldomain\tmime\tfloat");
}
@Override
public void process(String row) throws IOException {
List<CCIndexRecord> records = CCIndexRecord.parseRecords(row);
for (CCIndexRecord r : records) {
if (!r.getStatus().equals("200")) {
continue;
} else if (r.getUrl().endsWith("robots.txt")) {
continue;
}
String headerMime = CCIndexRecord.normalizeMime(r.getMime());
String detectedMime = CCIndexRecord.normalizeMime(r.getMimeDetected());
String tld = CCIndexRecord.getTLD(r.getUrl());
boolean select = shouldSelect(tld, headerMime, detectedMime);
if (select == true) {
selected++;
gson.toJson(r, writer);
writer.write("\n");
} else {
//System.out.println("IGNORE: "+m);
}
total++;
}
}
private boolean shouldSelect(String tld, String headerMime, String detectedMime) {
//try to find the sampling % for the actual tld
if (!StringUtils.isBlank(tld) && tldMimes.containsKey(tld)) {
MimeMatcher mimeMatcher = tldMimes.get(tld);
if (mimeMatcher != null) {
return mimeMatcher.matches(headerMime, detectedMime);
}
}
//if there was no tld, or no specific mime pattern
//had a hit, apply the any_tld sampling rules
MimeMatcher mimeMatcher = tldMimes.get(ANY_TLD);
if (mimeMatcher != null) {
return mimeMatcher.matches(headerMime, detectedMime);
}
return false;
}
@Override
public void close() throws IOException {
System.out.println(selected + " out of "+total);
writer.flush();
writer.close();
}
private class MimeMatcher {
private final Random random = new Random();
Map<String, Float> exactMatches = new HashMap<>();
Map<Matcher, Float> regexMatches = new HashMap<>();
Set<String> shouldIgnore = new HashSet<>();
void addMime(String mime, float samplingRate) {
if (mime.startsWith("/") && mime.endsWith("/")) {
mime = mime.substring(1, mime.length() - 1);
Matcher mimeMatcher = Pattern.compile(mime).matcher("");
regexMatches.put(mimeMatcher, samplingRate);
} else {
exactMatches.put(mime, samplingRate);
}
}
boolean matches(String headerMime, String detectedMime) {
switch (headerOrDetected) {
case HEADER_ONLY:
return matchesSingle(headerMime);
case DETECTED_ONLY:
return matchesSingle(detectedMime);
case HEADER_OR_DETECTED:
return matchesSingle(headerMime) || matchesSingle(detectedMime);
}
return false;
}
private boolean headerOrDetected(String headerMime, String detectedMime) {
return matchesSingle(headerMime) || matchesSingle(detectedMime);
}
private boolean matchesSingle(String mime) {
if (shouldIgnore.contains(mime)) {
return false;
}
boolean found = false;
if (exactMatches.containsKey(mime)) {
float p = exactMatches.get(mime);
if (p >= 1.0f || random.nextFloat() < p) {
return true;
}
return false;
}
for (Map.Entry<Matcher, Float> e : regexMatches.entrySet()) {
if (e.getKey().reset(mime).find()) {
found = true;
float p = exactMatches.get(mime);
if (p >= 1.0f || random.nextFloat() < p) {
return true;
}
break;
}
}
if (!found) {
shouldIgnore.add(mime);
}
return false;
}
}
}
|
|
// Copyright 2000-2021 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.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.util.text.StringUtil;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
/**
* @author Konstantin Bulenkov
*/
public class PlatformIconsAPITest extends TestCase {
public void testCurrentAPI() {
//todo[kb, tav] Check that icons added to AllIcons are also added to PUBLIC_API_ICONS. Add svg icons
}
/**
* Old icons can be used in UI Forms in 3rd party plugins
*/
public void testIconsAvailable() {
ArrayList<String> missedIcons = new ArrayList<>();
for (String path: PUBLIC_API_ICONS) {
if (AllIcons.class.getClassLoader().getResource(StringUtil.trimStart(path, "/")) == null) {
missedIcons.add(path);
}
}
assert missedIcons.isEmpty() : missedIconsMsg(missedIcons);
}
private static String missedIconsMsg(ArrayList<String> icons) {
StringBuilder str =
new StringBuilder("API compatibility is broken. Please add the following icons to './community/platform/icons/compatibilityResources/':");
for (String icon: icons) {
str.append("\n'").append(icon).append("'");
}
return str.toString();
}
public static final TreeSet<String> PUBLIC_API_ICONS = new TreeSet<>(Arrays.asList(
"/actions/addFacesSupport.png",
"/actions/AddMulticaret.png",
"/actions/allLeft.png",
"/actions/allRight.png",
"/actions/annotate.png",
"/actions/back.png",
"/actions/cancel.png",
"/actions/changeView.png",
"/actions/checked.png",
"/actions/checked_selected.png",
"/actions/checked_small_selected.png",
"/actions/checkedBlack.png",
"/actions/checkedGrey.png",
"/actions/CheckMulticaret.png",
"/actions/checkOut.png",
"/actions/close.png",
"/actions/closeHovered.png",
"/actions/collapseall.png",
"/actions/commit.png",
"/actions/compile.png",
"/actions/copy.png",
"/actions/createPatch.png",
"/actions/diagramDiff.png",
"/actions/diff.png",
"/actions/diffWithClipboard.png",
"/actions/download.png",
"/actions/dump.png",
"/actions/edit.png",
"/actions/editSource.png",
"/actions/erDiagram.png",
"/actions/execute.png",
"/actions/exit.png",
"/actions/expandall.png",
"/actions/fileStatus.png",
"/actions/find.png",
"/actions/findWhite.png",
"/actions/forceRefresh.png",
"/actions/forward.png",
"/actions/gc.png",
"/actions/get.png",
"/actions/GroupByClass.png",
"/actions/GroupByFile.png",
"/actions/groupByMethod.png",
"/actions/GroupByModule.png",
"/actions/GroupByModuleGroup.png",
"/actions/GroupByPackage.png",
"/actions/GroupByPrefix.png",
"/actions/groupByTestProduction.png",
"/actions/help.png",
"/actions/install.png",
"/actions/intentionBulb.png",
"/actions/lightning.png",
"/actions/listChanges.png",
"/actions/menu-cut.png",
"/actions/menu-find.png",
"/actions/menu-help.png",
"/actions/menu-open.png",
"/actions/menu-paste.png",
"/actions/menu-replace.png",
"/actions/menu-saveall.png",
"/actions/minimize.png",
"/actions/move-to-button-top.png",
"/actions/move-to-button.png",
"/actions/moveDown.png",
"/actions/MoveTo2.png",
"/actions/moveToStandardPlace.png",
"/actions/moveUp.png",
"/actions/new.png",
"/actions/newFolder.png",
"/actions/nextOccurence.png",
"/actions/pause.png",
"/actions/popFrame.png",
"/actions/preview.png",
"/actions/previewDetails.png",
"/actions/previousOccurence.png",
"/actions/profile.png",
"/actions/profileCPU.png",
"/actions/profileMemory.png",
"/actions/properties.png",
"/actions/quickfixBulb.png",
"/actions/quickfixOffBulb.png",
"/actions/realIntentionBulb.png",
"/actions/realIntentionOffBulb.png",
"/actions/redo.png",
"/actions/refactoringBulb.png",
"/actions/refresh.png",
"/actions/RemoveMulticaret.png",
"/actions/replace.png",
"/actions/rerun.png",
"/actions/restart.png",
"/actions/restartDebugger.png",
"/actions/resume.png",
"/actions/rollback.png",
"/actions/runToCursor.png",
"/actions/scratch.png",
"/actions/search.png",
"/actions/searchNewLine.png",
"/actions/searchNewLineHover.png",
"/actions/selectall.png",
"/actions/share.png",
"/actions/shortcutFilter.png",
"/actions/showAsTree.png",
"/actions/showHiddens.png",
"/actions/showImportStatements.png",
"/actions/showReadAccess.png",
"/actions/showViewer.png",
"/actions/showWriteAccess.png",
"/actions/sortAsc.png",
"/actions/sortDesc.png",
"/actions/splitHorizontally.png",
"/actions/splitVertically.png",
"/actions/startDebugger.png",
"/actions/startMemoryProfile.png",
"/actions/stepOut.png",
"/actions/stub.png",
"/actions/suspend.png",
"/actions/swapPanels.png",
"/actions/synchronizeFS.png",
"/actions/synchronizeScrolling.png",
"/actions/syncPanels.png",
"/actions/toggleSoftWrap.png",
"/actions/traceInto.png",
"/actions/traceOver.png",
"/actions/undo.png",
"/actions/uninstall.png",
"/actions/unselectall.png",
"/actions/unshare.png",
"/actions/upload.png",
"/codeStyle/AddNewSectionRule.png",
"/codeStyle/mac/AddNewSectionRule.png",
"/darcula/doubleComboArrow.png",
"/darcula/treeNodeCollapsed.png",
"/darcula/treeNodeExpanded.png",
"/debugger/actions/force_run_to_cursor.png",
"/debugger/actions/force_step_into.png",
"/debugger/actions/force_step_over.png",
"/debugger/addToWatch.png",
"/debugger/attachToProcess.png",
"/debugger/autoVariablesMode.png",
"/debugger/breakpointAlert.png",
"/debugger/class_filter.png",
"/debugger/console.png",
"/debugger/db_array.png",
"/debugger/db_db_object.png",
"/debugger/db_dep_exception_breakpoint.png",
"/debugger/db_dep_field_breakpoint.png",
"/debugger/db_dep_line_breakpoint.png",
"/debugger/db_dep_method_breakpoint.png",
"/debugger/db_disabled_breakpoint.png",
"/debugger/db_disabled_breakpoint_process.png",
"/debugger/db_disabled_exception_breakpoint.png",
"/debugger/db_disabled_field_breakpoint.png",
"/debugger/db_disabled_method_breakpoint.png",
"/debugger/db_exception_breakpoint.png",
"/debugger/db_field_breakpoint.png",
"/debugger/db_invalid_breakpoint.png",
"/debugger/db_invalid_method_breakpoint.png",
"/debugger/db_method_breakpoint.png",
"/debugger/db_method_warning_breakpoint.png",
"/debugger/db_muted_breakpoint.png",
"/debugger/db_muted_dep_exception_breakpoint.png",
"/debugger/db_muted_dep_field_breakpoint.png",
"/debugger/db_muted_dep_line_breakpoint.png",
"/debugger/db_muted_dep_method_breakpoint.png",
"/debugger/db_muted_disabled_breakpoint.png",
"/debugger/db_muted_disabled_breakpoint_process.png",
"/debugger/db_muted_disabled_exception_breakpoint.png",
"/debugger/db_muted_disabled_field_breakpoint.png",
"/debugger/db_muted_disabled_method_breakpoint.png",
"/debugger/db_muted_exception_breakpoint.png",
"/debugger/db_muted_field_breakpoint.png",
"/debugger/db_muted_invalid_method_breakpoint.png",
"/debugger/db_muted_method_breakpoint.png",
"/debugger/db_muted_method_warning_breakpoint.png",
"/debugger/db_muted_temporary_breakpoint.png",
"/debugger/db_muted_verified_method_breakpoint.png",
"/debugger/db_muted_verified_warning_breakpoint.png",
"/debugger/db_obsolete.png",
"/debugger/db_primitive.png",
"/debugger/db_set_breakpoint.png",
"/debugger/db_temporary_breakpoint.png",
"/debugger/db_verified_breakpoint.png",
"/debugger/db_verified_field_breakpoint.png",
"/debugger/db_verified_method_breakpoint.png",
"/debugger/db_verified_warning_breakpoint.png",
"/debugger/disable_value_calculation.png",
"/debugger/evaluateExpression.png",
"/debugger/explosion.png",
"/debugger/frame.png",
"/debugger/killProcess.png",
"/debugger/LambdaBreakpoint.png",
"/debugger/memoryView/active.png",
"/debugger/memoryView/classTracked.png",
"/debugger/memoryView/toolWindowDisabled.png",
"/debugger/memoryView/toolWindowEnabled.png",
"/debugger/MultipleBreakpoints.png",
"/debugger/muteBreakpoints.png",
"/debugger/newWatch.png",
"/debugger/overhead.png",
"/debugger/question_badge.png",
"/debugger/restoreLayout.png",
"/debugger/selfreference.png",
"/debugger/showCurrentFrame.png",
"/debugger/smartStepInto.png",
"/debugger/threadAtBreakpoint.png",
"/debugger/threadCurrent.png",
"/debugger/threadFrozen.png",
"/debugger/threadGroup.png",
"/debugger/threadGroupCurrent.png",
"/debugger/threadRunning.png",
"/debugger/threads.png",
"/debugger/threadStates/daemon_sign.png",
"/debugger/threadStates/idle.png",
"/debugger/threadStates/socket.png",
"/debugger/threadStates/threaddump.png",
"/debugger/threadSuspended.png",
"/debugger/value.png",
"/debugger/viewBreakpoints.png",
"/debugger/watch.png",
"/debugger/watches.png",
"/debugger/watchLastReturnValue.png",
"/diff/applyNotConflicts.png",
"/diff/applyNotConflictsLeft.png",
"/diff/applyNotConflictsRight.png",
"/diff/arrow.png",
"/diff/arrowLeftDown.png",
"/diff/arrowRight.png",
"/diff/arrowRightDown.png",
"/diff/compare3LeftMiddle.png",
"/diff/compare3LeftRight.png",
"/diff/compare3MiddleRight.png",
"/diff/compare4LeftBottom.png",
"/diff/compare4LeftMiddle.png",
"/diff/compare4LeftRight.png",
"/diff/compare4MiddleBottom.png",
"/diff/compare4MiddleRight.png",
"/diff/compare4RightBottom.png",
"/diff/currentLine.png",
"/diff/gutterCheckBox.png",
"/diff/gutterCheckBoxSelected.png",
"/diff/magicResolve.png",
"/diff/magicResolveToolbar.png",
"/diff/remove.png",
"/duplicates/sendToTheLeft.png",
"/duplicates/sendToTheLeftGrayed.png",
"/duplicates/sendToTheRight.png",
"/duplicates/sendToTheRightGrayed.png",
"/fileTypes/any_type.png",
"/fileTypes/archive.png",
"/fileTypes/as.png",
"/fileTypes/aspectj.png",
"/fileTypes/config.png",
"/fileTypes/css.png",
"/fileTypes/custom.png",
"/fileTypes/diagram.png",
"/fileTypes/dtd.png",
"/fileTypes/facelets.png",
"/fileTypes/facesConfig.png",
"/fileTypes/htaccess.png",
"/fileTypes/html.png",
"/fileTypes/idl.png",
"/fileTypes/java.png",
"/fileTypes/javaClass.png",
"/fileTypes/javaOutsideSource.png",
"/fileTypes/javaScript.png",
"/fileTypes/json.png",
"/fileTypes/jsonSchema.png",
"/fileTypes/jsp.png",
"/fileTypes/jspx.png",
"/fileTypes/manifest.png",
"/fileTypes/properties.png",
"/fileTypes/text.png",
"/fileTypes/uiForm.png",
"/fileTypes/unknown.png",
"/fileTypes/wsdlFile.png",
"/fileTypes/xhtml.png",
"/fileTypes/xml.png",
"/fileTypes/xsdFile.png",
"/general/add.png",
"/general/addJdk.png",
"/general/arrowDown.png",
"/general/arrowDown_white.png",
"/general/autohideOff.png",
"/general/autohideOffInactive.png",
"/general/autohideOffPressed.png",
"/general/autoscrollFromSource.png",
"/general/autoscrollToSource.png",
"/general/balloon.png",
"/general/balloonError.png",
"/general/balloonInformation.png",
"/general/balloonWarning.png",
"/general/balloonWarning12.png",
"/general/collapseAllHover.png",
"/general/collapseComponent.png",
"/general/collapseComponentHover.png",
"/general/combo.png",
"/general/combo2.png",
"/general/combo3.png",
"/general/comboArrowLeftPassive.png",
"/general/comboArrowRightPassive.png",
"/general/comboUpPassive.png",
"/general/configurableDefault.png",
"/general/contextHelp.png",
"/general/copyHovered.png",
"/general/CreateNewProjectfromExistingFiles.png",
"/general/defaultKeymap.png",
"/general/divider.png",
"/general/dropdown.png",
"/general/ellipsis.png",
"/general/error.png",
"/general/errorDialog.png",
"/general/errorsInProgress.png",
"/general/exclMark.png",
"/general/expandAllHover.png",
"/general/expandComponent.png",
"/general/expandComponentHover.png",
"/general/ExportSettings.png",
"/general/externalTools.png",
"/general/filter.png",
"/general/floating.png",
"/general/gearPlain.png",
"/general/getProjectfromVCS.png",
"/general/hideDownHover.png",
"/general/hideDownPartHover.png",
"/general/hideLeft.png",
"/general/hideLeftHover.png",
"/general/hideLeftPart.png",
"/general/hideLeftPartHover.png",
"/general/hideToolWindow.png",
"/general/hideToolWindowInactive.png",
"/general/hideWarnings.png",
"/general/implementingMethod.png",
"/general/importProject.png",
"/general/ImportSettings.png",
"/general/information.png",
"/general/informationDialog.png",
"/general/inheritedMethod.png",
"/general/inline_edit.png",
"/general/inline_edit_hovered.png",
"/general/inspectionsError.png",
"/general/inspectionsEye.png",
"/general/inspectionsOff.png",
"/general/inspectionsOK.png",
"/general/inspectionsPause.png",
"/general/inspectionsTrafficOff.png",
"/general/inspectionsTypos.png",
"/general/keymap.png",
"/general/layoutEditorOnly.png",
"/general/layoutEditorPreview.png",
"/general/layoutPreviewOnly.png",
"/general/locate.png",
"/general/locateHover.png",
"/general/macCorner.png",
"/general/mdot-empty.png",
"/general/mdot-white.png",
"/general/mdot.png",
"/general/modified.png",
"/general/moreTabs.png",
"/general/mouse.png",
"/general/mouseShortcut.png",
"/general/notificationError.png",
"/general/notificationInfo.png",
"/general/notificationWarning.png",
"/general/openDisk.png",
"/general/openDiskHover.png",
"/general/openProject.png",
"/general/overridenMethod.png",
"/general/overridingMethod.png",
"/general/pathVariables.png",
"/general/pin_tab.png",
"/general/pluginManager.png",
"/general/projectConfigurable.png",
"/general/projectConfigurableBanner.png",
"/general/projectConfigurableSelected.png",
"/general/projectStructure.png",
"/general/projectTab.png",
"/general/questionDialog.png",
"/general/readHelp.png",
"/general/remove.png",
"/general/reset.png",
"/general/runWithCoverage.png",
"/general/safeMode.png",
"/general/searchEverywhereGear.png",
"/general/separatorH.png",
"/general/settings.png",
"/general/show_to_implement.png",
"/general/show_to_override.png",
"/general/smallConfigurableVcs.png",
"/general/splitCenterH.png",
"/general/splitCenterV.png",
"/general/splitGlueV.png",
"/general/splitLeft.png",
"/general/splitUp.png",
"/general/tab-white-center.png",
"/general/tab-white-left.png",
"/general/tab-white-right.png",
"/general/tab_grey_bckgrnd.png",
"/general/tab_grey_left.png",
"/general/tab_grey_left_inner.png",
"/general/tab_grey_right.png",
"/general/tab_grey_right_inner.png",
"/general/tbHidden.png",
"/general/tbShown.png",
"/general/TemplateProjectSettings.png",
"/general/TemplateProjectStructure.png",
"/general/tip.png",
"/general/todoDefault.png",
"/general/todoImportant.png",
"/general/todoQuestion.png",
"/general/uninstallPlugin.png",
"/general/warning.png",
"/general/warningDecorator.png",
"/general/warningDialog.png",
"/general/web.png",
"/general/webSettings.png",
"/graph/actualZoom.png",
"/graph/fitContent.png",
"/graph/grid.png",
"/graph/layout.png",
"/graph/nodeSelectionMode.png",
"/graph/snapToGrid.png",
"/graph/zoomIn.png",
"/graph/zoomOut.png",
"/gutter/colors.png",
"/gutter/extAnnotation.png",
"/gutter/implementedMethod.png",
"/gutter/implementingFunctionalInterface.png",
"/gutter/implementingMethod.png",
"/gutter/java9Service.png",
"/gutter/overridenMethod.png",
"/gutter/overridingMethod.png",
"/gutter/recursiveMethod.png",
"/gutter/siblingInheritedMethod.png",
"/gutter/unique.png",
"/hierarchy/callee.png",
"/hierarchy/class.png",
"/hierarchy/methodDefined.png",
"/hierarchy/methodNotDefined.png",
"/hierarchy/shouldDefineMethod.png",
"/hierarchy/subtypes.png",
"/hierarchy/supertypes.png",
"/icon.png",
"/icons/ide/nextStep.png",
"/icons/ide/nextStepInverted.png",
"/ide/emptyFatalError.png",
"/ide/error_notifications.png",
"/ide/errorPoint.png",
"/ide/external_link_arrow.png",
"/ide/fatalError-read.png",
"/ide/fatalError.png",
"/ide/hectorOff.png",
"/ide/hectorOn.png",
"/ide/hectorSyntax.png",
"/ide/incomingChangesOff.png",
"/ide/incomingChangesOn.png",
"/ide/link.png",
"/ide/localScope.png",
"/ide/lookupAlphanumeric.png",
"/ide/lookupRelevance.png",
"/ide/macro/recording_1.png",
"/ide/macro/recording_2.png",
"/ide/macro/recording_3.png",
"/ide/macro/recording_4.png",
"/ide/noNotifications13.png",
"/ide/notification/close.png",
"/ide/notification/closeHover.png",
"/ide/notification/collapse.png",
"/ide/notification/collapseHover.png",
"/ide/notification/dropTriangle.png",
"/ide/notification/errorEvents.png",
"/ide/notification/expand.png",
"/ide/notification/expandHover.png",
"/ide/notification/gear.png",
"/ide/notification/gearHover.png",
"/ide/notification/infoEvents.png",
"/ide/notification/noEvents.png",
"/ide/notification/shadow/bottom-left.png",
"/ide/notification/shadow/bottom-right.png",
"/ide/notification/shadow/bottom.png",
"/ide/notification/shadow/left.png",
"/ide/notification/shadow/right.png",
"/ide/notification/shadow/top-left.png",
"/ide/notification/shadow/top-right.png",
"/ide/notification/shadow/top.png",
"/ide/notification/warningEvents.png",
"/ide/outgoingChangesOn.png",
"/ide/pipette.png",
"/ide/pipette_rollover.png",
"/ide/rating.png",
"/ide/rating1.png",
"/ide/rating2.png",
"/ide/rating3.png",
"/ide/rating4.png",
"/ide/readonly.png",
"/ide/readwrite.png",
"/ide/shadow/bottom-left.png",
"/ide/shadow/bottom-right.png",
"/ide/shadow/bottom.png",
"/ide/shadow/left.png",
"/ide/shadow/popup/bottom-left.png",
"/ide/shadow/popup/bottom-right.png",
"/ide/shadow/popup/bottom.png",
"/ide/shadow/popup/left.png",
"/ide/shadow/popup/right.png",
"/ide/shadow/popup/top-left.png",
"/ide/shadow/popup/top-right.png",
"/ide/shadow/popup/top.png",
"/ide/shadow/right.png",
"/ide/shadow/top-left.png",
"/ide/shadow/top-right.png",
"/ide/shadow/top.png",
"/ide/statusbar_arrows.png",
"/ide/upDown.png",
"/idea_logo_welcome.png",
"/javaee/application_xml.png",
"/javaee/buildOnFrameDeactivation.png",
"/javaee/dbSchemaImportBig.png",
"/javaee/ejb-jar_xml.png",
"/javaee/ejbClass.png",
"/javaee/ejbModule.png",
"/javaee/embeddedAttributeOverlay.png",
"/javaee/entityBean.png",
"/javaee/entityBeanBig.png",
"/javaee/home.png",
"/javaee/interceptorMethod.png",
"/javaee/JavaeeAppModule.png",
"/javaee/jpaFacet.png",
"/javaee/local.png",
"/javaee/localHome.png",
"/javaee/messageBean.png",
"/javaee/persistenceEmbeddable.png",
"/javaee/persistenceEntity.png",
"/javaee/persistenceEntityListener.png",
"/javaee/persistenceId.png",
"/javaee/persistenceIdRelationship.png",
"/javaee/persistenceMappedSuperclass.png",
"/javaee/persistenceUnit.png",
"/javaee/remote.png",
"/javaee/sessionBean.png",
"/javaee/updateRunningApplication.png",
"/javaee/web_xml.png",
"/javaee/webModuleGroup.png",
"/javaee/WebService.png",
"/javaee/WebService2.png",
"/javaee/WebServiceClient.png",
"/javaee/WebServiceClient2.png",
"/json/array.png",
"/json/object.png",
"/Logo_welcomeScreen.png",
"/mac/appIconOk512.png",
"/mac/text.png",
"/mac/yosemiteOptionButtonSelector.png",
"/modules/addContentEntry.png",
"/modules/addExcludedRoot.png",
"/modules/annotation.png",
"/modules/deleteContentRoot.png",
"/modules/deleteContentRootRollover.png",
"/modules/edit.png",
"/modules/editFolder.png",
"/modules/excludedGeneratedRoot.png",
"/modules/excludeRoot.png",
"/modules/generatedFolder.png",
"/modules/generatedSourceRoot.png",
"/modules/generatedTestRoot.png",
"/modules/output.png",
"/modules/resourcesRoot.png",
"/modules/sourceRoot.png",
"/modules/sourceRootFileLayer.png",
"/modules/split.png",
"/modules/testResourcesRoot.png",
"/modules/testRoot.png",
"/modules/unloadedModule.png",
"/modules/unmarkWebroot.png",
"/modules/webRoot.png",
"/nodes/abstractClass.png",
"/nodes/abstractException.png",
"/nodes/abstractMethod.png",
"/nodes/annotationtype.png",
"/nodes/anonymousClass.png",
"/nodes/artifact.png",
"/nodes/aspect.png",
"/nodes/c_plocal.png",
"/nodes/c_private.png",
"/nodes/c_protected.png",
"/nodes/c_public.png",
"/nodes/class.png",
"/nodes/classInitializer.png",
"/nodes/compiledClassesFolder.png",
"/nodes/copyOfFolder.png",
"/nodes/customRegion.png",
"/nodes/cvs_global.png",
"/nodes/cvs_roots.png",
"/nodes/dataColumn.png",
"/nodes/dataSchema.png",
"/nodes/DataTables.png",
"/nodes/deploy.png",
"/nodes/desktop.png",
"/nodes/disabledPointcut.png",
"/nodes/ejb.png",
"/nodes/ejbBusinessMethod.png",
"/nodes/ejbCmpField.png",
"/nodes/ejbCmrField.png",
"/nodes/ejbCreateMethod.png",
"/nodes/ejbFinderMethod.png",
"/nodes/ejbPrimaryKeyClass.png",
"/nodes/ejbReference.png",
"/nodes/emptyNode.png",
"/nodes/enterpriseProject.png",
"/nodes/entryPoints.png",
"/nodes/enum.png",
"/nodes/errorIntroduction.png",
"/nodes/errorMark.png",
"/nodes/exceptionClass.png",
"/nodes/excludedFromCompile.png",
"/nodes/extractedFolder.png",
"/nodes/field.png",
"/nodes/fieldPK.png",
"/nodes/finalMark.png",
"/nodes/folder.png",
"/nodes/function.png",
"/nodes/homeFolder.png",
"/nodes/ideaModule.png",
"/nodes/ideaProject.png",
"/nodes/inspectionResults.png",
"/nodes/interface.png",
"/nodes/j2eeParameter.png",
"/nodes/jarDirectory.png",
"/nodes/javaDocFolder.png",
"/nodes/javaModule.png",
"/nodes/jsf/component.png",
"/nodes/jsf/converter.png",
"/nodes/jsf/general.png",
"/nodes/jsf/genericValue.png",
"/nodes/jsf/managedBean.png",
"/nodes/jsf/navigationCase.png",
"/nodes/jsf/navigationRule.png",
"/nodes/jsf/renderer.png",
"/nodes/jsf/renderKit.png",
"/nodes/jsf/validator.png",
"/nodes/jsr45.png",
"/nodes/junitTestMark.png",
"/nodes/keymapAnt.png",
"/nodes/keymapEditor.png",
"/nodes/keymapMainMenu.png",
"/nodes/keymapOther.png",
"/nodes/keymapTools.png",
"/nodes/locked.png",
"/nodes/method.png",
"/nodes/methodReference.png",
"/nodes/Module.png",
"/nodes/moduleGroup.png",
"/nodes/nativeLibrariesFolder.png",
"/nodes/newException.png",
"/nodes/newFolder.png",
"/nodes/newParameter.png",
"/nodes/nodePlaceholder.png",
"/nodes/package.png",
"/nodes/padlock.png",
"/nodes/parameter.png",
"/nodes/pinToolWindow.png",
"/nodes/plugin.png",
"/nodes/pluginJB.png",
"/nodes/pluginLogo.png",
"/nodes/pluginnotinstalled.png",
"/nodes/pluginobsolete.png",
"/nodes/pluginRestart.png",
"/nodes/pluginUpdate.png",
"/nodes/pointcut.png",
"/nodes/ppFile.png",
"/nodes/ppInvalid.png",
"/nodes/ppJar.png",
"/nodes/ppJdk.png",
"/nodes/ppLib.png",
"/nodes/ppLibFolder.png",
"/nodes/ppWeb.png",
"/nodes/ppWebLogo.png",
"/nodes/project.png",
"/nodes/property.png",
"/nodes/propertyRead.png",
"/nodes/propertyReadStatic.png",
"/nodes/propertyReadWrite.png",
"/nodes/propertyReadWriteStatic.png",
"/nodes/propertyWrite.png",
"/nodes/propertyWriteStatic.png",
"/nodes/read-access.png",
"/nodes/resourceBundle.png",
"/nodes/runnableMark.png",
"/nodes/rw-access.png",
"/nodes/SecurityRole.png",
"/nodes/servlet.png",
"/nodes/shared.png",
"/nodes/sortBySeverity.png",
"/nodes/static.png",
"/nodes/staticMark.png",
"/nodes/symlink.png",
"/nodes/tabAlert.png",
"/nodes/tabPin.png",
"/nodes/tag.png",
"/nodes/testSourceFolder.png",
"/nodes/undeploy.png",
"/nodes/unknownJdk.png",
"/nodes/upFolder.png",
"/nodes/upLevel.png",
"/nodes/variable.png",
"/nodes/warningIntroduction.png",
"/nodes/webFolder.png",
"/nodes/weblistener.png",
"/nodes/write-access.png",
"/objectBrowser/abbreviatePackageNames.png",
"/objectBrowser/compactEmptyPackages.png",
"/objectBrowser/flattenModules.png",
"/objectBrowser/flattenPackages.png",
"/objectBrowser/showLibraryContents.png",
"/objectBrowser/showMembers.png",
"/objectBrowser/showModules.png",
"/objectBrowser/sortByType.png",
"/objectBrowser/sorted.png",
"/objectBrowser/sortedByUsage.png",
"/objectBrowser/visibilitySort.png",
"/preferences/Appearance.png",
"/preferences/CodeStyle.png",
"/preferences/Compiler.png",
"/preferences/Editor.png",
"/preferences/FileColors.png",
"/preferences/FileTypes.png",
"/preferences/General.png",
"/preferences/Keymap.png",
"/preferences/Plugins.png",
"/preferences/Updates.png",
"/preferences/VersionControl.png",
"/process/big/step_1.png",
"/process/big/step_10.png",
"/process/big/step_11.png",
"/process/big/step_12.png",
"/process/big/step_2.png",
"/process/big/step_3.png",
"/process/big/step_4.png",
"/process/big/step_5.png",
"/process/big/step_6.png",
"/process/big/step_7.png",
"/process/big/step_8.png",
"/process/big/step_9.png",
"/process/big/step_passive.png",
"/process/fs/step_1.png",
"/process/fs/step_10.png",
"/process/fs/step_11.png",
"/process/fs/step_12.png",
"/process/fs/step_13.png",
"/process/fs/step_14.png",
"/process/fs/step_15.png",
"/process/fs/step_16.png",
"/process/fs/step_17.png",
"/process/fs/step_18.png",
"/process/fs/step_2.png",
"/process/fs/step_3.png",
"/process/fs/step_4.png",
"/process/fs/step_5.png",
"/process/fs/step_6.png",
"/process/fs/step_7.png",
"/process/fs/step_8.png",
"/process/fs/step_9.png",
"/process/fs/step_mask.png",
"/process/fs/step_passive.png",
"/process/progressPause.png",
"/process/progressPauseHover.png",
"/process/progressPauseSmall.png",
"/process/progressPauseSmallHover.png",
"/process/progressResume.png",
"/process/progressResumeHover.png",
"/process/progressResumeSmall.png",
"/process/progressResumeSmallHover.png",
"/process/step_1.png",
"/process/step_10.png",
"/process/step_11.png",
"/process/step_12.png",
"/process/step_2.png",
"/process/step_3.png",
"/process/step_4.png",
"/process/step_5.png",
"/process/step_6.png",
"/process/step_7.png",
"/process/step_8.png",
"/process/step_9.png",
"/process/step_mask.png",
"/process/step_passive.png",
"/process/stop.png",
"/process/stopHovered.png",
"/process/stopSmall.png",
"/process/stopSmallHovered.png",
"/providers/apache.png",
"/providers/apacheDerby.png",
"/providers/azure.png",
"/providers/bea.png",
"/providers/DB2.png",
"/providers/eclipse.png",
"/providers/exasol.png",
"/providers/h2.png",
"/providers/hibernate.png",
"/providers/hsqldb.png",
"/providers/ibm.png",
"/providers/mariadb.png",
"/providers/microsoft.png",
"/providers/mysql.png",
"/providers/oracle.png",
"/providers/postgresql.png",
"/providers/redshift.png",
"/providers/sqlite.png",
"/providers/sqlServer.png",
"/providers/sun.png",
"/providers/sybase.png",
"/runConfigurations/applet.png",
"/runConfigurations/application.png",
"/runConfigurations/hideIgnored.png",
"/runConfigurations/hidePassed.png",
"/runConfigurations/ignoredTest.png",
"/runConfigurations/includeNonStartedTests_Rerun.png",
"/runConfigurations/invalidConfigurationLayer.png",
"/runConfigurations/junit.png",
"/runConfigurations/remote.png",
"/runConfigurations/rerunFailedTests.png",
"/runConfigurations/scroll_down.png",
"/runConfigurations/scrollToStackTrace.png",
"/runConfigurations/selectFirstDefect.png",
"/runConfigurations/sortbyDuration.png",
"/runConfigurations/sourceAtException.png",
"/runConfigurations/testCustom.png",
"/runConfigurations/testError.png",
"/runConfigurations/testFailed.png",
"/runConfigurations/testIgnored.png",
"/runConfigurations/testMark.png",
"/runConfigurations/testNotRan.png",
"/runConfigurations/testPassed.png",
"/runConfigurations/testPaused.png",
"/runConfigurations/testSkipped.png",
"/runConfigurations/testState/green2.png",
"/runConfigurations/testState/red2.png",
"/runConfigurations/testState/run.png",
"/runConfigurations/testState/run_run.png",
"/runConfigurations/testState/yellow2.png",
"/runConfigurations/testTerminated.png",
"/runConfigurations/testUnknown.png",
"/runConfigurations/tomcat.png",
"/runConfigurations/trackCoverage.png",
"/runConfigurations/trackTests.png",
"/runConfigurations/web_app.png",
"/runConfigurations/withCoverageLayer.png",
"/toolbar/filterdups.png",
"/toolbar/folders.png",
"/toolbar/unknown.png",
"/toolbarDecorator/addBlankLine.png",
"/toolbarDecorator/addClass.png",
"/toolbarDecorator/addFolder.png",
"/toolbarDecorator/addIcon.png",
"/toolbarDecorator/addJira.png",
"/toolbarDecorator/addLink.png",
"/toolbarDecorator/addPattern.png",
"/toolbarDecorator/addRemoteDatasource.png",
"/toolbarDecorator/addYouTrack.png",
"/toolbarDecorator/analyze.png",
"/toolbarDecorator/export.png",
"/toolbarDecorator/import.png",
"/toolbarDecorator/mac/add.png",
"/toolbarDecorator/mac/addBlankLine.png",
"/toolbarDecorator/mac/addClass.png",
"/toolbarDecorator/mac/addFolder.png",
"/toolbarDecorator/mac/addIcon.png",
"/toolbarDecorator/mac/addJira.png",
"/toolbarDecorator/mac/addLink.png",
"/toolbarDecorator/mac/addPackage.png",
"/toolbarDecorator/mac/addPattern.png",
"/toolbarDecorator/mac/addRemoteDatasource.png",
"/toolbarDecorator/mac/addYouTrack.png",
"/toolbarDecorator/mac/analyze.png",
"/toolbarDecorator/mac/edit.png",
"/toolbarDecorator/mac/moveDown.png",
"/toolbarDecorator/mac/moveUp.png",
"/toolbarDecorator/mac/remove.png",
"/toolwindows/documentation.png",
"/toolwindows/problems.png",
"/toolwindows/toolWindowAnt.png",
"/toolwindows/toolWindowBuild.png",
"/toolwindows/toolWindowChanges.png",
"/toolwindows/toolWindowCommander.png",
"/toolwindows/toolWindowCoverage.png",
"/toolwindows/toolWindowCvs.png",
"/toolwindows/toolWindowDebugger.png",
"/toolwindows/toolWindowFavorites.png",
"/toolwindows/toolWindowFind.png",
"/toolwindows/toolWindowHierarchy.png",
"/toolwindows/toolWindowInspection.png",
"/toolwindows/toolWindowMessages.png",
"/toolwindows/toolWindowModuleDependencies.png",
"/toolwindows/toolWindowPalette.png",
"/toolwindows/toolWindowPreview.png",
"/toolwindows/toolWindowProject.png",
"/toolwindows/toolWindowRun.png",
"/toolwindows/toolWindowStructure.png",
"/toolwindows/toolWindowTodo.png",
"/toolwindows/webToolWindow.png",
"/vcs/arrow_left.png",
"/vcs/arrow_right.png",
"/vcs/equal.png",
"/vcs/history.png",
"/vcs/mapBase.png",
"/vcs/merge.png",
"/vcs/not_equal.png",
"/vcs/patch.png",
"/vcs/patch_applied.png",
"/vcs/push.png",
"/vcs/remove.png",
"/vcs/resetStrip.png",
"/vcs/restoreDefaultSize.png",
"/vcs/Shelve.png",
"/vcs/shelveSilent.png",
"/vcs/ShowUnversionedFiles.png",
"/vcs/stripDown.png",
"/vcs/stripNull.png",
"/vcs/stripUp.png",
"/vcs/Unshelve.png",
"/vcs/unshelveSilent.png",
"/webreferences/server.png",
"/welcome/createNewProject.png",
"/welcome/CreateNewProjectfromExistingFiles.png",
"/welcome/importProject.png",
"/welcome/openProject.png",
"/windows/closeActive.png",
"/windows/closeHover.png",
"/windows/closeInactive.png",
"/windows/helpButton.png",
"/windows/maximize.png",
"/windows/maximizeInactive.png",
"/windows/minimize.png",
"/windows/minimizeInactive.png",
"/windows/restore.png",
"/windows/restoreInactive.png",
"/windows/shadow/bottom.png",
"/windows/shadow/bottomLeft.png",
"/windows/shadow/bottomRight.png",
"/windows/shadow/left.png",
"/windows/shadow/right.png",
"/windows/shadow/top.png",
"/windows/shadow/topLeft.png",
"/windows/shadow/topRight.png",
"/windows/winHelp.png",
"/xml/browsers/canary16.png",
"/xml/browsers/chrome16.png",
"/xml/browsers/chromium16.png",
"/xml/browsers/edge16.png",
"/xml/browsers/explorer16.png",
"/xml/browsers/firefox16.png",
"/xml/browsers/nwjs16.png",
"/xml/browsers/opera16.png",
"/xml/browsers/safari16.png",
"/xml/browsers/yandex16.png",
"/xml/css_class.png",
"/xml/html5.png",
"/xml/html_id.png"
));
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zookeeper.test;
import java.io.ByteArrayOutputStream;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import junit.framework.Assert;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NotReadOnlyException;
import org.apache.zookeeper.Transaction;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ReadOnlyModeTest extends ZKTestCase {
private static int CONNECTION_TIMEOUT = QuorumBase.CONNECTION_TIMEOUT;
private QuorumUtil qu = new QuorumUtil(1);
@Before
public void setUp() throws Exception {
System.setProperty("readonlymode.enabled", "true");
qu.startQuorum();
}
@After
public void tearDown() throws Exception {
System.setProperty("readonlymode.enabled", "false");
qu.tearDown();
}
/**
* Test write operations using multi request.
*/
@Test(timeout = 90000)
public void testMultiTransaction() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT); // ensure zk got connected
final String data = "Data to be read in RO mode";
final String node1 = "/tnode1";
final String node2 = "/tnode2";
zk.create(node1, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
watcher.reset();
qu.shutdown(2);
watcher.waitForConnected(CONNECTION_TIMEOUT);
Assert.assertEquals("Should be in r-o mode", States.CONNECTEDREADONLY,
zk.getState());
// read operation during r/o mode
String remoteData = new String(zk.getData(node1, false, null));
Assert.assertEquals("Failed to read data in r-o mode", data, remoteData);
try {
Transaction transaction = zk.transaction();
transaction.setData(node1, "no way".getBytes(), -1);
transaction.create(node2, data.getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
transaction.commit();
Assert.fail("Write operation using multi-transaction"
+ " api has succeeded during RO mode");
} catch (NotReadOnlyException e) {
// ok
}
Assert.assertNull("Should have created the znode:" + node2,
zk.exists(node2, false));
}
/**
* Basic test of read-only client functionality. Tries to read and write
* during read-only mode, then regains a quorum and tries to write again.
*/
@Test(timeout = 90000)
public void testReadOnlyClient() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT); // ensure zk got connected
final String data = "Data to be read in RO mode";
final String node = "/tnode";
zk.create(node, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
watcher.reset();
qu.shutdown(2);
zk.close();
// Re-connect the client (in case we were connected to the shut down
// server and the local session was not persisted).
zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// read operation during r/o mode
String remoteData = new String(zk.getData(node, false, null));
Assert.assertEquals(data, remoteData);
try {
zk.setData(node, "no way".getBytes(), -1);
Assert.fail("Write operation has succeeded during RO mode");
} catch (NotReadOnlyException e) {
// ok
}
watcher.reset();
qu.start(2);
Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
"127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
zk.close();
watcher.reset();
// Re-connect the client (in case we were connected to the shut down
// server and the local session was not persisted).
zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.setData(node, "We're in the quorum now".getBytes(), -1);
zk.close();
}
/**
* Ensures that upon connection to a read-only server client receives
* ConnectedReadOnly state notification.
*/
@Test(timeout = 90000)
public void testConnectionEvents() throws Exception {
final List<KeeperState> states = new ArrayList<KeeperState>();
ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
new Watcher() {
public void process(WatchedEvent event) {
states.add(event.getState());
}
}, true);
boolean success = false;
for (int i = 0; i < 30; i++) {
try {
zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
success=true;
break;
} catch(KeeperException.ConnectionLossException e) {
Thread.sleep(1000);
}
}
Assert.assertTrue("Did not succeed in connecting in 30s", success);
// kill peer and wait no more than 5 seconds for read-only server
// to be started (which should take one tickTime (2 seconds))
qu.shutdown(2);
// Re-connect the client (in case we were connected to the shut down
// server and the local session was not persisted).
zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
new Watcher() {
public void process(WatchedEvent event) {
states.add(event.getState());
}
}, true);
long start = Time.currentElapsedTime();
while (!(zk.getState() == States.CONNECTEDREADONLY)) {
Thread.sleep(200);
// FIXME this was originally 5 seconds, but realistically, on random/slow/virt hosts, there is no way to guarantee this
Assert.assertTrue("Can't connect to the server",
Time.currentElapsedTime() - start < 30000);
}
// At this point states list should contain, in the given order,
// SyncConnected, Disconnected, and ConnectedReadOnly states
Assert.assertTrue("ConnectedReadOnly event wasn't received", states
.get(2) == KeeperState.ConnectedReadOnly);
zk.close();
}
/**
* Tests a situation when client firstly connects to a read-only server and
* then connects to a majority server. Transition should be transparent for
* the user.
*/
@Test(timeout = 90000)
public void testSessionEstablishment() throws Exception {
qu.shutdown(2);
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
Assert.assertSame("should be in r/o mode", States.CONNECTEDREADONLY, zk
.getState());
long fakeId = zk.getSessionId();
watcher.reset();
qu.start(2);
Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
"127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertFalse("fake session and real session have same id", zk
.getSessionId() == fakeId);
zk.close();
}
/**
* Ensures that client seeks for r/w servers while it's connected to r/o
* server.
*/
@SuppressWarnings("deprecation")
@Test(timeout = 90000)
public void testSeekForRwServer() throws Exception {
// setup the logger to capture all logs
Layout layout = Logger.getRootLogger().getAppender("CONSOLE")
.getLayout();
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = new WriterAppender(layout, os);
appender.setImmediateFlush(true);
appender.setThreshold(Level.INFO);
Logger zlogger = Logger.getLogger("org.apache.zookeeper");
zlogger.addAppender(appender);
try {
qu.shutdown(2);
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(qu.getConnString(),
CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// if we don't suspend a peer it will rejoin a quorum
qu.getPeer(1).peer.suspend();
// start two servers to form a quorum; client should detect this and
// connect to one of them
watcher.reset();
qu.start(2);
qu.start(3);
ClientBase.waitForServerUp(qu.getConnString(), 2000);
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// resume poor fellow
qu.getPeer(1).peer.resume();
} finally {
zlogger.removeAppender(appender);
}
os.close();
LineNumberReader r = new LineNumberReader(new StringReader(os
.toString()));
String line;
Pattern p = Pattern.compile(".*Majority server found.*");
boolean found = false;
while ((line = r.readLine()) != null) {
if (p.matcher(line).matches()) {
found = true;
break;
}
}
Assert.assertTrue(
"Majority server wasn't found while connected to r/o server",
found);
}
}
|
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.inspections.quickfix;
import com.google.common.collect.Lists;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.Task.Backgroundable;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.Consumer;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PythonHelpersLocator;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.sdk.InvalidSdkException;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.sdk.flavors.IronPythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import com.jetbrains.python.sdk.skeletons.PySkeletonGenerator;
import com.jetbrains.python.sdk.skeletons.PySkeletonRefresher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public class GenerateBinaryStubsFix implements LocalQuickFix {
private static final Logger LOG = Logger.getInstance("#" + GenerateBinaryStubsFix.class.getName());
private final String myQualifiedName;
private final Sdk mySdk;
/**
* Generates pack of fixes available for some unresolved import statement.
* Be sure to call {@link #isApplicable(com.jetbrains.python.psi.PyImportStatementBase)} first to make sure this statement is supported
*
* @param importStatementBase statement to fix
* @return pack of fixes
*/
@NotNull
public static Collection<GenerateBinaryStubsFix> generateFixes(@NotNull final PyImportStatementBase importStatementBase) {
final List<String> names = importStatementBase.getFullyQualifiedObjectNames();
final List<GenerateBinaryStubsFix> result = new ArrayList<GenerateBinaryStubsFix>(names.size());
if (importStatementBase instanceof PyFromImportStatement && names.isEmpty()) {
final QualifiedName qName = ((PyFromImportStatement)importStatementBase).getImportSourceQName();
if (qName != null)
result.add(new GenerateBinaryStubsFix(importStatementBase, qName.toString()));
}
for (final String qualifiedName : names) {
result.add(new GenerateBinaryStubsFix(importStatementBase, qualifiedName));
}
return result;
}
/**
* @param importStatementBase statement to fix
* @param qualifiedName name should be fixed (one of {@link com.jetbrains.python.psi.PyImportStatementBase#getFullyQualifiedObjectNames()})
*/
private GenerateBinaryStubsFix(@NotNull final PyImportStatementBase importStatementBase, @NotNull final String qualifiedName) {
myQualifiedName = qualifiedName;
mySdk = getPythonSdk(importStatementBase);
}
@Override
@NotNull
public String getName() {
return PyBundle.message("sdk.gen.stubs.for.binary.modules", myQualifiedName);
}
@Override
@NotNull
public String getFamilyName() {
return "Generate binary stubs";
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
final PsiFile file = descriptor.getPsiElement().getContainingFile();
final Backgroundable backgroundable = getFixTask(file);
ProgressManager.getInstance().runProcessWithProgressAsynchronously(backgroundable, new BackgroundableProcessIndicator(backgroundable));
}
/**
* Returns fix task that is used to generate stubs
* @param fileToRunTaskIn file where task should run
* @return task itself
*/
@NotNull
public Backgroundable getFixTask(@NotNull final PsiFile fileToRunTaskIn) {
final Project project = fileToRunTaskIn.getProject();
final String folder = fileToRunTaskIn.getContainingDirectory().getVirtualFile().getCanonicalPath();
return new Task.Backgroundable(project, "Generating skeletons for binary module", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
final List<String> assemblyRefs = new ReadAction<List<String>>() {
@Override
protected void run(@NotNull Result<List<String>> result) throws Throwable {
result.setResult(collectAssemblyReferences(fileToRunTaskIn));
}
}.execute().getResultObject();
try {
final PySkeletonRefresher refresher = new PySkeletonRefresher(project, null, mySdk, null, null, folder);
if (needBinaryList(myQualifiedName)) {
if (!generateSkeletonsForList(refresher, indicator, folder)) return;
}
else {
//noinspection unchecked
refresher.generateSkeleton(myQualifiedName, "", assemblyRefs, Consumer.EMPTY_CONSUMER);
}
final VirtualFile skeletonDir;
skeletonDir = LocalFileSystem.getInstance().findFileByPath(refresher.getSkeletonsPath());
if (skeletonDir != null) {
skeletonDir.refresh(true, true);
}
}
catch (InvalidSdkException e) {
LOG.error(e);
}
}
};
}
private boolean generateSkeletonsForList(@NotNull final PySkeletonRefresher refresher,
ProgressIndicator indicator,
@Nullable final String currentBinaryFilesPath) throws InvalidSdkException {
final PySkeletonGenerator generator = new PySkeletonGenerator(refresher.getSkeletonsPath(), mySdk, currentBinaryFilesPath);
indicator.setIndeterminate(false);
final String homePath = mySdk.getHomePath();
if (homePath == null) return false;
final ProcessOutput runResult = PySdkUtil.getProcessOutput(
new File(homePath).getParent(),
new String[]{
homePath,
PythonHelpersLocator.getHelperPath("extra_syspath.py"), myQualifiedName},
PythonSdkType.getVirtualEnvExtraEnv(homePath), 5000
);
if (runResult.getExitCode() == 0 && !runResult.isTimeout()) {
final String extraPath = runResult.getStdout();
final PySkeletonGenerator.ListBinariesResult binaries = generator.listBinaries(mySdk, extraPath);
final List<String> names = Lists.newArrayList(binaries.modules.keySet());
Collections.sort(names);
final int size = names.size();
for (int i = 0; i != size; ++i) {
final String name = names.get(i);
indicator.setFraction((double)i / size);
if (needBinaryList(name)) {
indicator.setText2(name);
final PySkeletonRefresher.PyBinaryItem item = binaries.modules.get(name);
final String modulePath = item != null ? item.getPath() : "";
//noinspection unchecked
refresher.generateSkeleton(name, modulePath, new ArrayList<String>(), Consumer.EMPTY_CONSUMER);
}
}
}
return true;
}
private static boolean needBinaryList(@NotNull final String qualifiedName) {
return qualifiedName.startsWith("gi.repository");
}
private List<String> collectAssemblyReferences(PsiFile file) {
if (!(PythonSdkFlavor.getFlavor(mySdk) instanceof IronPythonSdkFlavor)) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<String>();
file.accept(new PyRecursiveElementVisitor() {
@Override
public void visitPyCallExpression(PyCallExpression node) {
super.visitPyCallExpression(node);
// TODO: What if user loads it not by literal? We need to ask user for list of DLLs
if (node.isCalleeText("AddReference", "AddReferenceByPartialName", "AddReferenceByName")) {
final PyExpression[] args = node.getArguments();
if (args.length == 1 && args[0] instanceof PyStringLiteralExpression) {
result.add(((PyStringLiteralExpression)args[0]).getStringValue());
}
}
}
});
return result;
}
/**
* Checks if this fix can help you to generate binary stubs
*
* @param importStatementBase statement to fix
* @return true if this fix could work
*/
public static boolean isApplicable(@NotNull final PyImportStatementBase importStatementBase) {
if (importStatementBase.getFullyQualifiedObjectNames().isEmpty() &&
!(importStatementBase instanceof PyFromImportStatement && ((PyFromImportStatement)importStatementBase).isStarImport())) {
return false;
}
final Sdk sdk = getPythonSdk(importStatementBase);
if (sdk == null) {
return false;
}
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(sdk);
if (flavor instanceof IronPythonSdkFlavor) {
return true;
}
return isGtk(importStatementBase);
}
private static boolean isGtk(@NotNull final PyImportStatementBase importStatementBase) {
if (importStatementBase instanceof PyFromImportStatement) {
final QualifiedName qName = ((PyFromImportStatement)importStatementBase).getImportSourceQName();
if (qName != null && qName.matches("gi", "repository")) {
return true;
}
}
return false;
}
@Nullable
private static Sdk getPythonSdk(@NotNull final PsiElement element) {
final Module module = ModuleUtilCore.findModuleForPsiElement(element);
return (module == null) ? null : PythonSdkType.findPythonSdk(module);
}
}
|
|
/*
* Copyright (C) 2013, 2014 Brett Wooldridge
*
* 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.zaxxer.hikari.util;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry;
import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_NOT_IN_USE;
import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_IN_USE;
import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_REMOVED;
import static com.zaxxer.hikari.util.ConcurrentBag.IConcurrentBagEntry.STATE_RESERVED;
/**
* This is a specialized concurrent bag that achieves superior performance
* to LinkedBlockingQueue and LinkedTransferQueue for the purposes of a
* connection pool. It uses ThreadLocal storage when possible to avoid
* locks, but resorts to scanning a common collection if there are no
* available items in the ThreadLocal list. Not-in-use items in the
* ThreadLocal lists can be "stolen" when the borrowing thread has none
* of its own. It is a "lock-less" implementation using a specialized
* AbstractQueuedLongSynchronizer to manage cross-thread signaling.
*
* Note that items that are "borrowed" from the bag are not actually
* removed from any collection, so garbage collection will not occur
* even if the reference is abandoned. Thus care must be taken to
* "requite" borrowed objects otherwise a memory leak will result. Only
* the "remove" method can completely remove an object from the bag.
*
* @author Brett Wooldridge
*
* @param <T> the templated type to store in the bag
*/
@SuppressWarnings("rawtypes")
public class ConcurrentBag<T extends IConcurrentBagEntry> implements AutoCloseable
{
private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentBag.class);
private final QueuedSequenceSynchronizer synchronizer;
private final CopyOnWriteArrayList<T> sharedList;
private final boolean weakThreadLocals;
private final ThreadLocal<List> threadList;
private final IBagStateListener listener;
private volatile boolean closed;
public interface IConcurrentBagEntry
{
int STATE_NOT_IN_USE = 0;
int STATE_IN_USE = 1;
int STATE_REMOVED = -1;
int STATE_RESERVED = -2;
boolean compareAndSet(int expectState, int newState);
void lazySet(int newState);
int getState();
}
public interface IBagStateListener
{
Future<Boolean> addBagItem();
}
/**
* Construct a ConcurrentBag with the specified listener.
*
* @param listener the IBagStateListener to attach to this bag
*/
public ConcurrentBag(IBagStateListener listener)
{
this.listener = listener;
this.weakThreadLocals = useWeakThreadLocals();
this.sharedList = new CopyOnWriteArrayList<>();
this.synchronizer = new QueuedSequenceSynchronizer();
if (weakThreadLocals) {
this.threadList = new ThreadLocal<>();
}
else {
this.threadList = new ThreadLocal<List>() {
@Override
protected List initialValue()
{
return new FastList<>(IConcurrentBagEntry.class, 16);
}
};
}
}
/**
* The method will borrow a BagEntry from the bag, blocking for the
* specified timeout if none are available.
*
* @param timeout how long to wait before giving up, in units of unit
* @param timeUnit a <code>TimeUnit</code> determining how to interpret the timeout parameter
* @return a borrowed instance from the bag or null if a timeout occurs
* @throws InterruptedException if interrupted while waiting
*/
@SuppressWarnings("unchecked")
public T borrow(long timeout, final TimeUnit timeUnit) throws InterruptedException
{
// Try the thread-local list first, if there are no blocked threads waiting already
List<?> list = threadList.get();
if (weakThreadLocals && list == null) {
list = new ArrayList<>(16);
threadList.set(list);
}
for (int i = list.size() - 1; i >= 0; i--) {
final T bagEntry = (T) (weakThreadLocals ? ((WeakReference) list.remove(i)).get() : list.remove(i));
if (bagEntry != null && bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
return bagEntry;
}
}
// Otherwise, scan the shared list ... for maximum of timeout
timeout = timeUnit.toNanos(timeout);
Future<Boolean> addItemFuture = null;
final long startScan = System.nanoTime();
final long originTimeout = timeout;
long startSeq;
do {
do {
startSeq = synchronizer.currentSequence();
for (final T bagEntry : sharedList) {
if (bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) {
return bagEntry;
}
}
} while (startSeq < synchronizer.currentSequence());
if (addItemFuture == null || addItemFuture.isDone()) {
addItemFuture = listener.addBagItem();
}
timeout = originTimeout - (System.nanoTime() - startScan);
} while (timeout > 1000L && synchronizer.waitUntilSequenceExceeded(startSeq, timeout));
return null;
}
/**
* This method will return a borrowed object to the bag. Objects
* that are borrowed from the bag but never "requited" will result
* in a memory leak.
*
* @param bagEntry the value to return to the bag
* @throws NullPointerException if value is null
* @throws IllegalStateException if the requited value was not borrowed from the bag
*/
@SuppressWarnings("unchecked")
public void requite(final T bagEntry)
{
bagEntry.lazySet(STATE_NOT_IN_USE);
final List threadLocalList = threadList.get();
if (threadLocalList != null) {
threadLocalList.add((weakThreadLocals ? new WeakReference<>(bagEntry) : bagEntry));
}
synchronizer.signal();
}
/**
* Add a new object to the bag for others to borrow.
*
* @param bagEntry an object to add to the bag
*/
public void add(final T bagEntry)
{
if (closed) {
LOGGER.info("ConcurrentBag has been closed, ignoring add()");
throw new IllegalStateException("ConcurrentBag has been closed, ignoring add()");
}
sharedList.add(bagEntry);
synchronizer.signal();
}
/**
* Remove a value from the bag. This method should only be called
* with objects obtained by <code>borrow(long, TimeUnit)</code> or <code>reserve(T)</code>
*
* @param bagEntry the value to remove
* @return true if the entry was removed, false otherwise
* @throws IllegalStateException if an attempt is made to remove an object
* from the bag that was not borrowed or reserved first
*/
public boolean remove(final T bagEntry)
{
if (!bagEntry.compareAndSet(STATE_IN_USE, STATE_REMOVED) && !bagEntry.compareAndSet(STATE_RESERVED, STATE_REMOVED) && !closed) {
LOGGER.warn("Attempt to remove an object from the bag that was not borrowed or reserved: {}", bagEntry);
return false;
}
final boolean removed = sharedList.remove(bagEntry);
if (!removed && !closed) {
LOGGER.warn("Attempt to remove an object from the bag that does not exist: {}", bagEntry);
}
return removed;
}
/**
* Close the bag to further adds.
*/
@Override
public void close()
{
closed = true;
}
/**
* This method provides a "snapshot" in time of the BagEntry
* items in the bag in the specified state. It does not "lock"
* or reserve items in any way. Call <code>reserve(T)</code>
* on items in list before performing any action on them.
*
* @param state one of the {@link IConcurrentBagEntry} states
* @return a possibly empty list of objects having the state specified
*/
public List<T> values(final int state)
{
final ArrayList<T> list = new ArrayList<>(sharedList.size());
for (final T entry : sharedList) {
if (entry.getState() == state) {
list.add(entry);
}
}
return list;
}
/**
* This method provides a "snapshot" in time of the bag items. It
* does not "lock" or reserve items in any way. Call <code>reserve(T)</code>
* on items in the list, or understand the concurrency implications of
* modifying items, before performing any action on them.
*
* @return a possibly empty list of (all) bag items
*/
@SuppressWarnings("unchecked")
public List<T> values()
{
return (List<T>) sharedList.clone();
}
/**
* The method is used to make an item in the bag "unavailable" for
* borrowing. It is primarily used when wanting to operate on items
* returned by the <code>values(int)</code> method. Items that are
* reserved can be removed from the bag via <code>remove(T)</code>
* without the need to unreserve them. Items that are not removed
* from the bag can be make available for borrowing again by calling
* the <code>unreserve(T)</code> method.
*
* @param bagEntry the item to reserve
* @return true if the item was able to be reserved, false otherwise
*/
public boolean reserve(final T bagEntry)
{
return bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_RESERVED);
}
/**
* This method is used to make an item reserved via <code>reserve(T)</code>
* available again for borrowing.
*
* @param bagEntry the item to unreserve
*/
public void unreserve(final T bagEntry)
{
if (bagEntry.compareAndSet(STATE_RESERVED, STATE_NOT_IN_USE)) {
synchronizer.signal();
}
else {
LOGGER.warn("Attempt to relinquish an object to the bag that was not reserved: {}", bagEntry);
}
}
/**
* Get the number of threads pending (waiting) for an item from the
* bag to become available.
*
* @return the number of threads waiting for items from the bag
*/
public int getPendingQueue()
{
return synchronizer.getQueueLength();
}
/**
* Get a count of the number of items in the specified state at the time of this call.
*
* @param state the state of the items to count
* @return a count of how many items in the bag are in the specified state
*/
public int getCount(final int state)
{
int count = 0;
for (final T entry : sharedList) {
if (entry.getState() == state) {
count++;
}
}
return count;
}
/**
* Get the total number of items in the bag.
*
* @return the number of items in the bag
*/
public int size()
{
return sharedList.size();
}
public void dumpState()
{
for (T bagEntry : sharedList) {
LOGGER.info(bagEntry.toString());
}
}
/**
* Determine whether to use WeakReferences based on whether there is a
* custom ClassLoader implementation sitting between this class and the
* System ClassLoader.
*
* @return true if we should use WeakReferences in our ThreadLocals, false otherwise
*/
private boolean useWeakThreadLocals()
{
try {
if (System.getProperty("com.zaxxer.hikari.useWeakReferences") != null) { // undocumented manual override of WeakReference behavior
return Boolean.getBoolean("com.zaxxer.hikari.useWeakReferences");
}
return getClass().getClassLoader() != ClassLoader.getSystemClassLoader();
}
catch (SecurityException se) {
return true;
}
}
}
|
|
/*
* 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.arrow.vector;
import static org.apache.arrow.vector.NullCheckingForGet.NULL_CHECKING_ENABLED;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.complex.impl.TimeSecReaderImpl;
import org.apache.arrow.vector.complex.reader.FieldReader;
import org.apache.arrow.vector.holders.NullableTimeSecHolder;
import org.apache.arrow.vector.holders.TimeSecHolder;
import org.apache.arrow.vector.types.Types.MinorType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.TransferPair;
/**
* TimeSecVector implements a fixed width (4 bytes) vector of
* time (seconds resolution) values which could be null. A validity buffer (bit vector) is
* maintained to track which elements in the vector are null.
*/
public final class TimeSecVector extends BaseFixedWidthVector {
private static final byte TYPE_WIDTH = 4;
private final FieldReader reader;
/**
* Instantiate a TimeSecVector. This doesn't allocate any memory for
* the data in vector.
*
* @param name name of the vector
* @param allocator allocator for memory management.
*/
public TimeSecVector(String name, BufferAllocator allocator) {
this(name, FieldType.nullable(MinorType.TIMESEC.getType()), allocator);
}
/**
* Instantiate a TimeSecVector. This doesn't allocate any memory for
* the data in vector.
*
* @param name name of the vector
* @param fieldType type of Field materialized by this vector
* @param allocator allocator for memory management.
*/
public TimeSecVector(String name, FieldType fieldType, BufferAllocator allocator) {
this(new Field(name, fieldType, null), allocator);
}
/**
* Instantiate a TimeSecVector. This doesn't allocate any memory for
* the data in vector.
*
* @param field Field materialized by this vector
* @param allocator allocator for memory management.
*/
public TimeSecVector(Field field, BufferAllocator allocator) {
super(field, allocator, TYPE_WIDTH);
reader = new TimeSecReaderImpl(TimeSecVector.this);
}
/**
* Get a reader that supports reading values from this vector.
*
* @return Field Reader for this vector
*/
@Override
public FieldReader getReader() {
return reader;
}
/**
* Get minor type for this vector. The vector holds values belonging
* to a particular type.
*
* @return {@link org.apache.arrow.vector.types.Types.MinorType}
*/
@Override
public MinorType getMinorType() {
return MinorType.TIMESEC;
}
/*----------------------------------------------------------------*
| |
| vector value retrieval methods |
| |
*----------------------------------------------------------------*/
/**
* Get the element at the given index from the vector.
*
* @param index position of element
* @return element at given index
*/
public int get(int index) throws IllegalStateException {
if (NULL_CHECKING_ENABLED && isSet(index) == 0) {
throw new IllegalStateException("Value at index is null");
}
return valueBuffer.getInt((long) index * TYPE_WIDTH);
}
/**
* Get the element at the given index from the vector and
* sets the state in holder. If element at given index
* is null, holder.isSet will be zero.
*
* @param index position of element
*/
public void get(int index, NullableTimeSecHolder holder) {
if (isSet(index) == 0) {
holder.isSet = 0;
return;
}
holder.isSet = 1;
holder.value = valueBuffer.getInt((long) index * TYPE_WIDTH);
}
/**
* Same as {@link #get(int)}.
*
* @param index position of element
* @return element at given index
*/
public Integer getObject(int index) {
if (isSet(index) == 0) {
return null;
} else {
return valueBuffer.getInt((long) index * TYPE_WIDTH);
}
}
/*----------------------------------------------------------------*
| |
| vector value setter methods |
| |
*----------------------------------------------------------------*/
private void setValue(int index, int value) {
valueBuffer.setInt((long) index * TYPE_WIDTH, value);
}
/**
* Set the element at the given index to the given value.
*
* @param index position of element
* @param value value of element
*/
public void set(int index, int value) {
BitVectorHelper.setBit(validityBuffer, index);
setValue(index, value);
}
/**
* Set the element at the given index to the value set in data holder.
* If the value in holder is not indicated as set, element in the
* at the given index will be null.
*
* @param index position of element
* @param holder nullable data holder for value of element
*/
public void set(int index, NullableTimeSecHolder holder) throws IllegalArgumentException {
if (holder.isSet < 0) {
throw new IllegalArgumentException();
} else if (holder.isSet > 0) {
BitVectorHelper.setBit(validityBuffer, index);
setValue(index, holder.value);
} else {
BitVectorHelper.unsetBit(validityBuffer, index);
}
}
/**
* Set the element at the given index to the value set in data holder.
*
* @param index position of element
* @param holder data holder for value of element
*/
public void set(int index, TimeSecHolder holder) {
BitVectorHelper.setBit(validityBuffer, index);
setValue(index, holder.value);
}
/**
* Same as {@link #set(int, int)} except that it handles the
* case when index is greater than or equal to existing
* value capacity {@link #getValueCapacity()}.
*
* @param index position of element
* @param value value of element
*/
public void setSafe(int index, int value) {
handleSafe(index);
set(index, value);
}
/**
* Same as {@link #set(int, NullableTimeSecHolder)} except that it handles the
* case when index is greater than or equal to existing
* value capacity {@link #getValueCapacity()}.
*
* @param index position of element
* @param holder nullable data holder for value of element
*/
public void setSafe(int index, NullableTimeSecHolder holder) throws IllegalArgumentException {
handleSafe(index);
set(index, holder);
}
/**
* Same as {@link #set(int, TimeSecHolder)} except that it handles the
* case when index is greater than or equal to existing
* value capacity {@link #getValueCapacity()}.
*
* @param index position of element
* @param holder data holder for value of element
*/
public void setSafe(int index, TimeSecHolder holder) {
handleSafe(index);
set(index, holder);
}
/**
* Store the given value at a particular position in the vector. isSet indicates
* whether the value is NULL or not.
*
* @param index position of the new value
* @param isSet 0 for NULL value, 1 otherwise
* @param value element value
*/
public void set(int index, int isSet, int value) {
if (isSet > 0) {
set(index, value);
} else {
BitVectorHelper.unsetBit(validityBuffer, index);
}
}
/**
* Same as {@link #set(int, int, int)} except that it handles the case
* when index is greater than or equal to current value capacity of the
* vector.
*
* @param index position of the new value
* @param isSet 0 for NULL value, 1 otherwise
* @param value element value
*/
public void setSafe(int index, int isSet, int value) {
handleSafe(index);
set(index, isSet, value);
}
/**
* Given a data buffer, get the value stored at a particular position
* in the vector.
*
* <p>This method should not be used externally.
*
* @param buffer data buffer
* @param index position of the element.
* @return value stored at the index.
*/
public static int get(final ArrowBuf buffer, final int index) {
return buffer.getInt((long) index * TYPE_WIDTH);
}
/*----------------------------------------------------------------*
| |
| vector transfer |
| |
*----------------------------------------------------------------*/
/**
* Construct a TransferPair comprising of this and a target vector of
* the same type.
*
* @param ref name of the target vector
* @param allocator allocator for the target vector
* @return {@link TransferPair}
*/
@Override
public TransferPair getTransferPair(String ref, BufferAllocator allocator) {
return new TransferImpl(ref, allocator);
}
/**
* Construct a TransferPair with a desired target vector of the same type.
*
* @param to target vector
* @return {@link TransferPair}
*/
@Override
public TransferPair makeTransferPair(ValueVector to) {
return new TransferImpl((TimeSecVector) to);
}
private class TransferImpl implements TransferPair {
TimeSecVector to;
public TransferImpl(String ref, BufferAllocator allocator) {
to = new TimeSecVector(ref, field.getFieldType(), allocator);
}
public TransferImpl(TimeSecVector to) {
this.to = to;
}
@Override
public TimeSecVector getTo() {
return to;
}
@Override
public void transfer() {
transferTo(to);
}
@Override
public void splitAndTransfer(int startIndex, int length) {
splitAndTransferTo(startIndex, length, to);
}
@Override
public void copyValueSafe(int fromIndex, int toIndex) {
to.copyFromSafe(fromIndex, toIndex, TimeSecVector.this);
}
}
}
|
|
package com.twolattes.json;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
/**
* JSON values.
*
* @see http://www.json.org
*/
public final class Json {
/** A JSON value.
*/
public interface Value {
void write(Writer writer) throws IOException;
<T> T visit(JsonVisitor<T> visitor);
}
/**
* An object, i.e. {@code {"hello":"world"}}.
*/
public interface Object extends Value {
Json.Value put(Json.String key, Json.Value value);
Json.Value get(Json.String key);
boolean containsKey(Json.String key);
Set<Json.String> keySet();
Set<Map.Entry<Json.String, Json.Value>> entrySet();
Collection<Json.Value> values();
boolean isEmpty();
int size();
}
/**
* An array, i.e {@code [0, 1, 2, 3, 4, 5]}.
*/
public interface Array extends Value, Iterable<Value> {
void add(int index, Json.Value element);
boolean add(Json.Value element);
Json.Value get(int index);
boolean isEmpty();
int size();
List<Json.Value> values();
}
/**
* A string, i.e. {@code "hello"}.
*/
public interface String extends Value, Comparable<Json.String> {
java.lang.String getString();
boolean isEmpty();
}
/**
* A number, i.e. {@code 5}, {@code 78.90} or {@code 12728971932}.
*/
public interface Number extends Value {
BigDecimal getNumber();
}
/**
* A boolean, i.e {@code true} or {@code false}.
*/
public interface Boolean extends Value {
boolean getBoolean();
}
/**
* Null, i.e. {@code null}.
*/
public interface Null extends Json.Array, Json.Boolean, Json.Number, Json.Object, Json.String {
}
private static abstract class BaseValue implements Json.Value {
@Override
public final java.lang.String toString() {
StringWriter writer = new StringWriter();
try {
write(writer);
} catch (IOException e) {
// unreachable
throw new RuntimeException(e);
}
return writer.toString();
}
}
private static class ObjectImpl extends BaseValue implements Json.Object {
private final Map<Json.String, Json.Value> delegate = new TreeMap<Json.String, Json.Value>();
public void write(Writer writer) throws IOException {
writer.append('{');
java.lang.String separator = "";
for (Json.String key : delegate.keySet()) {
writer.append(separator);
separator = ",";
key.write(writer);
writer.append(':');
delegate.get(key).write(writer);
}
writer.append('}');
}
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseObject(this);
}
public void clear() {
delegate.clear();
}
public boolean containsKey(java.lang.Object key) {
return delegate.containsKey(key);
}
public boolean containsValue(java.lang.Object value) {
return delegate.containsValue(value);
}
@Override
public boolean equals(java.lang.Object o) {
if (!(o instanceof Json.Object)) {
return false;
} else if (NULL.equals(o)) {
return false;
} else {
return delegate.entrySet().equals(((Json.Object) o).entrySet());
}
}
public Json.Value get(Json.String key) {
return delegate.get(key);
}
public boolean containsKey(String key) {
return delegate.containsKey(key);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
public boolean isEmpty() {
return delegate.isEmpty();
}
public Set<Json.String> keySet() {
return delegate.keySet();
}
public Set<Entry<String, Value>> entrySet() {
return delegate.entrySet();
}
public Json.Value put(Json.String key, Json.Value value) {
return delegate.put(key, value);
}
public int size() {
return delegate.size();
}
public Collection<Json.Value> values() {
return delegate.values();
}
}
private static class ArrayImpl extends BaseValue implements Json.Array {
private final List<Json.Value> delegate = new LinkedList<Json.Value>();
public ArrayImpl(Json.Value... values) {
for (Json.Value value : values) {
delegate.add(value);
}
}
public void write(Writer writer) throws IOException {
writer.append('[');
java.lang.String separator = "";
for (Json.Value value : delegate) {
writer.append(separator);
separator = ",";
value.write(writer);
}
writer.append(']');
}
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseArray(this);
}
public List<Value> values() {
return delegate;
}
public void add(int index, Json.Value element) {
delegate.add(index, element);
}
public boolean add(Json.Value e) {
return delegate.add(e);
}
@Override
public boolean equals(java.lang.Object o) {
if (!(o instanceof Json.Array)) {
return false;
} else if (NULL.equals(o)) {
return false;
} else {
return delegate.equals(((Json.Array) o).values());
}
}
public Json.Value get(int index) {
return delegate.get(index);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
public boolean isEmpty() {
return delegate.isEmpty();
}
public int size() {
return delegate.size();
}
public Iterator<Value> iterator() {
return delegate.iterator();
}
}
private static class BooleanImpl extends BaseValue implements Json.Boolean {
private final boolean b;
public BooleanImpl(boolean b) {
this.b = b;
}
public void write(Writer writer) throws IOException {
writer.append(java.lang.Boolean.toString(b));
}
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseBoolean(this);
}
@Override
public boolean equals(java.lang.Object obj) {
if (!(obj instanceof BooleanImpl)) {
return false;
} else {
return !(this.b ^ ((BooleanImpl) obj).b);
}
}
@Override
public int hashCode() {
if (b) {
return 982451653;
} else {
return 941083987;
}
}
public boolean getBoolean() {
return b;
}
}
private static abstract class NumberImpl extends BaseValue implements Json.Number {
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseNumber(this);
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Json.Number)) {
return false;
}
if (obj.equals(NULL)) {
return false;
}
return this.getNumber().compareTo(((Json.Number) obj).getNumber()) == 0;
}
@Override
public int hashCode() {
return (int) getNumber().doubleValue();
}
}
private static class NumberImplShort extends NumberImpl {
private final short number;
public NumberImplShort(short number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(Short.toString(number));
}
public BigDecimal getNumber() {
return BigDecimal.valueOf(number);
}
}
private static class NumberImplInt extends NumberImpl {
private final int number;
public NumberImplInt(int number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(Integer.toString(number));
}
public BigDecimal getNumber() {
return BigDecimal.valueOf(number);
}
}
private static class NumberImplLong extends NumberImpl {
private final long number;
public NumberImplLong(long number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(Long.toString(number));
}
public BigDecimal getNumber() {
return BigDecimal.valueOf(number);
}
}
private static class NumberImplFloat extends NumberImpl {
private final float number;
public NumberImplFloat(float number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(Float.toString(number));
}
public BigDecimal getNumber() {
return new BigDecimal(Float.toString(number));
}
}
private static class NumberImplDouble extends NumberImpl {
private final double number;
public NumberImplDouble(double number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(Double.toString(number));
}
public BigDecimal getNumber() {
return BigDecimal.valueOf(number);
}
}
private static class NumberImplBigDecimal extends NumberImpl {
private final BigDecimal number;
public NumberImplBigDecimal(BigDecimal number) {
this.number = number;
}
public void write(Writer writer) throws IOException {
writer.append(number.toPlainString());
}
public BigDecimal getNumber() {
return number;
}
}
private static class StringImpl extends BaseValue implements Json.String {
private final java.lang.String string;
public StringImpl(java.lang.String string) {
this.string = string;
}
public void write(Writer writer) throws IOException {
StringBuilder builder = new StringBuilder(string.length() << 1);
builder.append('"');
int length = string.length();
char c;
boolean safe = true;
for (int i = 0; safe && i < length; i++) {
c = string.charAt(i);
safe = c != '"' && c != '\\' && c >= 0x20 && (c < 0x7f || c >= 0xa0);
}
if (safe) {
builder.append(string);
} else {
for (int i = 0; i < length; i++) {
switch (c = string.charAt(i)) {
case '\b': builder.append("\\b"); break;
case '\n': builder.append("\\n"); break;
case '\f': builder.append("\\f"); break;
case '\r': builder.append("\\r"); break;
case '\t': builder.append("\\t"); break;
case '"': builder.append("\\\""); break;
case '\\': builder.append("\\\\"); break;
default:
if (c < 0x20 || (c >= 0x7f && c < 0xa0)) {
builder.append(java.lang.String.format("\\u%04x", Integer.valueOf(c)));
} else {
builder.append(c);
}
break;
}
}
}
builder.append('"');
writer.append(builder.toString());
}
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseString(this);
}
public int compareTo(Json.String that) {
return this.string.compareTo(that.getString());
}
@Override
public boolean equals(java.lang.Object obj) {
if (!(obj instanceof Json.String)) {
return false;
} else if (NULL.equals(obj)) {
return false;
} else {
return this.getString().equals(((Json.String) obj).getString());
}
}
@Override
public int hashCode() {
return string.hashCode();
}
public java.lang.String getString() {
return string;
}
public boolean isEmpty() {
return string.length() == 0; // 1.5 compatible
}
}
private static class NullImpl extends BaseValue implements Json.Null {
public void write(Writer writer) throws IOException {
writer.append("null");
}
public <T> T visit(JsonVisitor<T> visitor) {
return visitor.caseNull();
}
@Override
public boolean equals(java.lang.Object obj) {
return obj instanceof Json.NullImpl;
}
@Override
public int hashCode() {
return 900772187;
}
public boolean getBoolean() {
throw new NullPointerException();
}
public BigDecimal getNumber() {
throw new NullPointerException();
}
public java.lang.String getString() {
throw new NullPointerException();
}
public int compareTo(Json.String o) {
throw new NullPointerException();
}
public Value get(String key) {
throw new NullPointerException();
}
public boolean containsKey(String key) {
throw new NullPointerException();
}
public boolean isEmpty() {
throw new NullPointerException();
}
public Set<String> keySet() {
throw new NullPointerException();
}
public Set<Entry<String, Value>> entrySet() {
throw new NullPointerException();
}
public Value put(String key, Value value) {
throw new NullPointerException();
}
public int size() {
throw new NullPointerException();
}
public List<Value> values() {
throw new NullPointerException();
}
public void add(int index, Value element) {
throw new NullPointerException();
}
public boolean add(Value element) {
throw new NullPointerException();
}
public Value get(int index) {
throw new NullPointerException();
}
public Iterator<Value> iterator() {
throw new NullPointerException();
}
}
/**
* {@code new Json.Null()}.
*/
public static final Json.Null NULL = new Json.NullImpl();
/**
* {@code new Json.Boolean(true)}.
*/
public static final Json.Boolean TRUE = new Json.BooleanImpl(true);
/**
* {@code new Json.Boolean(false)}.
*/
public static final Json.Boolean FALSE = new Json.BooleanImpl(false);
/**
* Read a JSON value from a reader.
*/
public static Json.Value read(Reader reader) throws IOException {
CharStream stream = new CharStream(reader);
return read(stream, skip(stream));
}
private static int skip(CharStream reader) throws IOException {
int c;
while (Character.isWhitespace(c = reader.read())) {
}
return c;
}
private static Json.Value read(CharStream reader, int c) throws IOException {
StringBuilder sb;
switch (c) {
// null
case 'n': {
int u = reader.read(), l1 = reader.read(), l2 = reader.read();
if (u == 'u' && l1 == 'l' && l2 == 'l') {
return Json.NULL;
} else {
throw new IllegalArgumentException("null expected");
}
}
// true
case 't': {
int r = reader.read(), u = reader.read(), e = reader.read();
if (r == 'r' && u == 'u' && e == 'e') {
return Json.TRUE;
} else {
throw new IllegalArgumentException("true expected");
}
}
// false
case 'f': {
int a = reader.read(), l = reader.read(), s = reader.read(), e = reader.read();
if (a == 'a' && l == 'l' && s == 's' && e == 'e') {
return Json.FALSE;
} else {
throw new IllegalArgumentException("false expected");
}
}
// object
case '{':
Json.ObjectImpl object = new Json.ObjectImpl();
// Unrolling to avoid state, note that the first time around we must not
// skip when reading the key of the object.
c = skip(reader);
if (c == '}') {
return object;
}
Json.StringImpl key = (Json.StringImpl) read(reader, c);
if (skip(reader) != ':') {
throw new IllegalArgumentException(": expected");
}
object.put(key, read(reader, skip(reader)));
c = skip(reader);
do {
if (c == '}') {
return object;
}
key = (Json.StringImpl) read(reader, skip(reader));
if (skip(reader) != ':') {
throw new IllegalArgumentException(": expected");
}
object.put(key, read(reader, skip(reader)));
} while ((c = skip(reader)) == ',' || c == '}');
throw new IllegalArgumentException(java.lang.String.format(
"Non terminated object literal. Last character read was %s. " +
"Partial object literal read %s.",
Character.toString((char) c),
object.toString()));
// array
case '[':
Json.ArrayImpl array = new Json.ArrayImpl();
// Unrolling to avoid state, note that the first time around we must not
// skip when reading the value added to the array.
c = skip(reader);
if (c == ']') {
return array;
}
array.add(read(reader, c));
c = skip(reader);
do {
if (c == ']') {
return array;
}
array.add(read(reader, skip(reader)));
} while ((c = skip(reader)) == ',' || c == ']');
throw new IllegalArgumentException("non terminated array literal");
// string
case '"':
sb = new StringBuilder();
do {
switch (c = reader.read()) {
case '"':
return new Json.StringImpl(sb.toString());
case '\\':
switch (c = reader.read()) {
case '"':
case '\\':
case '/':
sb.append((char) c);
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'u':
int h1 = reader.read(), h2 = reader.read(), h3 = reader.read(), h4 = reader.read();
if (('a' <= h1 && h1 <= 'f' || 'A' <= h1 && h1 <= 'F' || '0' <= h1 && h1 <= '9') &&
('a' <= h2 && h2 <= 'f' || 'A' <= h2 && h2 <= 'F' || '0' <= h2 && h2 <= '9') &&
('a' <= h3 && h3 <= 'f' || 'A' <= h3 && h3 <= 'F' || '0' <= h3 && h3 <= '9') &&
('a' <= h4 && h4 <= 'f' || 'A' <= h4 && h4 <= 'F' || '0' <= h4 && h4 <= '9')) {
sb.append((char) (fromHex(h1) << 12 | fromHex(h2) << 8 | fromHex(h3) << 4 | fromHex(h4)));
} else {
throw new IllegalArgumentException("invalid hex code");
}
}
break;
case -1:
throw new IllegalArgumentException("non terminated string");
default:
sb.append((char) c);
}
} while (true);
// number
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
sb = new StringBuilder();
do {
sb.append((char) c);
} while ((c = reader.read()) <= '9' && '0' <= c);
switch (c) {
case '.':
do {
sb.append((char) c);
} while ((c = reader.read()) <= '9' && '0' <= c);
case 'e':
case 'E':
if (c != 'e' && c != 'E') {
reader.unread(c);
return new Json.NumberImplBigDecimal(new BigDecimal(sb.toString()));
}
sb.append((char) c);
c = reader.read();
if (c != '+' && c != '-' && c < '0' && '9' < c) {
reader.unread(c);
return new Json.NumberImplBigDecimal(new BigDecimal(sb.toString()));
}
do {
sb.append((char) c);
} while ((c = reader.read()) <= '9' && '0' <= c);
default:
reader.unread(c);
return new Json.NumberImplBigDecimal(new BigDecimal(sb.toString()));
}
// error
default:
throw new IllegalArgumentException("illegal character " + (char) c);
}
}
/* Visible for testing. */
static int fromHex(int codePoint) {
// '9' = 57, 'F' = 70, 'f' = 102
return (codePoint <= '9') ? codePoint - '0' :
(codePoint <= 'F') ? codePoint - 'A' + 10 : codePoint - 'a' + 10;
}
/**
* Create a JSON value from a string.
*/
public static Json.Value fromString(java.lang.String input) {
try {
return read(new StringReader(input));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Json.Array array(Json.Value... values) {
return new Json.ArrayImpl(values);
}
public static Json.Object object() {
return new Json.ObjectImpl();
}
public static Json.Object object(
Json.String k1, Json.Value v1) {
Json.Object o = object();
o.put(k1, v1);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2) {
Json.Object o = object(k1, v1);
o.put(k2, v2);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3) {
Json.Object o = object(k1, v1, k2, v2);
o.put(k3, v3);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4) {
Json.Object o = object(k1, v1, k2, v2, k3, v3);
o.put(k4, v4);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4,
Json.String k5, Json.Value v5) {
Json.Object o = object(k1, v1, k2, v2, k3, v3, k4, v4);
o.put(k5, v5);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4,
Json.String k5, Json.Value v5,
Json.String k6, Json.Value v6) {
Json.Object o = object(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
o.put(k6, v6);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4,
Json.String k5, Json.Value v5,
Json.String k6, Json.Value v6,
Json.String k7, Json.Value v7) {
Json.Object o = object(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6);
o.put(k7, v7);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4,
Json.String k5, Json.Value v5,
Json.String k6, Json.Value v6,
Json.String k7, Json.Value v7,
Json.String k8, Json.Value v8) {
Json.Object o = object(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7);
o.put(k8, v8);
return o;
}
public static Json.Object object(
Json.String k1, Json.Value v1,
Json.String k2, Json.Value v2,
Json.String k3, Json.Value v3,
Json.String k4, Json.Value v4,
Json.String k5, Json.Value v5,
Json.String k6, Json.Value v6,
Json.String k7, Json.Value v7,
Json.String k8, Json.Value v8,
Json.String k9, Json.Value v9) {
Json.Object o = object(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8);
o.put(k9, v9);
return o;
}
public static Json.Object object(Json.Value... keyValuePairs) {
if (keyValuePairs.length % 2 != 0) {
throw new IllegalArgumentException("Number of arguments must be even");
}
Json.Object o = object();
for (int i = 0; i < keyValuePairs.length; i += 2) {
Json.Value key = keyValuePairs[i];
if (key instanceof Json.String) {
o.put((Json.String) key, keyValuePairs[i + 1]);
} else {
throw new IllegalArgumentException("Keys must be JSON strings");
}
}
return o;
}
public static Json.Number number(short number) {
return new Json.NumberImplShort(number);
}
public static Json.Number number(int number) {
return new Json.NumberImplInt(number);
}
public static Json.Number number(long number) {
return new Json.NumberImplLong(number);
}
public static Json.Number number(float number) {
return new Json.NumberImplFloat(number);
}
public static Json.Number number(double number) {
return new Json.NumberImplDouble(number);
}
public static Json.Number number(BigDecimal number) {
return new Json.NumberImplBigDecimal(number);
}
public static Json.String string(java.lang.String string) {
return new Json.StringImpl(string);
}
/** See {@link #TRUE}, {@link #FALSE}. */
static Json.Boolean booleanValue(boolean b) {
return new Json.BooleanImpl(b);
}
/** See {@link #NULL}. */
static Json.Null nullValue() {
return new Json.NullImpl();
}
}
|
|
package edu.jhu.pacaya.gm.model;
import java.io.Serializable;
import edu.jhu.pacaya.autodiff.Tensor;
import edu.jhu.pacaya.util.semiring.Algebra;
import edu.jhu.pacaya.util.semiring.AlgebraLambda;
import edu.jhu.prim.iter.IntIter;
/**
* A {@link Tensor} where each row corresponds to a variable (i.e. a {@link Var}). It can represent
* a not-necessarily-normalized multivariate Multinomial distribution.
*
* @author mgormley
*
*/
public class VarTensor extends Tensor implements Serializable {
private static final long serialVersionUID = 1L;
/** All variables without an id are given this value. */
public static final int UNINITIALIZED_NODE_ID = -1;
/** The set of variables in this factor. */
private VarSet vars;
/** Constructs a factor initializing the values to 0.0. */
public VarTensor(Algebra s, VarSet vars) {
this(s, vars, s.zero());
}
/** Constructs a factor where each value is set to some initial value. */
public VarTensor(Algebra s, VarSet vars, double initialValue) {
super(s, getDims(vars));
this.vars = vars;
this.fill(initialValue);
}
/** Copy constructor. */
public VarTensor(VarTensor other) {
super(other);
this.vars = other.vars;
}
/**
* Gets the tensor dimensions: dimension i corresponds to the i'th variable, and the size of
* that dimension is the number of states for the variable.
*/
private static int[] getDims(VarSet vars) {
int[] dims = new int[vars.size()];
for (int i=0; i<vars.size(); i++) {
dims[i] = vars.get(i).getNumStates();
}
return dims;
}
/**
* Gets the marginal distribution over a subset of the variables in this
* factor, optionally normalized.
*
* @param vars The subset of variables for the marginal distribution. This will sum over all variables not in this set.
* @param normalize Whether to normalize the resulting distribution.
* @return The marginal distribution.
*/
public VarTensor getMarginal(VarSet vars, boolean normalize) {
VarSet margVars = new VarSet(this.vars);
margVars.retainAll(vars);
VarTensor marg = new VarTensor(s, margVars, s.zero());
if (margVars.size() == 0) {
return marg;
}
IntIter iter = margVars.getConfigIter(this.vars);
for (int i=0; i<this.values.length; i++) {
int j = iter.next();
marg.values[j] = s.plus(marg.values[j], this.values[i]);
}
if (normalize) {
marg.normalize();
}
return marg;
}
public VarTensor getClamped(VarConfig clmpVarConfig) {
if (clmpVarConfig.size() == 0) {
return new VarTensor(this);
}
VarSet clmpVars = clmpVarConfig.getVars();
VarSet unclmpVars = new VarSet(this.vars);
unclmpVars.removeAll(clmpVars);
VarTensor clmp = new VarTensor(s, unclmpVars);
IntIter iter = IndexForVc.getConfigIter(this.vars, clmpVarConfig);
if (clmp.values.length > 0) {
for (int c=0; c<clmp.values.length; c++) {
int config = iter.next();
clmp.values[c] = this.values[config];
}
}
return clmp;
}
/** Gets the variables associated with this factor. */
public VarSet getVars() {
return vars;
}
/**
* Adds a factor to this one.
*
* From libDAI:
* The sum of two factors is defined as follows: if
* \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
* \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
*/
public void add(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.Add());
internalSet(newFactor);
}
/**
* Multiplies a factor to this one.
*
* From libDAI:
* The product of two factors is defined as follows: if
* \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
* \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
*/
public void prod(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.Prod());
internalSet(newFactor);
}
/**
* this /= f
* indices matching 0 /= 0 are set to 0.
*/
public void divBP(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.DivBP());
internalSet(newFactor);
}
/**
* this /= f
* indices matching 0 /= 0 are set to 0.
*/
public void elemDivBP(VarTensor f) {
elemApplyBinOp(this, f, new AlgebraLambda.DivBP());
}
/** This set method is used to internally update ALL the fields. */
private void internalSet(VarTensor newFactor) {
this.vars = newFactor.vars;
this.dims = newFactor.dims;
this.strides = newFactor.strides;
this.values = newFactor.values;
}
/**
* Applies the binary operator to factors f1 and f2.
*
* This method will opt to be destructive on f1 (returning it instead of a
* new factor) if time/space can be saved by doing so.
*
* Note: destructive if necessary.
*
* @param f1 The first factor. (returned if it will save time/space)
* @param f2 The second factor.
* @param op The binary operator.
* @return The new factor.
*/
private static VarTensor applyBinOp(final VarTensor f1, final VarTensor f2, final AlgebraLambda.LambdaBinOp op) {
checkSameAlgebra(f1, f2);
Algebra s = f1.s;
if (f1.vars.size() == 0) {
// Return a copy of f2.
return new VarTensor(f2);
} else if (f2.vars.size() == 0) {
// Don't use the copy constructor, just return f1.
return f1;
} else if (f1.vars == f2.vars || f1.vars.equals(f2.vars)) {
// Special case where the factors have identical variable sets.
assert (f1.values.length == f2.values.length);
for (int c = 0; c < f1.values.length; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[c]);
}
return f1;
} else if (f1.vars.isSuperset(f2.vars)) {
// Special case where f1 is a superset of f2.
IntIter iter2 = f2.vars.getConfigIter(f1.vars);
int n = f1.vars.calcNumConfigs();
for (int c = 0; c < n; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[iter2.next()]);
}
assert(!iter2.hasNext());
return f1;
} else {
// The union of the two variable sets must be created.
VarSet union = new VarSet(f1.vars, f2.vars);
VarTensor out = new VarTensor(s, union);
IntIter iter1 = f1.vars.getConfigIter(union);
IntIter iter2 = f2.vars.getConfigIter(union);
int n = out.vars.calcNumConfigs();
for (int c = 0; c < n; c++) {
out.values[c] = op.call(s, f1.values[iter1.next()], f2.values[iter2.next()]);
}
assert(!iter1.hasNext());
assert(!iter2.hasNext());
return out;
}
}
/**
* Applies the operation to each element of f1 and f2, which are assumed to be of the same size.
* The result is stored in f1.
*
* @param f1 Input factor 1 and the output factor.
* @param f2 Input factor 2.
* @param op The operation to apply.
*/
private static void elemApplyBinOp(final VarTensor f1, final VarTensor f2, final AlgebraLambda.LambdaBinOp op) {
checkSameAlgebra(f1, f2);
Algebra s = f1.s;
if (f1.size() != f2.size()) {
throw new IllegalArgumentException("VarTensors are different sizes");
}
for (int c = 0; c < f1.values.length; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[c]);
}
}
/**
* Sets each entry in this factor to that of the given factor.
* @param factor
*/
// TODO: Is this called, if so, it should become setValuesOnly.
public void set(VarTensor f) {
if (!this.vars.equals(f.vars)) {
throw new IllegalStateException("The varsets must be equal.");
}
super.setValuesOnly(f);
}
@Override
public String toString() {
return toString(false);
}
/** Returns a string representation of the VarTensor, which (optionally) excludes zero-valued rows. */
public String toString(boolean sparse) {
StringBuilder sb = new StringBuilder();
sb.append("VarTensor [\n");
for (Var var : vars) {
String name = var.getName();
// Take the 5-char suffix if the variable name is too long.
name = name.substring(Math.max(0, name.length()-5));
sb.append(String.format("%6s", name));
}
sb.append(String.format(" | %s\n", "value"));
for (int c=0; c<vars.calcNumConfigs(); c++) {
if (!sparse || values[c] != 0.0) {
int[] states = vars.getVarConfigAsArray(c);
for (int i=0; i<states.length; i++) {
int state = states[i];
Var v = vars.get(i);
if (v.getStateNames() != null) {
// Use string names for states if available.
sb.append(String.format("%6s", v.getStateNames().get(state)));
} else {
sb.append(String.format("%6d", state));
}
}
sb.append(String.format(" | %g\n", values[c]));
}
}
sb.append("]");
return sb.toString();
}
// TODO: Move this to BeliefPropagation.java.
public boolean containsBadValues() {
for(int i=0; i<values.length; i++) {
if(s.isNaN(values[i])) {
return true;
}
if (s.lt(values[i], s.zero()) || values[i] == s.posInf()) {
return true;
}
}
return false;
}
/* Note that VarTensors do not implement the standard hashCode() or equals() methods. */
/** Special equals with a tolerance. */
public boolean equals(VarTensor other, double delta) {
if (this == other)
return true;
if (other == null)
return false;
if (!super.equals(other, delta))
return false;
if (vars == null) {
if (other.vars != null)
return false;
} else if (!vars.equals(other.vars))
return false;
return true;
}
/** Takes the log of each value. */
public void convertRealToLog() {
this.log();
}
@Override
public VarTensor copy() {
return new VarTensor(this);
}
@Override
public VarTensor copyAndFill(double val) {
VarTensor other = this.copy();
other.fill(val);
return other;
}
@Override
public VarTensor copyAndConvertAlgebra(Algebra newS) {
VarTensor t = new VarTensor(newS, this.vars);
t.setFromDiffAlgebra(this);
return t;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.