code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.common.policy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.lang.Validate;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordLifeTimeType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
*
* @author mamut
*
*/
public class PasswordPolicyUtils {
private static final transient Trace LOGGER = TraceManager.getTrace(PasswordPolicyUtils.class);
private static final String DOT_CLASS = PasswordPolicyUtils.class.getName() + ".";
private static final String OPERATION_PASSWORD_VALIDATION = DOT_CLASS + "passwordValidation";
/**
* add defined default values
*
* @param pp
* @return
*/
public static void normalize(ValuePolicyType pp) {
if (null == pp) {
throw new IllegalArgumentException("Password policy cannot be null");
}
if (null == pp.getStringPolicy()) {
StringPolicyType sp = new StringPolicyType();
pp.setStringPolicy(StringPolicyUtils.normalize(sp));
} else {
pp.setStringPolicy(StringPolicyUtils.normalize(pp.getStringPolicy()));
}
if (null == pp.getLifetime()) {
PasswordLifeTimeType lt = new PasswordLifeTimeType();
lt.setExpiration(-1);
lt.setWarnBeforeExpiration(0);
lt.setLockAfterExpiration(0);
lt.setMinPasswordAge(0);
lt.setPasswordHistoryLength(0);
}
return;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param policies
* - Password List of policies used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, List <ValuePolicyType> policies, OperationResult result) {
boolean ret=true;
//iterate through policies
for (ValuePolicyType pp: policies) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(String password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password, pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(ProtectedStringType password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password.getClearValue(), pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, ValuePolicyType pp, OperationResult result) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
return op.isSuccess();
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used
* @return - Operation result of this validation
*/
public static OperationResult validatePassword(String password, ValuePolicyType pp) {
// check input params
// if (null == pp) {
// throw new IllegalArgumentException("No policy provided: NULL");
// }
//
// if (null == password) {
// throw new IllegalArgumentException("Password for validaiton is null.");
// }
Validate.notNull(pp, "Password policy must not be null.");
Validate.notNull(password, "Password to validate must not be null.");
OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
ret.addParam("policyName", pp.getName());
normalize(pp);
LimitationsType lims = pp.getStringPolicy().getLimitations();
StringBuilder message = new StringBuilder();
// Test minimal length
if (lims.getMinLength() == null){
lims.setMinLength(0);
}
if (lims.getMinLength() > password.length()) {
String msg = "Required minimal size (" + lims.getMinLength() + ") of password is not met (password length: "
+ password.length() + ")";
ret.addSubresult(new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal length
if (lims.getMaxLength() != null) {
if (lims.getMaxLength() < password.length()) {
String msg = "Required maximal size (" + lims.getMaxLength()
+ ") of password was exceeded (password length: " + password.length() + ").";
ret.addSubresult(new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// Test uniqueness criteria
HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
if (lims.getMinUniqueChars() != null) {
if (lims.getMinUniqueChars() > tmp.size()) {
String msg = "Required minimal count of unique characters ("
+ lims.getMinUniqueChars()
+ ") in password are not met (unique characters in password " + tmp.size() + ")";
ret.addSubresult(new OperationResult("Check minimal count of unique chars",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult(
// "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// check limitation
HashSet<String> allValidChars = new HashSet<String>(128);
ArrayList<String> validChars = null;
ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);
if (lims.getLimit() == null || lims.getLimit().isEmpty()){
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
for (StringLimitType l : lims.getLimit()) {
OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
if (null != l.getCharacterClass().getValue()) {
validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
} else {
validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(pp
.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
}
// memorize validChars
allValidChars.addAll(validChars);
// Count how many character for this limitation are there
int count = 0;
for (String s : passwd) {
if (validChars.contains(s)) {
count++;
}
}
// Test minimal occurrence
if (l.getMinOccurs() == null){
l.setMinOccurs(0);
}
if (l.getMinOccurs() > count) {
String msg = "Required minimal occurrence (" + l.getMinOccurs()
+ ") of characters ("+l.getDescription()+") in password is not met (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal occurrence
if (l.getMaxOccurs() != null) {
if (l.getMaxOccurs() < count) {
String msg = "Required maximal occurrence (" + l.getMaxOccurs()
+ ") of characters ("+l.getDescription()+") in password was exceeded (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult(
// "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
// "PASSED"));
// }
}
// test if first character is valid
if (l.isMustBeFirst() == null){
l.setMustBeFirst(false);
}
if (l.isMustBeFirst() && !validChars.contains(password.substring(0, 1))) {
String msg = "First character is not from allowed set. Allowed set: "
+ validChars.toString();
limitResult.addSubresult(new OperationResult("Check valid first char",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
limitResult.computeStatus();
ret.addSubresult(limitResult);
}
// Check if there is no invalid character
StringBuilder sb = new StringBuilder();
for (String s : passwd) {
if (!allValidChars.contains(s)) {
// memorize all invalid characters
sb.append(s);
}
}
if (sb.length() > 0) {
String msg = "Characters [ " + sb
+ " ] are not allowed to be use in password";
ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
}
| sabriarabacioglu/engerek | infra/common/src/main/java/com/evolveum/midpoint/common/policy/PasswordPolicyUtils.java | Java | apache-2.0 | 12,321 |
/* Copyright 2018 The TensorFlow 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.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.linalg;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.family.TType;
/**
* Returns the batched diagonal part of a batched tensor.
* Returns a tensor with the {@code k[0]}-th to {@code k[1]}-th diagonals of the batched
* {@code input}.
* <p>Assume {@code input} has {@code r} dimensions {@code [I, J, ..., L, M, N]}.
* Let {@code max_diag_len} be the maximum length among all diagonals to be extracted,
* {@code max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))}
* Let {@code num_diags} be the number of diagonals to extract,
* {@code num_diags = k[1] - k[0] + 1}.
* <p>If {@code num_diags == 1}, the output tensor is of rank {@code r - 1} with shape
* {@code [I, J, ..., L, max_diag_len]} and values:
* <pre>
* diagonal[i, j, ..., l, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code y = max(-k[1], 0)}, {@code x = max(k[1], 0)}.
* <p>Otherwise, the output tensor has rank {@code r} with dimensions
* {@code [I, J, ..., L, num_diags, max_diag_len]} with values:
* <pre>
* diagonal[i, j, ..., l, m, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code d = k[1] - m}, {@code y = max(-d, 0)}, and {@code x = max(d, 0)}.
* <p>The input must be at least a matrix.
* <p>For example:
* <pre>
* input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)
* [5, 6, 7, 8],
* [9, 8, 7, 6]],
* [[5, 4, 3, 2],
* [1, 2, 3, 4],
* [5, 6, 7, 8]]])
*
* # A main diagonal from each batch.
* tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)
* [5, 2, 7]]
*
* # A superdiagonal from each batch.
* tf.matrix_diag_part(input, k = 1)
* ==> [[2, 7, 6], # Output shape: (2, 3)
* [4, 3, 8]]
*
* # A tridiagonal band from each batch.
* tf.matrix_diag_part(input, k = (-1, 1))
* ==> [[[2, 7, 6], # Output shape: (2, 3, 3)
* [1, 6, 7],
* [5, 8, 0]],
* [[4, 3, 8],
* [5, 2, 7],
* [1, 6, 0]]]
*
* # Padding value = 9
* tf.matrix_diag_part(input, k = (1, 3), padding_value = 9)
* ==> [[[4, 9, 9], # Output shape: (2, 3, 3)
* [3, 8, 9],
* [2, 7, 6]],
* [[2, 9, 9],
* [3, 4, 9],
* [4, 3, 8]]]
* </pre>
*
* @param <T> data type for {@code diagonal} output
*/
@OpMetadata(
opType = MatrixDiagPart.OP_NAME,
inputsClass = MatrixDiagPart.Inputs.class
)
@Operator(
group = "linalg"
)
public final class MatrixDiagPart<T extends TType> extends RawOp implements Operand<T> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "MatrixDiagPartV2";
private Output<T> diagonal;
public MatrixDiagPart(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
diagonal = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new MatrixDiagPartV2 operation.
*
* @param scope current scope
* @param input Rank {@code r} tensor where {@code r >= 2}.
* @param k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
* @param paddingValue The value to fill the area outside the specified diagonal band with.
* Default is 0.
* @param <T> data type for {@code MatrixDiagPartV2} output and operands
* @return a new instance of MatrixDiagPart
*/
@Endpoint(
describeByClass = true
)
public static <T extends TType> MatrixDiagPart<T> create(Scope scope, Operand<T> input,
Operand<TInt32> k, Operand<T> paddingValue) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "MatrixDiagPart");
opBuilder.addInput(input.asOutput());
opBuilder.addInput(k.asOutput());
opBuilder.addInput(paddingValue.asOutput());
return new MatrixDiagPart<>(opBuilder.build());
}
/**
* Gets diagonal.
* The extracted diagonal(s).
* @return diagonal.
*/
public Output<T> diagonal() {
return diagonal;
}
@Override
public Output<T> asOutput() {
return diagonal;
}
@OpInputsMetadata(
outputsClass = MatrixDiagPart.class
)
public static class Inputs<T extends TType> extends RawOpInputs<MatrixDiagPart<T>> {
/**
* Rank {@code r} tensor where {@code r >= 2}.
*/
public final Operand<T> input;
/**
* Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
*/
public final Operand<TInt32> k;
/**
* The value to fill the area outside the specified diagonal band with.
* Default is 0.
*/
public final Operand<T> paddingValue;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new MatrixDiagPart<>(op), op, Arrays.asList("T"));
int inputIndex = 0;
input = (Operand<T>) op.input(inputIndex++);
k = (Operand<TInt32>) op.input(inputIndex++);
paddingValue = (Operand<T>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
}
}
}
| tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/linalg/MatrixDiagPart.java | Java | apache-2.0 | 7,043 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP Development Team
*
* 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.zaproxy.zap.control;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.junit.jupiter.api.Test;
import org.zaproxy.zap.control.AddOn.BundleData;
import org.zaproxy.zap.control.AddOn.HelpSetData;
import org.zaproxy.zap.control.AddOn.ValidationResult;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
/** Unit test for {@link AddOn}. */
class AddOnUnitTest extends AddOnTestUtils {
private static final File ZAP_VERSIONS_XML =
getResourcePath("ZapVersions-deps.xml", AddOnUnitTest.class).toFile();
@Test
void testAlpha2UpdatesAlpha1() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnA1));
}
@Test
void testAlpha1DoesNotUpdateAlpha2() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "1"));
assertFalse(addOnA1.isUpdateTo(addOnA2));
}
@Test
void testAlpha2UpdatesBeta1() throws Exception {
AddOn addOnB1 = new AddOn(createAddOnFile("test-beta-1.zap", "beta", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnB1));
}
@Test
void testAlpha2DoesNotUpdateTestyAlpha1() throws Exception {
// Given
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("testy-alpha-2.zap", "alpha", "1"));
// When
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> addOnA2.isUpdateTo(addOnA1));
// Then
assertThat(e.getMessage(), containsString("Different addons"));
}
@Test
void shouldBeUpdateIfSameVersionWithHigherStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOnHigherStatus.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfSameVersionWithLowerStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOn.isUpdateTo(addOnHigherStatus);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfFileIsNewerWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = newestAddOn.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfFileIsOlderWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = addOn.isUpdateTo(newestAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfOtherAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOn.isUpdateTo(addOnWithoutFile);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfCurrentAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOnWithoutFile.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void testCanLoadAddOnNotBefore() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertFalse(ao.canLoadInVersion("1.4.0"));
assertFalse(ao.canLoadInVersion("2.0.alpha"));
}
@Test
void testCanLoadAddOnNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
ao.setNotFromVersion("2.8.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.8.0"));
assertFalse(ao.canLoadInVersion("2.8.0.1"));
assertFalse(ao.canLoadInVersion("2.9.0"));
}
@Test
void testCanLoadAddOnNotBeforeNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotFromVersion("2.7.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.6.0"));
assertFalse(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.7.0.1"));
assertFalse(ao.canLoadInVersion("2.8.0"));
}
@Test
void shouldNotBeAddOnFileNameIfNull() throws Exception {
// Given
String fileName = null;
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnFileNameIfNotEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.txt";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldBeAddOnFileNameIfEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.zap";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldBeAddOnFileNameEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
String fileName = "addon.ZAP";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldNotBeAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfFileNameNotEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.txt", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfAddOnDoesNotHaveManifestFile() throws Exception {
// Given
Path file = createEmptyAddOnFile("addon.zap");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldBeAddOnIfPathEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldBeAddOnEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
Path file = createAddOnFile("addon.ZAP", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfPathHasNoFileName() throws Exception {
// Given
Path file = Paths.get("/");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfFileDoesNotHaveZapExtension() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zip"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_FILE_NAME)));
}
@Test
void shouldNotBeValidAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNotReadable() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
assumeTrue(
Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class),
"Test requires support for POSIX file attributes.");
Set<PosixFilePermission> perms =
Files.readAttributes(file, PosixFileAttributes.class).permissions();
perms.remove(PosixFilePermission.OWNER_READ);
Files.setPosixFilePermissions(file, perms);
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfNotZipFile() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(
result.getValidity(), is(equalTo(ValidationResult.Validity.UNREADABLE_ZIP_FILE)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfItHasNoManifest() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry("Not a manifest"));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.MISSING_MANIFEST)));
}
@Test
void shouldNotBeValidAddOnIfManifestIsMalformed() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry(AddOn.MANIFEST_FILE_NAME));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_MANIFEST)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfHasMissingLib() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>missing.jar</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldNotBeValidAddOnIfHasLibWithMissingName() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>dir/</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldBeValidAddOnIfValid() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.VALID)));
assertThat(result.getManifest(), is(notNullValue()));
}
@Test
void shouldFailToCreateAddOnFromNullFile() {
// Given
Path file = null;
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_PATH.name()));
}
@Test
void shouldFailToCreateAddOnFromFileWithInvalidFileName() throws Exception {
// Given
String invalidFileName = "addon.txt";
Path file = createAddOnFile(invalidFileName, "alpha", "1");
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_FILE_NAME.name()));
}
@Test
@SuppressWarnings("deprecation")
void shouldCreateAddOnFromFileAndUseManifestData() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "beta", "1.6.7");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.beta)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.6.7")));
assertThat(addOn.getFileVersion(), is(equalTo(1)));
}
@Test
void shouldCreateAddOnWithDotsInId() throws Exception {
// Given
Path file = createAddOnFile("addon.x.zap", "release", "1.0.0");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon.x")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.0.0")));
}
@Test
void shouldIgnoreStatusInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha.zap", "release", "1");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
}
@Test
@SuppressWarnings("deprecation")
void shouldIgnoreVersionInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha-2.zap", "alpha", "3.2.10");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getVersion().toString(), is(equalTo("3.2.10")));
assertThat(addOn.getFileVersion(), is(equalTo(3)));
}
@Test
void shouldReturnNormalisedFileName() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "2.8.1");
AddOn addOn = new AddOn(file);
// When
String normalisedFileName = addOn.getNormalisedFileName();
// Then
assertThat(normalisedFileName, is(equalTo("addon-2.8.1.zap")));
}
@Test
void shouldHaveNoReleaseDate() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
String releaseDate = addOn.getReleaseDate();
// Then
assertThat(releaseDate, is(nullValue()));
}
@Test
void shouldHaveCorrectSize() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
long size = addOn.getSize();
// Then
assertThat(size, is(equalTo(189L)));
}
@Test
void shouldHaveEmptyBundleByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(true)));
assertThat(bundleData.getBaseName(), is(equalTo("")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundle() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle>")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundleWithPrefix() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle prefix=\"msgs\">")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("msgs")));
}
@Test
void shouldHaveEmptyHelpSetByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(true)));
assertThat(helpSetData.getBaseName(), is(equalTo("")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSet() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset>")
.append("org.zaproxy.help.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSetWithLocaleToken() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset localetoken=\"%LC%\">")
.append("org.zaproxy.help%LC%.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help%LC%.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("%LC%")));
}
@Test
void shouldDependOnDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(dependency);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDependIfNoDependencies() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("AddOn-release-1.zap", "release", "1"));
AddOn nonDependency = createAddOn("AddOn3", createZapVersionsXml());
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDirectDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnItSelf() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn sameAddOn = createAddOn("AddOn1", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(sameAddOn);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldDependOnDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, dependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, nonDirectDependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency1 = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency2 = createAddOn("AddOn9", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency1, nonDependency2});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldBeUpdateToOlderVersionIfNewer() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = newerAddOn.isUpdateTo(olderAddOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateToNewerVersionIfOlder() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = olderAddOn.isUpdateTo(newerAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeAbleToRunIfItHasNoMinimumJavaVersion() throws Exception {
// Given
String minimumJavaVersion = null;
String runningJavaVersion = "1.8";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MajorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MinorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldNotBeAbleToRunInJava9MajorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldNotBeAbleToRunInJava9MinorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldReturnLibsInManifest() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "dir/lib2.jar";
Path file = createAddOnWithLibs(lib1, lib2);
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getLibs(), contains(new AddOn.Lib(lib1), new AddOn.Lib(lib2)));
}
@Test
void shouldNotBeRunnableIfLibsAreNotInFileSystem() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnWithLibs("lib1.jar", "lib2.jar"));
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(false)));
assertThat(reqs.hasMissingLibs(), is(equalTo(true)));
assertThat(reqs.getAddOnMissingLibs(), is(equalTo(addOn)));
}
@Test
void shouldBeRunnableIfLibsAreInFileSystem() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "lib2.jar";
AddOn addOn = new AddOn(createAddOnWithLibs(lib1, lib2));
Path libsDir = newTempDir("libsDir");
addOn.getLibs().get(0).setFileSystemUrl(libsDir.resolve(lib1).toUri().toURL());
addOn.getLibs().get(1).setFileSystemUrl(libsDir.resolve(lib2).toUri().toURL());
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(true)));
assertThat(reqs.hasMissingLibs(), is(equalTo(false)));
assertThat(reqs.getAddOnMissingLibs(), is(nullValue()));
}
@Test
void shouldCreateAddOnLibFromRootJarPath() throws Exception {
// Given
String jarPath = "lib.jar";
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(jarPath)));
}
@Test
void shouldCreateAddOnLibFromNonRootJarPath() throws Exception {
// Given
String name = "lib.jar";
String jarPath = "dir/" + name;
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(name)));
}
@Test
void shouldNotHaveFileSystemUrlInAddOnLibByDefault() throws Exception {
// Given / When
AddOn.Lib lib = new AddOn.Lib("lib.jar");
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
@Test
void shouldSetFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
URL fsUrl = new URL("file:///some/path");
// When
lib.setFileSystemUrl(fsUrl);
// Then
assertThat(lib.getFileSystemUrl(), is(equalTo(fsUrl)));
}
@Test
void shouldSetNullFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
lib.setFileSystemUrl(new URL("file:///some/path"));
// When
lib.setFileSystemUrl(null);
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
private static ZapXmlConfiguration createZapVersionsXml() throws Exception {
ZapXmlConfiguration zapVersionsXml = new ZapXmlConfiguration(ZAP_VERSIONS_XML);
zapVersionsXml.setExpressionEngine(new XPathExpressionEngine());
return zapVersionsXml;
}
}
| zaproxy/zaproxy | zap/src/test/java/org/zaproxy/zap/control/AddOnUnitTest.java | Java | apache-2.0 | 36,238 |
package com.qinyadan.monitor.network.util;
import java.util.Map;
import com.qinyadan.monitor.network.control.ControlMessageDecoder;
import com.qinyadan.monitor.network.control.ControlMessageEncoder;
import com.qinyadan.monitor.network.control.ProtocolException;
public final class ControlMessageEncodingUtils {
private static final ControlMessageEncoder encoder = new ControlMessageEncoder();
private static final ControlMessageDecoder decoder = new ControlMessageDecoder();
private ControlMessageEncodingUtils() {
}
public static byte[] encode(Map<String, Object> value) throws ProtocolException {
return encoder.encode(value);
}
public static Object decode(byte[] in) throws ProtocolException {
return decoder.decode(in);
}
}
| O2O-Market/Market-monitor | market-network/src/main/java/com/qinyadan/monitor/network/util/ControlMessageEncodingUtils.java | Java | apache-2.0 | 809 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.specificmodels.tests.testsourcemodel.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import de.hub.specificmodels.tests.testsourcemodel.ClassWithListFeatures;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass1;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass2;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass3;
import de.hub.specificmodels.tests.testsourcemodel.RootClass;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelFactory;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class TestSourceModelPackageImpl extends EPackageImpl implements TestSourceModelPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass rootClassEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass classWithListFeaturesEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass1EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass2EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass3EClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage#eNS_URI
* @see #init()
* @generated
*/
private TestSourceModelPackageImpl() {
super(eNS_URI, TestSourceModelFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link TestSourceModelPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static TestSourceModelPackage init() {
if (isInited) return (TestSourceModelPackage)EPackage.Registry.INSTANCE.getEPackage(TestSourceModelPackage.eNS_URI);
// Obtain or create and register package
TestSourceModelPackageImpl theTestSourceModelPackage = (TestSourceModelPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof TestSourceModelPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new TestSourceModelPackageImpl());
isInited = true;
// Create package meta-data objects
theTestSourceModelPackage.createPackageContents();
// Initialize created meta-data
theTestSourceModelPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theTestSourceModelPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(TestSourceModelPackage.eNS_URI, theTestSourceModelPackage);
return theTestSourceModelPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRootClass() {
return rootClassEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_AnAttribute1() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NormalReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_Any() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NonManyReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getClassWithListFeatures() {
return classWithListFeaturesEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature1() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature2() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getClassWithListFeatures_AnAttribute1() {
return (EAttribute)classWithListFeaturesEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass1() {
return listFeatureElementClass1EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Name() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getListFeatureElementClass1_ListFeature3() {
return (EReference)listFeatureElementClass1EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_AnAttributeOfFeatureClass1() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Any() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass2() {
return listFeatureElementClass2EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_Name() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_AnAttributeOfFeatureClass2() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass3() {
return listFeatureElementClass3EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_Name() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_AnAttributeOfFeatureClass3() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TestSourceModelFactory getTestSourceModelFactory() {
return (TestSourceModelFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
rootClassEClass = createEClass(ROOT_CLASS);
createEAttribute(rootClassEClass, ROOT_CLASS__AN_ATTRIBUTE1);
createEReference(rootClassEClass, ROOT_CLASS__NORMAL_REFERENCE);
createEAttribute(rootClassEClass, ROOT_CLASS__ANY);
createEReference(rootClassEClass, ROOT_CLASS__NON_MANY_REFERENCE);
classWithListFeaturesEClass = createEClass(CLASS_WITH_LIST_FEATURES);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE1);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE2);
createEAttribute(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__AN_ATTRIBUTE1);
listFeatureElementClass1EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__NAME);
createEReference(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__LIST_FEATURE3);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__AN_ATTRIBUTE_OF_FEATURE_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__ANY);
listFeatureElementClass2EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS2);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__NAME);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__AN_ATTRIBUTE_OF_FEATURE_CLASS2);
listFeatureElementClass3EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS3);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__NAME);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__AN_ATTRIBUTE_OF_FEATURE_CLASS3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
// Initialize classes and features; add operations and parameters
initEClass(rootClassEClass, RootClass.class, "RootClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getRootClass_AnAttribute1(), ecorePackage.getEString(), "anAttribute1", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NormalReference(), this.getClassWithListFeatures(), null, "normalReference", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRootClass_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NonManyReference(), this.getClassWithListFeatures(), null, "nonManyReference", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(classWithListFeaturesEClass, ClassWithListFeatures.class, "ClassWithListFeatures", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getClassWithListFeatures_ListFeature1(), this.getListFeatureElementClass1(), null, "listFeature1", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getClassWithListFeatures_ListFeature2(), this.getListFeatureElementClass2(), null, "listFeature2", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getClassWithListFeatures_AnAttribute1(), ecorePackage.getEInt(), "anAttribute1", null, 0, 1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass1EClass, ListFeatureElementClass1.class, "ListFeatureElementClass1", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass1_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getListFeatureElementClass1_ListFeature3(), this.getListFeatureElementClass3(), null, "listFeature3", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_AnAttributeOfFeatureClass1(), ecorePackage.getEString(), "anAttributeOfFeatureClass1", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass2EClass, ListFeatureElementClass2.class, "ListFeatureElementClass2", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass2_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass2_AnAttributeOfFeatureClass2(), ecorePackage.getEString(), "anAttributeOfFeatureClass2", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass3EClass, ListFeatureElementClass3.class, "ListFeatureElementClass3", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass3_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass3_AnAttributeOfFeatureClass3(), ecorePackage.getEString(), "anAttributeOfFeatureClass3", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create resource
createResource(eNS_URI);
// Create annotations
// http:///org/eclipse/emf/ecore/util/ExtendedMetaData
createExtendedMetaDataAnnotations();
}
/**
* Initializes the annotations for <b>http:///org/eclipse/emf/ecore/util/ExtendedMetaData</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void createExtendedMetaDataAnnotations() {
String source = "http:///org/eclipse/emf/ecore/util/ExtendedMetaData";
addAnnotation
(getRootClass_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
addAnnotation
(getListFeatureElementClass1_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
}
} //TestSourceModelPackageImpl
| markus1978/clickwatch | util/de.hub.specificmodels.test/src-gen/de/hub/specificmodels/tests/testsourcemodel/impl/TestSourceModelPackageImpl.java | Java | apache-2.0 | 16,757 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.typeCook.deductive.util;
import com.intellij.psi.*;
import com.intellij.refactoring.typeCook.Settings;
import com.intellij.refactoring.typeCook.Util;
import java.util.HashSet;
/**
* @author db
*/
public class VictimCollector extends Visitor {
final HashSet<PsiElement> myVictims = new HashSet<PsiElement>();
final PsiElement[] myElements;
final Settings mySettings;
public VictimCollector(final PsiElement[] elements, final Settings settings) {
myElements = elements;
mySettings = settings;
}
private void testNAdd(final PsiElement element, final PsiType t) {
if (Util.isRaw(t, mySettings)) {
if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){
return;
}
myVictims.add(element);
}
}
@Override public void visitLocalVariable(final PsiLocalVariable variable) {
testNAdd(variable, variable.getType());
super.visitLocalVariable(variable);
}
@Override public void visitForeachStatement(final PsiForeachStatement statement) {
super.visitForeachStatement(statement);
final PsiParameter parameter = statement.getIterationParameter();
testNAdd(parameter, parameter.getType());
}
@Override public void visitField(final PsiField field) {
testNAdd(field, field.getType());
super.visitField(field);
}
@Override public void visitMethod(final PsiMethod method) {
final PsiParameter[] parms = method.getParameterList().getParameters();
for (PsiParameter parm : parms) {
testNAdd(parm, parm.getType());
}
if (Util.isRaw(method.getReturnType(), mySettings)) {
myVictims.add(method);
}
final PsiCodeBlock body = method.getBody();
if (body != null) {
body.accept(this);
}
}
@Override public void visitNewExpression(final PsiNewExpression expression) {
if (expression.getClassReference() != null) {
testNAdd(expression, expression.getType());
}
super.visitNewExpression(expression);
}
@Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){
final PsiTypeElement typeElement = cast.getCastType();
if (typeElement != null) {
testNAdd(cast, typeElement.getType());
}
super.visitTypeCastExpression(cast);
}
@Override public void visitReferenceExpression(final PsiReferenceExpression expression) {
}
@Override public void visitFile(PsiFile file) {
if (file instanceof PsiJavaFile) {
super.visitFile(file);
}
}
public HashSet<PsiElement> getVictims() {
for (PsiElement element : myElements) {
element.accept(this);
}
return myVictims;
}
}
| joewalnes/idea-community | java/java-impl/src/com/intellij/refactoring/typeCook/deductive/util/VictimCollector.java | Java | apache-2.0 | 3,283 |
/**
* Copyright 2002-2016 xiaoyuepeng
*
* 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.
*
*
* @author xiaoyuepeng <xyp260466@163.com>
*/
package com.xyp260466.dubbo.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by xyp on 16-5-9.
*/
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Documented
public @interface Consumer {
String value() default "";
}
| xyp260466/dubbo-lite | dubbo-spring/src/main/java/com/xyp260466/dubbo/annotation/Consumer.java | Java | apache-2.0 | 1,109 |
/**
* 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.hdfs.server.namenode;
import org.apache.commons.logging.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.ipc.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.net.NetUtils;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode. The Secondary is
* responsible for supporting periodic checkpoints of the HDFS metadata. The
* current design allows only one Secondary NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes up (determined by
* the schedule specified in the configuration), triggers a periodic checkpoint
* and then goes back to sleep. The Secondary NameNode uses the ClientProtocol
* to talk to the primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
public static final Log LOG = LogFactory.getLog(SecondaryNameNode.class
.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if (simulation == null)
return false;
assert (index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch (IOException e) {
shutdown();
throw e;
}
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(Configuration conf) throws IOException {
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode = (NamenodeProtocol) RPC.waitForProxy(
NamenodeProtocol.class, NamenodeProtocol.versionID,
nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
infoBindAddress = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
infoServer.setAttribute("name.system.image", checkpointImage);
this.infoServer.setAttribute("name.conf", conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class);
infoServer.start();
// The web-server port can be ephemeral... ensure we have the correct
// info
infoPort = infoServer.getPort();
conf
.set("dfs.secondary.http.address", infoBindAddress + ":"
+ infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":"
+ infoPort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "("
+ checkpointPeriod / 60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "("
+ checkpointSize / 1024 + " KB)");
}
/**
* Shut down this instance of the datanode. Returns only after shutdown is
* complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null)
infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null)
checkpointImage.close();
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
//
// The main work loop
//
public void run() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize
|| now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code> files from the
* name-node.
*
* @throws IOException
*/
private void downloadCheckpointFiles(CheckpointSignature sig)
throws IOException {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + infoPort + "&machine="
+ InetAddress.getLocalHost().getHostAddress() + "&token="
+ sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[]) null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
return NetUtils.getServerAddress(conf, "dfs.info.bindAddress",
"dfs.info.port", "dfs.http.address");
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 "
+ "after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 "
+ "after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into current
* storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem = new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv
* The parameters passed to this program.
* @exception Exception
* if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize || argv.length == 2
&& "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is "
+ "smaller than configured checkpoint " + "size "
+ checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": " + content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
*
* @param cmd
* The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode "
+ "[-checkpoint [force]] " + "[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
*
* @param argv
* Command line parameters.
* @exception Exception
* if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories. Create directories if they do not
* exist. Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs, Collection<File> editsDirs)
throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if (!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch (SecurityException se) {
isAccessible = false;
}
if (!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd
.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch (curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are
// inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current
// and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code> and
* recreate <code>current</code>.
*
* @throws IOException
*/
void startCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File curDir = sd.getCurrentDir();
File tmpCkptDir = sd.getLastCheckpointTmp();
assert !tmpCkptDir.exists() : tmpCkptDir.getName()
+ " directory must not exist.";
if (curDir.exists()) {
// rename current to tmp
rename(curDir, tmpCkptDir);
}
if (!curDir.mkdir())
throw new IOException("Cannot create directory " + curDir);
}
}
void endCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File tmpCkptDir = sd.getLastCheckpointTmp();
File prevCkptDir = sd.getPreviousCheckpoint();
// delete previous dir
if (prevCkptDir.exists())
deleteDir(prevCkptDir);
// rename tmp to previous
if (tmpCkptDir.exists())
rename(tmpCkptDir, prevCkptDir);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveFSImage();
}
}
}
| shot/hadoop-source-reading | src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java | Java | apache-2.0 | 18,270 |
package me.soulmachine;
import org.jruby.embed.ScriptingContainer;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* A simple JRuby example to execute Python scripts from Java.
*/
final class JRubyExample {
private JRubyExample() {}
/**
* Main entrypoint.
*
* @param args arguments
* @throws ScriptException ScriptException
*/
public static void main(final String[] args) throws ScriptException {
listEngines();
final String rubyHelloWord = "puts 'Hello World from JRuby!'";
// First way: Use built-in ScriptEngine from JDK
{
final ScriptEngineManager mgr = new ScriptEngineManager();
final ScriptEngine pyEngine = mgr.getEngineByName("ruby");
try {
pyEngine.eval(rubyHelloWord);
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
// Second way: Use ScriptingContainer() from JRuby
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
scriptingContainer.runScriptlet(rubyHelloWord);
}
// Call Ruby Methods from Java
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
final String rubyMethod = "def myAdd(a,b)\n\treturn a+b\nend";
final Object receiver = scriptingContainer.runScriptlet(rubyMethod);
final Object[] arguments = new Object[2];
arguments[0] = Integer.valueOf(6);
arguments[1] = Integer.valueOf(4);
final Integer result = scriptingContainer.callMethod(receiver, "myAdd",
arguments, Integer.class);
System.out.println("Result: " + result);
}
}
/**
* Display all script engines.
*/
public static void listEngines() {
final ScriptEngineManager mgr = new ScriptEngineManager();
final List<ScriptEngineFactory> factories =
mgr.getEngineFactories();
for (final ScriptEngineFactory factory: factories) {
System.out.println("ScriptEngineFactory Info");
final String engName = factory.getEngineName();
final String engVersion = factory.getEngineVersion();
final String langName = factory.getLanguageName();
final String langVersion = factory.getLanguageVersion();
System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);
final List<String> engNames = factory.getNames();
for (final String name: engNames) {
System.out.printf("\tEngine Alias: %s\n", name);
}
System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
}
}
}
| soulmachine/JRubyExample | JRubyExample/src/main/java/me/soulmachine/JRubyExample.java | Java | apache-2.0 | 2,633 |
package com.arthurb.iterator.dinermergergery;
import java.util.Iterator;
/**
* Created by Blackwood on 07.03.2016 18:16.
*/
public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu() {
menuItems = new MenuItem[MAX_ITEMS];
addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 2.99);
addItem("Hotdog", "A got dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99);
addItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89);
}
private void addItem(String name, String description, boolean vegetarian, double price) {
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS) { // Ограничиваем размер меню, чтобы не запоминать слишком много рецептов
System.err.println("Sorry, menu is full! Can't add item to menu");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}
public Iterator createIterator() {
return new DinerMenuIterator(menuItems);
}
}
| NeverNight/SimplesPatterns.Java | src/com/arthurb/iterator/dinermergergery/DinerMenu.java | Java | apache-2.0 | 1,583 |
package org.apache.helix.controller.rebalancer.waged.model;
/*
* 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.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.helix.HelixException;
import org.apache.helix.controller.rebalancer.util.WagedValidationUtil;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents a possible allocation of the replication.
* Note that any usage updates to the AssignableNode are not thread safe.
*/
public class AssignableNode implements Comparable<AssignableNode> {
private static final Logger LOG = LoggerFactory.getLogger(AssignableNode.class.getName());
// Immutable Instance Properties
private final String _instanceName;
private final String _faultZone;
// maximum number of the partitions that can be assigned to the instance.
private final int _maxPartition;
private final ImmutableSet<String> _instanceTags;
private final ImmutableMap<String, List<String>> _disabledPartitionsMap;
private final ImmutableMap<String, Integer> _maxAllowedCapacity;
// Mutable (Dynamic) Instance Properties
// A map of <resource name, <partition name, replica>> that tracks the replicas assigned to the
// node.
private Map<String, Map<String, AssignableReplica>> _currentAssignedReplicaMap;
// A map of <capacity key, capacity value> that tracks the current available node capacity
private Map<String, Integer> _remainingCapacity;
/**
* Update the node with a ClusterDataCache. This resets the current assignment and recalculates
* currentCapacity.
* NOTE: While this is required to be used in the constructor, this can also be used when the
* clusterCache needs to be
* refreshed. This is under the assumption that the capacity mappings of InstanceConfig and
* ResourceConfig could
* subject to change. If the assumption is no longer true, this function should become private.
*/
AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) {
_instanceName = instanceName;
Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig);
_faultZone = computeFaultZone(clusterConfig, instanceConfig);
_instanceTags = ImmutableSet.copyOf(instanceConfig.getTags());
_disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap());
// make a copy of max capacity
_maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity);
_remainingCapacity = new HashMap<>(instanceCapacity);
_maxPartition = clusterConfig.getMaxPartitionsPerInstance();
_currentAssignedReplicaMap = new HashMap<>();
}
/**
* This function should only be used to assign a set of new partitions that are not allocated on
* this node. It's because the any exception could occur at the middle of batch assignment and the
* previous finished assignment cannot be reverted
* Using this function avoids the overhead of updating capacity repeatedly.
*/
void assignInitBatch(Collection<AssignableReplica> replicas) {
Map<String, Integer> totalPartitionCapacity = new HashMap<>();
for (AssignableReplica replica : replicas) {
// TODO: the exception could occur in the middle of for loop and the previous added records cannot be reverted
addToAssignmentRecord(replica);
// increment the capacity requirement according to partition's capacity configuration.
for (Map.Entry<String, Integer> capacity : replica.getCapacity().entrySet()) {
totalPartitionCapacity.compute(capacity.getKey(),
(key, totalValue) -> (totalValue == null) ? capacity.getValue()
: totalValue + capacity.getValue());
}
}
// Update the global state after all single replications' calculation is done.
for (String capacityKey : totalPartitionCapacity.keySet()) {
updateRemainingCapacity(capacityKey, totalPartitionCapacity.get(capacityKey));
}
}
/**
* Assign a replica to the node.
* @param assignableReplica - the replica to be assigned
*/
void assign(AssignableReplica assignableReplica) {
addToAssignmentRecord(assignableReplica);
assignableReplica.getCapacity().entrySet().stream()
.forEach(capacity -> updateRemainingCapacity(capacity.getKey(), capacity.getValue()));
}
/**
* Release a replica from the node.
* If the replication is not on this node, the assignable node is not updated.
* @param replica - the replica to be released
*/
void release(AssignableReplica replica)
throws IllegalArgumentException {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
// Check if the release is necessary
if (!_currentAssignedReplicaMap.containsKey(resourceName)) {
LOG.warn("Resource {} is not on node {}. Ignore the release call.", resourceName,
getInstanceName());
return;
}
Map<String, AssignableReplica> partitionMap = _currentAssignedReplicaMap.get(resourceName);
if (!partitionMap.containsKey(partitionName) || !partitionMap.get(partitionName)
.equals(replica)) {
LOG.warn("Replica {} is not assigned to node {}. Ignore the release call.",
replica.toString(), getInstanceName());
return;
}
AssignableReplica removedReplica = partitionMap.remove(partitionName);
removedReplica.getCapacity().entrySet().stream()
.forEach(entry -> updateRemainingCapacity(entry.getKey(), -1 * entry.getValue()));
}
/**
* @return A set of all assigned replicas on the node.
*/
Set<AssignableReplica> getAssignedReplicas() {
return _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream()).collect(Collectors.toSet());
}
/**
* @return The current assignment in a map of <resource name, set of partition names>
*/
Map<String, Set<String>> getAssignedPartitionsMap() {
Map<String, Set<String>> assignmentMap = new HashMap<>();
for (String resourceName : _currentAssignedReplicaMap.keySet()) {
assignmentMap.put(resourceName, _currentAssignedReplicaMap.get(resourceName).keySet());
}
return assignmentMap;
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names in the specified resource.
*/
public Set<String> getAssignedPartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).keySet();
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names with the top state in the
* specified resource.
*/
Set<String> getAssignedTopStatePartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).entrySet()
.stream().filter(partitionEntry -> partitionEntry.getValue().isReplicaTopState())
.map(partitionEntry -> partitionEntry.getKey()).collect(Collectors.toSet());
}
/**
* @return The total count of assigned top state partitions.
*/
public int getAssignedTopStatePartitionsCount() {
return (int) _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream())
.filter(AssignableReplica::isReplicaTopState).count();
}
/**
* @return The total count of assigned replicas.
*/
public int getAssignedReplicaCount() {
return _currentAssignedReplicaMap.values().stream().mapToInt(Map::size).sum();
}
/**
* @return The current available capacity.
*/
public Map<String, Integer> getRemainingCapacity() {
return _remainingCapacity;
}
/**
* @return A map of <capacity category, capacity number> that describes the max capacity of the
* node.
*/
public Map<String, Integer> getMaxCapacity() {
return _maxAllowedCapacity;
}
/**
* Return the most concerning capacity utilization number for evenly partition assignment.
* The method dynamically calculates the projected highest utilization number among all the
* capacity categories assuming the new capacity usage is added to the node.
* For example, if the current node usage is {CPU: 0.9, MEM: 0.4, DISK: 0.6}. Then this call shall
* return 0.9.
* @param newUsage the proposed new additional capacity usage.
* @return The highest utilization number of the node among all the capacity category.
*/
public float getProjectedHighestUtilization(Map<String, Integer> newUsage) {
float highestCapacityUtilization = 0;
for (String capacityKey : _maxAllowedCapacity.keySet()) {
float capacityValue = _maxAllowedCapacity.get(capacityKey);
float utilization = (capacityValue - _remainingCapacity.get(capacityKey) + newUsage
.getOrDefault(capacityKey, 0)) / capacityValue;
highestCapacityUtilization = Math.max(highestCapacityUtilization, utilization);
}
return highestCapacityUtilization;
}
public String getInstanceName() {
return _instanceName;
}
public Set<String> getInstanceTags() {
return _instanceTags;
}
public String getFaultZone() {
return _faultZone;
}
public boolean hasFaultZone() {
return _faultZone != null;
}
/**
* @return A map of <resource name, set of partition names> contains all the partitions that are
* disabled on the node.
*/
public Map<String, List<String>> getDisabledPartitionsMap() {
return _disabledPartitionsMap;
}
/**
* @return The max partition count that are allowed to be allocated on the node.
*/
public int getMaxPartition() {
return _maxPartition;
}
/**
* Computes the fault zone id based on the domain and fault zone type when topology is enabled.
* For example, when
* the domain is "zone=2, instance=testInstance" and the fault zone type is "zone", this function
* returns "2".
* If cannot find the fault zone type, this function leaves the fault zone id as the instance name.
* Note the WAGED rebalancer does not require full topology tree to be created. So this logic is
* simpler than the CRUSH based rebalancer.
*/
private String computeFaultZone(ClusterConfig clusterConfig, InstanceConfig instanceConfig) {
if (!clusterConfig.isTopologyAwareEnabled()) {
// Instance name is the default fault zone if topology awareness is false.
return instanceConfig.getInstanceName();
}
String topologyStr = clusterConfig.getTopology();
String faultZoneType = clusterConfig.getFaultZoneType();
if (topologyStr == null || faultZoneType == null) {
LOG.debug("Topology configuration is not complete. Topology define: {}, Fault Zone Type: {}",
topologyStr, faultZoneType);
// Use the instance name, or the deprecated ZoneId field (if exists) as the default fault
// zone.
String zoneId = instanceConfig.getZoneId();
return zoneId == null ? instanceConfig.getInstanceName() : zoneId;
} else {
// Get the fault zone information from the complete topology definition.
String[] topologyKeys = topologyStr.trim().split("/");
if (topologyKeys.length == 0 || Arrays.stream(topologyKeys)
.noneMatch(type -> type.equals(faultZoneType))) {
throw new HelixException(
"The configured topology definition is empty or does not contain the fault zone type.");
}
Map<String, String> domainAsMap = instanceConfig.getDomainAsMap();
StringBuilder faultZoneStringBuilder = new StringBuilder();
for (String key : topologyKeys) {
if (!key.isEmpty()) {
// if a key does not exist in the instance domain config, apply the default domain value.
faultZoneStringBuilder.append(domainAsMap.getOrDefault(key, "Default_" + key));
if (key.equals(faultZoneType)) {
break;
} else {
faultZoneStringBuilder.append('/');
}
}
}
return faultZoneStringBuilder.toString();
}
}
/**
* @throws HelixException if the replica has already been assigned to the node.
*/
private void addToAssignmentRecord(AssignableReplica replica) {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
if (_currentAssignedReplicaMap.containsKey(resourceName) && _currentAssignedReplicaMap
.get(resourceName).containsKey(partitionName)) {
throw new HelixException(String
.format("Resource %s already has a replica with state %s from partition %s on node %s",
replica.getResourceName(), replica.getReplicaState(), replica.getPartitionName(),
getInstanceName()));
} else {
_currentAssignedReplicaMap.computeIfAbsent(resourceName, key -> new HashMap<>())
.put(partitionName, replica);
}
}
private void updateRemainingCapacity(String capacityKey, int usage) {
if (!_remainingCapacity.containsKey(capacityKey)) {
//if the capacityKey belongs to replicas does not exist in the instance's capacity,
// it will be treated as if it has unlimited capacity of that capacityKey
return;
}
_remainingCapacity.put(capacityKey, _remainingCapacity.get(capacityKey) - usage);
}
/**
* Get and validate the instance capacity from instance config.
* @throws HelixException if any required capacity key is not configured in the instance config.
*/
private Map<String, Integer> fetchInstanceCapacity(ClusterConfig clusterConfig,
InstanceConfig instanceConfig) {
Map<String, Integer> instanceCapacity =
WagedValidationUtil.validateAndGetInstanceCapacity(clusterConfig, instanceConfig);
// Remove all the non-required capacity items from the map.
instanceCapacity.keySet().retainAll(clusterConfig.getInstanceCapacityKeys());
return instanceCapacity;
}
@Override
public int hashCode() {
return _instanceName.hashCode();
}
@Override
public int compareTo(AssignableNode o) {
return _instanceName.compareTo(o.getInstanceName());
}
@Override
public String toString() {
return _instanceName;
}
}
| lei-xia/helix | helix-core/src/main/java/org/apache/helix/controller/rebalancer/waged/model/AssignableNode.java | Java | apache-2.0 | 15,277 |
/*
* 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.taverna.workbench.views.graph.config;
import javax.swing.JPanel;
import org.apache.taverna.configuration.Configurable;
import org.apache.taverna.configuration.ConfigurationUIFactory;
/**
* ConfigurationFactory for the GraphViewConfiguration.
*
* @author David Withers
*/
public class GraphViewConfigurationUIFactory implements ConfigurationUIFactory {
private GraphViewConfiguration graphViewConfiguration;
@Override
public boolean canHandle(String uuid) {
return uuid.equals(getConfigurable().getUUID());
}
@Override
public JPanel getConfigurationPanel() {
return new GraphViewConfigurationPanel(graphViewConfiguration);
}
@Override
public Configurable getConfigurable() {
return graphViewConfiguration;
}
public void setGraphViewConfiguration(
GraphViewConfiguration graphViewConfiguration) {
this.graphViewConfiguration = graphViewConfiguration;
}
}
| ThilinaManamgoda/incubator-taverna-workbench | taverna-graph-view/src/main/java/org/apache/taverna/workbench/views/graph/config/GraphViewConfigurationUIFactory.java | Java | apache-2.0 | 1,714 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudsearchv2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* UpdateDomainEndpointOptionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDomainEndpointOptionsResultStaxUnmarshaller implements Unmarshaller<UpdateDomainEndpointOptionsResult, StaxUnmarshallerContext> {
public UpdateDomainEndpointOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
UpdateDomainEndpointOptionsResult updateDomainEndpointOptionsResult = new UpdateDomainEndpointOptionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return updateDomainEndpointOptionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("DomainEndpointOptions", targetDepth)) {
updateDomainEndpointOptionsResult.setDomainEndpointOptions(DomainEndpointOptionsStatusStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return updateDomainEndpointOptionsResult;
}
}
}
}
private static UpdateDomainEndpointOptionsResultStaxUnmarshaller instance;
public static UpdateDomainEndpointOptionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new UpdateDomainEndpointOptionsResultStaxUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-cloudsearch/src/main/java/com/amazonaws/services/cloudsearchv2/model/transform/UpdateDomainEndpointOptionsResultStaxUnmarshaller.java | Java | apache-2.0 | 2,682 |
/*
* Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved.
*
* The Sun Project JXTA(TM) Software License
*
* 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 end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by Sun Microsystems, Inc. for JXTA(TM) technology."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please contact
* Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA", nor may
* "JXTA" appear in their name, without prior written permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 SUN
* MICROSYSTEMS OR ITS 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.
*
* JXTA is a registered trademark of Sun Microsystems, Inc. in the United
* States and other countries.
*
* Please see the license information page at :
* <http://www.jxta.org/project/www/license.html> for instructions on use of
* the license in source files.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of Project JXTA. For more information on Project JXTA, please see
* http://www.jxta.org.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.platform;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredDocumentUtils;
import net.jxta.document.XMLDocument;
import net.jxta.document.XMLElement;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.impl.membership.pse.PSEUtils;
import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo;
import net.jxta.impl.peergroup.StdPeerGroup;
import net.jxta.impl.protocol.HTTPAdv;
import net.jxta.impl.protocol.PSEConfigAdv;
import net.jxta.impl.protocol.PeerGroupConfigAdv;
import net.jxta.impl.protocol.PlatformConfig;
import net.jxta.impl.protocol.RdvConfigAdv;
import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration;
import net.jxta.impl.protocol.RelayConfigAdv;
import net.jxta.impl.protocol.TCPAdv;
import net.jxta.logging.Logging;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.protocol.ConfigParams;
import net.jxta.protocol.TransportAdvertisement;
import javax.security.cert.CertificateException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.List;
import java.util.MissingResourceException;
import java.util.NoSuchElementException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Logger;
import net.jxta.impl.protocol.MulticastAdv;
/**
* NetworkConfigurator provides a simple programmatic interface for JXTA configuration.
* <p/>
* By default, it defines an edge configuration with TCP in auto mode w/port
* range 9701-9799, multicast enabled on group "224.0.1.85", and port 1234,
* HTTP transport with only outgoing enabled.
* <p/>
* By default a new PeerID is always generated. This can be overridden via
* {@link NetworkConfigurator#setPeerID} method or loading a PlatformConfig via
* {@link NetworkConfigurator#load}.
* <p/>
* A facility is provided to initialize a configuration by loading from an
* existing configuration. This provides limited platform configuration lifecycle
* management as well as configuration change management.
* <p/>
* Also by default, this class sets the default platform configurator to
* {@link net.jxta.impl.peergroup.NullConfigurator}. <code>NullConfigurator<code>
* is a no operation configurator intended to prevent any other configurators from
* being invoked.
* <p/>
* NetworkConfigurator makes use of classes from the {@code net.jxta.impl.*}
* packages. Applications are very strongly encouraged to avoid importing these
* classes as their interfaces may change without notice in future JXTA releases.
* The NetworkConfigurator API abstracts the configuration implementation details
* and will provide continuity and stability i.e. the NetworkConfigurator API
* won't change and it will automatically accommodate changes to service
* configuration.
* <p/>
* <em> Configuration example :</em>
* <pre>
* NetworkConfigurator config = new NetworkConfigurator();
* if (!config.exists()) {
* // Create a new configuration with a new name, principal, and pass
* config.setName("New Name");
* config.setPrincipal("username");
* config.setPassword("password");
* try {
* //persist it
* config.save();
* } catch (IOException io) {
* // deal with the io error
* }
* } else {
* // Load the pre-existing configuration
* File pc = new File(config.getHome(), "PlatformConfig");
* try {
* config.load(pc.toURI());
* // make changes if so desired
* ..
* ..
* // store the PlatformConfig under the default home
* config.save();
* } catch (CertificateException ce) {
* // In case the root cert is invalid, this creates a new one
* try {
* //principal
* config.setPrincipal("principal");
* //password to encrypt private key with
* config.setPassword("password");
* config.save();
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
* <p/>
* </pre>
*
* @since JXTA JSE 2.4
*/
public class NetworkConfigurator {
/**
* Logger
*/
private final static transient Logger LOG = Logger.getLogger(NetworkConfigurator.class.getName());
// begin configuration modes
/**
* Relay off Mode
*/
public final static int RELAY_OFF = 1 << 2;
/**
* Relay client Mode
*/
public final static int RELAY_CLIENT = 1 << 3;
/**
* Relay Server Mode
*/
public final static int RELAY_SERVER = 1 << 4;
/**
* Proxy Server Mode
*/
public final static int PROXY_SERVER = 1 << 5;
/**
* TCP transport client Mode
*/
public final static int TCP_CLIENT = 1 << 6;
/**
* TCP transport Server Mode
*/
public final static int TCP_SERVER = 1 << 7;
/**
* HTTP transport client Mode
*/
public final static int HTTP_CLIENT = 1 << 8;
/**
* HTTP transport server Mode
*/
public final static int HTTP_SERVER = 1 << 9;
/**
* IP multicast transport Mode
*/
public final static int IP_MULTICAST = 1 << 10;
/**
* RendezVousService Mode
*/
public final static int RDV_SERVER = 1 << 11;
/**
* RendezVousService Client
*/
public final static int RDV_CLIENT = 1 << 12;
/**
* RendezVousService Ad-Hoc mode
*/
public final static int RDV_AD_HOC = 1 << 13;
/**
* HTTP2 (netty http tunnel) client
*/
public final static int HTTP2_CLIENT = 1 << 14;
/**
* HTTP2 (netty http tunnel) server
*/
public final static int HTTP2_SERVER = 1 << 15;
/**
* Default AD-HOC configuration
*/
public final static int ADHOC_NODE = TCP_CLIENT | TCP_SERVER | IP_MULTICAST | RDV_AD_HOC | RELAY_OFF;
/**
* Default Edge configuration
*/
public final static int EDGE_NODE = TCP_CLIENT | TCP_SERVER | HTTP_CLIENT | HTTP2_CLIENT | IP_MULTICAST | RDV_CLIENT | RELAY_CLIENT;
/**
* Default Rendezvous configuration
*/
public final static int RDV_NODE = RDV_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
/**
* Default Relay configuration
*/
public final static int RELAY_NODE = RELAY_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
// /**
// * Default Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int PROXY_NODE = PROXY_SERVER | RELAY_NODE;
// /**
// * Default Rendezvous/Relay/Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int RDV_RELAY_PROXY_NODE = RDV_NODE | PROXY_NODE;
// end configuration modes
/**
* Default mode
*/
protected transient int mode = EDGE_NODE;
/**
* Default PlatformConfig Peer Description
*/
protected transient String description = "Platform Config Advertisement created by : " + NetworkConfigurator.class.getName();
/**
* The location which will serve as the parent for all stored items used
* by JXTA.
*/
private transient URI storeHome = null;
/**
* Default peer name
*/
protected transient String name = "unknown";
/**
* AuthenticationType used by PSEMembership to specify the type of authentication.
*/
protected transient String authenticationType = null;
/**
* Password value used to generate root Certificate and to protect the
* Certificate's PrivateKey.
*/
protected transient String password = null;
/**
* Default PeerID
*/
protected transient PeerID peerid = null;
/**
* Principal value used to generate root certificate
*/
protected transient String principal = null;
/**
* Public Certificate chain
*/
protected transient X509Certificate[] cert = null;
/**
* Subject private key
*/
protected transient PrivateKey subjectPkey = null;
/**
* Freestanding keystore location
*/
protected transient URI keyStoreLocation = null;
/**
* Proxy Service Document
*/
@Deprecated
protected transient XMLElement proxyConfig;
/**
* Personal Security Environment Config Advertisement
*
* @see net.jxta.impl.membership.pse.PSEConfig
*/
protected transient PSEConfigAdv pseConf;
/**
* Rendezvous Config Advertisement
*/
protected transient RdvConfigAdv rdvConfig;
/**
* Default Rendezvous Seeding URI
*/
protected URI rdvSeedingURI = null;
/**
* Relay Config Advertisement
*/
protected transient RelayConfigAdv relayConfig;
/**
* Default Relay Seeding URI
*/
protected transient URI relaySeedingURI = null;
/**
* TCP Config Advertisement
*/
protected transient TCPAdv tcpConfig;
/**
* Multicating Config Advertisement
*/
protected transient MulticastAdv multicastConfig;
/**
* Default TCP transport state
*/
protected transient boolean tcpEnabled = true;
/**
* Default Multicast transport state
*/
protected transient boolean multicastEnabled = true;
/**
* HTTP Config Advertisement
*/
protected transient HTTPAdv httpConfig;
/**
* Default HTTP transport state
*/
protected transient boolean httpEnabled = true;
/**
* HTTP2 Config Advertisement
*/
protected transient TCPAdv http2Config;
/**
* Default HTTP2 transport state
*/
protected transient boolean http2Enabled = true;
/**
* Infrastructure Peer Group Configuration
*/
protected transient PeerGroupConfigAdv infraPeerGroupConfig;
/**
* Creates NetworkConfigurator instance with default AD-HOC configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newAdHocConfiguration(URI storeHome) {
return new NetworkConfigurator(ADHOC_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Edge configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newEdgeConfiguration(URI storeHome) {
return new NetworkConfigurator(EDGE_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Relay configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Relay configuration
*/
public static NetworkConfigurator newRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RELAY_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE | RELAY_SERVER, storeHome);
}
// /**
// * Creates NetworkConfigurator instance with default Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with defaultProxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(PROXY_NODE, storeHome);
// }
// /**
// * Creates NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @since 2.6 It will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newRdvRelayProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(RDV_RELAY_PROXY_NODE, storeHome);
// }
/**
* Creates the default NetworkConfigurator. The configuration is stored with a default configuration mode of EDGE_NODE
*/
public NetworkConfigurator() {
this(EDGE_NODE, new File(".jxta").toURI());
}
/**
* Creates a NetworkConfigurator with the default configuration of the
* specified mode. <p/>Valid modes include ADHOC_NODE, EDGE_NODE, RDV_NODE
* PROXY_NODE, RELAY_NODE, RDV_RELAY_PROXY_NODE, or any combination of
* specific configuration.<p/> e.g. RDV_NODE | HTTP_CLIENT
*
* @param mode the new configuration mode
* @param storeHome the URI to persistent store
* @see #setMode
*/
public NetworkConfigurator(int mode, URI storeHome) {
Logging.logCheckedFine(LOG, "Creating a default configuration");
setStoreHome(storeHome);
httpConfig = createHttpAdv();
rdvConfig = createRdvConfigAdv();
relayConfig = createRelayConfigAdv();
// proxyConfig = createProxyAdv();
tcpConfig = createTcpAdv();
multicastConfig = createMulticastAdv();
http2Config = createHttp2Adv();
infraPeerGroupConfig = createInfraConfigAdv();
setMode(mode);
}
/**
* Sets PlaformConfig Peer Description element
*
* @param description the peer description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Set the current directory for configuration and cache persistent store
* <p/>(default is $CWD/.jxta)
* <p/>
* <dt>Simple example :</dt>
* <pre>
* <code>
* //Create an application home
* File appHome = new File(System.getProperty("JXTA_HOME", ".cache"));
* //Create an instance home under the application home
* File instanceHome = new File(appHome, instanceName);
* jxtaConfig.setHome(instanceHome);
* </code>
* </pre>
*
* @param home the new home value
* @see #getHome
*/
public void setHome(File home) {
this.storeHome = home.toURI();
}
/**
* Returns the current directory for configuration and cache persistent
* store. This is the same location as returned by {@link #getStoreHome()}
* which is more general than this method.
*
* @return Returns the current home directory
* @see #setHome
*/
public File getHome() {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
return new File(storeHome);
} else {
throw new UnsupportedOperationException("Home location is not a file:// URI : " + storeHome);
}
}
/**
* Returns the location which will serve as the parent for all stored items
* used by JXTA.
*
* @return The location which will serve as the parent for all stored
* items used by JXTA.
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public URI getStoreHome() {
return storeHome;
}
/**
* Sets the location which will serve as the parent for all stored items
* used by JXTA.
*
* @param newHome new home directory URI
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public void setStoreHome(URI newHome) {
// Fail if the URI is not absolute.
if (!newHome.isAbsolute()) {
throw new IllegalArgumentException("Only absolute URIs accepted for store home location.");
}
// Fail if the URI is Opaque.
if (newHome.isOpaque()) {
throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location.");
}
// FIXME this should be removed when 1488 is committed
if (!"file".equalsIgnoreCase(newHome.getScheme())) {
throw new IllegalArgumentException("Only file based URI currently supported");
}
// Adds a terminating /
if (!newHome.toString().endsWith("/")) {
newHome = URI.create(newHome.toString() + "/");
}
storeHome = newHome;
}
/**
* Toggles HTTP transport state
*
* @param enabled if true, enables HTTP transport
*/
public void setHttpEnabled(boolean enabled) {
this.httpEnabled = enabled;
if (!httpEnabled) {
httpConfig.setClientEnabled(false);
httpConfig.setServerEnabled(false);
}
}
/**
* Toggles the HTTP transport server (incoming) mode
*
* @param incoming toggles HTTP transport server mode
*/
public void setHttpIncoming(boolean incoming) {
httpConfig.setServerEnabled(incoming);
}
/**
* Toggles the HTTP transport client (outgoing) mode
*
* @param outgoing toggles HTTP transport client mode
*/
public void setHttpOutgoing(boolean outgoing) {
httpConfig.setClientEnabled(outgoing);
}
/**
* Sets the HTTP listening port (default 9901)
*
* @param port the new HTTP port value
*/
public void setHttpPort(int port) {
httpConfig.setPort(port);
}
/**
* Sets the HTTP interface Address to bind the HTTP transport to
* <p/>e.g. "192.168.1.1"
*
* @param address the new address value
*/
public void setHttpInterfaceAddress(String address) {
httpConfig.setInterfaceAddress(address);
}
/**
* Returns the HTTP interface Address
*
* @param address the HTTP interface address
*/
public String getHttpInterfaceAddress() {
return httpConfig.getInterfaceAddress();
}
/**
* Sets the HTTP JXTA Public Address
* e.g. "192.168.1.1:9700"
*
* @param address the HTTP transport public address
* @param exclusive determines whether an address is advertised exclusively
*/
public void setHttpPublicAddress(String address, boolean exclusive) {
httpConfig.setServer(address);
httpConfig.setPublicAddressOnly(exclusive);
}
public boolean isHttp2Enabled() {
return http2Enabled;
}
public void setHttp2Enabled(boolean enabled) {
http2Enabled = enabled;
if(http2Enabled) {
http2Config.setClientEnabled(false);
http2Config.setServerEnabled(false);
}
}
public boolean getHttp2IncomingStatus() {
return http2Config.getServerEnabled();
}
public void setHttp2Incoming(boolean enabled) {
http2Config.setServerEnabled(enabled);
}
public boolean getHttp2OutgoingStatus() {
return http2Config.getClientEnabled();
}
public void setHttp2Outgoing(boolean enabled) {
http2Config.setClientEnabled(enabled);
}
public int getHttp2Port() {
return http2Config.getPort();
}
public void setHttp2Port(int port) {
http2Config.setPort(port);
}
public int getHttp2StartPort() {
return http2Config.getStartPort();
}
public void setHttp2StartPort(int startPort) {
http2Config.setStartPort(startPort);
}
public int getHttp2EndPort() {
return http2Config.getEndPort();
}
public void setHttp2EndPort(int endPort) {
http2Config.setEndPort(endPort);
}
public String getHttp2InterfaceAddress() {
return http2Config.getInterfaceAddress();
}
public void setHttp2InterfaceAddress(String address) {
http2Config.setInterfaceAddress(address);
}
public String getHttp2PublicAddress() {
return http2Config.getServer();
}
public boolean isHttp2PublicAddressExclusive() {
return http2Config.getPublicAddressOnly();
}
public void setHttp2PublicAddress(String address, boolean exclusive) {
http2Config.setServer(address);
http2Config.setPublicAddressOnly(exclusive);
}
/**
* Returns the HTTP JXTA Public Address
*
* @return exclusive determines whether an address is advertised exclusively
*/
public String getHttpPublicAddress() {
return httpConfig.getServer();
}
/**
* Returns the HTTP JXTA Public Address exclusivity
*
* @return exclusive determines whether an address is advertised exclusively
*/
public boolean isHttpPublicAddressExclusive() {
return httpConfig.getPublicAddressOnly();
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param id the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(ID id) {
if (id == null || id.equals(ID.nullID)) {
throw new IllegalArgumentException("PeerGroupID can not be null");
}
infraPeerGroupConfig.setPeerGroupID(id);
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param idStr the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(String idStr) {
if (idStr == null || idStr.length() == 0) {
throw new IllegalArgumentException("PeerGroupID string can not be empty or null");
}
PeerGroupID pgid = (PeerGroupID) ID.create(URI.create(idStr));
setInfrastructureID(pgid);
}
/**
* Gets the ID which will be used for new net peer group instances.
* <p/>
*
* @return the infrastructure PeerGroupID as a string
*/
public String getInfrastructureIDStr() {
return infraPeerGroupConfig.getPeerGroupID().toString();
}
/**
* Sets the infrastructure PeerGroup name meta-data
*
* @param name the Infrastructure PeerGroup name
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGName
*/
public void setInfrastructureName(String name) {
infraPeerGroupConfig.setName(name);
}
/**
* Gets the infrastructure PeerGroup name meta-data
*
* @return the Infrastructure PeerGroup name
*/
public String getInfrastructureName() {
return infraPeerGroupConfig.getName();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDescriptionStr(String description) {
infraPeerGroupConfig.setDescription(description);
}
/**
* Returns the infrastructure PeerGroup description meta-data
*
* @return the infrastructure PeerGroup description meta-data
*/
public String getInfrastructureDescriptionStr() {
return infraPeerGroupConfig.getDescription();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDesc(XMLElement description) {
infraPeerGroupConfig.setDesc(description);
}
/**
* Sets the current node configuration mode.
* <p/>The default mode is EDGE, unless modified at construction time.
* A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
* <p/> Valid modes include EDGE, RDV_SERVER,
* RELAY_OFF, RELAY_CLIENT, RELAY_SERVER, PROXY_SERVER, or any combination
* of which.<p/> e.g. RDV_SERVER + RELAY_SERVER
*
* @param mode the new configuration mode
* @see #getMode
*/
public void setMode(int mode) {
this.mode = mode;
if ((mode & PROXY_SERVER) == PROXY_SERVER && ((mode & RELAY_SERVER) != RELAY_SERVER)) {
mode = mode | RELAY_SERVER;
}
// RELAY config
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
// RDV_SERVER
if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_AD_HOC) == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
}
// TCP
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
// HTTP
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
// HTTP2
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == HTTP2_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == HTTP2_SERVER);
// Multicast
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
// EDGE
if (mode == EDGE_NODE) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
}
}
/**
* Returns the current configuration mode
* <p/>The default mode is EDGE, unless modified at construction time or through
* Method {@link NetworkConfigurator#setMode}. A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
*
* @return mode the current mode value
* @see #setMode
*/
public int getMode() {
return mode;
}
/**
* Sets the IP group multicast packet size
*
* @param size the new multicast packet
*/
public void setMulticastSize(int size) {
multicastConfig.setMulticastSize(size);
}
/**
* Gets the IP group multicast packet size
*
* @return the multicast packet
*/
public int getMulticastSize() {
return multicastConfig.getMulticastSize();
}
/**
* Sets the IP group multicast address (default 224.0.1.85)
*
* @param mcastAddress the new multicast group address
* @see #setMulticastPort
*/
public void setMulticastAddress(String mcastAddress) {
multicastConfig.setMulticastAddr(mcastAddress);
}
/**
* Gets the multicast network interface
*
* @return the multicast network interface, null if none specified
*/
public String getMulticastInterface() {
return multicastConfig.getMulticastInterface();
}
/**
* Sets the multicast network interface
*
* @param interfaceAddress multicast network interface
*/
public void setMulticastInterface(String interfaceAddress) {
multicastConfig.setMulticastInterface(interfaceAddress);
}
/**
* Sets the IP group multicast port (default 1234)
*
* @param port the new IP group multicast port
* @see #setMulticastAddress
*/
public void setMulticastPort(int port) {
multicastConfig.setMulticastPort(port);
}
/**
* Sets the group multicast thread pool size (default 10)
*
* @param size the new multicast thread pool size
*/
public void setMulticastPoolSize(int size) {
multicastConfig.setMulticastPoolSize(size);
}
/**
* Sets the node name
*
* @param name node name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the node name
*
* @return node name
*/
public String getName() {
return this.name;
}
/**
* Sets the Principal for the peer root certificate
*
* @param principal the new principal value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPrincipal(String principal) {
this.principal = principal;
}
/**
* Gets the Principal for the peer root certificate
*
* @return principal if a principal is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPrincipal() {
return principal;
}
/**
* Sets the public Certificate for this configuration.
*
* @param cert the new cert value
*/
public void setCertificate(X509Certificate cert) {
this.cert = new X509Certificate[]{cert};
}
/**
* Returns the public Certificate for this configuration.
*
* @return X509Certificate
*/
public X509Certificate getCertificate() {
return (cert == null || cert.length == 0 ? null : cert[0]);
}
/**
* Sets the public Certificate chain for this configuration.
*
* @param certificateChain the new Certificate chain value
*/
public void setCertificateChain(X509Certificate[] certificateChain) {
this.cert = certificateChain;
}
/**
* Gets the public Certificate chain for this configuration.
*
* @return X509Certificate chain
*/
public X509Certificate[] getCertificateChain() {
return cert;
}
/**
* Sets the Subject private key
*
* @param subjectPkey the subject private key
*/
public void setPrivateKey(PrivateKey subjectPkey) {
this.subjectPkey = subjectPkey;
}
/**
* Gets the Subject private key
*
* @return the subject private key
*/
public PrivateKey getPrivateKey() {
return this.subjectPkey;
}
/**
* Sets freestanding keystore location
*
* @param keyStoreLocation the absolute location of the freestanding keystore
*/
public void setKeyStoreLocation(URI keyStoreLocation) {
this.keyStoreLocation = keyStoreLocation;
}
/**
* Gets the freestanding keystore location
*
* @return the location of the freestanding keystore
*/
public URI getKeyStoreLocation() {
return keyStoreLocation;
}
/**
* Gets the authenticationType
*
* @return authenticationType the authenticationType value
*/
public String getAuthenticationType() {
return this.authenticationType;
}
/**
* Sets the authenticationType
*
* @param authenticationType the new authenticationType value
*/
public void setAuthenticationType(String authenticationType) {
this.authenticationType = authenticationType;
}
/**
* Sets the password used to sign the private key of the root certificate
*
* @param password the new password value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Gets the password used to sign the private key of the root certificate
*
* @return password if a password is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPassword() {
return password;
}
/**
* Sets the PeerID (by default, a new PeerID is generated).
* <p/>Note: Persist the PeerID generated, or use load()
* to avoid overridding a node's PeerID between restarts.
*
* @param peerid the new <code>net.jxta.peer.PeerID</code>
*/
public void setPeerID(PeerID peerid) {
this.peerid = peerid;
}
/**
* Gets the PeerID
*
* @return peerid the <code>net.jxta.peer.PeerID</code> value
*/
public PeerID getPeerID() {
return this.peerid;
}
/**
* Sets Rendezvous Seeding URI
*
* @param seedURI Rendezvous service seeding URI
*/
public void addRdvSeedingURI(URI seedURI) {
rdvConfig.addSeedingURI(seedURI);
}
// /**
// * Sets Rendezvous Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @param aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRdvACLURI(URI aclURI) {
// rdvConfig.setAclUri(aclURI);
// }
// /**
// * Gets Rendezvous Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @return aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRdvACLURI() {
// return rdvConfig.getAclUri();
// }
// /**
// * Sets Relay Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @param aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRelayACLURI(URI aclURI) {
// relayConfig.setAclUri(aclURI);
// }
// /**
// * Gets Relay Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @return aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRelayACLURI() {
// return relayConfig.getAclUri();
// }
/**
* Sets the RelayService maximum number of simultaneous relay clients
*
* @param relayMaxClients the new relayMaxClients value
*/
public void setRelayMaxClients(int relayMaxClients) {
if ((relayMaxClients != -1) && (relayMaxClients <= 0)) {
throw new IllegalArgumentException("Relay Max Clients : " + relayMaxClients + " must be > 0");
}
relayConfig.setMaxClients(relayMaxClients);
}
/**
* Sets the RelayService Seeding URI
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint addresse(s) to relay peers
*
* @param seedURI RelayService seeding URI
*/
public void addRelaySeedingURI(URI seedURI) {
relayConfig.addSeedingURI(seedURI);
}
/**
* Sets the RendezVousService maximum number of simultaneous rendezvous clients
*
* @param rdvMaxClients the new rendezvousMaxClients value
*/
public void setRendezvousMaxClients(int rdvMaxClients) {
if ((rdvMaxClients != -1) && (rdvMaxClients <= 0)) {
throw new IllegalArgumentException("Rendezvous Max Clients : " + rdvMaxClients + " must be > 0");
}
rdvConfig.setMaxClients(rdvMaxClients);
}
/**
* Toggles TCP transport state
*
* @param enabled if true, enables TCP transport
*/
public void setTcpEnabled(boolean enabled) {
this.tcpEnabled = enabled;
if (!tcpEnabled) {
tcpConfig.setClientEnabled(false);
tcpConfig.setServerEnabled(false);
}
}
/**
* Sets the TCP transport listening port (default 9701)
*
* @param port the new tcpPort value
*/
public void setTcpPort(int port) {
tcpConfig.setPort(port);
}
/**
* Sets the lowest port on which the TCP Transport will listen if configured
* to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or less than the value
* used for end port.
*
* @param start the lowest port on which to listen.
*/
public void setTcpStartPort(int start) {
tcpConfig.setStartPort(start);
}
/**
* Returns the highest port on which the TCP Transport will listen if
* configured to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or greater than the value
* used for start port.
*
* @param end the new TCP end port
*/
public void setTcpEndPort(int end) {
tcpConfig.setEndPort(end);
}
/**
* Toggles TCP transport server (incoming) mode (default is on)
*
* @param incoming the new TCP server mode
*/
public void setTcpIncoming(boolean incoming) {
tcpConfig.setServerEnabled(incoming);
}
/**
* Toggles TCP transport client (outgoing) mode (default is true)
*
* @param outgoing the new tcpOutgoing value
*/
public void setTcpOutgoing(boolean outgoing) {
tcpConfig.setClientEnabled(outgoing);
}
/**
* Sets the TCP transport interface address
* <p/>e.g. "192.168.1.1"
*
* @param address the TCP transport interface address
*/
public void setTcpInterfaceAddress(String address) {
tcpConfig.setInterfaceAddress(address);
}
/**
* Sets the node public address
* <p/>e.g. "192.168.1.1:9701"
* <p/>This address is the physical address defined in a node's
* AccessPointAdvertisement. This often required for NAT'd/FW nodes
*
* @param address the TCP transport public address
* @param exclusive public address advertised exclusively
*/
public void setTcpPublicAddress(String address, boolean exclusive) {
tcpConfig.setServer(address);
tcpConfig.setPublicAddressOnly(exclusive);
}
/**
* Toggles whether to use IP group multicast (default is true)
*
* @param multicastOn the new useMulticast value
*/
public void setUseMulticast(boolean multicastOn) {
multicastConfig.setMulticastState(multicastOn);
}
/**
* Determines whether to restrict RelayService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
* </p>WARNING: Disabling 'use only relay seed' will cause this peer to
* search and fetch RdvAdvertisements for use as relay candidates. Rdvs
* are not necessarily relays.
*
* @param useOnlyRelaySeeds restrict RelayService lease to seed list
*/
public void setUseOnlyRelaySeeds(boolean useOnlyRelaySeeds) {
relayConfig.setUseOnlySeeds(useOnlyRelaySeeds);
}
/**
* Determines whether to restrict RendezvousService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
*
* @param useOnlyRendezvouSeeds restrict RendezvousService lease to seed list
*/
public void setUseOnlyRendezvousSeeds(boolean useOnlyRendezvouSeeds) {
rdvConfig.setUseOnlySeeds(useOnlyRendezvouSeeds);
}
/**
* Adds RelayService peer seed address
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the relay seed URI
*/
public void addSeedRelay(URI seedURI) {
relayConfig.addSeedRelay(seedURI.toString());
}
/**
* Adds Rendezvous peer seed, physical endpoint address
* <p/>A RendezVousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the rendezvous seed URI
*/
public void addSeedRendezvous(URI seedURI) {
rdvConfig.addSeedRendezvous(seedURI);
}
/**
* Returns true if a PlatformConfig file exist under store home
*
* @return true if a PlatformConfig file exist under store home
*/
public boolean exists() {
URI platformConfig = storeHome.resolve("PlatformConfig");
try {
return null != read(platformConfig);
} catch (IOException failed) {
return false;
}
}
/**
* Sets the PeerID for this Configuration
*
* @param peerIdStr the new PeerID as a string
*/
public void setPeerId(String peerIdStr) {
this.peerid = (PeerID) ID.create(URI.create(peerIdStr));
}
/**
* Sets the new RendezvousService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers
*
* @param seedURIStr the new rendezvous seed URI as a string
*/
public void addRdvSeedingURI(String seedURIStr) {
rdvConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the new RelayService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIStr the new RelayService seed URI as a string
*/
public void addRelaySeedingURI(String seedURIStr) {
relayConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the List relaySeeds represented as Strings
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set RelayService seed URIs as a string
*/
public void setRelaySeedURIs(List<String> seeds) {
relayConfig.clearSeedRelays();
for (String seedStr : seeds) {
relayConfig.addSeedRelay(new EndpointAddress(seedStr));
}
}
/**
* Sets the relaySeeds represented as Strings
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIs the List relaySeeds represented as Strings
*/
public void setRelaySeedingURIs(Set<String> seedURIs) {
relayConfig.clearSeedingURIs();
for (String seedStr : seedURIs) {
relayConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the List of RelayService seeds
*/
public void clearRelaySeeds() {
relayConfig.clearSeedRelays();
}
/**
* Clears the List of RelayService seeding URIs
*/
public void clearRelaySeedingURIs() {
relayConfig.clearSeedingURIs();
}
/**
* Sets the List of RendezVousService seeds represented as Strings
* <p/>A RendezvousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set of rendezvousSeeds represented as Strings
*/
public void setRendezvousSeeds(Set<String> seeds) {
rdvConfig.clearSeedRendezvous();
for (String seedStr : seeds) {
rdvConfig.addSeedRendezvous(URI.create(seedStr));
}
}
/**
* Sets the List of RendezVousService seeding URIs represented as Strings.
* A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers.
*
* @param seedingURIs the List rendezvousSeeds represented as Strings.
*/
public void setRendezvousSeedingURIs(List<String> seedingURIs) {
rdvConfig.clearSeedingURIs();
for (String seedStr : seedingURIs) {
rdvConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the list of RendezVousService seeds
*/
public void clearRendezvousSeeds() {
rdvConfig.clearSeedRendezvous();
}
/**
* Clears the list of RendezVousService seeding URIs
*/
public void clearRendezvousSeedingURIs() {
rdvConfig.clearSeedingURIs();
}
/**
* Load a configuration from the specified store home uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MembershipService is invalid
*/
public ConfigParams load() throws IOException, CertificateException {
return load(storeHome.resolve("PlatformConfig"));
}
/**
* Loads a configuration from a specified uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @param uri the URI to PlatformConfig
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MemebershipService is invalid
*/
public ConfigParams load(URI uri) throws IOException, CertificateException {
if (uri == null) throw new IllegalArgumentException("URI can not be null");
Logging.logCheckedFine(LOG, "Loading configuration : ", uri);
PlatformConfig platformConfig = read(uri);
name = platformConfig.getName();
peerid = platformConfig.getPeerID();
description = platformConfig.getDescription();
XMLElement<?> param;
// TCP
tcpEnabled = platformConfig.isSvcEnabled(PeerGroup.tcpProtoClassID);
tcpConfig = loadTcpAdv(platformConfig, PeerGroup.tcpProtoClassID);
multicastEnabled = platformConfig.isSvcEnabled(PeerGroup.multicastProtoClassID);
multicastConfig = loadMulticastAdv(platformConfig, PeerGroup.multicastProtoClassID);
// HTTP
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.httpProtoClassID);
httpEnabled = platformConfig.isSvcEnabled(PeerGroup.httpProtoClassID);
Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv
if (httpChilds.hasMoreElements()) {
param = (XMLElement) httpChilds.nextElement();
} else {
throw new IllegalStateException("Missing HTTP Advertisment");
}
// Read-in the adv as it is now.
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the HTTP config advertisement");
ioe.initCause(failure);
throw ioe;
}
// HTTP2
http2Enabled = platformConfig.isSvcEnabled(PeerGroup.http2ProtoClassID);
http2Config = loadTcpAdv(platformConfig, PeerGroup.http2ProtoClassID);
// // ProxyService
// try {
// param = (XMLElement) platformConfig.getServiceParam(PeerGroup.proxyClassID);
// if (param != null && !platformConfig.isSvcEnabled(PeerGroup.proxyClassID)) {
// mode = mode | PROXY_SERVER;
// }
// } catch (Exception failure) {
// IOException ioe = new IOException("error processing the pse config advertisement");
// ioe.initCause(failure);
// throw ioe;
// }
// Rendezvous
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.rendezvousClassID);
// backwards compatibility
param.addAttribute("type", RdvConfigAdv.getAdvertisementType());
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param);
if (rdvConfig.getConfiguration() == RendezVousConfiguration.AD_HOC) {
mode = mode | RDV_AD_HOC;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.EDGE) {
mode = mode | RDV_CLIENT;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.RENDEZVOUS) {
mode = mode | RDV_SERVER;
}
} catch (Exception failure) {
IOException ioe = new IOException("error processing the rendezvous config advertisement");
ioe.initCause(failure);
throw ioe;
}
// Relay
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.relayProtoClassID);
if (param != null && !platformConfig.isSvcEnabled(PeerGroup.relayProtoClassID)) {
mode = mode | RELAY_OFF;
}
// backwards compatibility
param.addAttribute("type", RelayConfigAdv.getAdvertisementType());
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the relay config advertisement");
ioe.initCause(failure);
throw ioe;
}
// PSE
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID);
if (param != null) {
Advertisement adv = null;
try {
adv = AdvertisementFactory.newAdvertisement(param);
} catch (NoSuchElementException notAnAdv) {
CertificateException cnfe = new CertificateException("No membership advertisement found");
cnfe.initCause(notAnAdv);
} catch (IllegalArgumentException invalidAdv) {
CertificateException cnfe = new CertificateException("Invalid membership advertisement");
cnfe.initCause(invalidAdv);
}
if (adv instanceof PSEConfigAdv) {
pseConf = (PSEConfigAdv) adv;
cert = pseConf.getCertificateChain();
} else {
throw new CertificateException("Error processing the Membership config advertisement. Unexpected membership advertisement "
+ adv.getAdvertisementType());
}
}
// Infra Group
infraPeerGroupConfig = (PeerGroupConfigAdv) platformConfig.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID);
if (null == infraPeerGroupConfig) {
infraPeerGroupConfig = createInfraConfigAdv();
try {
URI configPropsURI = storeHome.resolve("config.properties");
InputStream configPropsIS = configPropsURI.toURL().openStream();
ResourceBundle rsrcs = new PropertyResourceBundle(configPropsIS);
configPropsIS.close();
NetGroupTunables tunables = new NetGroupTunables(rsrcs, new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
} catch (IOException ignored) {
//ignored
} catch (MissingResourceException ignored) {
//ignored
}
}
return platformConfig;
}
private TCPAdv loadTcpAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or tcpConfig
if (tcpChilds.hasMoreElements()) {
param = (XMLElement<?>) tcpChilds.nextElement();
} else {
throw new IllegalStateException("Missing TCP Advertisement");
}
return (TCPAdv) AdvertisementFactory.newAdvertisement(param);
}
private MulticastAdv loadMulticastAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param2 = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds2 = param2.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or multicastConfig
if (tcpChilds2.hasMoreElements()) {
param2 = (XMLElement<?>) tcpChilds2.nextElement();
} else {
throw new IllegalStateException("Missing Multicast Advertisment");
}
return (MulticastAdv) AdvertisementFactory.newAdvertisement(param2);
}
/**
* Persists a PlatformConfig advertisement under getStoreHome()+"/PlaformConfig"
* <p/>
* Home may be overridden by a call to setHome()
*
* @throws IOException If there is a failure saving the PlatformConfig.
* @see #load
*/
public void save() throws IOException {
httpEnabled = (httpConfig.isClientEnabled() || httpConfig.isServerEnabled());
tcpEnabled = (tcpConfig.isClientEnabled() || tcpConfig.isServerEnabled());
http2Enabled = (http2Config.isClientEnabled() || http2Config.isServerEnabled());
ConfigParams advertisement = getPlatformConfig();
OutputStream out = null;
try {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
File saveDir = new File(storeHome);
saveDir.mkdirs();
// Sadly we can't use URL.openConnection() to create the
// OutputStream for file:// URLs. bogus.
out = new FileOutputStream(new File(saveDir, "PlatformConfig"));
} else {
out = storeHome.resolve("PlatformConfig").toURL().openConnection().getOutputStream();
}
XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8);
OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");
aDoc.sendToWriter(os);
os.flush();
} finally {
if (null != out) {
out.close();
}
}
}
/**
* Returns a XMLDocument representation of an Advertisement
*
* @param enabled whether the param doc is enabled, adds a "isOff"
* element if disabled
* @param adv the Advertisement to retrieve the param doc from
* @return the parmDoc value
*/
protected XMLDocument getParmDoc(boolean enabled, Advertisement adv) {
XMLDocument parmDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
XMLDocument doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8);
StructuredDocumentUtils.copyElements(parmDoc, parmDoc, doc);
if (!enabled) {
parmDoc.appendChild(parmDoc.createElement("isOff"));
}
return parmDoc;
}
/**
* Creates an HTTP transport advertisement
*
* @return an HTTP transport advertisement
*/
protected HTTPAdv createHttpAdv() {
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType());
httpConfig.setProtocol("http");
httpConfig.setPort(9700);
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
return httpConfig;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param principal principal
* @param password the password used to sign the private key of the root certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(String principal, String password) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (principal != null && password != null) {
IssuerInfo info = PSEUtils.genCert(principal, null);
pseConf.setCertificate(info.cert);
pseConf.setPrivateKey(info.subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param cert X509Certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate cert) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificate(cert);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param certificateChain X509Certificate[]
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate[] certificateChain) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificateChain(certificateChain);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates a ProxyService configuration advertisement
*
* @return ProxyService configuration advertisement
*/
@Deprecated
protected XMLDocument createProxyAdv() {
return (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
}
/**
* Creates a RendezVousService configuration advertisement with default values (EDGE)
*
* @return a RdvConfigAdv
*/
protected RdvConfigAdv createRdvConfigAdv() {
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType());
if (mode == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
}
// A better alternative is to reference rdv service defaults (currently private)
// rdvConfig.setMaxClients(200);
return rdvConfig;
}
/**
* Creates a RelayService configuration advertisement with default values (EDGE)
*
* @return a RelayConfigAdv
*/
protected RelayConfigAdv createRelayConfigAdv() {
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType());
// Since 2.6 - We should only use seeds when it comes to relay (see Javadoc)
// relayConfig.setUseOnlySeeds(false);
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT || mode == EDGE_NODE);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
return relayConfig;
}
/**
* Creates an TCP transport advertisement with the platform default values.
* multicast on, 224.0.1.85:1234, with a max packet size of 16K
*
* @return a TCP transport advertisement
*/
protected TCPAdv createTcpAdv() {
tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
tcpConfig.setProtocol("tcp");
tcpConfig.setInterfaceAddress(null);
tcpConfig.setPort(9701);
//tcpConfig.setStartPort(9701);
//tcpConfig.setEndPort(9799);
tcpConfig.setServer(null);
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
return tcpConfig;
}
/**
* Creates an multicast transport advertisement with the platform default values.
* Multicast on, 224.0.1.85:1234, with a max packet size of 16K.
*
* @return a TCP transport advertisement
*/
protected MulticastAdv createMulticastAdv() {
multicastConfig = (MulticastAdv) AdvertisementFactory.newAdvertisement(MulticastAdv.getAdvertisementType());
multicastConfig.setProtocol("tcp");
multicastConfig.setMulticastAddr("224.0.1.85");
multicastConfig.setMulticastPort(1234);
multicastConfig.setMulticastSize(16384);
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
return multicastConfig;
}
protected TCPAdv createHttp2Adv() {
http2Config = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
http2Config.setProtocol("http2");
http2Config.setInterfaceAddress(null);
http2Config.setPort(8080);
http2Config.setStartPort(8080);
http2Config.setEndPort(8089);
http2Config.setServer(null);
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == TCP_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == TCP_SERVER);
return http2Config;
}
protected PeerGroupConfigAdv createInfraConfigAdv() {
infraPeerGroupConfig = (PeerGroupConfigAdv) AdvertisementFactory.newAdvertisement(
PeerGroupConfigAdv.getAdvertisementType());
NetGroupTunables tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
return infraPeerGroupConfig;
}
/**
* Returns a PlatformConfig which represents a platform configuration.
* <p/>Fine tuning is achieved through accessing each configured advertisement
* and achieved through accessing each configured advertisement and modifying
* each object directly.
*
* @return the PeerPlatformConfig Advertisement
*/
public ConfigParams getPlatformConfig() {
PlatformConfig advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement(
PlatformConfig.getAdvertisementType());
advertisement.setName(name);
advertisement.setDescription(description);
if (tcpConfig != null) {
boolean enabled = tcpEnabled && (tcpConfig.isServerEnabled() || tcpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.tcpProtoClassID, getParmDoc(enabled, tcpConfig));
}
if (multicastConfig != null) {
boolean enabled = multicastConfig.getMulticastState();
advertisement.putServiceParam(PeerGroup.multicastProtoClassID, getParmDoc(enabled, multicastConfig));
}
if (httpConfig != null) {
boolean enabled = httpEnabled && (httpConfig.isServerEnabled() || httpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.httpProtoClassID, getParmDoc(enabled, httpConfig));
}
if (http2Config != null) {
boolean enabled = http2Enabled && (http2Config.isServerEnabled() || http2Config.isClientEnabled());
advertisement.putServiceParam(PeerGroup.http2ProtoClassID, getParmDoc(enabled, http2Config));
}
if (relayConfig != null) {
boolean isOff = ((mode & RELAY_OFF) == RELAY_OFF) || (relayConfig.isServerEnabled() && relayConfig.isClientEnabled());
XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8);
if (isOff) {
relayDoc.appendChild(relayDoc.createElement("isOff"));
}
advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc);
}
if (rdvConfig != null) {
XMLDocument rdvDoc = (XMLDocument) rdvConfig.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc);
}
if (principal == null) {
principal = System.getProperty("impl.membership.pse.authentication.principal", "JxtaCN");
}
if (password == null) {
password = System.getProperty("impl.membership.pse.authentication.password", "the!one!password");
}
if (cert != null) {
pseConf = createPSEAdv(cert);
} else {
pseConf = createPSEAdv(principal, password);
cert = pseConf.getCertificateChain();
}
if (pseConf != null) {
if (keyStoreLocation != null) {
if (keyStoreLocation.isAbsolute()) {
pseConf.setKeyStoreLocation(keyStoreLocation);
} else {
Logging.logCheckedWarning(LOG, "Keystore location set, but is not absolute: ", keyStoreLocation);
}
}
XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc);
}
if (authenticationType == null) {
authenticationType = System.getProperty("impl.membership.pse.authentication.type", "StringAuthentication");
}
StdPeerGroup.setPSEMembershipServiceKeystoreInfoFactory(new StdPeerGroup.DefaultPSEMembershipServiceKeystoreInfoFactory(authenticationType, password));
if (peerid == null) {
peerid = IDFactory.newPeerID(PeerGroupID.worldPeerGroupID, cert[0].getPublicKey().getEncoded());
}
advertisement.setPeerID(peerid);
// if (proxyConfig != null && ((mode & PROXY_SERVER) == PROXY_SERVER)) {
// advertisement.putServiceParam(PeerGroup.proxyClassID, proxyConfig);
// }
if ((null != infraPeerGroupConfig) && (null != infraPeerGroupConfig.getPeerGroupID())
&& (ID.nullID != infraPeerGroupConfig.getPeerGroupID())
&& (PeerGroupID.defaultNetPeerGroupID != infraPeerGroupConfig.getPeerGroupID())) {
advertisement.setSvcConfigAdvertisement(PeerGroup.peerGroupClassID, infraPeerGroupConfig);
}
return advertisement;
}
/**
* @param location The location of the platform config.
* @return The platformConfig
* @throws IOException Thrown for failures reading the PlatformConfig.
*/
private PlatformConfig read(URI location) throws IOException {
URL url;
try {
url = location.toURL();
} catch (MalformedURLException mue) {
IllegalArgumentException failure = new IllegalArgumentException("Failed to convert URI to URL");
failure.initCause(mue);
throw failure;
}
InputStream input = url.openStream();
try {
XMLDocument document = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, input);
PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(document);
return platformConfig;
} finally {
input.close();
}
}
/**
* Indicates whether Http is enabled
*
* @return true if Http is enabled, else returns false
* @see #setHttpEnabled
*/
public boolean isHttpEnabled() {
return this.httpEnabled;
}
/**
* Retrieves the Http incoming status
*
* @return true if Http incomming status is enabled, else returns false
* @see #setHttpIncoming
*/
public boolean getHttpIncomingStatus() {
return httpConfig.getServerEnabled();
}
/**
* Retrieves the Http outgoing status
*
* @return true if Http outgoing status is enabled, else returns false
* @see #setHttpOutgoing
*/
public boolean getHttpOutgoingStatus() {
return httpConfig.getClientEnabled();
}
/**
* Retrieves the Http port
*
* @return the current Http port
* @see #setHttpPort
*/
public int getHttpPort() {
return httpConfig.getPort();
}
/**
* Retrieves the current infrastructure ID
*
* @return the current infrastructure ID
* @see #setInfrastructureID
*/
public ID getInfrastructureID() {
return infraPeerGroupConfig.getPeerGroupID();
}
/**
* Retrieves the current multicast address
*
* @return the current multicast address
* @see #setMulticastAddress
*/
public String getMulticastAddress() {
return multicastConfig.getMulticastAddr();
}
/**
* Retrieves the current multicast port
*
* @return the current mutlicast port
* @see #setMulticastPort
*/
public int getMulticastPort() {
return multicastConfig.getMulticastPort();
}
/**
* Gets the group multicast thread pool size
*
* @return multicast thread pool size
*/
public int getMulticastPoolSize() {
return multicastConfig.getMulticastPoolSize();
}
/**
* Indicates whether tcp is enabled
*
* @return true if tcp is enabled, else returns false
* @see #setTcpEnabled
*/
public boolean isTcpEnabled() {
return this.tcpEnabled;
}
/**
* Retrieves the current tcp end port
*
* @return the current tcp port
* @see #setTcpEndPort
*/
public int getTcpEndport() {
return tcpConfig.getEndPort();
}
/**
* Retrieves the Tcp incoming status
*
* @return true if tcp incoming is enabled, else returns false
* @see #setTcpIncoming
*/
public boolean getTcpIncomingStatus() {
return tcpConfig.getServerEnabled();
}
/**
* Retrieves the Tcp outgoing status
*
* @return true if tcp outcoming is enabled, else returns false
* @see #setTcpOutgoing
*/
public boolean getTcpOutgoingStatus() {
return tcpConfig.getClientEnabled();
}
/**
* Retrieves the Tcp interface address
*
* @return the current tcp interface address
* @see #setTcpInterfaceAddress
*/
public String getTcpInterfaceAddress() {
return tcpConfig.getInterfaceAddress();
}
/**
* Retrieves the current Tcp port
*
* @return the current tcp port
* @see #setTcpPort
*/
public int getTcpPort() {
return tcpConfig.getPort();
}
/**
* Retrieves the current Tcp public address
*
* @return the current tcp public address
* @see #setTcpPublicAddress
*/
public String getTcpPublicAddress() {
return tcpConfig.getServer();
}
/**
* Indicates whether the current Tcp public address is exclusive
*
* @return true if the current tcp public address is exclusive, else returns false
* @see #setTcpPublicAddress
*/
public boolean isTcpPublicAddressExclusive() {
return tcpConfig.getPublicAddressOnly();
}
/**
* Retrieves the current Tcp start port
*
* @return the current tcp start port
* @see #setTcpStartPort
*/
public int getTcpStartPort() {
return tcpConfig.getStartPort();
}
/**
* Retrieves the multicast use status
*
* @return true if multicast is enabled, else returns false
* @see #setUseMulticast
*/
public boolean getMulticastStatus() {
return multicastConfig.getMulticastState();
}
/**
* Retrieves the use relay seeds only status
*
* @return true if only relay seeds are used, else returns false
* @see #setUseOnlyRelaySeeds
*/
public boolean getUseOnlyRelaySeedsStatus() {
return relayConfig.getUseOnlySeeds();
}
/**
* Retrieves the use rendezvous seeds only status
*
* @return true if only rendezvous seeds are used, else returns false
* @see #setUseOnlyRendezvousSeeds
*/
public boolean getUseOnlyRendezvousSeedsStatus() {
return rdvConfig.getUseOnlySeeds();
}
/**
* Retrieves the RendezVousService maximum number of simultaneous rendezvous clients
*
* @return the RendezVousService maximum number of simultaneous rendezvous clients
* @see #setRendezvousMaxClients
*/
public int getRendezvousMaxClients() {
return rdvConfig.getMaxClients();
}
/**
* Retrieves the RelayVousService maximum number of simultaneous relay clients
*
* @return the RelayService maximum number of simultaneous relay clients
* @see #setRelayMaxClients
*/
public int getRelayMaxClients() {
return relayConfig.getMaxClients();
}
/**
* Retrieves the rendezvous seedings
*
* @return the array of rendezvous seeding URL
* @see #addRdvSeedingURI
*/
public URI[] getRdvSeedingURIs() {
return rdvConfig.getSeedingURIs();
}
/**
* Retrieves the rendezvous seeds
*
* @return the array of rendezvous seeds URL
* @see #addRdvSeedURI
*/
public URI[] getRdvSeedURIs() {
return rdvConfig.getSeedRendezvous();
}
/**
* Retrieves the relay seeds
*
* @return the array of relay seeds URL
* @see #addRelaySeedURI
*/
public URI[] getRelaySeedURIs() {
return relayConfig.getSeedRelayURIs();
}
/**
* Retrieves the relay seeds
*
* @return the array of rendezvous seed URL
* @see #addRelaySeedingURI
*/
public URI[] getRelaySeedingURIs() {
return relayConfig.getSeedingURIs();
}
/**
* Holds the construction tunables for the Net Peer Group. This consists of
* the peer group id, the peer group name and the peer group description.
*/
static class NetGroupTunables {
final ID id;
final String name;
final XMLElement desc;
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*/
NetGroupTunables() {
id = PeerGroupID.defaultNetPeerGroupID;
name = "NetPeerGroup";
desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group");
}
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*
* @param pgid the PeerGroupID
* @param pgname the group name
* @param pgdesc the group description
*/
NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) {
id = pgid;
name = pgname;
desc = pgdesc;
}
/**
* Constructor for loading the Net Peer Group construction
* tunables from the provided resource bundle.
*
* @param rsrcs The resource bundle from which resources will be loaded.
* @param defaults default values
*/
NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) {
ID idTmp;
String nameTmp;
XMLElement descTmp;
try {
String idTmpStr = rsrcs.getString("NetPeerGroupID").trim();
if (idTmpStr.startsWith(ID.URNNamespace + ":")) {
idTmpStr = idTmpStr.substring(5);
}
idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr));
nameTmp = rsrcs.getString("NetPeerGroupName").trim();
descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", rsrcs.getString("NetPeerGroupDesc").trim());
} catch (Exception failed) {
if (null != defaults) {
Logging.logCheckedFine(LOG, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.\n\n", failed);
idTmp = defaults.id;
nameTmp = defaults.name;
descTmp = defaults.desc;
} else {
Logging.logCheckedSevere(LOG, "NetPeerGroup tunables not defined or could not be loaded.\n", failed);
throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded.");
}
}
id = idTmp;
name = nameTmp;
desc = descTmp;
}
}
}
| johnjianfang/jxse | src/main/java/net/jxta/platform/NetworkConfigurator.java | Java | apache-2.0 | 82,829 |
package com.sissi.protocol.message;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import com.sissi.io.read.Metadata;
/**
* @author kim 2014年1月28日
*/
@Metadata(uri = Message.XMLNS, localName = Thread.NAME)
@XmlRootElement
public class Thread {
public final static String NAME = "thread";
private String text;
private String parent;
public Thread() {
super();
}
public Thread(String text) {
super();
this.text = text;
}
public Thread(String text, String parent) {
super();
this.text = text;
this.parent = parent;
}
@XmlValue
public String getText() {
return this.text;
}
public Thread setText(String text) {
this.text = text;
return this;
}
@XmlAttribute
public String getParent() {
return this.parent;
}
public Thread setParent(String parent) {
this.parent = parent;
return this;
}
public boolean content() {
return this.text != null && this.text.length() > 0;
}
}
| KimShen/sissi | src/main/java/com/sissi/protocol/message/Thread.java | Java | apache-2.0 | 1,026 |
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.asm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.yx.bean.Loader;
import org.yx.conf.AppInfo;
import org.yx.exception.SumkException;
import org.yx.log.Log;
import org.yx.log.Logs;
import org.yx.main.StartContext;
public final class AsmUtils {
private static Method defineClass;
static {
try {
defineClass = getMethod(ClassLoader.class, "defineClass",
new Class<?>[] { String.class, byte[].class, int.class, int.class });
defineClass.setAccessible(true);
} catch (Exception e) {
Log.printStack("sumk.error", e);
StartContext.startFailed();
}
}
public static String proxyCalssName(Class<?> clz) {
String name = clz.getName();
int index = name.lastIndexOf('.');
return name.substring(0, index) + ".sumkbox" + name.substring(index);
}
public static int asmVersion() {
return AppInfo.getInt("sumk.asm.version", Opcodes.ASM7);
}
public static int jvmVersion() {
return AppInfo.getInt("sumk.asm.jvm.version", Opcodes.V1_8);
}
public static InputStream openStreamForClass(String name) {
String internalName = name.replace('.', '/') + ".class";
return Loader.getResourceAsStream(internalName);
}
public static boolean sameType(Type[] types, Class<?>[] clazzes) {
if (types.length != clazzes.length) {
return false;
}
for (int i = 0; i < types.length; i++) {
if (!Type.getType(clazzes[i]).equals(types[i])) {
return false;
}
}
return true;
}
public static List<MethodParamInfo> buildMethodInfos(List<Method> methods) throws IOException {
Map<Class<?>, List<Method>> map = new HashMap<>();
for (Method m : methods) {
List<Method> list = map.get(m.getDeclaringClass());
if (list == null) {
list = new ArrayList<>();
map.put(m.getDeclaringClass(), list);
}
list.add(m);
}
List<MethodParamInfo> ret = new ArrayList<>();
for (List<Method> ms : map.values()) {
ret.addAll(buildMethodInfos(ms.get(0).getDeclaringClass(), ms));
}
return ret;
}
private static List<MethodParamInfo> buildMethodInfos(Class<?> declaringClass, List<Method> methods)
throws IOException {
String classFullName = declaringClass.getName();
ClassReader cr = new ClassReader(openStreamForClass(classFullName));
MethodInfoClassVisitor cv = new MethodInfoClassVisitor(methods);
cr.accept(cv, 0);
return cv.getMethodInfos();
}
public static Method getMethod(Class<?> clz, String methodName, Class<?>[] paramTypes) {
while (clz != Object.class) {
Method[] ms = clz.getDeclaredMethods();
for (Method m : ms) {
if (!m.getName().equals(methodName)) {
continue;
}
Class<?>[] paramTypes2 = m.getParameterTypes();
if (!Arrays.equals(paramTypes2, paramTypes)) {
continue;
}
return m;
}
clz = clz.getSuperclass();
}
return null;
}
public static Class<?> loadClass(String fullName, byte[] b) throws Exception {
String clzOutPath = AppInfo.get("sumk.asm.debug.output");
if (clzOutPath != null && clzOutPath.length() > 0) {
try {
File f = new File(clzOutPath, fullName + ".class");
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(b);
fos.flush();
}
} catch (Exception e) {
if (Logs.asm().isTraceEnabled()) {
Logs.asm().error(e.getLocalizedMessage(), e);
}
}
}
synchronized (AsmUtils.class) {
try {
return Loader.loadClass(fullName);
} catch (Throwable e) {
if (!(e instanceof ClassNotFoundException)) {
Logs.asm().warn(fullName + " 加载失败", e);
}
}
Class<?> clz = (Class<?>) defineClass.invoke(Loader.loader(), fullName, b, 0, b.length);
if (clz == null) {
throw new SumkException(-235345436, "cannot load class " + fullName);
}
return clz;
}
}
public static final int BADMODIFIERS = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.PRIVATE;
public static boolean notPublicOnly(int modifiers) {
return (modifiers & (Modifier.PUBLIC | BADMODIFIERS)) != Modifier.PUBLIC;
}
public static boolean canProxy(int modifiers) {
return (modifiers & BADMODIFIERS) == 0;
}
public static List<Object> getImplicitFrame(String desc) {
List<Object> locals = new ArrayList<>(5);
if (desc.isEmpty()) {
return locals;
}
int i = 0;
while (desc.length() > i) {
int j = i;
switch (desc.charAt(i++)) {
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
locals.add(Opcodes.INTEGER);
break;
case 'F':
locals.add(Opcodes.FLOAT);
break;
case 'J':
locals.add(Opcodes.LONG);
break;
case 'D':
locals.add(Opcodes.DOUBLE);
break;
case '[':
while (desc.charAt(i) == '[') {
++i;
}
if (desc.charAt(i) == 'L') {
++i;
while (desc.charAt(i) != ';') {
++i;
}
}
locals.add(desc.substring(j, ++i));
break;
case 'L':
while (desc.charAt(i) != ';') {
++i;
}
locals.add(desc.substring(j + 1, i++));
break;
default:
break;
}
}
return locals;
}
public static Method getSameMethod(Method method, Class<?> otherClass) {
Class<?> clz = method.getDeclaringClass();
if (clz == otherClass) {
return method;
}
String methodName = method.getName();
Class<?>[] argTypes = method.getParameterTypes();
Method[] proxyedMethods = otherClass.getMethods();
for (Method proxyedMethod : proxyedMethods) {
if (proxyedMethod.getName().equals(methodName) && Arrays.equals(argTypes, proxyedMethod.getParameterTypes())
&& !proxyedMethod.getDeclaringClass().isInterface()) {
return proxyedMethod;
}
}
return method;
}
}
| youtongluan/sumk | src/main/java/org/yx/asm/AsmUtils.java | Java | apache-2.0 | 6,539 |
/**********************************************************************
Copyright (c) 2009 Stefan Seelmann. 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.example.dao;
import java.util.Collection;
import com.example.Team;
public class TeamDao extends AbstractDao<Team>
{
public Collection<Team> findByName( String name )
{
return super.findByQuery( "name.startsWith(s1)", "java.lang.String s1", name );
}
public Team loadWithUsers( Object id )
{
return super.load( id, "users" );
}
public Team load( Object id )
{
return super.load( id );
}
public Collection<Team> loadAll()
{
return super.loadAll();
}
}
| seelmann/ldapcon2009-datanucleus | DataNucleus-Advanced/src/main/java/com/example/dao/TeamDao.java | Java | apache-2.0 | 1,280 |
package com.metrink.action;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.metrink.alert.ActionBean;
import com.metrink.alert.AlertBean;
import com.metrink.metric.Metric;
/**
* The base action for all SMS actions.
*
* A list of gateways can be found here: http://www.emailtextmessages.com/
*
*/
public abstract class SmsAction implements Action {
private static final Logger LOG = LoggerFactory.getLogger(SmsAction.class);
private final Provider<SimpleEmail> emailProvider;
public SmsAction(final Provider<SimpleEmail> emailProvider) {
this.emailProvider = emailProvider;
}
@Override
public void triggerAction(Metric metric, AlertBean alertBean, ActionBean actionBean) {
final String toAddr = constructAddress(actionBean.getValue());
final String alertQuery = alertBean.getAlertQuery().substring(0, alertBean.getAlertQuery().lastIndexOf(" do "));
final StringBuilder sb = new StringBuilder();
sb.append(metric.getId());
sb.append(" ");
sb.append(metric.getValue());
sb.append(" triggered ");
sb.append(alertQuery);
try {
final SimpleEmail email = emailProvider.get();
email.addTo(toAddr);
email.setSubject("METRINK Alert");
email.setMsg(sb.toString());
final String messageId = email.send();
LOG.info("Sent message {} to {}", messageId, toAddr);
} catch (final EmailException e) {
LOG.error("Error sending email: {}", e.getMessage());
}
}
/**
* Given a phone number, create the address for the gateway.
* @param phoneNumber the phone number.
* @return the email address to use.
*/
protected abstract String constructAddress(String phoneNumber);
}
| Metrink/metrink | src/main/java/com/metrink/action/SmsAction.java | Java | apache-2.0 | 1,947 |
/**
* Copyright 2017-2019 The GreyCat Authors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 greycat.internal.task;
import greycat.*;
import greycat.base.BaseNode;
import greycat.plugin.Job;
import greycat.struct.Buffer;
class ActionDelete implements Action {
@Override
public void eval(final TaskContext ctx) {
TaskResult previous = ctx.result();
DeferCounter counter = ctx.graph().newCounter(previous.size());
for (int i = 0; i < previous.size(); i++) {
if (previous.get(i) instanceof BaseNode) {
((Node) previous.get(i)).drop(new Callback() {
@Override
public void on(Object result) {
counter.count();
}
});
}
}
counter.then(new Job() {
@Override
public void run() {
previous.clear();
ctx.continueTask();
}
});
}
@Override
public void serialize(final Buffer builder) {
builder.writeString(CoreActionNames.DELETE);
builder.writeChar(Constants.TASK_PARAM_OPEN);
builder.writeChar(Constants.TASK_PARAM_CLOSE);
}
@Override
public final String name() {
return CoreActionNames.DELETE;
}
}
| datathings/greycat | greycat/src/main/java/greycat/internal/task/ActionDelete.java | Java | apache-2.0 | 1,871 |
package com.at.springboot.mybatis.po;
public class JsonUser {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private byte[] jsonUserId;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String userName;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginResult;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginInfo;
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.JSON_USER_ID
* @return the value of JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public byte[] getJsonUserId() {
return jsonUserId;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.JSON_USER_ID
* @param jsonUserId the value for JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setJsonUserId(byte[] jsonUserId) {
this.jsonUserId = jsonUserId;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.USER_NAME
* @return the value of JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getUserName() {
return userName;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.USER_NAME
* @param userName the value for JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @return the value of JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginResult() {
return lastLoginResult;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @param lastLoginResult the value for JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginResult(String lastLoginResult) {
this.lastLoginResult = lastLoginResult == null ? null : lastLoginResult.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_INFO
* @return the value of JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginInfo() {
return lastLoginInfo;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_INFO
* @param lastLoginInfo the value for JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginInfo(String lastLoginInfo) {
this.lastLoginInfo = lastLoginInfo == null ? null : lastLoginInfo.trim();
}
} | alphatan/workspace_java | spring-boot-web-fps-demo/src/main/java/com/at/springboot/mybatis/po/JsonUser.java | Java | apache-2.0 | 3,937 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.stylehair.servicos;
import br.com.stylehair.dao.AgendamentoDAO;
import br.com.stylehair.entity.Agendamento;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
/**
*
* @author vinicius
*/
@Stateless
@Path("agendamento")
public class AgendamentoResource {
@PersistenceContext(unitName = "StyleHairPU")
private EntityManager em;
private Gson gson = new Gson();
@Context
private UriInfo context;
@GET
@Produces("application/json")
public String getJson() {
AgendamentoDAO dao = new AgendamentoDAO(em);
List<Agendamento> agendamentos;
agendamentos = dao.buscarTodosAgendamentos();
return gson.toJson(agendamentos);
}
@GET
@Path("{agendamentoId}")
@Produces("application/json")
public String getAgendamento(@PathParam("agendamentoId") String id){
System.out.println("pegando o cliente");
Long n = Long.parseLong(id);
System.out.println(n);
AgendamentoDAO dao = new AgendamentoDAO(em);
Agendamento agend = dao.consultarPorId(Agendamento.class, Long.parseLong(id));
return gson.toJson(agend);
}
@GET
@Path("{buscardata}/{dia}/{mes}/{ano}")
@Produces("application/json")
public String getAgendamentoPorData(@PathParam("dia") String dia,@PathParam("mes") String mes,@PathParam("ano") String ano ) {
AgendamentoDAO dao = new AgendamentoDAO(em);
List<Agendamento> agendamentos;
SimpleDateFormat dateFormat_hora = new SimpleDateFormat("HH:mm");
Date data = new Date();
String horaAtual = dateFormat_hora.format(data);
System.out.println("hora Atual" + horaAtual);
Date d1 = new Date();
SimpleDateFormat dateFormataData = new SimpleDateFormat("dd/MM/yyyy");
String dataHoje = dateFormataData.format(d1);
System.out.println("dataHoje ----" + dataHoje + "-------- " + dia+"/"+mes+"/"+ano );
if(dataHoje.equalsIgnoreCase(dia+"/"+mes+"/"+ano)){
agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ",horaAtual);
return gson.toJson(agendamentos);
}
agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ","08:00");
return gson.toJson(agendamentos);
}
@POST
@Consumes("application/json")
@Produces("application/json")
public String salvarAgendamento(String agendamento) throws Exception{
Agendamento ag1 = gson.fromJson(agendamento, Agendamento.class);
AgendamentoDAO dao = new AgendamentoDAO(em);
return gson.toJson(dao.salvar(ag1));
}
@PUT
@Consumes("application/json")
public void atualizarAgendamento(String agendamento) throws Exception {
salvarAgendamento(agendamento);
}
}
| ViniciusBezerra94/WsStyleHair | src/main/java/br/com/stylehair/servicos/AgendamentoResource.java | Java | apache-2.0 | 3,529 |
package com.sampleapp.base;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.sampleapp.BuildConfig;
import com.sampleapp.utils.UtilsModule;
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;
/**
* Created by saveen_dhiman on 05-November-16.
* Initialization of required libraries
*/
public class SampleApplication extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
//create component
mAppComponent = DaggerAppComponent.builder()
.utilsModule(new UtilsModule(this)).build();
//configure timber for logging
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
}
public AppComponent getAppComponent() {
return mAppComponent;
}
}
| saveendhiman/SampleApp | app/src/main/java/com/sampleapp/base/SampleApplication.java | Java | apache-2.0 | 915 |
/*
* Copyright 2017 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.filesystem.exceptions;
import java.io.File;
import com.axway.ats.common.filesystem.FileSystemOperationException;
/**
* Exception thrown when a file does not exist
*/
@SuppressWarnings( "serial")
public class FileDoesNotExistException extends FileSystemOperationException {
/**
* Constructor
*
* @param fileName name of the file which does not exist
*/
public FileDoesNotExistException( String fileName ) {
super("File '" + fileName + "' does not exist");
}
/**
* Constructor
*
* @param file the file which does not exist
*/
public FileDoesNotExistException( File file ) {
super("File '" + file.getPath() + "' does not exist");
}
}
| Axway/ats-framework | corelibrary/src/main/java/com/axway/ats/core/filesystem/exceptions/FileDoesNotExistException.java | Java | apache-2.0 | 1,344 |
package com.fasterxml.jackson.databind.node;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.NumberOutput;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Numeric node that contains simple 32-bit integer values.
*/
@SuppressWarnings("serial")
public class IntNode
extends NumericNode
{
// // // Let's cache small set of common value
final static int MIN_CANONICAL = -1;
final static int MAX_CANONICAL = 10;
private final static IntNode[] CANONICALS;
static {
int count = MAX_CANONICAL - MIN_CANONICAL + 1;
CANONICALS = new IntNode[count];
for (int i = 0; i < count; ++i) {
CANONICALS[i] = new IntNode(MIN_CANONICAL + i);
}
}
/**
* Integer value this node contains
*/
protected final int _value;
/*
************************************************
* Construction
************************************************
*/
public IntNode(int v) { _value = v; }
public static IntNode valueOf(int i) {
if (i > MAX_CANONICAL || i < MIN_CANONICAL) return new IntNode(i);
return CANONICALS[i - MIN_CANONICAL];
}
/*
/**********************************************************
/* BaseJsonNode extended API
/**********************************************************
*/
@Override public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; }
@Override
public JsonParser.NumberType numberType() { return JsonParser.NumberType.INT; }
/*
/**********************************************************
/* Overrridden JsonNode methods
/**********************************************************
*/
@Override
public boolean isIntegralNumber() { return true; }
@Override
public boolean isInt() { return true; }
@Override public boolean canConvertToInt() { return true; }
@Override public boolean canConvertToLong() { return true; }
@Override
public Number numberValue() {
return Integer.valueOf(_value);
}
@Override
public short shortValue() { return (short) _value; }
@Override
public int intValue() { return _value; }
@Override
public long longValue() { return (long) _value; }
@Override
public float floatValue() { return (float) _value; }
@Override
public double doubleValue() { return (double) _value; }
@Override
public BigDecimal decimalValue() { return BigDecimal.valueOf(_value); }
@Override
public BigInteger bigIntegerValue() { return BigInteger.valueOf(_value); }
@Override
public String asText() {
return NumberOutput.toString(_value);
}
@Override
public boolean asBoolean(boolean defaultValue) {
return _value != 0;
}
@Override
public final void serialize(JsonGenerator g, SerializerProvider provider)
throws IOException
{
g.writeNumber(_value);
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o instanceof IntNode) {
return ((IntNode) o)._value == _value;
}
return false;
}
@Override
public int hashCode() { return _value; }
}
| FasterXML/jackson-databind | src/main/java/com/fasterxml/jackson/databind/node/IntNode.java | Java | apache-2.0 | 3,398 |
package lena.lerning.selenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleContains;
/**
* Created by Lena on 01/05/2017.
*/
public class EdgeTest {
private WebDriver driver;
private WebDriverWait wait;
@Before
public void edgeStart(){
driver = new EdgeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void firstTest(){
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("webdriver");
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
wait.until(titleContains("webdriver"));
}
@After
public void stop(){
driver.quit();
driver=null;
}
}
| etarnovskaya/sel_6_Lena | sel-test/src/test/java/lena/lerning/selenium/EdgeTest.java | Java | apache-2.0 | 1,062 |
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed 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://www.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.common.notification.exception;
/**
* This exception is thrown if the given role id is not known to the given context.
*/
public class UnknownRoleException extends Exception {
private static final long serialVersionUID = -1925770520412550327L;
private final String roleId;
private final String context;
/**
* Constructs an Unknown Role exception.
*
* @param roleId
* @param context
*/
public UnknownRoleException(final String roleId, final String context) {
super("Role " + roleId + " not recognized for context " + context);
this.roleId = roleId;
this.context = context;
}
public String getRoleId() {
return roleId;
}
public String getContext() {
return context;
}
} | vivantech/kc_fixes | src/main/java/org/kuali/kra/common/notification/exception/UnknownRoleException.java | Java | apache-2.0 | 1,435 |
package org.develnext.jphp.android.ext.classes.app;
import android.os.Bundle;
import org.develnext.jphp.android.AndroidStandaloneLoader;
import org.develnext.jphp.android.ext.AndroidExtension;
import php.runtime.annotation.Reflection;
@Reflection.Name(AndroidExtension.NAMESPACE + "app\\BootstrapActivity")
public class WrapBootstrapActivity extends WrapActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreateClearly(savedInstanceState);
AndroidStandaloneLoader.INSTANCE.run(this);
getEnvironment().invokeMethodNoThrow(this, "onCreate");
}
}
| livingvirus/jphp | jphp-android/src/main/java/org/develnext/jphp/android/ext/classes/app/WrapBootstrapActivity.java | Java | apache-2.0 | 616 |
package com.truward.brikar.maintenance.log.processor;
import com.truward.brikar.common.log.LogUtil;
import com.truward.brikar.maintenance.log.CommaSeparatedValueParser;
import com.truward.brikar.maintenance.log.Severity;
import com.truward.brikar.maintenance.log.message.LogMessage;
import com.truward.brikar.maintenance.log.message.MaterializedLogMessage;
import com.truward.brikar.maintenance.log.message.MultiLinePartLogMessage;
import com.truward.brikar.maintenance.log.message.NullLogMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Message processor that converts a line into a message.
*
* @author Alexander Shabanov
*/
@ParametersAreNonnullByDefault
public final class LogMessageProcessor {
public static final Pattern RECORD_PATTERN = Pattern.compile(
"^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}) " + // date+time
"(\\p{Upper}+) " + // severity
"([\\w\\p{Punct}]+) " + // class name
"((?:[\\w]+=[\\w\\+/.\\$]+)(?:, (?:[\\w]+=[\\w\\+/\\.\\$]+))*)? " + // variables
"\\[[\\w\\p{Punct}&&[^\\]]]+\\] " + // thread ID
"(.+)" + // message
"$"
);
private static final String METRIC_MARKER = LogUtil.METRIC_ENTRY + ' ';
private final Logger log = LoggerFactory.getLogger(getClass());
private final DateFormat dateFormat;
public LogMessageProcessor() {
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public LogMessage parse(String line, LogMessage previousMessage) {
if (previousMessage.hasMetrics() && line.startsWith("\t")) {
// special case: this line is a continuation of metrics entry started on the previous line
final MaterializedLogMessage logMessage = new MaterializedLogMessage(previousMessage.getUnixTime(),
previousMessage.getSeverity(), line);
addAttributesFromMetrics(logMessage, line.substring(1));
return logMessage;
}
final Matcher matcher = RECORD_PATTERN.matcher(line);
if (!matcher.matches()) {
return new MultiLinePartLogMessage(line);
}
if (matcher.groupCount() < 5) {
log.error("Count of groups is not six: actual={} for line={}", matcher.groupCount(), line);
return NullLogMessage.INSTANCE; // should not happen
}
final Date date;
try {
date = dateFormat.parse(matcher.group(1));
} catch (ParseException e) {
log.error("Malformed date in line={}", line, e);
return NullLogMessage.INSTANCE; // should not happen
}
final Severity severity = Severity.fromString(matcher.group(2), Severity.WARN);
final MaterializedLogMessage logMessage = new MaterializedLogMessage(date.getTime(), severity, line);
addAttributesFromVariables(logMessage, matcher.group(4));
final String message = matcher.group(5);
if (message != null) {
final int metricIndex = message.indexOf(METRIC_MARKER);
if (metricIndex >= 0) {
addAttributesFromMetrics(logMessage, message.substring(metricIndex + METRIC_MARKER.length()));
}
}
return logMessage;
}
//
// Private
//
private void addAttributesFromMetrics(MaterializedLogMessage logMessage, String metricBody) {
putAllAttributes(logMessage, new CommaSeparatedValueParser(metricBody).readAsMap());
}
private void addAttributesFromVariables(MaterializedLogMessage logMessage, @Nullable String variables) {
if (variables != null) {
putAllAttributes(logMessage, new CommaSeparatedValueParser(variables).readAsMap());
}
}
private void putAllAttributes(MaterializedLogMessage logMessage, Map<String, String> vars) {
for (final Map.Entry<String, String> entry : vars.entrySet()) {
final String key = entry.getKey();
final Object value;
if (LogUtil.TIME_DELTA.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.START_TIME.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.COUNT.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.FAILED.equals(key)) {
value = Boolean.valueOf(entry.getValue());
} else {
value = entry.getValue();
}
logMessage.putAttribute(key, value);
}
}
}
| truward/brikar | brikar-maintenance/src/main/java/com/truward/brikar/maintenance/log/processor/LogMessageProcessor.java | Java | apache-2.0 | 4,636 |
package ru.job4j.servlet.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.job4j.servlet.model.User;
import ru.job4j.servlet.repository.RepositoryException;
import ru.job4j.servlet.repository.UserStore;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* UpdateUserController.
*
* @author Stanislav (376825@mail.ru)
* @since 11.01.2018
*/
public class UpdateUserController extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(UpdateUserController.class);
private static final long serialVersionUID = 6328444530140780881L;
private UserStore userStore = UserStore.getInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
User user = userStore.findByID(Integer.valueOf(req.getParameter("id")));
if (user != null) {
String name = req.getParameter("name");
String login = req.getParameter("login");
String email = req.getParameter("email");
if (name != null && !name.trim().isEmpty()) {
user.setName(name);
}
if (login != null && !login.trim().isEmpty()) {
user.setLogin(login);
}
if (email != null && !email.trim().isEmpty()) {
user.setEmail(email);
}
userStore.update(user);
}
} catch (NumberFormatException e) {
LOG.error("Not the correct format id. ", e);
} catch (RepositoryException e) {
LOG.error("Error adding user. ", e);
}
resp.sendRedirect(req.getContextPath().length() == 0 ? "/" : req.getContextPath());
}
} | StanislavEsin/estanislav | chapter_007/src/main/java/ru/job4j/servlet/services/UpdateUserController.java | Java | apache-2.0 | 1,967 |
package com.kenshin.windystreet.db;
import org.litepal.crud.DataSupport;
/**
* Created by Kenshin on 2017/4/3.
*/
public class County extends DataSupport {
private int id; //编号
private String countyName; //县名
private String weatherId; //对应的天气id
private int cityId; //所属市的id
public void setId(int id) {
this.id = id;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getId() {
return id;
}
public String getCountyName() {
return countyName;
}
public String getWeatherId() {
return weatherId;
}
public int getCityId() {
return cityId;
}
}
| Asucanc/Windy-Street-Weather | app/src/main/java/com/kenshin/windystreet/db/County.java | Java | apache-2.0 | 901 |
/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.core.model.actiongraph;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import org.immutables.value.Value;
/** Holds an ActionGraph with the BuildRuleResolver that created it. */
@Value.Immutable
@BuckStyleImmutable
interface AbstractActionGraphAndResolver {
@Value.Parameter
ActionGraph getActionGraph();
@Value.Parameter
BuildRuleResolver getResolver();
}
| LegNeato/buck | src/com/facebook/buck/core/model/actiongraph/AbstractActionGraphAndResolver.java | Java | apache-2.0 | 1,075 |
package water.api;
import org.reflections.Reflections;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hex.schemas.ModelBuilderSchema;
import water.DKV;
import water.H2O;
import water.Iced;
import water.Job;
import water.Key;
import water.Value;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OKeyNotFoundArgumentException;
import water.exceptions.H2ONotFoundArgumentException;
import water.fvec.Frame;
import water.util.IcedHashMap;
import water.util.Log;
import water.util.MarkdownBuilder;
import water.util.Pair;
import water.util.PojoUtils;
import water.util.ReflectionUtils;
/**
* Base Schema class; all REST API Schemas inherit from here.
* <p>
* The purpose of Schemas is to provide a stable, versioned interface to
* the functionality in H2O, which allows the back end implementation to
* change rapidly without breaking REST API clients such as the Web UI
* and R and Python bindings. Schemas also allow for functionality which exposes the
* schema metadata to clients, allowing them to do service discovery and
* to adapt dynamically to new H2O functionality, e.g. to be able to call
* any ModelBuilder, even new ones written since the client was built,
* without knowing any details about the specific algo.
* <p>
* In most cases, Java developers who wish to expose new functionality through the
* REST API will need only to define their schemas with the fields that they
* wish to expose, adding @API annotations to denote the field metadata.
* Their fields will be copied back and forth through the reflection magic in this
* class. If there are fields they have to adapt between the REST API representation
* and the back end this can be done piecemeal by overriding the fill* methods, calling
* the versions in super, and making only those changes that are absolutely necessary.
* A lot of work has gone into avoiding boilerplate code.
* <p>
* Schemas are versioned for stability. When you look up the schema for a given impl
* object or class you supply a version number. If a schema for that version doesn't
* exist then the versions are searched in reverse order. For example, if you ask for
* version 5 and the highest schema version for that impl class is 3 then V3 will be returned.
* This allows us to move to higher versions without having to write gratuitous new schema
* classes for the things that haven't changed in the new version.
* <p>
* The current version can be found by calling
* Schema.getHighestSupportedVersion(). For schemas that are still in flux
* because development is ongoing we also support an EXPERIMENTAL_VERSION, which
* indicates that there are no interface stability guarantees between H2O versions.
* Eventually these schemas will move to a normal, stable version number. Call
* Schema.getExperimentalVersion() to find the experimental version number (99 as
* of this writing).
* <p>
* Schema names must be unique within an application in a single namespace. The
* class getSimpleName() is used as the schema name. During Schema discovery and
* registration there are checks to ensure that the names are unique.
* <p>
* Most schemas have a 1-to-1 mapping to an Iced implementation object, aka the "impl"
* or implementation class. This class is specified as a type parameter to the Schema class.
* This type parameter is used by reflection magic to avoid a large amount of boilerplate
* code.
* <p>
* Both the Schema and the Iced object may have children, or (more often) not.
* Occasionally, e.g. in the case of schemas used only to handle HTTP request
* parameters, there will not be a backing impl object and the Schema will be
* parameterized by Iced.
* <p>
* Other than Schemas backed by Iced this 1-1 mapping is enforced: a check at Schema
* registration time ensures that at most one Schema is registered for each Iced class.
* This 1-1 mapping allows us to have generic code here in the Schema class which does
* all the work for common cases. For example, one can write code which accepts any
* Schema instance and creates and fills an instance of its associated impl class:
* {@code
* I impl = schema.createAndFillImpl();
* }
* <p>
* Schemas have a State section (broken into Input, Output and InOut fields)
* and an Adapter section. The adapter methods fill the State to and from the
* Iced impl objects and from HTTP request parameters. In the simple case, where
* the backing object corresponds 1:1 with the Schema and no adapting need be
* done, the methods here in the Schema class will do all the work based on
* reflection. In that case your Schema need only contain the fields you wish
* to expose, and no adapter code.
* <p>
* Methods here allow us to convert from Schema to Iced (impl) and back in a
* flexible way. The default behaviour is to map like-named fields back and
* forth, often with some default type conversions (e.g., a Keyed object like a
* Model will be automagically converted back and forth to a Key).
* Subclasses can override methods such as fillImpl or fillFromImpl to
* provide special handling when adapting from schema to impl object and back.
* Usually they will want to call super to get the default behavior, and then
* modify the results a bit (e.g., to map differently-named fields, or to
* compute field values).
* <p>
* Schema Fields must have a single @API annotation describing their direction
* of operation and any other properties such as "required". Fields are
* API.Direction.INPUT by default. Transient and static fields are ignored.
* <p>
* Most Java developers need not be concerned with the details that follow, because the
* framework will make these calls as necessary.
* <p>
* Some use cases:
* <p>
* To find and create an instance of the appropriate schema for an Iced object, with the
* given version or the highest previous version:<pre>
* Schema s = Schema.schema(6, impl);
* </pre>
* <p>
* To create a schema object and fill it from an existing impl object (the common case):<pre>
* S schema = MySchemaClass(version).fillFromImpl(impl);</pre>
* or more generally:
* <pre>
* S schema = Schema(version, impl).fillFromImpl(impl);</pre>
* To create an impl object and fill it from an existing schema object (the common case):
* <pre>
* I impl = schema.createImpl(); // create an empty impl object and any empty children
* schema.fillImpl(impl); // fill the empty impl object and any children from the Schema and its children</pre>
* or
* <pre>
* I impl = schema.createAndFillImpl(); // helper which does schema.fillImpl(schema.createImpl())</pre>
* <p>
* Schemas that are used for HTTP requests are filled with the default values of their impl
* class, and then any present HTTP parameters override those default values.
* <p>
* To create a schema object filled from the default values of its impl class and then
* overridden by HTTP request params:
* <pre>
* S schema = MySchemaClass(version);
* I defaults = schema.createImpl();
* schema.fillFromImpl(defaults);
* schema.fillFromParms(parms);
* </pre>
* or more tersely:
* <pre>
* S schema = MySchemaClass(version).fillFromImpl(schema.createImpl()).fillFromParms(parms);
* </pre>
* @see Meta#getSchema_version()
* @see Meta#getSchema_name()
* @see Meta#getSchema_type()
* @see water.api.API
*/
public class Schema<I extends Iced, S extends Schema<I,S>> extends Iced {
private transient Class<I> _impl_class = getImplClass(); // see getImplClass()
private static final int HIGHEST_SUPPORTED_VERSION = 3;
private static final int EXPERIMENTAL_VERSION = 99;
/**
* Metadata for a Schema, including the version, name and type. This information is included in all REST API
* responses as a field in the Schema so that the payloads are self-describing, and it is also available through
* the /Metadata/schemas REST API endpoint for the purposes of REST service discovery.
*/
public static final class Meta extends Iced {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CAREFUL: This class has its own JSON serializer. If you add a field here you probably also want to add it to the serializer!
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that
* there are no stability guarantees between H2O versions.
*/
@API(help="Version number of this Schema. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT)
private int schema_version;
/** Get the simple schema (class) name, for example DeepLearningParametersV3. Must not be changed after creation (treat as final). */
@API(help="Simple name of this Schema. NOTE: the schema_names form a single namespace.", direction=API.Direction.OUTPUT)
private String schema_name;
/** Get the simple name of H2O type that this Schema represents, for example DeepLearningParameters. */
@API(help="Simple name of H2O type that this Schema represents. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT)
private String schema_type; // subclasses can redefine this
/** Default constructor used only for newInstance() in generic reflection-based code. */
public Meta() {}
/** Standard constructor which supplies all the fields. The fields should be treated as immutable once set. */
public Meta(int version, String name, String type) {
this.schema_version = version;
this.schema_name = name;
this.schema_type = type;
}
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version,
* meaning that there are no stability guarantees between H2O versions.
*/
public int getSchema_version() {
return schema_version;
}
/** Get the simple schema (class) name, for example DeepLearningParametersV3. */
public String getSchema_name() {
return schema_name;
}
/** Get the simple name of the H2O type that this Schema represents, for example DeepLearningParameters. */
public String getSchema_type() {
return schema_type;
}
/** Set the simple name of the H2O type that this Schema represents, for example Key<Frame>. NOTE: using this is a hack and should be avoided. */
protected void setSchema_type(String schema_type) {
this.schema_type = schema_type;
}
// TODO: make private in Iced:
/** Override the JSON serializer to prevent a recursive loop in AutoBuffer. User code should not call this, and soon it should be made protected. */
@Override
public final water.AutoBuffer writeJSON_impl(water.AutoBuffer ab) {
// Overridden because otherwise we get in a recursive loop trying to serialize this$0.
ab.putJSON4("schema_version", schema_version)
.put1(',').putJSONStr("schema_name", schema_name)
.put1(',').putJSONStr("schema_type", schema_type);
return ab;
}
}
@API(help="Metadata on this schema instance, to make it self-describing.", direction=API.Direction.OUTPUT)
private Meta __meta = null;
/** Get the metadata for this schema instance which makes it self-describing when serialized to JSON. */
protected Meta get__meta() {
return __meta;
}
// Registry which maps a simple schema name to its class. NOTE: the simple names form a single namespace.
// E.g., "DeepLearningParametersV2" -> hex.schemas.DeepLearningV2.DeepLearningParametersV2
private static Map<String, Class<? extends Schema>> schemas = new HashMap<>();
// Registry which maps a Schema simpleName to its Iced Class.
// E.g., "DeepLearningParametersV2" -> hex.deeplearning.DeepLearning.DeepLearningParameters
private static Map<String, Class<? extends Iced>> schema_to_iced = new HashMap<>();
// Registry which maps an Iced simpleName (type) and schema_version to its Schema Class.
// E.g., (DeepLearningParameters, 2) -> "DeepLearningParametersV2"
//
// Note that iced_to_schema gets lazily filled if a higher version is asked for than is
// available (e.g., if the highest version of Frame is FrameV2 and the client asks for
// the schema for (Frame, 17) then FrameV2 will be returned, and all the mappings between
// 17 and 3 will get added to the Map.
private static Map<Pair<String, Integer>, Class<? extends Schema>> iced_to_schema = new HashMap<>();
/**
* Default constructor; triggers lazy schema registration.
* @throws water.exceptions.H2OFailException if there is a name collision or there is more than one schema which maps to the same Iced class
*/
public Schema() {
String name = this.getClass().getSimpleName();
int version = extractVersion(name);
String type = _impl_class.getSimpleName();
__meta = new Meta(version, name, type);
if (null == schema_to_iced.get(name)) {
Log.debug("Registering schema: " + name + " schema_version: " + version + " with Iced class: " + _impl_class.toString());
if (null != schemas.get(name))
throw H2O.fail("Found a duplicate schema name in two different packages: " + schemas.get(name) + " and: " + this.getClass().toString());
schemas.put(name, this.getClass());
schema_to_iced.put(name, _impl_class);
if (_impl_class != Iced.class) {
Pair versioned = new Pair(type, version);
// Check for conflicts
if (null != iced_to_schema.get(versioned)) {
throw H2O.fail("Found two schemas mapping to the same Iced class with the same version: " + iced_to_schema.get(versioned) + " and: " + this.getClass().toString() + " both map to version: " + version + " of Iced class: " + _impl_class);
}
iced_to_schema.put(versioned, this.getClass());
}
}
}
private static Pattern _version_pattern = null;
/** Extract the version number from the schema class name. Returns -1 if there's no version number at the end of the classname. */
private static int extractVersion(String clz_name) {
if (null == _version_pattern) // can't just use a static initializer
_version_pattern = Pattern.compile(".*V(\\d+)");
Matcher m = _version_pattern.matcher(clz_name);
if (! m.matches()) return -1;
return Integer.valueOf(m.group(1));
}
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that
* there are no stability guarantees between H2O versions.
*/
public int getSchemaVersion() {
return __meta.schema_version;
}
private static int latest_version = -1;
/**
* Get the highest schema version number that we've encountered during schema registration.
*/
public final static int getLatestVersion() {
return latest_version;
}
/**
* Get the highest schema version that we support. This bounds the search for a schema if we haven't yet
* registered all schemas and don't yet know the latest_version.
*/
public final static int getHighestSupportedVersion() {
return HIGHEST_SUPPORTED_VERSION;
}
/**
* Get the experimental schema version, which indicates that a schema is not guaranteed stable between H2O releases.
*/
public final static int getExperimentalVersion() {
return EXPERIMENTAL_VERSION;
}
/**
* Register the given schema class.
* @throws water.exceptions.H2OFailException if there is a name collision, if the type parameters are bad, or if the version is bad
*/
private static void register(Class<? extends Schema> clz) {
synchronized(clz) {
// Was there a race to get here? If so, return.
Class<? extends Schema> existing = schemas.get(clz.getSimpleName());
if (null != existing) {
if (clz != existing)
throw H2O.fail("Two schema classes have the same simpleName; this is not supported: " + clz + " and " + existing + ".");
return;
}
// Check that the Schema has the correct type parameters:
if (clz.getGenericSuperclass() instanceof ParameterizedType) {
Type[] schema_type_parms = ((ParameterizedType) (clz.getGenericSuperclass())).getActualTypeArguments();
if (schema_type_parms.length < 2)
throw H2O.fail("Found a Schema that does not pass at least two type parameters. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz);
Class parm0 = ReflectionUtils.findActualClassParameter(clz, 0);
if (!Iced.class.isAssignableFrom(parm0))
throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Iced. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0);
if (Schema.class.isAssignableFrom(parm0))
throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0);
Class parm1 = ReflectionUtils.findActualClassParameter(clz, 1);
if (!Schema.class.isAssignableFrom(parm1))
throw H2O.fail("Found a Schema with bad type parameters. Second parameter is not a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm1);
} else {
throw H2O.fail("Found a Schema that does not have a parameterized superclass. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz);
}
int version = extractVersion(clz.getSimpleName());
if (version > getHighestSupportedVersion() && version != EXPERIMENTAL_VERSION)
throw H2O.fail("Found a schema with a version higher than the highest supported version; you probably want to bump the highest supported version: " + clz);
// NOTE: we now allow non-versioned schemas, for example base classes like ModelMetricsBase, so that we can fetch the metadata for them.
if (version > -1 && version != EXPERIMENTAL_VERSION) {
// Track highest version of all schemas; only valid after all are registered at startup time.
if (version > HIGHEST_SUPPORTED_VERSION)
throw H2O.fail("Found a schema with a version greater than the highest supported version of: " + getHighestSupportedVersion() + ": " + clz);
if (version > latest_version) {
synchronized (Schema.class) {
if (version > latest_version) latest_version = version;
}
}
}
Schema s = null;
try {
s = clz.newInstance();
} catch (Exception e) {
Log.err("Failed to instantiate schema class: " + clz + " because: " + e);
}
if (null != s) {
Log.debug("Registered Schema: " + clz.getSimpleName());
// Validate the fields:
SchemaMetadata meta = new SchemaMetadata(s);
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
String name = field_meta.name;
if ("__meta".equals(name) || "__http_status".equals(name) || "_exclude_fields".equals(name) || "_include_fields".equals(name))
continue;
if ("Gini".equals(name)) // proper name
continue;
if (name.endsWith("AUC")) // trainAUC, validAUC
continue;
// TODO: remove after we move these into a TwoDimTable:
if ("F0point5".equals(name) || "F0point5_for_criteria".equals(name) || "F1_for_criteria".equals(name) || "F2_for_criteria".equals(name))
continue;
if (name.startsWith("_"))
Log.warn("Found schema field which violates the naming convention; name starts with underscore: " + meta.name + "." + name);
if (!name.equals(name.toLowerCase()) && !name.equals(name.toUpperCase())) // allow AUC but not residualDeviance
Log.warn("Found schema field which violates the naming convention; name has mixed lowercase and uppercase characters: " + meta.name + "." + name);
}
}
}
}
/**
* Create an appropriate implementation object and any child objects but does not fill them.
* The standard purpose of a createImpl without a fillImpl is to be able to get the default
* values for all the impl's fields.
* <p>
* For objects without children this method does all the required work. For objects
* with children the subclass will need to override, e.g. by calling super.createImpl()
* and then calling createImpl() on its children.
* <p>
* Note that impl objects for schemas which override this method don't need to have
* a default constructor (e.g., a Keyed object constructor can still create and set
* the Key), but they must not fill any fields which can be filled later from the schema.
* <p>
* TODO: We could handle the common case of children with the same field names here
* by finding all of our fields that are themselves Schemas.
* @throws H2OIllegalArgumentException if Class.newInstance fails
*/
public I createImpl() {
try {
return this.getImplClass().newInstance();
}
catch (Exception e) {
String msg = "Exception instantiating implementation object of class: " + this.getImplClass().toString() + " for schema class: " + this.getClass();
Log.err(msg + ": " + e);
H2OIllegalArgumentException heae = new H2OIllegalArgumentException(msg);
heae.initCause(e);
throw heae;
}
}
/** Fill an impl object and any children from this schema and its children. If a schema doesn't need to adapt any fields if does not need to override this method. */
public I fillImpl(I impl) {
PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove
PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES);
return impl;
}
/** Convenience helper which creates and fills an impl object from this schema. */
final public I createAndFillImpl() {
return this.fillImpl(this.createImpl());
}
/** Fill this Schema from the given implementation object. If a schema doesn't need to adapt any fields if does not need to override this method. */
public S fillFromImpl(I impl) {
PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES);
PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove
return (S)this;
}
/** Return the class of the implementation type parameter I for the given Schema class. Used by the metadata facilities and the reflection-base field-copying magic in PojoUtils. */
public static Class<? extends Iced> getImplClass(Class<? extends Schema> clz) {
Class<? extends Iced> impl_class = (Class<? extends Iced>)ReflectionUtils.findActualClassParameter(clz, 0);
if (null == impl_class)
Log.warn("Failed to find an impl class for Schema: " + clz);
return impl_class;
}
/** Return the class of the implementation type parameter I for this Schema. Used by generic code which deals with arbitrary schemas and their backing impl classes. */
public Class<I> getImplClass() {
if (null == _impl_class)
_impl_class = (Class<I>) ReflectionUtils.findActualClassParameter(this.getClass(), 0);
if (null == _impl_class)
Log.warn("Failed to find an impl class for Schema: " + this.getClass());
return _impl_class;
}
/**
* Fill this Schema object from a set of parameters.
*
* @param parms parameters - set of tuples (parameter name, parameter value)
* @return this schema
*
* @see #fillFromParms(Properties, boolean)
*/
public S fillFromParms(Properties parms) {
return fillFromParms(parms, true);
}
/**
* Fill this Schema from a set of (generally HTTP) parameters.
* <p>
* Using reflection this process determines the type of the target field and
* conforms the types if possible. For example, if the field is a Keyed type
* the name (ID) will be looked up in the DKV and mapped appropriately.
* <p>
* The process ignores parameters which are not fields in the schema, and it
* verifies that all fields marked as required are present in the parameters
* list.
* <p>
* It also does various sanity checks for broken Schemas, for example fields must
* not be private, and since input fields get filled here they must not be final.
* @param parms Properties map of parameter values
* @param checkRequiredFields perform check for missing required fields
* @return this schema
* @throws H2OIllegalArgumentException for bad/missing parameters
*/
public S fillFromParms(Properties parms, boolean checkRequiredFields) {
// Get passed-in fields, assign into Schema
Class thisSchemaClass = this.getClass();
Map<String, Field> fields = new HashMap<>();
Field current = null; // declare here so we can print in catch{}
try {
Class clz = thisSchemaClass;
do {
Field[] some_fields = clz.getDeclaredFields();
for (Field f : some_fields) {
current = f;
if (null == fields.get(f.getName()))
fields.put(f.getName(), f);
}
clz = clz.getSuperclass();
} while (Iced.class.isAssignableFrom(clz.getSuperclass()));
}
catch (SecurityException e) {
throw H2O.fail("Exception accessing field: " + current + " in class: " + this.getClass() + ": " + e);
}
for( String key : parms.stringPropertyNames() ) {
try {
Field f = fields.get(key); // No such field error, if parm is junk
if (null == f) {
throw new H2OIllegalArgumentException("Unknown parameter: " + key, "Unknown parameter in fillFromParms: " + key + " for class: " + this.getClass().toString());
}
int mods = f.getModifiers();
if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) {
// Attempting to set a transient or static; treat same as junk fieldname
throw new H2OIllegalArgumentException(
"Bad parameter for field: " + key + " for class: " + this.getClass().toString(),
"Bad parameter definition for field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was declared static or transient)");
}
// Only support a single annotation which is an API, and is required
API api = (API)f.getAnnotations()[0];
// Must have one of these set to be an input field
if( api.direction() == API.Direction.OUTPUT ) {
throw new H2OIllegalArgumentException(
"Attempting to set output field: " + key + " for class: " + this.getClass().toString(),
"Attempting to set output field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was annotated as API.Direction.OUTPUT)");
}
// Parse value and set the field
setField(this, f, key, parms.getProperty(key), api.required(), thisSchemaClass);
} catch( ArrayIndexOutOfBoundsException aioobe ) {
// Come here if missing annotation
throw H2O.fail("Broken internal schema; missing API annotation for field: " + key);
} catch( IllegalAccessException iae ) {
// Come here if field is final or private
throw H2O.fail("Broken internal schema; field cannot be private nor final: " + key);
}
}
// Here every thing in 'parms' was set into some field - so we have already
// checked for unknown or extra parms.
// Confirm required fields are set
if (checkRequiredFields) {
for (Field f : fields.values()) {
int mods = f.getModifiers();
if (Modifier.isTransient(mods) || Modifier.isStatic(mods))
continue; // Ignore transient & static
try {
API
api =
(API) f.getAnnotations()[0]; // TODO: is there a more specific way we can do this?
if (api.required()) {
if (parms.getProperty(f.getName()) == null) {
IcedHashMap.IcedHashMapStringObject
values =
new IcedHashMap.IcedHashMapStringObject();
values.put("schema", this.getClass().getSimpleName());
values.put("argument", f.getName());
throw new H2OIllegalArgumentException(
"Required field " + f.getName() + " not specified",
"Required field " + f.getName() + " not specified for schema class: " + this
.getClass(),
values);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw H2O.fail("Missing annotation for API field: " + f.getName());
}
}
}
return (S) this;
}
/**
* Safe method to set the field on given schema object
* @param o schema object to modify
* @param f field to modify
* @param key name of field to modify
* @param value string-based representation of value to set
* @param required is field required by API
* @param thisSchemaClass class of schema handling this (can be null)
* @throws IllegalAccessException
*/
public static <T extends Schema> void setField(T o, Field f, String key, String value, boolean required, Class thisSchemaClass) throws IllegalAccessException {
// Primitive parse by field type
Object parse_result = parse(key, value, f.getType(), required, thisSchemaClass);
if (parse_result != null && f.getType().isArray() && parse_result.getClass().isArray() && (f.getType().getComponentType() != parse_result.getClass().getComponentType())) {
// We have to conform an array of primitives. There's got to be a better way. . .
if (parse_result.getClass().getComponentType() == int.class && f.getType().getComponentType() == Integer.class) {
int[] from = (int[])parse_result;
Integer[] copy = new Integer[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Integer.class && f.getType().getComponentType() == int.class) {
Integer[] from = (Integer[])parse_result;
int[] copy = new int[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Double.class && f.getType().getComponentType() == double.class) {
Double[] from = (Double[])parse_result;
double[] copy = new double[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Float.class && f.getType().getComponentType() == float.class) {
Float[] from = (Float[])parse_result;
float[] copy = new float[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else {
throw H2O.fail("Don't know how to cast an array of: " + parse_result.getClass().getComponentType() + " to an array of: " + f.getType().getComponentType());
}
} else {
f.set(o, parse_result);
}
}
static <E> Object parsePrimitve(String s, Class fclz) {
if (fclz.equals(String.class)) return s; // Strings already the right primitive type
if (fclz.equals(int.class)) return parseInteger(s, int.class);
if (fclz.equals(long.class)) return parseInteger(s, long.class);
if (fclz.equals(short.class)) return parseInteger(s, short.class);
if (fclz.equals(boolean.class)) {
if (s.equals("0")) return Boolean.FALSE;
if (s.equals("1")) return Boolean.TRUE;
return Boolean.valueOf(s);
}
if (fclz.equals(byte.class)) return parseInteger(s, byte.class);
if (fclz.equals(double.class)) return Double.valueOf(s);
if (fclz.equals(float.class)) return Float.valueOf(s);
//FIXME: if (fclz.equals(char.class)) return Character.valueOf(s);
throw H2O.fail("Unknown primitive type to parse: " + fclz.getSimpleName());
}
// URL parameter parse
static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) {
if (fclz.isPrimitive() || String.class.equals(fclz)) {
try {
return parsePrimitve(s, fclz);
} catch (NumberFormatException ne) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
throw new H2OIllegalArgumentException(msg);
}
}
// An array?
if (fclz.isArray()) {
// Get component type
Class<E> afclz = (Class<E>) fclz.getComponentType();
// Result
E[] a = null;
// Handle simple case with null-array
if (s.equals("null") || s.length() == 0) return null;
// Splitted values
String[] splits; // "".split(",") => {""} so handle the empty case explicitly
if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array
read(s, 0, '[', fclz);
read(s, s.length() - 1, ']', fclz);
String inside = s.substring(1, s.length() - 1).trim();
if (inside.length() == 0)
splits = new String[]{};
else
splits = splitArgs(inside);
} else { // Lets try to parse single value as an array!
// See PUBDEV-1955
splits = new String[] { s.trim() };
}
// Can't cast an int[] to an Object[]. Sigh.
if (afclz == int.class) { // TODO: other primitive types. . .
a = (E[]) Array.newInstance(Integer.class, splits.length);
} else if (afclz == double.class) {
a = (E[]) Array.newInstance(Double.class, splits.length);
} else if (afclz == float.class) {
a = (E[]) Array.newInstance(Float.class, splits.length);
} else {
// Fails with primitive classes; need the wrapper class. Thanks, Java.
a = (E[]) Array.newInstance(afclz, splits.length);
}
for (int i = 0; i < splits.length; i++) {
if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) {
// strip quotes off string values inside array
String stripped = splits[i].trim();
if ("null".equals(stripped)) {
a[i] = null;
} else if (!stripped.startsWith("\"") || !stripped.endsWith("\"")) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": string and key arrays' values must be double quoted, but the client sent: " + stripped;
IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject();
values.put("function", fclz.getSimpleName() + ".fillFromParms()");
values.put("argument", field_name);
values.put("value", stripped);
throw new H2OIllegalArgumentException(msg, msg, values);
}
stripped = stripped.substring(1, stripped.length() - 1);
a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass);
} else {
a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass);
}
}
return a;
}
if (fclz.equals(Key.class))
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else
return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes.
if (KeyV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
if (!required && (s == null || s.length() == 0)) return null;
return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes.
}
if (Enum.class.isAssignableFrom(fclz))
return Enum.valueOf(fclz, s); // TODO: try/catch needed!
// TODO: these can be refactored into a single case using the facilities in Schema:
if (FrameV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass());
return new FrameV3((Frame) v.get()); // TODO: version!
}
}
if (JobV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass());
return new JobV3().fillFromImpl((Job) v.get()); // TODO: version!
}
}
// TODO: for now handle the case where we're only passing the name through; later we need to handle the case
// where the frame name is also specified.
if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) {
return new FrameV3.ColSpecifierV3(s);
}
if (ModelSchema.class.isAssignableFrom(fclz))
throw H2O.fail("Can't yet take ModelSchema as input.");
/*
if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key");
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object.");
return v.get();
}
*/
throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName());
} // parse()
/**
* Helper functions for parse()
**/
/**
* Parses a string into an integer data type specified by parameter return_type. Accepts any format that
* is accepted by java's BigDecimal class.
* - Throws a NumberFormatException if the evaluated string is not an integer or if the value is too large to
* be stored into return_type without overflow.
* - Throws an IllegalAgumentException if return_type is not an integer data type.
**/
static private <T> T parseInteger(String s, Class<T> return_type) {
try {
java.math.BigDecimal num = new java.math.BigDecimal(s);
T result = (T) num.getClass().getDeclaredMethod(return_type.getSimpleName() + "ValueExact", new Class[0]).invoke(num);
return result;
} catch (InvocationTargetException ite) {
throw new NumberFormatException("The expression's numeric value is out of the range of type " + return_type.getSimpleName());
} catch (NoSuchMethodException nsme) {
throw new IllegalArgumentException(return_type.getSimpleName() + " is not an integer data type");
} catch (IllegalAccessException iae) {
throw H2O.fail("Cannot parse expression as " + return_type.getSimpleName() + " (Illegal Access)");
}
}
static private int read( String s, int x, char c, Class fclz ) {
if( peek(s,x,c) ) return x+1;
throw new IllegalArgumentException("Expected '"+c+"' while reading a "+fclz.getSimpleName()+", but found "+s);
}
static private boolean peek( String s, int x, char c ) { return x < s.length() && s.charAt(x) == c; }
// Splits on commas, but ignores commas in double quotes. Required
// since using a regex blow the stack on long column counts
// TODO: detect and complain about malformed JSON
private static String[] splitArgs(String argStr) {
StringBuffer sb = new StringBuffer (argStr);
StringBuffer arg = new StringBuffer ();
List<String> splitArgList = new ArrayList<String> ();
boolean inDoubleQuotes = false;
boolean inSquareBrackets = false; // for arrays of arrays
for (int i=0; i < sb.length(); i++) {
if (sb.charAt(i) == '"' && !inDoubleQuotes && !inSquareBrackets) {
inDoubleQuotes = true;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == '"' && inDoubleQuotes && !inSquareBrackets) {
inDoubleQuotes = false;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == ',' && !inDoubleQuotes && !inSquareBrackets) {
splitArgList.add(arg.toString());
// clear the field for next word
arg.setLength(0);
} else if (sb.charAt(i) == '[') {
inSquareBrackets = true;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == ']') {
inSquareBrackets = false;
arg.append(sb.charAt(i));
} else {
arg.append(sb.charAt(i));
}
}
if (arg.length() > 0)
splitArgList.add(arg.toString());
return splitArgList.toArray(new String[splitArgList.size()]);
}
private static boolean schemas_registered = false;
/**
* Find all schemas using reflection and register them.
*/
synchronized static public void registerAllSchemasIfNecessary() {
if (schemas_registered) return;
// if (!Paxos._cloudLocked) return; // TODO: It's never getting locked. . . :-(
long before = System.currentTimeMillis();
// Microhack to effect Schema.register(Schema.class), which is
// normally not allowed because it has no version:
new Schema();
String[] packages = new String[] { "water", "hex", /* Disallow schemas whose parent is in another package because it takes ~4s to do the getSubTypesOf call: "" */};
// For some reason when we're run under Hadoop Reflections is failing to find some of the classes unless we're extremely explicit here:
Class<? extends Schema> clzs[] = new Class[] { Schema.class, ModelBuilderSchema.class, ModelSchema.class, ModelOutputSchema.class, ModelParametersSchema.class };
for (String pkg : packages) {
Reflections reflections = new Reflections(pkg);
for (Class<? extends Schema> clz : clzs) {
// NOTE: Reflections sees ModelOutputSchema but not ModelSchema. Another bug to work around:
Log.debug("Registering: " + clz.toString() + " in package: " + pkg);
if (!Modifier.isAbstract(clz.getModifiers()))
Schema.register(clz);
// Register the subclasses:
Log.debug("Registering subclasses of: " + clz.toString() + " in package: " + pkg);
for (Class<? extends Schema> schema_class : reflections.getSubTypesOf(clz))
if (!Modifier.isAbstract(schema_class.getModifiers()))
Schema.register(schema_class);
}
}
schemas_registered = true;
Log.info("Registered: " + Schema.schemas().size() + " schemas in: " + (System.currentTimeMillis() - before) + "mS");
}
/**
* Return an immutable Map of all the schemas: schema_name -> schema Class.
*/
protected static Map<String, Class<? extends Schema>> schemas() {
return Collections.unmodifiableMap(new HashMap<>(schemas));
}
/**
* For a given version and Iced class return the appropriate Schema class, if any.f
* @see #schemaClass(int, java.lang.String)
*/
protected static Class<? extends Schema> schemaClass(int version, Class<? extends Iced> impl_class) {
return schemaClass(version, impl_class.getSimpleName());
}
/**
* For a given version and type (Iced class simpleName) return the appropriate Schema
* class, if any.
* <p>
* If a higher version is asked for than is available (e.g., if the highest version of
* Frame is FrameV2 and the client asks for the schema for (Frame, 17) then FrameV2 will
* be returned. This compatibility lookup is cached.
*/
private static Class<? extends Schema> schemaClass(int version, String type) {
if (version < 1) return null;
Class<? extends Schema> clz = iced_to_schema.get(new Pair(type, version));
if (null != clz) return clz; // found!
clz = schemaClass(version - 1, type);
if (null != clz) iced_to_schema.put(new Pair(type, version), clz); // found a lower-numbered schema: cache
return clz;
}
/**
* For a given version and Iced object return an appropriate Schema instance, if any.
* @see #schema(int, java.lang.String)
*/
public static Schema schema(int version, Iced impl) {
return schema(version, impl.getClass().getSimpleName());
}
/**
* For a given version and Iced class return an appropriate Schema instance, if any.
* @throws H2OIllegalArgumentException if Class.newInstance() throws
* @see #schema(int, java.lang.String)
*/
public static Schema schema(int version, Class<? extends Iced> impl_class) {
return schema(version, impl_class.getSimpleName());
}
// FIXME: can be parameterized by type: public static <T extends Schema> T newInstance(Class<T> clz)
public static <T extends Schema> T newInstance(Class<T> clz) {
T s = null;
try {
s = clz.newInstance();
}
catch (Exception e) {
throw new H2OIllegalArgumentException("Failed to instantiate schema of class: " + clz.getCanonicalName() + ", cause: " + e);
}
return s;
}
/**
* For a given version and type (Iced class simpleName) return an appropriate new Schema
* object, if any.
* <p>
* If a higher version is asked for than is available (e.g., if the highest version of
* Frame is FrameV2 and the client asks for the schema for (Frame, 17) then an instance
* of FrameV2 will be returned. This compatibility lookup is cached.
* @throws H2ONotFoundArgumentException if an appropriate schema is not found
*/
private static Schema schema(int version, String type) {
Class<? extends Schema> clz = schemaClass(version, type);
if (null == clz)
clz = schemaClass(Schema.getExperimentalVersion(), type);
if (null == clz)
throw new H2ONotFoundArgumentException("Failed to find schema for version: " + version + " and type: " + type,
"Failed to find schema for version: " + version + " and type: " + type);
return Schema.newInstance(clz);
}
/**
* For a given schema_name (e.g., "FrameV2") return an appropriate new schema object (e.g., a water.api.Framev2).
* @throws H2ONotFoundArgumentException if an appropriate schema is not found
*/
protected static Schema newInstance(String schema_name) {
Class<? extends Schema> clz = schemas.get(schema_name);
if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for schema_name: " + schema_name,
"Failed to find schema for schema_name: " + schema_name);
return Schema.newInstance(clz);
}
/**
* Generate Markdown documentation for this Schema possibly including only the input or output fields.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) {
return markdown(new SchemaMetadata(this), appendToMe, include_input_fields, include_output_fields);
}
/**
* Append Markdown documentation for another Schema, given we already have the metadata constructed.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(SchemaMetadata meta, StringBuffer appendToMe) {
return markdown(meta, appendToMe, true, true);
}
/**
* Generate Markdown documentation for this Schema, given we already have the metadata constructed.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(SchemaMetadata meta , StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) {
MarkdownBuilder builder = new MarkdownBuilder();
builder.comment("Preview with http://jbt.github.io/markdown-editor");
builder.heading1("schema ", this.getClass().getSimpleName());
builder.hline();
// builder.paragraph(metadata.summary);
// TODO: refactor with Route.markdown():
// fields
boolean first; // don't print the table at all if there are no rows
try {
if (include_input_fields) {
first = true;
builder.heading2("input fields");
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
if (field_meta.direction == API.Direction.INPUT || field_meta.direction == API.Direction.INOUT) {
if (first) {
builder.tableHeader("name", "required?", "level", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
first = false;
}
builder.tableRow(
field_meta.name,
String.valueOf(field_meta.required),
field_meta.level.name(),
field_meta.type,
String.valueOf(field_meta.is_schema),
field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // Something better for toString()?
field_meta.help,
(field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
(field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
(field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with))
);
}
}
if (first)
builder.paragraph("(none)");
}
if (include_output_fields) {
first = true;
builder.heading2("output fields");
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
if (field_meta.direction == API.Direction.OUTPUT || field_meta.direction == API.Direction.INOUT) {
if (first) {
builder.tableHeader("name", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
first = false;
}
builder.tableRow(
field_meta.name,
field_meta.type,
String.valueOf(field_meta.is_schema),
field_meta.is_schema ? field_meta.schema_name : "",
(null == field_meta.value ? "(null)" : field_meta.value.toString()), // something better than toString()?
field_meta.help,
(field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
(field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
(field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with)));
}
}
if (first)
builder.paragraph("(none)");
}
// TODO: render examples and other stuff, if it's passed in
}
catch (Exception e) {
IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject();
values.put("schema", this);
// TODO: This isn't quite the right exception type:
throw new H2OIllegalArgumentException("Caught exception using reflection on schema: " + this,
"Caught exception using reflection on schema: " + this + ": " + e,
values);
}
if (null != appendToMe)
appendToMe.append(builder.stringBuffer());
return builder.stringBuffer();
} // markdown()
}
| madmax983/h2o-3 | h2o-core/src/main/java/water/api/Schema.java | Java | apache-2.0 | 52,870 |
package eu.uqasar.model.measure;
/*
* #%L
* U-QASAR
* %%
* Copyright (C) 2012 - 2015 U-QASAR Consortium
* %%
* 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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.wicket.model.IModel;
import eu.uqasar.util.resources.IResourceKeyProvider;
import eu.uqasar.util.resources.ResourceBundleLocator;
public enum MetricSource implements IResourceKeyProvider {
TestingFramework("test"),
IssueTracker("issue"),
StaticAnalysis("static"),
ContinuousIntegration("ci"),
CubeAnalysis("cube"),
VersionControl("vcs"),
Manual("manual"),
;
private final String labelKey;
MetricSource(final String labelKey) {
this.labelKey = labelKey;
}
public String toString() {
return getLabelModel().getObject();
}
public IModel<String> getLabelModel() {
return ResourceBundleLocator.getLabelModel(this.getClass(), this);
}
@Override
public String getKey() {
return "label.source." + this.labelKey;
}
public static List<MetricSource> getAllMetricSources(){
List<MetricSource> list = new ArrayList<>();
Collections.addAll(list, MetricSource.values());
return list;
}
}
| U-QASAR/u-qasar.platform | src/main/java/eu/uqasar/model/measure/MetricSource.java | Java | apache-2.0 | 1,796 |
package com.feiyu.storm.streamingdatacollection.spout;
/**
* from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/src/jvm/storm/starter/spout/RandomSentenceSpout.java
* modified by feiyu
*/
import java.util.Map;
import java.util.Random;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
@SuppressWarnings("serial")
public class ForTestFakeSpout extends BaseRichSpout {
private SpoutOutputCollector _collector;
private Random _rand;
@SuppressWarnings("rawtypes")
@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
_collector = collector;
_rand = new Random();
}
@Override
public void nextTuple() {
Utils.sleep(5000);
String[] tweets = new String[]{
"I rated X-Men: Days of Future Past 8/10 #IMDb http://www.imdb.com/title/tt1877832",
"I rated Game of Thrones 10/10 #IMDb http://www.imdb.com/title/tt0944947",
"I rated Snowpiercer 7/10 #IMDb really enjoyed this. Beautifully shot & choreographed. Great performance from Swinton http://www.imdb.com/title/tt1706620",
"Back on form. That ending = awesome! - I rated X-Men: Days of Future Past 7/10 #IMDb http://www.imdb.com/title/tt1877832",
"A great movie especially for those trying to learn German ~> I rated Run Lola Run 8/10 #IMDb http://www.imdb.com/title/tt0130827",
"I rated Breaking Bad 8/10 #IMDb :: I would say 7 but last season made it worth it... Matter of taste @mmelgarejoc http://www.imdb.com/title/tt0903747",
"I rated White House Down 7/10 #IMDb bunch of explosions and one liners, fun for all http://www.imdb.com/title/tt2334879"
};
String tweet = tweets[_rand.nextInt(tweets.length)];
_collector.emit(new Values(tweet));
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("tweet"));
}
}
| faustineinsun/WiseCrowdRec | deprecated-wisecrowdrec-springmvc/WiseCrowdRec/src/main/java/com/feiyu/storm/streamingdatacollection/spout/ForTestFakeSpout.java | Java | apache-2.0 | 2,356 |
/*
* Copyright 2016 Axibase Corporation or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* https://www.axibase.com/atsd/axibase-apache-2.0.pdf
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.axibase.tsd.model.meta;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Map;
@Data
/* Use chained setters that return this instead of void */
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class EntityAndTags {
@JsonProperty("entity")
private String entityName;
private Long lastInsertTime;
@JsonProperty
private Map<String, String> tags;
}
| axibase/atsd-api-java | src/main/java/com/axibase/tsd/model/meta/EntityAndTags.java | Java | apache-2.0 | 1,151 |
package br.com.ceducarneiro.analisadorsintatico;
public class LexException extends Exception {
private char badCh;
private int line, column;
public LexException(int line, int column, char ch) {
badCh = ch;
this.line = line;
this.column = column;
}
@Override
public String toString() {
return String.format("Caractere inesperado: \"%s\" na linha %d coluna %d", badCh != 0 ? badCh : "EOF", line, column);
}
}
| edu1910/AnalisadorSintatico | src/br/com/ceducarneiro/analisadorsintatico/LexException.java | Java | apache-2.0 | 473 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtasks.v2.model;
/**
* Encapsulates settings provided to GetIamPolicy.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GetPolicyOptions extends com.google.api.client.json.GenericJson {
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer requestedPolicyVersion;
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* @return value or {@code null} for none
*/
public java.lang.Integer getRequestedPolicyVersion() {
return requestedPolicyVersion;
}
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* @param requestedPolicyVersion requestedPolicyVersion or {@code null} for none
*/
public GetPolicyOptions setRequestedPolicyVersion(java.lang.Integer requestedPolicyVersion) {
this.requestedPolicyVersion = requestedPolicyVersion;
return this;
}
@Override
public GetPolicyOptions set(String fieldName, Object value) {
return (GetPolicyOptions) super.set(fieldName, value);
}
@Override
public GetPolicyOptions clone() {
return (GetPolicyOptions) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-cloudtasks/v2/1.31.0/com/google/api/services/cloudtasks/v2/model/GetPolicyOptions.java | Java | apache-2.0 | 4,445 |
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.impl.spi.impl.discovery;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientAutoDetectionDiscoveryTest extends HazelcastTestSupport {
@After
public void tearDown() {
Hazelcast.shutdownAll();
}
@Test
public void defaultDiscovery() {
Hazelcast.newHazelcastInstance();
Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient();
assertClusterSizeEventually(2, client);
}
@Test
public void autoDetectionDisabled() {
Config config = new Config();
config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
Hazelcast.newHazelcastInstance(config);
Hazelcast.newHazelcastInstance(config);
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().getAutoDetectionConfig().setEnabled(false);
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
// uses 127.0.0.1 and finds only one standalone member
assertClusterSizeEventually(1, client);
}
@Test
public void autoDetectionNotUsedWhenOtherDiscoveryEnabled() {
Config config = new Config();
config.getNetworkConfig().setPort(5710);
config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
Hazelcast.newHazelcastInstance(config);
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().addAddress("127.0.0.1:5710");
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
assertClusterSizeEventually(1, client);
}
}
| mdogan/hazelcast | hazelcast/src/test/java/com/hazelcast/client/impl/spi/impl/discovery/ClientAutoDetectionDiscoveryTest.java | Java | apache-2.0 | 2,849 |
package me.banxi.androiddemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity{
public void onCreate(Bundle bundle){
super.onCreate(bundle);
TextView textView = new TextView(this);
textView.setText("Hello,World");
setContentView(textView);
}
}
| banxi1988/android-demo | src/main/java/me/banxi/androiddemo/MainActivity.java | Java | apache-2.0 | 366 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.server;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ExpiryRunnerTest extends ActiveMQTestBase {
private ActiveMQServer server;
private ClientSession clientSession;
private final SimpleString qName = new SimpleString("ExpiryRunnerTestQ");
private final SimpleString qName2 = new SimpleString("ExpiryRunnerTestQ2");
private SimpleString expiryQueue;
private SimpleString expiryAddress;
private ServerLocator locator;
@Test
public void testBasicExpire() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireFromMultipleQueues() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
clientSession.createQueue(qName2, qName2, null, false);
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
ClientProducer producer2 = clientSession.createProducer(qName2);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer2.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireHalf() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
if (i % 2 == 0) {
m.setExpiration(expiration);
}
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(numMessages / 2, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireConsumeHalf() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis() + 1000;
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
ClientConsumer consumer = clientSession.createConsumer(qName);
clientSession.start();
for (int i = 0; i < numMessages / 2; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull("message not received " + i, cm);
cm.acknowledge();
Assert.assertEquals("m" + i, cm.getBodyBuffer().readString());
}
consumer.close();
Thread.sleep(2100);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireToExpiryQueue() throws Exception {
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
clientSession.deleteQueue(qName);
clientSession.createQueue(qName, qName, null, false);
clientSession.createQueue(qName, qName2, null, false);
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
ClientConsumer consumer = clientSession.createConsumer(expiryQueue);
clientSession.start();
for (int i = 0; i < numMessages; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull(cm);
// assertEquals("m" + i, cm.getBody().getString());
}
for (int i = 0; i < numMessages; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull(cm);
// assertEquals("m" + i, cm.getBody().getString());
}
consumer.close();
}
@Test
public void testExpireWhilstConsumingMessagesStillInOrder() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
ClientConsumer consumer = clientSession.createConsumer(qName);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageHandler dummyMessageHandler = new DummyMessageHandler(consumer, latch);
clientSession.start();
Thread thr = new Thread(dummyMessageHandler);
thr.start();
long expiration = System.currentTimeMillis() + 1000;
int numMessages = 0;
long sendMessagesUntil = System.currentTimeMillis() + 2000;
do {
ClientMessage m = createTextMessage(clientSession, "m" + numMessages++);
m.setExpiration(expiration);
producer.send(m);
Thread.sleep(100);
} while (System.currentTimeMillis() < sendMessagesUntil);
Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
consumer.close();
consumer = clientSession.createConsumer(expiryQueue);
do {
ClientMessage cm = consumer.receive(2000);
if (cm == null) {
break;
}
String text = cm.getBodyBuffer().readString();
cm.acknowledge();
Assert.assertFalse(dummyMessageHandler.payloads.contains(text));
dummyMessageHandler.payloads.add(text);
} while (true);
for (int i = 0; i < numMessages; i++) {
if (dummyMessageHandler.payloads.isEmpty()) {
break;
}
Assert.assertTrue("m" + i, dummyMessageHandler.payloads.remove("m" + i));
}
consumer.close();
thr.join();
}
//
// public static void main(final String[] args) throws Exception
// {
// for (int i = 0; i < 1000; i++)
// {
// TestSuite suite = new TestSuite();
// ExpiryRunnerTest expiryRunnerTest = new ExpiryRunnerTest();
// expiryRunnerTest.setName("testExpireWhilstConsuming");
// suite.addTest(expiryRunnerTest);
//
// TestResult result = TestRunner.run(suite);
// if (result.errorCount() > 0 || result.failureCount() > 0)
// {
// System.exit(1);
// }
// }
// }
@Override
@Before
public void setUp() throws Exception {
super.setUp();
ConfigurationImpl configuration = (ConfigurationImpl) createDefaultInVMConfig().setMessageExpiryScanPeriod(1000);
server = addServer(ActiveMQServers.newActiveMQServer(configuration, false));
// start the server
server.start();
// then we create a client as normal
locator = createInVMNonHALocator().setBlockOnAcknowledge(true);
ClientSessionFactory sessionFactory = createSessionFactory(locator);
clientSession = sessionFactory.createSession(false, true, true);
clientSession.createQueue(qName, qName, null, false);
expiryAddress = new SimpleString("EA");
expiryQueue = new SimpleString("expiryQ");
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
clientSession.createQueue(expiryAddress, expiryQueue, null, false);
}
private static class DummyMessageHandler implements Runnable {
List<String> payloads = new ArrayList<>();
private final ClientConsumer consumer;
private final CountDownLatch latch;
private DummyMessageHandler(final ClientConsumer consumer, final CountDownLatch latch) {
this.consumer = consumer;
this.latch = latch;
}
@Override
public void run() {
while (true) {
try {
ClientMessage message = consumer.receive(5000);
if (message == null) {
break;
}
message.acknowledge();
payloads.add(message.getBodyBuffer().readString());
Thread.sleep(110);
}
catch (Exception e) {
e.printStackTrace();
}
}
latch.countDown();
}
}
}
| lburgazzoli/apache-activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java | Java | apache-2.0 | 11,691 |
package org.plista.kornakapi.core.training.preferencechanges;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DelegatingPreferenceChangeListenerForLabel implements PreferenceChangeListenerForLabel {
private final Map<String,List<PreferenceChangeListener>> delegates = Maps.newLinkedHashMap();
public void addDelegate(PreferenceChangeListener listener, String label) {
if(delegates.containsKey(label)){
delegates.get(label).add(listener);
}else{
List<PreferenceChangeListener> delegatesPerLabel = Lists.newArrayList();
delegatesPerLabel.add(listener);
delegates.put(label, delegatesPerLabel);
}
}
@Override
public void notifyOfPreferenceChange(String label) {
for (PreferenceChangeListener listener : delegates.get(label)) {
listener.notifyOfPreferenceChange();
}
}
}
| plista/kornakapi | src/main/java/org/plista/kornakapi/core/training/preferencechanges/DelegatingPreferenceChangeListenerForLabel.java | Java | apache-2.0 | 935 |
/**
* 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 tools.descartes.teastore.persistence.rest;
import java.util.ArrayList;
import java.util.List;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
import tools.descartes.teastore.persistence.domain.OrderItemRepository;
import tools.descartes.teastore.persistence.repository.DataGenerator;
import tools.descartes.teastore.registryclient.util.AbstractCRUDEndpoint;
import tools.descartes.teastore.entities.OrderItem;
/**
* Persistence endpoint for for CRUD operations on orders.
* @author Joakim von Kistowski
*
*/
@Path("orderitems")
public class OrderItemEndpoint extends AbstractCRUDEndpoint<OrderItem> {
/**
* {@inheritDoc}
*/
@Override
protected long createEntity(final OrderItem orderItem) {
if (DataGenerator.GENERATOR.isMaintenanceMode()) {
return -1L;
}
return OrderItemRepository.REPOSITORY.createEntity(orderItem);
}
/**
* {@inheritDoc}
*/
@Override
protected OrderItem findEntityById(final long id) {
OrderItem item = OrderItemRepository.REPOSITORY.getEntity(id);
if (item == null) {
return null;
}
return new OrderItem(item);
}
/**
* {@inheritDoc}
*/
@Override
protected List<OrderItem> listAllEntities(final int startIndex, final int maxResultCount) {
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntities(startIndex, maxResultCount)) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean updateEntity(long id, OrderItem orderItem) {
return OrderItemRepository.REPOSITORY.updateEntity(id, orderItem);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean deleteEntity(long id) {
if (DataGenerator.GENERATOR.isMaintenanceMode()) {
return false;
}
return OrderItemRepository.REPOSITORY.removeEntity(id);
}
/**
* Returns all order items with the given product Id (all order items for that product).
* @param productId The id of the product.
* @param startPosition The index (NOT ID) of the first order item with the product to return.
* @param maxResult The max number of order items to return.
* @return list of order items with the product.
*/
@GET
@Path("product/{product:[0-9][0-9]*}")
public List<OrderItem> listAllForProduct(@PathParam("product") final Long productId,
@QueryParam("start") final Integer startPosition,
@QueryParam("max") final Integer maxResult) {
if (productId == null) {
return listAll(startPosition, maxResult);
}
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithProduct(productId,
parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
/**
* Returns all order items with the given order Id (all order items for that order).
* @param orderId The id of the product.
* @param startPosition The index (NOT ID) of the first order item with the product to return.
* @param maxResult The max number of order items to return.
* @return list of order items with the product.
*/
@GET
@Path("order/{order:[0-9][0-9]*}")
public List<OrderItem> listAllForOrder(@PathParam("order") final Long orderId,
@QueryParam("start") final Integer startPosition,
@QueryParam("max") final Integer maxResult) {
if (orderId == null) {
return listAll(startPosition, maxResult);
}
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithOrder(orderId,
parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
}
| DescartesResearch/Pet-Supply-Store | services/tools.descartes.teastore.persistence/src/main/java/tools/descartes/teastore/persistence/rest/OrderItemEndpoint.java | Java | apache-2.0 | 4,492 |
package apple.mlcompute;
import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
/**
* MLCRMSPropOptimizer
* <p>
* The MLCRMSPropOptimizer specifies the RMSProp optimizer.
*/
@Generated
@Library("MLCompute")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MLCRMSPropOptimizer extends MLCOptimizer implements NSCopying {
static {
NatJ.register();
}
@Generated
protected MLCRMSPropOptimizer(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native MLCRMSPropOptimizer alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native MLCRMSPropOptimizer allocWithZone(VoidPtr zone);
/**
* [@property] alpha
* <p>
* The smoothing constant.
* <p>
* The default is 0.99.
*/
@Generated
@Selector("alpha")
public native float alpha();
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Owned
@Selector("copyWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public native Object copyWithZone(VoidPtr zone);
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
/**
* [@property] epsilon
* <p>
* A term added to improve numerical stability.
* <p>
* The default is 1e-8.
*/
@Generated
@Selector("epsilon")
public native float epsilon();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("init")
public native MLCRMSPropOptimizer init();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
/**
* [@property] isCentered
* <p>
* If True, compute the centered RMSProp, the gradient is normalized by an estimation of its variance.
* <p>
* The default is false.
*/
@Generated
@Selector("isCentered")
public native boolean isCentered();
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
/**
* [@property] momentumScale
* <p>
* The momentum factor. A hyper-parameter.
* <p>
* The default is 0.0.
*/
@Generated
@Selector("momentumScale")
public native float momentumScale();
@Generated
@Owned
@Selector("new")
public static native MLCRMSPropOptimizer new_objc();
/**
* Create a MLCRMSPropOptimizer object with defaults
*
* @return A new MLCRMSPropOptimizer object.
*/
@Generated
@Selector("optimizerWithDescriptor:")
public static native MLCRMSPropOptimizer optimizerWithDescriptor(MLCOptimizerDescriptor optimizerDescriptor);
/**
* Create a MLCRMSPropOptimizer object
*
* @param optimizerDescriptor The optimizer descriptor object
* @param momentumScale The momentum scale
* @param alpha The smoothing constant value
* @param epsilon The epsilon value to use to improve numerical stability
* @param isCentered A boolean to specify whether to compute the centered RMSProp or not
* @return A new MLCRMSPropOptimizer object.
*/
@Generated
@Selector("optimizerWithDescriptor:momentumScale:alpha:epsilon:isCentered:")
public static native MLCRMSPropOptimizer optimizerWithDescriptorMomentumScaleAlphaEpsilonIsCentered(
MLCOptimizerDescriptor optimizerDescriptor, float momentumScale, float alpha, float epsilon,
boolean isCentered);
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
}
| multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/mlcompute/MLCRMSPropOptimizer.java | Java | apache-2.0 | 6,672 |
package com.jflyfox.dudu.module.system.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.jflyfox.dudu.component.model.Query;
import com.jflyfox.dudu.module.system.model.SysMenu;
import com.jflyfox.util.StrUtils;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;
import java.util.List;
/**
* 菜单 数据层
*
* @author flyfox 369191470@qq.com on 2017-06-20.
*/
public interface MenuMapper extends BaseMapper<SysMenu> {
@SelectProvider(type = SqlBuilder.class, method = "selectMenuPage")
List<SysMenu> selectMenuPage(Query query);
class SqlBuilder {
public String selectMenuPage(Query query) {
String sqlColumns = "t.id,t.parentid,t.name,t.urlkey,t.url,t.status,t.type,t.sort,t.level,t.enable,t.update_time as updateTime,t.update_id as updateId,t.create_time as createTime,t.create_id as createId";
return new SQL() {{
SELECT(sqlColumns +
" ,p.name as parentName,uu.username as updateName,uc.username as createName");
FROM(" sys_menu t ");
LEFT_OUTER_JOIN(" sys_user uu on t.update_id = uu.id ");
LEFT_OUTER_JOIN(" sys_user uc on t.create_id = uc.id ");
LEFT_OUTER_JOIN(" sys_menu p on t.parentid = p.id ");
if (StrUtils.isNotEmpty(query.getStr("name"))) {
WHERE(" t.name like concat('%',#{name},'%')");
}
if (StrUtils.isNotEmpty(query.getOrderBy())) {
ORDER_BY(query.getOrderBy());
} else {
ORDER_BY(" t.id desc");
}
}}.toString();
}
}
}
| jflyfox/dudu | dudu-admin/src/main/java/com/jflyfox/dudu/module/system/dao/MenuMapper.java | Java | apache-2.0 | 1,715 |
/**
*
* Copyright 2003-2007 Jive 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 org.jivesoftware.smack.chat;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.StanzaCollector;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jxmpp.jid.EntityJid;
/**
* A chat is a series of messages sent between two users. Each chat has a unique
* thread ID, which is used to track which messages are part of a particular
* conversation. Some messages are sent without a thread ID, and some clients
* don't send thread IDs at all. Therefore, if a message without a thread ID
* arrives it is routed to the most recently created Chat with the message
* sender.
*
* @author Matt Tucker
* @deprecated use <code>org.jivesoftware.smack.chat2.Chat</code> from <code>smack-extensions</code> instead.
*/
@Deprecated
public class Chat {
private final ChatManager chatManager;
private final String threadID;
private final EntityJid participant;
private final Set<ChatMessageListener> listeners = new CopyOnWriteArraySet<>();
/**
* Creates a new chat with the specified user and thread ID.
*
* @param chatManager the chatManager the chat will use.
* @param participant the user to chat with.
* @param threadID the thread ID to use.
*/
Chat(ChatManager chatManager, EntityJid participant, String threadID) {
if (StringUtils.isEmpty(threadID)) {
throw new IllegalArgumentException("Thread ID must not be null");
}
this.chatManager = chatManager;
this.participant = participant;
this.threadID = threadID;
}
/**
* Returns the thread id associated with this chat, which corresponds to the
* <tt>thread</tt> field of XMPP messages. This method may return <tt>null</tt>
* if there is no thread ID is associated with this Chat.
*
* @return the thread ID of this chat.
*/
public String getThreadID() {
return threadID;
}
/**
* Returns the name of the user the chat is with.
*
* @return the name of the user the chat is occuring with.
*/
public EntityJid getParticipant() {
return participant;
}
/**
* Sends the specified text as a message to the other chat participant.
* This is a convenience method for:
*
* <pre>
* Message message = chat.createMessage();
* message.setBody(messageText);
* chat.sendMessage(message);
* </pre>
*
* @param text the text to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
public void sendMessage(String text) throws NotConnectedException, InterruptedException {
Message message = new Message();
message.setBody(text);
sendMessage(message);
}
/**
* Sends a message to the other chat participant. The thread ID, recipient,
* and message type of the message will automatically set to those of this chat.
*
* @param message the message to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
public void sendMessage(Message message) throws NotConnectedException, InterruptedException {
// Force the recipient, message type, and thread ID since the user elected
// to send the message through this chat object.
message.setTo(participant);
message.setType(Message.Type.chat);
message.setThread(threadID);
chatManager.sendMessage(this, message);
}
/**
* Adds a stanza(/packet) listener that will be notified of any new messages in the
* chat.
*
* @param listener a stanza(/packet) listener.
*/
public void addMessageListener(ChatMessageListener listener) {
if (listener == null) {
return;
}
// TODO these references should be weak.
listeners.add(listener);
}
public void removeMessageListener(ChatMessageListener listener) {
listeners.remove(listener);
}
/**
* Closes the Chat and removes all references to it from the {@link ChatManager}. The chat will
* be unusable when this method returns, so it's recommend to drop all references to the
* instance right after calling {@link #close()}.
*/
public void close() {
chatManager.closeChat(this);
listeners.clear();
}
/**
* Returns an unmodifiable set of all of the listeners registered with this chat.
*
* @return an unmodifiable set of all of the listeners registered with this chat.
*/
public Set<ChatMessageListener> getListeners() {
return Collections.unmodifiableSet(listeners);
}
/**
* Creates a {@link org.jivesoftware.smack.StanzaCollector} which will accumulate the Messages
* for this chat. Always cancel StanzaCollectors when finished with them as they will accumulate
* messages indefinitely.
*
* @return the StanzaCollector which returns Messages for this chat.
*/
public StanzaCollector createCollector() {
return chatManager.createStanzaCollector(this);
}
/**
* Delivers a message directly to this chat, which will add the message
* to the collector and deliver it to all listeners registered with the
* Chat. This is used by the XMPPConnection class to deliver messages
* without a thread ID.
*
* @param message the message.
*/
void deliver(Message message) {
// Because the collector and listeners are expecting a thread ID with
// a specific value, set the thread ID on the message even though it
// probably never had one.
message.setThread(threadID);
for (ChatMessageListener listener : listeners) {
listener.processMessage(this, message);
}
}
@Override
public String toString() {
return "Chat [(participant=" + participant + "), (thread=" + threadID + ")]";
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 31 + threadID.hashCode();
hash = hash * 31 + participant.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Chat
&& threadID.equals(((Chat) obj).getThreadID())
&& participant.equals(((Chat) obj).getParticipant());
}
}
| vanitasvitae/smack-omemo | smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java | Java | apache-2.0 | 7,127 |
package edu.kit.tm.pseprak2.alushare.view;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import java.io.IOException;
/**
* Represent the AudioRecorder of the ChatActivity.
* Enables recording sound and playing the music before sending.
*
* Created by Arthur Anselm on 17.08.15.
*/
public class AudioRecorder {
private String mFileName = null;
private String TAG = "AudioRecorder";
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ChatController controller;
private boolean busy;
//private SeekBar mSeekbar;
//private Handler mHandler;
/**
* The constructor of this class.
* @param controller the controller for this audioRecorder object
*/
public AudioRecorder(ChatController controller){
if(controller == null){
throw new NullPointerException();
}
this.controller = controller;
//this.mSeekbar = seekBar;
//this.mHandler = new Handler();
this.mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
this.mFileName += "/audiorecord_alushare.m4a";
this.busy = false;
}
/**
* Invokes the method startRecording() (and sets busy to true) if start is true else
* stopRecording().
* @param start boolean to start or stop recording
*/
public void onRecord(boolean start) {
if (start) {
busy = true;
startRecording();
} else {
stopRecording();
}
}
/**
* Invokes startPlaying() if start is true else stopPlaying().
* @param start boolean to start or stop playing
*/
public void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
/**
* Creates a new mediaPlayer and sets it up. After that starts playing the audoFile stored in
* the filesPath mFileName
*/
private void startPlaying() {
if(mFileName == null){
throw new NullPointerException("Recorded file is null.");
}
setUpMediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
}
}
/**
* Creates a new mediaPlayer and sets the completion listener.
*/
private void setUpMediaPlayer(){
mPlayer = new MediaPlayer();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.e(TAG, " : Playing of Sound completed");
controller.setPlayButtonVisible(true);
}
});
/*
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(final MediaPlayer mp) {
mSeekbar.setMax(mp.getDuration());
new Thread(new Runnable() {
@Override
public void run() {
while (mp != null && mp.getCurrentPosition() < mp.getDuration()) {
mSeekbar.setProgress(mp.getCurrentPosition());
Message msg = new Message();
int millis = mp.getCurrentPosition();
msg.obj = millis / 1000;
mHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});*/
}
/**
* Stops playing the mediaPlayer with the method release() and releases the references to the
* mediaPlayer if the mediaPlayer isn't null.
*/
private void stopPlaying() {
if(mPlayer != null) {
mPlayer.release();
mPlayer = null;
} else {
Log.e(TAG, "MediaPlayer is null. stopPlaying() can't be executed.");
}
}
/**
* Creates a new mediaRecorder and set it up.
* Start recording and saving the audio data into the file stored at fileName.
*/
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setAudioChannels(1);
mRecorder.setAudioSamplingRate(44100);
mRecorder.setAudioEncodingBitRate(96000);
mRecorder.setOutputFile(mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
return;
}
mRecorder.start();
}
/**
* Stops recording, invokes release of the mediaRecorder and releases the references to the
* mediaRecorder if the mediaRecorder isn't null.
*/
private void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
} else {
Log.e(TAG, "MediaRecorder is null. stopRecording() can't be executed.");
}
}
/**
*Return the filePath of the recorded audio file
* @return this.mFileName
*/
public String getFilePath(){
return mFileName;
}
/**
* Sets the busyness of this audioRecorder
* @param busy true if the audioRecorder is active else false
*/
public void setBusy(boolean busy){
this.busy = busy;
}
/**
* Checks if this audioRecorder is active oder not. Returns busy.
* @return busy
*/
public boolean isBusy(){
return busy;
}
}
| weichweich/AluShare | app/src/main/java/edu/kit/tm/pseprak2/alushare/view/AudioRecorder.java | Java | apache-2.0 | 6,151 |
package com.zts.service.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = DataSourceProperties.DS, ignoreUnknownFields = false)
public class DataSourceProperties {
//对应配置文件里的配置键
public final static String DS="mysql";
private String driverClassName ="com.mysql.jdbc.Driver";
private String url;
private String username;
private String password;
private int maxActive = 100;
private int maxIdle = 8;
private int minIdle = 8;
private int initialSize = 10;
private String validationQuery;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
} | tushengtuzhang/zts | cloud-simple-service/src/main/java/com/zts/service/config/DataSourceProperties.java | Java | apache-2.0 | 2,197 |
package com.github.approval.sesame;
/*
* #%L
* approval-sesame
* %%
* Copyright (C) 2014 Nikolavp
* %%
* 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 com.github.approval.Reporter;
import com.github.approval.reporters.ExecutableDifferenceReporter;
import com.github.approval.reporters.Reporters;
import com.github.approval.reporters.SwingInteractiveReporter;
import java.io.File;
/**
* <p>
* A reporter that can be used to verify dot files. It will compile the file to an image and open it through
* {@link com.github.approval.reporters.Reporters#fileLauncher()}.
* </p>
* <p>
* Note that this reporter cannot be used for anything else and will give you an error beceause it will
* try to compile the verification file with the "dot" command.
* </p>
*/
public final class GraphReporter extends ExecutableDifferenceReporter {
/**
* Get an instance of the reporter.
* @return a graph reporter
*/
public static Reporter getInstance() {
return SwingInteractiveReporter.wrap(new GraphReporter());
}
/**
* Main constructor for the executable reporter.
*/
private GraphReporter() {
super("dot -T png -O ", "dot -T png -O ", "dot");
}
private static File addPng(File file) {
return new File(file.getAbsoluteFile().getAbsolutePath() + ".png");
}
@Override
public void approveNew(byte[] value, File approvalDestination, File fileForVerification) {
super.approveNew(value, approvalDestination, fileForVerification);
Reporters.fileLauncherWithoutInteraction().approveNew(value, addPng(approvalDestination), addPng(fileForVerification));
}
@Override
protected String[] buildApproveNewCommand(File approvalDestination, File fileForVerification) {
return new String[]{getApprovalCommand(), approvalDestination.getAbsolutePath()};
}
@Override
protected String[] buildNotTheSameCommand(File fileForVerification, File fileForApproval) {
return new String[]{getDiffCommand(), fileForApproval.getAbsolutePath()};
}
@Override
public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) {
super.notTheSame(oldValue, fileForVerification, newValue, fileForApproval);
Reporters.fileLauncherWithoutInteraction().notTheSame(oldValue, addPng(fileForVerification), newValue, addPng(fileForApproval));
}
}
| nikolavp/approval | approval-sesame/src/main/java/com/github/approval/sesame/GraphReporter.java | Java | apache-2.0 | 2,951 |
package AbsSytree;
import java.util.ArrayList;
public class SynExprSeq extends AbsSynNode {
public ArrayList<AbsSynNode> exprs;
public SynExprSeq(AbsSynNode e) {
this.exprs = new ArrayList<AbsSynNode>();
this.exprs.add(e);
}
public SynExprSeq append(AbsSynNode e) {
this.exprs.add(e);
return this;
}
@Override
public Object visit(SynNodeVisitor visitor) {
return visitor.visit(this);
}
@Override
public void dumpNode(int indent) {
for (int i = 0; i < this.exprs.size(); ++i) {
this.exprs.get(i).dumpNode(indent);
this.dumpFormat(indent, ";");
}
}
@Override
public void clearAttr() {
this.attr = null;
for (int i = 0; i < this.exprs.size(); ++i)
this.exprs.get(i).clearAttr();
}
}
| mingyuan-xia/TigerCC | src/AbsSytree/SynExprSeq.java | Java | apache-2.0 | 767 |
/**
* Copyright 2017 Matthieu Jimenez. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 paw.graph.customTypes.bitset;
import greycat.base.BaseCustomType;
import greycat.struct.EStructArray;
import greycat.utility.HashHelper;
import org.roaringbitmap.IntIterator;
import java.util.List;
public abstract class CTBitset extends BaseCustomType{
public static final String BITS = "bits";
protected static final int BITS_H = HashHelper.hash(BITS);
public CTBitset(EStructArray p_backend) {
super(p_backend);
}
public abstract void save();
public abstract void clear();
public abstract boolean add(int index);
public abstract boolean addAll(List<Integer> indexs);
public abstract void clear(int index);
public abstract int size();
public abstract int cardinality();
public abstract boolean get(int index);
public abstract int nextSetBit(int startIndex);
public abstract IntIterator iterator();
}
| greycat-incubator/Paw | src/main/java/paw/graph/customTypes/bitset/CTBitset.java | Java | apache-2.0 | 1,522 |
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.core.pipeline;
import com.sun.jersey.core.util.Base64;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/*
* JAXB adapter for a Base64 encoded string element
*/
public class Base64StringAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String arg0) throws Exception {
return new String(Base64.encode(arg0), "UTF-8");
}
@Override
public String unmarshal(String arg0) throws Exception {
return Base64.base64Decode(arg0);
}
}
| southworkscom/azure-sdk-for-java | core/azure-core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java | Java | apache-2.0 | 1,133 |
/**
* Copyright 2016 William Van Woensel
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.
*
*
* @author wvw
*
*/
package wvw.utils.rule.builder;
public abstract class RuleBuilder {
protected String id;
protected StringBuffer templateClause = new StringBuffer();
protected StringBuffer conditionClause = new StringBuffer();
public RuleBuilder() {
}
public RuleBuilder(String id) {
this.id = id;
}
public void appendTemplate(String template) {
templateClause.append("\t").append(template);
}
public void appendCondition(String condition) {
conditionClause.append("\t").append(condition);
}
public String getId() {
return id;
}
public abstract String toString();
}
| darth-willy/mobibench | MobiBenchWebService/src/main/java/wvw/utils/rule/builder/RuleBuilder.java | Java | apache-2.0 | 1,192 |
/*
* Copyright 2013, Unitils.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitils.core.reflect;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Tim Ducheyne
*/
public class TypeWrapperIsAssignableParameterizedTypeTest {
/* Tested object */
private TypeWrapper typeWrapper;
private ParameterizedType type1;
private ParameterizedType type2;
private ParameterizedType type3;
private ParameterizedType type4;
private ParameterizedType type5;
private ParameterizedType type6;
private ParameterizedType type7;
private ParameterizedType type8;
@Before
public void initialize() throws Exception {
typeWrapper = new TypeWrapper(null);
type1 = (ParameterizedType) MyClass.class.getDeclaredField("field1").getGenericType();
type2 = (ParameterizedType) MyClass.class.getDeclaredField("field2").getGenericType();
type3 = (ParameterizedType) MyClass.class.getDeclaredField("field3").getGenericType();
type4 = (ParameterizedType) MyClass.class.getDeclaredField("field4").getGenericType();
type5 = (ParameterizedType) MyClass.class.getDeclaredField("field5").getGenericType();
type6 = (ParameterizedType) MyClass.class.getDeclaredField("field6").getGenericType();
type7 = (ParameterizedType) MyClass.class.getDeclaredField("field7").getGenericType();
type8 = (ParameterizedType) MyClass.class.getDeclaredField("field8").getGenericType();
}
@Test
public void equal() {
boolean result = typeWrapper.isAssignableParameterizedType(type1, type2);
assertTrue(result);
}
@Test
public void assignableParameter() {
boolean result = typeWrapper.isAssignableParameterizedType(type6, type7);
assertTrue(result);
}
@Test
public void nestedAssignableParameters() {
boolean result = typeWrapper.isAssignableParameterizedType(type3, type4);
assertTrue(result);
}
@Test
public void falseWhenDifferentNrOfTypeParameters() {
boolean result = typeWrapper.isAssignableParameterizedType(type2, type7);
assertFalse(result);
}
@Test
public void falseWhenNotEqualNonWildCardType() {
boolean result = typeWrapper.isAssignableParameterizedType(type7, type8);
assertFalse(result);
}
@Test
public void falseWhenNotAssignableToWildCard() {
boolean result = typeWrapper.isAssignableParameterizedType(type6, type8);
assertFalse(result);
}
@Test
public void falseWhenNotAssignableToNestedWildCard() {
boolean result = typeWrapper.isAssignableParameterizedType(type3, type5);
assertFalse(result);
}
private static class MyClass {
private Map<Type1, Type1> field1;
private Map<Type1, Type1> field2;
private Map<? extends List<? extends Type1>, ? extends List<?>> field3;
private Map<List<Type1>, List<Type2>> field4;
private Map<List<String>, List<String>> field5;
private List<? extends Type1> field6;
private List<Type2> field7;
private List<String> field8;
}
private static class Type1 {
}
private static class Type2 extends Type1 {
}
}
| Silvermedia/unitils | unitils-test/src/test/java/org/unitils/core/reflect/TypeWrapperIsAssignableParameterizedTypeTest.java | Java | apache-2.0 | 4,075 |
/*
* Copyright (c) 2010-2014. Axon Framework
*
* 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.axonframework.common.lock;
/**
* Interface to the lock factory. A lock factory produces locks on resources that are shared between threads.
*
* @author Allard Buijze
* @since 0.3
*/
public interface LockFactory {
/**
* Obtain a lock for a resource identified by given {@code identifier}. Depending on the strategy, this
* method may return immediately or block until a lock is held.
*
* @param identifier the identifier of the resource to obtain a lock for.
* @return a handle to release the lock.
*/
Lock obtainLock(String identifier);
}
| soulrebel/AxonFramework | core/src/main/java/org/axonframework/common/lock/LockFactory.java | Java | apache-2.0 | 1,205 |
package site;
public class Autocomplete {
private final String label;
private final String value;
public Autocomplete(String label, String value) {
this.label = label;
this.value = value;
}
public final String getLabel() {
return this.label;
}
public final String getValue() {
return this.value;
}
} | CaroleneBertoldi/CountryDetails | country/src/main/java/site/Autocomplete.java | Java | apache-2.0 | 337 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.routing;
import com.carrotsearch.hppc.ObjectIntHashMap;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* {@link RoutingNodes} represents a copy the routing information contained in
* the {@link ClusterState cluster state}.
*/
public class RoutingNodes implements Iterable<RoutingNode> {
private final MetaData metaData;
private final ClusterBlocks blocks;
private final RoutingTable routingTable;
private final Map<String, RoutingNode> nodesToShards = new HashMap<>();
private final UnassignedShards unassignedShards = new UnassignedShards(this);
private final Map<ShardId, List<ShardRouting>> assignedShards = new HashMap<>();
private final ImmutableOpenMap<String, ClusterState.Custom> customs;
private final boolean readOnly;
private int inactivePrimaryCount = 0;
private int inactiveShardCount = 0;
private int relocatingShards = 0;
private final Map<String, ObjectIntHashMap<String>> nodesPerAttributeNames = new HashMap<>();
private final Map<String, Recoveries> recoveryiesPerNode = new HashMap<>();
public RoutingNodes(ClusterState clusterState) {
this(clusterState, true);
}
public RoutingNodes(ClusterState clusterState, boolean readOnly) {
this.readOnly = readOnly;
this.metaData = clusterState.metaData();
this.blocks = clusterState.blocks();
this.routingTable = clusterState.routingTable();
this.customs = clusterState.customs();
Map<String, List<ShardRouting>> nodesToShards = new HashMap<>();
// fill in the nodeToShards with the "live" nodes
for (ObjectCursor<DiscoveryNode> cursor : clusterState.nodes().dataNodes().values()) {
nodesToShards.put(cursor.value.id(), new ArrayList<>());
}
// fill in the inverse of node -> shards allocated
// also fill replicaSet information
for (ObjectCursor<IndexRoutingTable> indexRoutingTable : routingTable.indicesRouting().values()) {
for (IndexShardRoutingTable indexShard : indexRoutingTable.value) {
assert indexShard.primary != null;
for (ShardRouting shard : indexShard) {
// to get all the shards belonging to an index, including the replicas,
// we define a replica set and keep track of it. A replica set is identified
// by the ShardId, as this is common for primary and replicas.
// A replica Set might have one (and not more) replicas with the state of RELOCATING.
if (shard.assignedToNode()) {
List<ShardRouting> entries = nodesToShards.computeIfAbsent(shard.currentNodeId(), k -> new ArrayList<>());
final ShardRouting sr = getRouting(shard, readOnly);
entries.add(sr);
assignedShardsAdd(sr);
if (shard.relocating()) {
relocatingShards++;
entries = nodesToShards.computeIfAbsent(shard.relocatingNodeId(), k -> new ArrayList<>());
// add the counterpart shard with relocatingNodeId reflecting the source from which
// it's relocating from.
ShardRouting targetShardRouting = shard.buildTargetRelocatingShard();
addInitialRecovery(targetShardRouting);
if (readOnly) {
targetShardRouting.freeze();
}
entries.add(targetShardRouting);
assignedShardsAdd(targetShardRouting);
} else if (shard.active() == false) { // shards that are initializing without being relocated
if (shard.primary()) {
inactivePrimaryCount++;
}
inactiveShardCount++;
addInitialRecovery(shard);
}
} else {
final ShardRouting sr = getRouting(shard, readOnly);
assignedShardsAdd(sr);
unassignedShards.add(sr);
}
}
}
}
for (Map.Entry<String, List<ShardRouting>> entry : nodesToShards.entrySet()) {
String nodeId = entry.getKey();
this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue()));
}
}
private void addRecovery(ShardRouting routing) {
addRecovery(routing, true, false);
}
private void removeRecovery(ShardRouting routing) {
addRecovery(routing, false, false);
}
public void addInitialRecovery(ShardRouting routing) {
addRecovery(routing,true, true);
}
private void addRecovery(final ShardRouting routing, final boolean increment, final boolean initializing) {
final int howMany = increment ? 1 : -1;
assert routing.initializing() : "routing must be initializing: " + routing;
Recoveries.getOrAdd(recoveryiesPerNode, routing.currentNodeId()).addIncoming(howMany);
final String sourceNodeId;
if (routing.relocatingNodeId() != null) { // this is a relocation-target
sourceNodeId = routing.relocatingNodeId();
if (routing.primary() && increment == false) { // primary is done relocating
int numRecoveringReplicas = 0;
for (ShardRouting assigned : assignedShards(routing)) {
if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) {
numRecoveringReplicas++;
}
}
// we transfer the recoveries to the relocated primary
recoveryiesPerNode.get(sourceNodeId).addOutgoing(-numRecoveringReplicas);
recoveryiesPerNode.get(routing.currentNodeId()).addOutgoing(numRecoveringReplicas);
}
} else if (routing.primary() == false) { // primary without relocationID is initial recovery
ShardRouting primary = findPrimary(routing);
if (primary == null && initializing) {
primary = routingTable.index(routing.index().getName()).shard(routing.shardId().id()).primary;
} else if (primary == null) {
throw new IllegalStateException("replica is initializing but primary is unassigned");
}
sourceNodeId = primary.currentNodeId();
} else {
sourceNodeId = null;
}
if (sourceNodeId != null) {
Recoveries.getOrAdd(recoveryiesPerNode, sourceNodeId).addOutgoing(howMany);
}
}
public int getIncomingRecoveries(String nodeId) {
return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getIncoming();
}
public int getOutgoingRecoveries(String nodeId) {
return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getOutgoing();
}
private ShardRouting findPrimary(ShardRouting routing) {
List<ShardRouting> shardRoutings = assignedShards.get(routing.shardId());
ShardRouting primary = null;
if (shardRoutings != null) {
for (ShardRouting shardRouting : shardRoutings) {
if (shardRouting.primary()) {
if (shardRouting.active()) {
return shardRouting;
} else if (primary == null) {
primary = shardRouting;
} else if (primary.relocatingNodeId() != null) {
primary = shardRouting;
}
}
}
}
return primary;
}
private static ShardRouting getRouting(ShardRouting src, boolean readOnly) {
if (readOnly) {
src.freeze(); // we just freeze and reuse this instance if we are read only
} else {
src = new ShardRouting(src);
}
return src;
}
@Override
public Iterator<RoutingNode> iterator() {
return Collections.unmodifiableCollection(nodesToShards.values()).iterator();
}
public RoutingTable routingTable() {
return routingTable;
}
public RoutingTable getRoutingTable() {
return routingTable();
}
public MetaData metaData() {
return this.metaData;
}
public MetaData getMetaData() {
return metaData();
}
public ClusterBlocks blocks() {
return this.blocks;
}
public ClusterBlocks getBlocks() {
return this.blocks;
}
public ImmutableOpenMap<String, ClusterState.Custom> customs() {
return this.customs;
}
public <T extends ClusterState.Custom> T custom(String type) { return (T) customs.get(type); }
public UnassignedShards unassigned() {
return this.unassignedShards;
}
public RoutingNodesIterator nodes() {
return new RoutingNodesIterator(nodesToShards.values().iterator());
}
public RoutingNode node(String nodeId) {
return nodesToShards.get(nodeId);
}
public ObjectIntHashMap<String> nodesPerAttributesCounts(String attributeName) {
ObjectIntHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName);
if (nodesPerAttributesCounts != null) {
return nodesPerAttributesCounts;
}
nodesPerAttributesCounts = new ObjectIntHashMap<>();
for (RoutingNode routingNode : this) {
String attrValue = routingNode.node().attributes().get(attributeName);
nodesPerAttributesCounts.addTo(attrValue, 1);
}
nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts);
return nodesPerAttributesCounts;
}
/**
* Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned primaries even if the
* primaries are marked as temporarily ignored.
*/
public boolean hasUnassignedPrimaries() {
return unassignedShards.getNumPrimaries() + unassignedShards.getNumIgnoredPrimaries() > 0;
}
/**
* Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned shards even if the
* shards are marked as temporarily ignored.
* @see UnassignedShards#isEmpty()
* @see UnassignedShards#isIgnoredEmpty()
*/
public boolean hasUnassignedShards() {
return unassignedShards.isEmpty() == false || unassignedShards.isIgnoredEmpty() == false;
}
public boolean hasInactivePrimaries() {
return inactivePrimaryCount > 0;
}
public boolean hasInactiveShards() {
return inactiveShardCount > 0;
}
public int getRelocatingShardCount() {
return relocatingShards;
}
/**
* Returns the active primary shard for the given ShardRouting or <code>null</code> if
* no primary is found or the primary is not active.
*/
public ShardRouting activePrimary(ShardRouting shard) {
for (ShardRouting shardRouting : assignedShards(shard.shardId())) {
if (shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns one active replica shard for the given ShardRouting shard ID or <code>null</code> if
* no active replica is found.
*/
public ShardRouting activeReplica(ShardRouting shard) {
for (ShardRouting shardRouting : assignedShards(shard.shardId())) {
if (!shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns all shards that are not in the state UNASSIGNED with the same shard
* ID as the given shard.
*/
public Iterable<ShardRouting> assignedShards(ShardRouting shard) {
return assignedShards(shard.shardId());
}
/**
* Returns <code>true</code> iff all replicas are active for the given shard routing. Otherwise <code>false</code>
*/
public boolean allReplicasActive(ShardRouting shardRouting) {
final List<ShardRouting> shards = assignedShards(shardRouting.shardId());
if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index().getName()).shard(shardRouting.id()).size()) {
return false; // if we are empty nothing is active if we have less than total at least one is unassigned
}
for (ShardRouting shard : shards) {
if (!shard.active()) {
return false;
}
}
return true;
}
public List<ShardRouting> shards(Predicate<ShardRouting> predicate) {
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
for (ShardRouting shardRouting : routingNode) {
if (predicate.test(shardRouting)) {
shards.add(shardRouting);
}
}
}
return shards;
}
public List<ShardRouting> shardsWithState(ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(state));
}
for (ShardRoutingState s : state) {
if (s == ShardRoutingState.UNASSIGNED) {
unassigned().forEach(shards::add);
break;
}
}
return shards;
}
public List<ShardRouting> shardsWithState(String index, ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(index, state));
}
for (ShardRoutingState s : state) {
if (s == ShardRoutingState.UNASSIGNED) {
for (ShardRouting unassignedShard : unassignedShards) {
if (unassignedShard.index().equals(index)) {
shards.add(unassignedShard);
}
}
break;
}
}
return shards;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder("routing_nodes:\n");
for (RoutingNode routingNode : this) {
sb.append(routingNode.prettyPrint());
}
sb.append("---- unassigned\n");
for (ShardRouting shardEntry : unassignedShards) {
sb.append("--------").append(shardEntry.shortSummary()).append('\n');
}
return sb.toString();
}
/**
* Moves a shard from unassigned to initialize state
*
* @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated.
*/
public void initialize(ShardRouting shard, String nodeId, @Nullable String existingAllocationId, long expectedSize) {
ensureMutable();
assert shard.unassigned() : shard;
shard.initialize(nodeId, existingAllocationId, expectedSize);
node(nodeId).add(shard);
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
addRecovery(shard);
assignedShardsAdd(shard);
}
/**
* Relocate a shard to another node, adding the target initializing
* shard as well as assigning it. And returning the target initializing
* shard.
*/
public ShardRouting relocate(ShardRouting shard, String nodeId, long expectedShardSize) {
ensureMutable();
relocatingShards++;
shard.relocate(nodeId, expectedShardSize);
ShardRouting target = shard.buildTargetRelocatingShard();
node(target.currentNodeId()).add(target);
assignedShardsAdd(target);
addRecovery(target);
return target;
}
/**
* Mark a shard as started and adjusts internal statistics.
*/
public void started(ShardRouting shard) {
ensureMutable();
assert !shard.active() : "expected an initializing shard " + shard;
if (shard.relocatingNodeId() == null) {
// if this is not a target shard for relocation, we need to update statistics
inactiveShardCount--;
if (shard.primary()) {
inactivePrimaryCount--;
}
}
removeRecovery(shard);
shard.moveToStarted();
}
/**
* Cancels a relocation of a shard that shard must relocating.
*/
public void cancelRelocation(ShardRouting shard) {
ensureMutable();
relocatingShards--;
shard.cancelRelocation();
}
/**
* swaps the status of a shard, making replicas primary and vice versa.
*
* @param shards the shard to have its primary status swapped.
*/
public void swapPrimaryFlag(ShardRouting... shards) {
ensureMutable();
for (ShardRouting shard : shards) {
if (shard.primary()) {
shard.moveFromPrimary();
if (shard.unassigned()) {
unassignedShards.primaries--;
}
} else {
shard.moveToPrimary();
if (shard.unassigned()) {
unassignedShards.primaries++;
}
}
}
}
private static final List<ShardRouting> EMPTY = Collections.emptyList();
private List<ShardRouting> assignedShards(ShardId shardId) {
final List<ShardRouting> replicaSet = assignedShards.get(shardId);
return replicaSet == null ? EMPTY : Collections.unmodifiableList(replicaSet);
}
/**
* Cancels the give shard from the Routing nodes internal statistics and cancels
* the relocation if the shard is relocating.
*/
private void remove(ShardRouting shard) {
ensureMutable();
if (!shard.active() && shard.relocatingNodeId() == null) {
inactiveShardCount--;
assert inactiveShardCount >= 0;
if (shard.primary()) {
inactivePrimaryCount--;
}
} else if (shard.relocating()) {
cancelRelocation(shard);
}
assignedShardsRemove(shard);
if (shard.initializing()) {
removeRecovery(shard);
}
}
private void assignedShardsAdd(ShardRouting shard) {
if (shard.unassigned()) {
// no unassigned
return;
}
List<ShardRouting> shards = assignedShards.computeIfAbsent(shard.shardId(), k -> new ArrayList<>());
assert assertInstanceNotInList(shard, shards);
shards.add(shard);
}
private boolean assertInstanceNotInList(ShardRouting shard, List<ShardRouting> shards) {
for (ShardRouting s : shards) {
assert s != shard;
}
return true;
}
private void assignedShardsRemove(ShardRouting shard) {
ensureMutable();
final List<ShardRouting> replicaSet = assignedShards.get(shard.shardId());
if (replicaSet != null) {
final Iterator<ShardRouting> iterator = replicaSet.iterator();
while(iterator.hasNext()) {
// yes we check identity here
if (shard == iterator.next()) {
iterator.remove();
return;
}
}
assert false : "Illegal state";
}
}
public boolean isKnown(DiscoveryNode node) {
return nodesToShards.containsKey(node.getId());
}
public void addNode(DiscoveryNode node) {
ensureMutable();
RoutingNode routingNode = new RoutingNode(node.id(), node);
nodesToShards.put(routingNode.nodeId(), routingNode);
}
public RoutingNodeIterator routingNodeIter(String nodeId) {
final RoutingNode routingNode = nodesToShards.get(nodeId);
if (routingNode == null) {
return null;
}
return new RoutingNodeIterator(routingNode);
}
public RoutingNode[] toArray() {
return nodesToShards.values().toArray(new RoutingNode[nodesToShards.size()]);
}
public void reinitShadowPrimary(ShardRouting candidate) {
ensureMutable();
if (candidate.relocating()) {
cancelRelocation(candidate);
}
candidate.reinitializeShard();
inactivePrimaryCount++;
inactiveShardCount++;
}
/**
* Returns the number of routing nodes
*/
public int size() {
return nodesToShards.size();
}
public static final class UnassignedShards implements Iterable<ShardRouting> {
private final RoutingNodes nodes;
private final List<ShardRouting> unassigned;
private final List<ShardRouting> ignored;
private int primaries = 0;
private int ignoredPrimaries = 0;
public UnassignedShards(RoutingNodes nodes) {
this.nodes = nodes;
unassigned = new ArrayList<>();
ignored = new ArrayList<>();
}
public void add(ShardRouting shardRouting) {
if(shardRouting.primary()) {
primaries++;
}
unassigned.add(shardRouting);
}
public void sort(Comparator<ShardRouting> comparator) {
CollectionUtil.timSort(unassigned, comparator);
}
/**
* Returns the size of the non-ignored unassigned shards
*/
public int size() { return unassigned.size(); }
/**
* Returns the size of the temporarily marked as ignored unassigned shards
*/
public int ignoredSize() { return ignored.size(); }
/**
* Returns the number of non-ignored unassigned primaries
*/
public int getNumPrimaries() {
return primaries;
}
/**
* Returns the number of temporarily marked as ignored unassigned primaries
*/
public int getNumIgnoredPrimaries() { return ignoredPrimaries; }
@Override
public UnassignedIterator iterator() {
return new UnassignedIterator();
}
/**
* The list of ignored unassigned shards (read only). The ignored unassigned shards
* are not part of the formal unassigned list, but are kept around and used to build
* back the list of unassigned shards as part of the routing table.
*/
public List<ShardRouting> ignored() {
return Collections.unmodifiableList(ignored);
}
/**
* Marks a shard as temporarily ignored and adds it to the ignore unassigned list.
* Should be used with caution, typically,
* the correct usage is to removeAndIgnore from the iterator.
* @see #ignored()
* @see UnassignedIterator#removeAndIgnore()
* @see #isIgnoredEmpty()
*/
public void ignoreShard(ShardRouting shard) {
if (shard.primary()) {
ignoredPrimaries++;
}
ignored.add(shard);
}
public class UnassignedIterator implements Iterator<ShardRouting> {
private final Iterator<ShardRouting> iterator;
private ShardRouting current;
public UnassignedIterator() {
this.iterator = unassigned.iterator();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public ShardRouting next() {
return current = iterator.next();
}
/**
* Initializes the current unassigned shard and moves it from the unassigned list.
*
* @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated.
*/
public void initialize(String nodeId, @Nullable String existingAllocationId, long expectedShardSize) {
innerRemove();
nodes.initialize(new ShardRouting(current), nodeId, existingAllocationId, expectedShardSize);
}
/**
* Removes and ignores the unassigned shard (will be ignored for this run, but
* will be added back to unassigned once the metadata is constructed again).
* Typically this is used when an allocation decision prevents a shard from being allocated such
* that subsequent consumers of this API won't try to allocate this shard again.
*/
public void removeAndIgnore() {
innerRemove();
ignoreShard(current);
}
/**
* Unsupported operation, just there for the interface. Use {@link #removeAndIgnore()} or
* {@link #initialize(String, String, long)}.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("remove is not supported in unassigned iterator, use removeAndIgnore or initialize");
}
private void innerRemove() {
nodes.ensureMutable();
iterator.remove();
if (current.primary()) {
primaries--;
}
}
}
/**
* Returns <code>true</code> iff this collection contains one or more non-ignored unassigned shards.
*/
public boolean isEmpty() {
return unassigned.isEmpty();
}
/**
* Returns <code>true</code> iff any unassigned shards are marked as temporarily ignored.
* @see UnassignedShards#ignoreShard(ShardRouting)
* @see UnassignedIterator#removeAndIgnore()
*/
public boolean isIgnoredEmpty() {
return ignored.isEmpty();
}
public void shuffle() {
Randomness.shuffle(unassigned);
}
/**
* Drains all unassigned shards and returns it.
* This method will not drain ignored shards.
*/
public ShardRouting[] drain() {
ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[unassigned.size()]);
unassigned.clear();
primaries = 0;
return mutableShardRoutings;
}
}
/**
* Calculates RoutingNodes statistics by iterating over all {@link ShardRouting}s
* in the cluster to ensure the book-keeping is correct.
* For performance reasons, this should only be called from asserts
*
* @return this method always returns <code>true</code> or throws an assertion error. If assertion are not enabled
* this method does nothing.
*/
public static boolean assertShardStats(RoutingNodes routingNodes) {
boolean run = false;
assert (run = true); // only run if assertions are enabled!
if (!run) {
return true;
}
int unassignedPrimaryCount = 0;
int unassignedIgnoredPrimaryCount = 0;
int inactivePrimaryCount = 0;
int inactiveShardCount = 0;
int relocating = 0;
Map<Index, Integer> indicesAndShards = new HashMap<>();
for (RoutingNode node : routingNodes) {
for (ShardRouting shard : node) {
if (!shard.active() && shard.relocatingNodeId() == null) {
if (!shard.relocating()) {
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
}
}
if (shard.relocating()) {
relocating++;
}
Integer i = indicesAndShards.get(shard.index());
if (i == null) {
i = shard.id();
}
indicesAndShards.put(shard.index(), Math.max(i, shard.id()));
}
}
// Assert that the active shard routing are identical.
Set<Map.Entry<Index, Integer>> entries = indicesAndShards.entrySet();
final List<ShardRouting> shards = new ArrayList<>();
for (Map.Entry<Index, Integer> e : entries) {
Index index = e.getKey();
for (int i = 0; i < e.getValue(); i++) {
for (RoutingNode routingNode : routingNodes) {
for (ShardRouting shardRouting : routingNode) {
if (shardRouting.index().equals(index) && shardRouting.id() == i) {
shards.add(shardRouting);
}
}
}
List<ShardRouting> mutableShardRoutings = routingNodes.assignedShards(new ShardId(index, i));
assert mutableShardRoutings.size() == shards.size();
for (ShardRouting r : mutableShardRoutings) {
assert shards.contains(r);
shards.remove(r);
}
assert shards.isEmpty();
}
}
for (ShardRouting shard : routingNodes.unassigned()) {
if (shard.primary()) {
unassignedPrimaryCount++;
}
}
for (ShardRouting shard : routingNodes.unassigned().ignored()) {
if (shard.primary()) {
unassignedIgnoredPrimaryCount++;
}
}
for (Map.Entry<String, Recoveries> recoveries : routingNodes.recoveryiesPerNode.entrySet()) {
String node = recoveries.getKey();
final Recoveries value = recoveries.getValue();
int incoming = 0;
int outgoing = 0;
RoutingNode routingNode = routingNodes.nodesToShards.get(node);
if (routingNode != null) { // node might have dropped out of the cluster
for (ShardRouting routing : routingNode) {
if (routing.initializing()) {
incoming++;
} else if (routing.relocating()) {
outgoing++;
}
if (routing.primary() && (routing.initializing() && routing.relocatingNodeId() != null) == false) { // we don't count the initialization end of the primary relocation
List<ShardRouting> shardRoutings = routingNodes.assignedShards.get(routing.shardId());
for (ShardRouting assigned : shardRoutings) {
if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) {
outgoing++;
}
}
}
}
}
assert incoming == value.incoming : incoming + " != " + value.incoming;
assert outgoing == value.outgoing : outgoing + " != " + value.outgoing + " node: " + routingNode;
}
assert unassignedPrimaryCount == routingNodes.unassignedShards.getNumPrimaries() :
"Unassigned primaries is [" + unassignedPrimaryCount + "] but RoutingNodes returned unassigned primaries [" + routingNodes.unassigned().getNumPrimaries() + "]";
assert unassignedIgnoredPrimaryCount == routingNodes.unassignedShards.getNumIgnoredPrimaries() :
"Unassigned ignored primaries is [" + unassignedIgnoredPrimaryCount + "] but RoutingNodes returned unassigned ignored primaries [" + routingNodes.unassigned().getNumIgnoredPrimaries() + "]";
assert inactivePrimaryCount == routingNodes.inactivePrimaryCount :
"Inactive Primary count [" + inactivePrimaryCount + "] but RoutingNodes returned inactive primaries [" + routingNodes.inactivePrimaryCount + "]";
assert inactiveShardCount == routingNodes.inactiveShardCount :
"Inactive Shard count [" + inactiveShardCount + "] but RoutingNodes returned inactive shards [" + routingNodes.inactiveShardCount + "]";
assert routingNodes.getRelocatingShardCount() == relocating : "Relocating shards mismatch [" + routingNodes.getRelocatingShardCount() + "] but expected [" + relocating + "]";
return true;
}
public class RoutingNodesIterator implements Iterator<RoutingNode>, Iterable<ShardRouting> {
private RoutingNode current;
private final Iterator<RoutingNode> delegate;
public RoutingNodesIterator(Iterator<RoutingNode> iterator) {
delegate = iterator;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public RoutingNode next() {
return current = delegate.next();
}
public RoutingNodeIterator nodeShards() {
return new RoutingNodeIterator(current);
}
@Override
public void remove() {
delegate.remove();
}
@Override
public Iterator<ShardRouting> iterator() {
return nodeShards();
}
}
public final class RoutingNodeIterator implements Iterator<ShardRouting>, Iterable<ShardRouting> {
private final RoutingNode iterable;
private ShardRouting shard;
private final Iterator<ShardRouting> delegate;
private boolean removed = false;
public RoutingNodeIterator(RoutingNode iterable) {
this.delegate = iterable.mutableIterator();
this.iterable = iterable;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public ShardRouting next() {
removed = false;
return shard = delegate.next();
}
@Override
public void remove() {
ensureMutable();
delegate.remove();
RoutingNodes.this.remove(shard);
removed = true;
}
/** returns true if {@link #remove()} or {@link #moveToUnassigned(UnassignedInfo)} were called on the current shard */
public boolean isRemoved() {
return removed;
}
@Override
public Iterator<ShardRouting> iterator() {
return iterable.iterator();
}
public void moveToUnassigned(UnassignedInfo unassignedInfo) {
ensureMutable();
if (isRemoved() == false) {
remove();
}
ShardRouting unassigned = new ShardRouting(shard); // protective copy of the mutable shard
unassigned.moveToUnassigned(unassignedInfo);
unassigned().add(unassigned);
}
public ShardRouting current() {
return shard;
}
}
private void ensureMutable() {
if (readOnly) {
throw new IllegalStateException("can't modify RoutingNodes - readonly");
}
}
private static final class Recoveries {
private static final Recoveries EMPTY = new Recoveries();
private int incoming = 0;
private int outgoing = 0;
int getTotal() {
return incoming + outgoing;
}
void addOutgoing(int howMany) {
assert outgoing + howMany >= 0 : outgoing + howMany+ " must be >= 0";
outgoing += howMany;
}
void addIncoming(int howMany) {
assert incoming + howMany >= 0 : incoming + howMany+ " must be >= 0";
incoming += howMany;
}
int getOutgoing() {
return outgoing;
}
int getIncoming() {
return incoming;
}
public static Recoveries getOrAdd(Map<String, Recoveries> map, String key) {
Recoveries recoveries = map.get(key);
if (recoveries == null) {
recoveries = new Recoveries();
map.put(key, recoveries);
}
return recoveries;
}
}
}
| mapr/elasticsearch | core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java | Java | apache-2.0 | 37,917 |
/*
* Copyright 2017 Yahoo Holdings, 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.yahoo.athenz.zms;
import java.util.List;
import com.yahoo.athenz.zms.store.ObjectStoreConnection;
import com.yahoo.athenz.zms.utils.ZMSUtils;
import com.yahoo.rdl.Timestamp;
class QuotaChecker {
private final Quota defaultQuota;
private boolean quotaCheckEnabled;
public QuotaChecker() {
// first check if the quota check is enabled or not
quotaCheckEnabled = Boolean.parseBoolean(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_CHECK, "true"));
// retrieve default quota values
int roleQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE, "1000"));
int roleMemberQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE_MEMBER, "100"));
int policyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_POLICY, "1000"));
int assertionQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ASSERTION, "100"));
int serviceQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE, "250"));
int serviceHostQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE_HOST, "10"));
int publicKeyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_PUBLIC_KEY, "100"));
int entityQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ENTITY, "100"));
int subDomainQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SUBDOMAIN, "100"));
defaultQuota = new Quota().setName("server-default")
.setAssertion(assertionQuota).setEntity(entityQuota)
.setPolicy(policyQuota).setPublicKey(publicKeyQuota)
.setRole(roleQuota).setRoleMember(roleMemberQuota)
.setService(serviceQuota).setServiceHost(serviceHostQuota)
.setSubdomain(subDomainQuota).setModified(Timestamp.fromCurrentTime());
}
public Quota getDomainQuota(ObjectStoreConnection con, String domainName) {
Quota quota = con.getQuota(domainName);
return (quota == null) ? defaultQuota : quota;
}
void setQuotaCheckEnabled(boolean quotaCheckEnabled) {
this.quotaCheckEnabled = quotaCheckEnabled;
}
int getListSize(List<?> list) {
return (list == null) ? 0 : list.size();
}
void checkSubdomainQuota(ObjectStoreConnection con, String domainName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// for sub-domains we need to run the quota check against
// the top level domain so let's get that first. If we are
// creating a top level domain then there is no need for
// quota check
int idx = domainName.indexOf('.');
if (idx == -1) {
return;
}
final String topLevelDomain = domainName.substring(0, idx);
// now get the quota for the top level domain
final Quota quota = getDomainQuota(con, topLevelDomain);
// get the list of sub-domains for our given top level domain
final String domainPrefix = topLevelDomain + ".";
int objectCount = con.listDomains(domainPrefix, 0).size() + 1;
if (quota.getSubdomain() < objectCount) {
throw ZMSUtils.quotaLimitError("subdomain quota exceeded - limit: "
+ quota.getSubdomain() + " actual: " + objectCount, caller);
}
}
void checkRoleQuota(ObjectStoreConnection con, String domainName, Role role, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our role is null then there is no quota check
if (role == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(role.getRoleMembers());
if (quota.getRoleMember() < objectCount) {
throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: "
+ quota.getRoleMember() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this role in the domain
objectCount = con.countRoles(domainName) + 1;
if (quota.getRole() < objectCount) {
throw ZMSUtils.quotaLimitError("role quota exceeded - limit: "
+ quota.getRole() + " actual: " + objectCount, caller);
}
}
void checkRoleMembershipQuota(ObjectStoreConnection con, String domainName,
String roleName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more member
// to this role without exceeding the quota
int objectCount = con.countRoleMembers(domainName, roleName) + 1;
if (quota.getRoleMember() < objectCount) {
throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: "
+ quota.getRoleMember() + " actual: " + objectCount, caller);
}
}
void checkPolicyQuota(ObjectStoreConnection con, String domainName, Policy policy, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our policy is null then there is no quota check
if (policy == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(policy.getAssertions());
if (quota.getAssertion() < objectCount) {
throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: "
+ quota.getAssertion() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this policy in the domain
objectCount = con.countPolicies(domainName) + 1;
if (quota.getPolicy() < objectCount) {
throw ZMSUtils.quotaLimitError("policy quota exceeded - limit: "
+ quota.getPolicy() + " actual: " + objectCount, caller);
}
}
void checkPolicyAssertionQuota(ObjectStoreConnection con, String domainName,
String policyName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more assertion
// to this policy without exceeding the quota
int objectCount = con.countAssertions(domainName, policyName) + 1;
if (quota.getAssertion() < objectCount) {
throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: "
+ quota.getAssertion() + " actual: " + objectCount, caller);
}
}
void checkServiceIdentityQuota(ObjectStoreConnection con, String domainName,
ServiceIdentity service, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our service is null then there is no quota check
if (service == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(service.getHosts());
if (quota.getServiceHost() < objectCount) {
throw ZMSUtils.quotaLimitError("service host quota exceeded - limit: "
+ quota.getServiceHost() + " actual: " + objectCount, caller);
}
objectCount = getListSize(service.getPublicKeys());
if (quota.getPublicKey() < objectCount) {
throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: "
+ quota.getPublicKey() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this service in the domain
objectCount = con.countServiceIdentities(domainName) + 1;
if (quota.getService() < objectCount) {
throw ZMSUtils.quotaLimitError("service quota exceeded - limit: "
+ quota.getService() + " actual: " + objectCount, caller);
}
}
void checkServiceIdentityPublicKeyQuota(ObjectStoreConnection con, String domainName,
String serviceName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more public key
// to this policy without exceeding the quota
int objectCount = con.countPublicKeys(domainName, serviceName) + 1;
if (quota.getPublicKey() < objectCount) {
throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: "
+ quota.getPublicKey() + " actual: " + objectCount, caller);
}
}
void checkEntityQuota(ObjectStoreConnection con, String domainName, Entity entity,
String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our entity is null then there is no quota check
if (entity == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// we're going to check if we'll be allowed
// to create this entity in the domain
int objectCount = con.countEntities(domainName) + 1;
if (quota.getEntity() < objectCount) {
throw ZMSUtils.quotaLimitError("entity quota exceeded - limit: "
+ quota.getEntity() + " actual: " + objectCount, caller);
}
}
}
| gurleen-gks/athenz | servers/zms/src/main/java/com/yahoo/athenz/zms/QuotaChecker.java | Java | apache-2.0 | 12,013 |
/* 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 java.nio;
import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a char buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by
* the adapter. It must NOT be accessed outside the adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter.
* The adapter extends Buffer, thus has its own position and limit.</li>
* </ul>
* </p>
*
*/
final class ByteBufferAsCharBuffer extends CharBuffer {
private final ByteBuffer byteBuffer;
static CharBuffer asCharBuffer(ByteBuffer byteBuffer) {
ByteBuffer slice = byteBuffer.slice();
slice.order(byteBuffer.order());
return new ByteBufferAsCharBuffer(slice);
}
private ByteBufferAsCharBuffer(ByteBuffer byteBuffer) {
super(byteBuffer.capacity() / SizeOf.CHAR);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public CharBuffer asReadOnlyBuffer() {
ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
buf.byteBuffer.order = byteBuffer.order;
return buf;
}
@Override
public CharBuffer compact() {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public CharBuffer duplicate() {
ByteBuffer bb = byteBuffer.duplicate().order(byteBuffer.order());
ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(bb);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public char get() {
if (position == limit) {
throw new BufferUnderflowException();
}
return byteBuffer.getChar(position++ * SizeOf.CHAR);
}
@Override
public char get(int index) {
checkIndex(index);
return byteBuffer.getChar(index * SizeOf.CHAR);
}
@Override
public CharBuffer get(char[] dst, int dstOffset, int charCount) {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
if (byteBuffer instanceof DirectByteBuffer) {
((DirectByteBuffer) byteBuffer).get(dst, dstOffset, charCount);
} else {
((ByteArrayBuffer) byteBuffer).get(dst, dstOffset, charCount);
}
this.position += charCount;
return this;
}
@Override
public boolean isDirect() {
return byteBuffer.isDirect();
}
@Override
public boolean isReadOnly() {
return byteBuffer.isReadOnly();
}
@Override
public ByteOrder order() {
return byteBuffer.order();
}
@Override char[] protectedArray() {
throw new UnsupportedOperationException();
}
@Override int protectedArrayOffset() {
throw new UnsupportedOperationException();
}
@Override boolean protectedHasArray() {
return false;
}
@Override
public CharBuffer put(char c) {
if (position == limit) {
throw new BufferOverflowException();
}
byteBuffer.putChar(position++ * SizeOf.CHAR, c);
return this;
}
@Override
public CharBuffer put(int index, char c) {
checkIndex(index);
byteBuffer.putChar(index * SizeOf.CHAR, c);
return this;
}
@Override
public CharBuffer put(char[] src, int srcOffset, int charCount) {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
if (byteBuffer instanceof DirectByteBuffer) {
((DirectByteBuffer) byteBuffer).put(src, srcOffset, charCount);
} else {
((ByteArrayBuffer) byteBuffer).put(src, srcOffset, charCount);
}
this.position += charCount;
return this;
}
@Override
public CharBuffer slice() {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
ByteBuffer bb = byteBuffer.slice().order(byteBuffer.order());
CharBuffer result = new ByteBufferAsCharBuffer(bb);
byteBuffer.clear();
return result;
}
@Override public CharBuffer subSequence(int start, int end) {
checkStartEndRemaining(start, end);
CharBuffer result = duplicate();
result.limit(position + end);
result.position(position + start);
return result;
}
}
| indashnet/InDashNet.Open.UN2000 | android/libcore/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java | Java | apache-2.0 | 5,714 |
/*
* Copyright © 2014 - 2018 Leipzig University (Database Research Group)
*
* 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.gradoop.examples.io;
import org.apache.flink.api.common.ProgramDescription;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.gradoop.examples.AbstractRunner;
import org.gradoop.flink.io.impl.deprecated.json.JSONDataSink;
import org.gradoop.flink.io.impl.deprecated.json.JSONDataSource;
import org.gradoop.flink.model.impl.epgm.GraphCollection;
import org.gradoop.flink.model.impl.epgm.LogicalGraph;
import org.gradoop.flink.model.impl.operators.combination.ReduceCombination;
import org.gradoop.flink.model.impl.operators.grouping.Grouping;
import org.gradoop.flink.util.GradoopFlinkConfig;
import static java.util.Collections.singletonList;
/**
* Example program that reads a graph from an EPGM-specific JSON representation
* into a {@link GraphCollection}, does some computation and stores the
* resulting {@link LogicalGraph} as JSON.
*
* In the JSON representation, an EPGM graph collection (or Logical Graph) is
* stored in three (or two) separate files. Each line in those files contains
* a valid JSON-document describing a single entity:
*
* Example graphHead (data attached to logical graphs):
*
* {
* "id":"graph-uuid-1",
* "data":{"interest":"Graphs","vertexCount":4},
* "meta":{"label":"Community"}
* }
*
* Example vertex JSON document:
*
* {
* "id":"vertex-uuid-1",
* "data":{"gender":"m","city":"Dresden","name":"Dave","age":40},
* "meta":{"label":"Person","graphs":["graph-uuid-1"]}
* }
*
* Example edge JSON document:
*
* {
* "id":"edge-uuid-1",
* "source":"14505ae1-5003-4458-b86b-d137daff6525",
* "target":"ed8386ee-338a-4177-82c4-6c1080df0411",
* "data":{},
* "meta":{"label":"friendOf","graphs":["graph-uuid-1"]}
* }
*
* An example graph collection can be found under src/main/resources/data.json.
* For further information, have a look at the {@link org.gradoop.flink.io.impl.deprecated.json}
* package.
*/
public class JSONExample extends AbstractRunner implements ProgramDescription {
/**
* Reads an EPGM graph collection from a directory that contains the separate
* files. Files can be stored in local file system or HDFS.
*
* args[0]: path to input graph
* args[1]: path to output graph
*
* @param args program arguments
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException(
"provide graph/vertex/edge paths and output directory");
}
final String inputPath = args[0];
final String outputPath = args[1];
// init Flink execution environment
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
// create default Gradoop config
GradoopFlinkConfig config = GradoopFlinkConfig.createConfig(env);
// create DataSource
JSONDataSource dataSource = new JSONDataSource(inputPath, config);
// read graph collection from DataSource
GraphCollection graphCollection = dataSource.getGraphCollection();
// do some analytics
LogicalGraph schema = graphCollection
.reduce(new ReduceCombination())
.groupBy(singletonList(Grouping.LABEL_SYMBOL), singletonList(Grouping.LABEL_SYMBOL));
// write resulting graph to DataSink
schema.writeTo(new JSONDataSink(outputPath, config));
// execute program
env.execute();
}
@Override
public String getDescription() {
return "EPGM JSON IO Example";
}
}
| niklasteichmann/gradoop | gradoop-examples/src/main/java/org/gradoop/examples/io/JSONExample.java | Java | apache-2.0 | 4,053 |
package com.altas.preferencevobjectfile.model;
import java.io.Serializable;
/**
* @author Altas
* @email Altas.TuTu@gmail.com
* @date 2014年9月27日
*/
public class UserInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8558071977129572083L;
public int id;
public String token;
public String userName;
public String headImg;
public String phoneNum;
public double balance;
public int integral;
public UserInfo(){}
public UserInfo(int i,String t,String un,String hi,String pn,double b,int point){
id=i;
token=t;
userName = un;
headImg = hi;
phoneNum = pn;
balance = b;
integral = point;
}
}
| mdreza/PreferenceVObjectFile | PreferenceVObjectFile/src/com/altas/preferencevobjectfile/model/UserInfo.java | Java | apache-2.0 | 663 |
/* Copyright 2017 Braden Farmer
*
* 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.farmerbb.secondscreen.service;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.text.InputType;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import com.farmerbb.secondscreen.R;
import com.farmerbb.secondscreen.receiver.KeyboardChangeReceiver;
import com.farmerbb.secondscreen.util.U;
import java.util.Random;
public class DisableKeyboardService extends InputMethodService {
Integer notificationId;
@Override
public boolean onShowInputRequested(int flags, boolean configChange) {
return false;
}
@Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
boolean isEditingText = attribute.inputType != InputType.TYPE_NULL;
boolean hasHardwareKeyboard = getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
if(notificationId == null && isEditingText && !hasHardwareKeyboard) {
Intent keyboardChangeIntent = new Intent(this, KeyboardChangeReceiver.class);
PendingIntent keyboardChangePendingIntent = PendingIntent.getBroadcast(this, 0, keyboardChangeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setContentIntent(keyboardChangePendingIntent)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setContentTitle(getString(R.string.disabling_soft_keyboard))
.setContentText(getString(R.string.tap_to_change_keyboards))
.setOngoing(true)
.setShowWhen(false);
// Respect setting to hide notification
SharedPreferences prefMain = U.getPrefMain(this);
if(prefMain.getBoolean("hide_notification", false))
notification.setPriority(Notification.PRIORITY_MIN);
notificationId = new Random().nextInt();
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationId, notification.build());
boolean autoShowInputMethodPicker = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
switch(devicePolicyManager.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
break;
default:
autoShowInputMethodPicker = true;
break;
}
}
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if(keyguardManager.inKeyguardRestrictedInputMode() && autoShowInputMethodPicker) {
InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
manager.showInputMethodPicker();
}
} else if(notificationId != null && !isEditingText) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
}
@Override
public void onDestroy() {
if(notificationId != null) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
super.onDestroy();
}
}
| farmerbb/SecondScreen | app/src/main/java/com/farmerbb/secondscreen/service/DisableKeyboardService.java | Java | apache-2.0 | 4,734 |
/**
* Copyright (c) 2005-2012 https://github.com/zhuruiboqq
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.common.entity.search.filter;
import com.sishuok.es.common.entity.search.SearchOperator;
import com.sishuok.es.common.entity.search.exception.InvlidSearchOperatorException;
import com.sishuok.es.common.entity.search.exception.SearchException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import java.util.List;
/**
* <p>查询过滤条件</p>
* <p>User: Zhang Kaitao
* <p>Date: 13-1-15 上午7:12
* <p>Version: 1.0
*/
public final class Condition implements SearchFilter {
//查询参数分隔符
public static final String separator = "_";
private String key;
private String searchProperty;
private SearchOperator operator;
private Object value;
/**
* 根据查询key和值生成Condition
*
* @param key 如 name_like
* @param value
* @return
*/
static Condition newCondition(final String key, final Object value) throws SearchException {
Assert.notNull(key, "Condition key must not null");
String[] searchs = StringUtils.split(key, separator);
if (searchs.length == 0) {
throw new SearchException("Condition key format must be : property or property_op");
}
String searchProperty = searchs[0];
SearchOperator operator = null;
if (searchs.length == 1) {
operator = SearchOperator.custom;
} else {
try {
operator = SearchOperator.valueOf(searchs[1]);
} catch (IllegalArgumentException e) {
throw new InvlidSearchOperatorException(searchProperty, searchs[1]);
}
}
boolean allowBlankValue = SearchOperator.isAllowBlankValue(operator);
boolean isValueBlank = (value == null);
isValueBlank = isValueBlank || (value instanceof String && StringUtils.isBlank((String) value));
isValueBlank = isValueBlank || (value instanceof List && ((List) value).size() == 0);
//过滤掉空值,即不参与查询
if (!allowBlankValue && isValueBlank) {
return null;
}
Condition searchFilter = newCondition(searchProperty, operator, value);
return searchFilter;
}
/**
* 根据查询属性、操作符和值生成Condition
*
* @param searchProperty
* @param operator
* @param value
* @return
*/
static Condition newCondition(final String searchProperty, final SearchOperator operator, final Object value) {
return new Condition(searchProperty, operator, value);
}
/**
* @param searchProperty 属性名
* @param operator 操作
* @param value 值
*/
private Condition(final String searchProperty, final SearchOperator operator, final Object value) {
this.searchProperty = searchProperty;
this.operator = operator;
this.value = value;
this.key = this.searchProperty + separator + this.operator;
}
public String getKey() {
return key;
}
public String getSearchProperty() {
return searchProperty;
}
/**
* 获取 操作符
*
* @return
*/
public SearchOperator getOperator() throws InvlidSearchOperatorException {
return operator;
}
/**
* 获取自定义查询使用的操作符
* 1、首先获取前台传的
* 2、返回空
*
* @return
*/
public String getOperatorStr() {
if (operator != null) {
return operator.getSymbol();
}
return "";
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
public void setOperator(final SearchOperator operator) {
this.operator = operator;
}
public void setSearchProperty(final String searchProperty) {
this.searchProperty = searchProperty;
}
/**
* 得到实体属性名
*
* @return
*/
public String getEntityProperty() {
return searchProperty;
}
/**
* 是否是一元过滤 如is null is not null
*
* @return
*/
public boolean isUnaryFilter() {
String operatorStr = getOperator().getSymbol();
return StringUtils.isNotEmpty(operatorStr) && operatorStr.startsWith("is");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Condition that = (Condition) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
return true;
}
@Override
public int hashCode() {
return key != null ? key.hashCode() : 0;
}
@Override
public String toString() {
return "Condition{" +
"searchProperty='" + searchProperty + '\'' +
", operator=" + operator +
", value=" + value +
'}';
}
}
| zhuruiboqq/romantic-factor_baseOnES | common/src/main/java/com/sishuok/es/common/entity/search/filter/Condition.java | Java | apache-2.0 | 5,176 |
package com.hzh.corejava.proxy;
public class SpeakerExample {
public static void main(String[] args) {
AiSpeaker speaker = (AiSpeaker) AuthenticationProxy.newInstance(new XiaoaiAiSpeeker());
speaker.greeting();
}
}
| huangzehai/core-java | src/main/java/com/hzh/corejava/proxy/SpeakerExample.java | Java | apache-2.0 | 240 |
package io.skysail.server.queryfilter.nodes.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import io.skysail.domain.Entity;
import io.skysail.server.domain.jvm.FieldFacet;
import io.skysail.server.domain.jvm.facets.NumberFacet;
import io.skysail.server.domain.jvm.facets.YearFacet;
import io.skysail.server.filter.ExprNode;
import io.skysail.server.filter.FilterVisitor;
import io.skysail.server.filter.Operation;
import io.skysail.server.filter.PreparedStatement;
import io.skysail.server.filter.SqlFilterVisitor;
import io.skysail.server.queryfilter.nodes.LessNode;
import lombok.Data;
public class LessNodeTest {
@Data
public class SomeEntity implements Entity {
private String id, A, B;
}
@Test
public void defaultConstructor_creates_node_with_AND_operation_and_zero_children() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
assertThat(lessNode.isLeaf(),is(true));
}
@Test
public void listConstructor_creates_node_with_AND_operation_and_assigns_the_children_parameter() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
}
@Test
public void lessNode_with_one_children_gets_rendered() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.asLdapString(),is("(A<0)"));
}
@Test
public void nodes_toString_method_provides_representation() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.toString(),is("(A<0)"));
}
@Test
public void reduce_removes_the_matching_child() {
LessNode lessNode = new LessNode("A", 0);
Map<String, String> config = new HashMap<>();
config.put("BORDERS", "1");
assertThat(lessNode.reduce("(A<0)", new NumberFacet("A",config), null).asLdapString(),is(""));
}
@Test
public void reduce_does_not_remove_non_matching_child() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.reduce("b",null, null).asLdapString(),is("(A<0)"));
}
@Test
public void creates_a_simple_preparedStatement() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A<:A"));
}
@Test
public void creates_a_preparedStatement_with_year_facet() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
Map<String, String> config = new HashMap<>();
facets.put("A", new YearFacet("A", config));
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A.format('YYYY')<:A"));
}
// @Test
// public void evaluateEntity() {
// LessNode lessNode = new LessNode("A", 0);
// Map<String, FieldFacet> facets = new HashMap<>();
// Map<String, String> config = new HashMap<>();
// facets.put("A", new YearFacet("A", config));
//
// SomeEntity someEntity = new SomeEntity();
// someEntity.setA(0);
// someEntity.setB("b");
//
// EntityEvaluationFilterVisitor entityEvaluationVisitor = new EntityEvaluationFilterVisitor(someEntity, facets);
// boolean evaluateEntity = lessNode.evaluateEntity(entityEvaluationVisitor);
//
// assertThat(evaluateEntity,is(false));
// }
@Test
@Ignore
public void getSelected() {
LessNode lessNode = new LessNode("A", 0);
FieldFacet facet = new YearFacet("id", Collections.emptyMap());
Iterator<String> iterator = lessNode.getSelected(facet,Collections.emptyMap()).iterator();
assertThat(iterator.next(),is("0"));
}
@Test
public void getKeys() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getKeys().size(),is(1));
Iterator<String> iterator = lessNode.getKeys().iterator();
assertThat(iterator.next(),is("A"));
}
@Test
public void accept() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.accept(new FilterVisitor() {
@Override
public String visit(ExprNode node) {
return ".";
}
}),is("."));
}
}
| evandor/skysail | skysail.server.queryfilter/test/io/skysail/server/queryfilter/nodes/test/LessNodeTest.java | Java | apache-2.0 | 4,873 |
import ch.usi.overseer.OverAgent;
import ch.usi.overseer.OverHpc;
/**
* Overseer.OverAgent sample application.
* This example shows a basic usage of the OverAgent java agent to keep track of all the threads created
* by the JVM. Threads include garbage collectors, finalizers, etc. In order to use OverAgent, make sure to
* append this option to your command-line:
*
* -agentpath:/usr/local/lib/liboverAgent.so
*
* @author Achille Peternier (C) 2011 USI
*/
public class java_agent
{
static public void main(String argv[])
{
// Credits:
System.out.println("Overseer Java Agent test, A. Peternier (C) USI 2011\n");
// Check that -agentpath is working:
if (OverAgent.isRunning())
System.out.println(" OverAgent is running");
else
{
System.out.println(" OverAgent is not running (check your JVM settings)");
return;
}
// Get some info:
System.out.println(" Threads running: " + OverAgent.getNumberOfThreads());
System.out.println();
OverAgent.initEventCallback(new OverAgent.Callback()
{
// Callback invoked at thread creation:
public int onThreadCreation(int pid, String name)
{
System.out.println("[new] " + name + " (" + pid + ")");
return 0;
}
// Callback invoked at thread termination:
public int onThreadTermination(int pid, String name)
{
System.out.println("[delete] " + name + " (" + pid + ")");
return 0;
}});
OverHpc oHpc = OverHpc.getInstance();
int pid = oHpc.getThreadId();
OverAgent.updateStats();
// Waste some time:
double r = 0.0;
for (int d=0; d<10; d++)
{
if (true)
{
for (long c=0; c<100000000; c++)
{
r += r * Math.sqrt(r) * Math.pow(r, 40.0);
}
}
else
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
OverAgent.updateStats();
System.out.println(" Thread " + pid + " abs: " + OverAgent.getThreadCpuUsage(pid) + "%, rel: " + OverAgent.getThreadCpuUsageRelative(pid) + "%");
}
// Done:
System.out.println("Application terminated");
}
}
| IvanMamontov/overseer | examples/java_agent.java | Java | apache-2.0 | 2,131 |
package mat.model;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The Class SecurityRole.
*/
public class SecurityRole implements IsSerializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant ADMIN_ROLE. */
public static final String ADMIN_ROLE = "Administrator";
/** The Constant USER_ROLE. */
public static final String USER_ROLE = "User";
/** The Constant SUPER_USER_ROLE. */
public static final String SUPER_USER_ROLE = "Super user";
/** The Constant ADMIN_ROLE_ID. */
public static final String ADMIN_ROLE_ID = "1";
/** The Constant USER_ROLE_ID. */
public static final String USER_ROLE_ID = "2";
/** The Constant SUPER_USER_ROLE_ID. */
public static final String SUPER_USER_ROLE_ID = "3";
/** The id. */
private String id;
/** The description. */
private String description;
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id
* the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description
* the new description
*/
public void setDescription(String description) {
this.description = description;
}
}
| JaLandry/MeasureAuthoringTool_LatestSprint | mat/src/mat/model/SecurityRole.java | Java | apache-2.0 | 1,430 |
package com.gaojun.appmarket.ui.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.gaojun.appmarket.R;
/**
* Created by Administrator on 2016/6/29.
*/
public class RationLayout extends FrameLayout {
private float ratio;
public RationLayout(Context context) {
super(context);
initView();
}
public RationLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RationLayout);
int n = array.length();
for (int i = 0; i < n; i++) {
switch (i){
case R.styleable.RationLayout_ratio:
ratio = array.getFloat(R.styleable.RationLayout_ratio,-1);
break;
}
}
array.recycle();
}
public RationLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY &&
ratio>0){
int imageWidth = width - getPaddingLeft() - getPaddingRight();
int imageHeight = (int) (imageWidth/ratio);
height = imageHeight + getPaddingTop() + getPaddingBottom();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initView() {
}
}
| GaoJunLoveHL/AppMaker | market/src/main/java/com/gaojun/appmarket/ui/view/RationLayout.java | Java | apache-2.0 | 1,962 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a block storage disk mapping.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DiskMap" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DiskMap implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*/
private String originalDiskPath;
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*/
private String newDiskName;
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public void setOriginalDiskPath(String originalDiskPath) {
this.originalDiskPath = originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @return The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public String getOriginalDiskPath() {
return this.originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withOriginalDiskPath(String originalDiskPath) {
setOriginalDiskPath(originalDiskPath);
return this;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
*/
public void setNewDiskName(String newDiskName) {
this.newDiskName = newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @return The new disk name (e.g., <code>my-new-disk</code>).
*/
public String getNewDiskName() {
return this.newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withNewDiskName(String newDiskName) {
setNewDiskName(newDiskName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getOriginalDiskPath() != null)
sb.append("OriginalDiskPath: ").append(getOriginalDiskPath()).append(",");
if (getNewDiskName() != null)
sb.append("NewDiskName: ").append(getNewDiskName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DiskMap == false)
return false;
DiskMap other = (DiskMap) obj;
if (other.getOriginalDiskPath() == null ^ this.getOriginalDiskPath() == null)
return false;
if (other.getOriginalDiskPath() != null && other.getOriginalDiskPath().equals(this.getOriginalDiskPath()) == false)
return false;
if (other.getNewDiskName() == null ^ this.getNewDiskName() == null)
return false;
if (other.getNewDiskName() != null && other.getNewDiskName().equals(this.getNewDiskName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getOriginalDiskPath() == null) ? 0 : getOriginalDiskPath().hashCode());
hashCode = prime * hashCode + ((getNewDiskName() == null) ? 0 : getNewDiskName().hashCode());
return hashCode;
}
@Override
public DiskMap clone() {
try {
return (DiskMap) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lightsail.model.transform.DiskMapMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/DiskMap.java | Java | apache-2.0 | 6,034 |
/*
* Copyright 2011-2014 Zhaotian Wang <zhaotianzju@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flex.android.magiccube;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import flex.android.magiccube.R;
import flex.android.magiccube.bluetooth.MessageSender;
import flex.android.magiccube.interfaces.OnStateListener;
import flex.android.magiccube.interfaces.OnStepListener;
import flex.android.magiccube.solver.MagicCubeSolver;
import flex.android.magiccube.solver.SolverFactory;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.Matrix;
public class MagicCubeRender implements GLSurfaceView.Renderer {
protected Context context;
private int width;
private int height;
//eye-coordinate
private float eyex;
private float eyey;
protected float eyez;
private float angle = 65.f;
protected float ratio = 0.6f;
protected float zfar = 25.5f;
private float bgdist = 25.f;
//background texture
private int[] BgTextureID = new int[1];
private Bitmap[] bitmap = new Bitmap[1];
private FloatBuffer bgtexBuffer; // Texture Coords Buffer for background
private FloatBuffer bgvertexBuffer; // Vertex Buffer for background
protected final int nStep = 9;//nstep for one rotate
protected int volume;
private boolean solved = false; //indicate if the cube has been solved
//background position
//...
//rotation variable
public float rx, ry;
protected Vector<Command> commands;
private Vector<Command> commandsBack; //backward command
private Vector<Command> commandsForward; //forward command
private Vector<Command> commandsAuto; //forward command
protected int[] command;
protected boolean HasCommand;
protected int CommandLoop;
private String CmdStrBefore = "";
private String CmdStrAfter = "";
public static final boolean ROTATE = true;
public static final boolean MOVE = false;
//matrix
public float[] pro_matrix = new float[16];
public int [] view_matrix = new int[4];
public float[] mod_matrix = new float[16];
//minimal valid move distance
private float MinMovedist;
//the cubes!
protected Magiccube magiccube;
private boolean DrawCube;
private boolean Finished = false;
private boolean Resetting = false;
protected OnStateListener stateListener = null;
private MessageSender messageSender = null;
private OnStepListener stepListener = null;
public MagicCubeRender(Context context, int w, int h) {
this.context = context;
this.width = w;
this.height = h;
this.eyex = 0.f;
this.eyey = 0.f;
this.eyez = 20.f;
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
this.commands = new Vector<Command>(1,1);
this.commandsBack = new Vector<Command>(100, 10);
this.commandsForward = new Vector<Command>(100, 10);
this.commandsAuto = new Vector<Command>(40,5);
//this.Command = new int[3];
magiccube = new Magiccube();
DrawCube = true;
solved = false;
volume = MagiccubePreference.GetPreference(MagiccubePreference.MoveVolume, context);
//SetCommands("L- R2 F- D+ L+ U2 L2 D2 R+ D2 L+ F- D+ L2 D2 R2 B+ L+ U2 R2 U2 F2 R+ D2 U+");
//SetCommands("F- U+ F- D- L- D- F- U- L2 D-");
// SetCommands("U+");
// mediaPlayer = MediaPlayer.create(context, R.raw.move2);
}
public void SetDrawCube(boolean DrawCube)
{
this.DrawCube = DrawCube;
}
private void LoadBgTexture(GL10 gl)
{
//Load texture bitmap
bitmap[0] = BitmapFactory.decodeStream(
context.getResources().openRawResource(R.drawable.mainbg2));
gl.glGenTextures(1, BgTextureID, 0); // Generate texture-ID array for 6 IDs
//Set texture uv
float[] texCoords = {
0.0f, 1.0f, // A. left-bottom
1.0f, 1.0f, // B. right-bottom
0.0f, 0.0f, // C. left-top
1.0f, 0.0f // D. right-top
};
ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4 );
tbb.order(ByteOrder.nativeOrder());
bgtexBuffer = tbb.asFloatBuffer();
bgtexBuffer.put(texCoords);
bgtexBuffer.position(0); // Rewind
// Generate OpenGL texture images
gl.glBindTexture(GL10.GL_TEXTURE_2D, BgTextureID[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap[0], 0);
bitmap[0].recycle();
}
protected void DrawBg(GL10 gl)
{
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, bgvertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, bgtexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D); // Enable texture (NEW)
gl.glPushMatrix();
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.BgTextureID[0]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glPopMatrix();
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void onDrawFrame(GL10 gl) {
// Clear color and depth buffers using clear-value set earlier
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// You OpenGL|ES rendering code here
gl.glLoadIdentity();
GLU.gluLookAt(gl, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
Matrix.setIdentityM(mod_matrix, 0);
Matrix.setLookAtM(mod_matrix, 0, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
DrawScene(gl);
}
private void SetBackgroundPosition()
{
float halfheight = (float)Math.tan(angle/2.0/180.0*Math.PI)*bgdist*1.f;
float halfwidth = halfheight/this.height*this.width;
float[] vertices = {
-halfwidth, -halfheight, eyez-bgdist, // 0. left-bottom-front
halfwidth, -halfheight, eyez-bgdist, // 1. right-bottom-front
-halfwidth, halfheight,eyez-bgdist, // 2. left-top-front
halfwidth, halfheight, eyez-bgdist, // 3. right-top-front
};
ByteBuffer vbb = ByteBuffer.allocateDirect(12 * 4);
vbb.order(ByteOrder.nativeOrder());
bgvertexBuffer = vbb.asFloatBuffer();
bgvertexBuffer.put(vertices); // Populate
bgvertexBuffer.position(0); // Rewind
}
@Override
public void onSurfaceChanged(GL10 gl, int w, int h) {
//reset the width and the height;
//Log.e("screen", w+" "+h);
if (h == 0) h = 1; // To prevent divide by zero
this.width = w;
this.height = h;
float aspect = (float)w / h;
// Set the viewport (display area) to cover the entire window
gl.glViewport(0, 0, w, h);
this.view_matrix[0] = 0;
this.view_matrix[1] = 0;
this.view_matrix[2] = w;
this.view_matrix[3] = h;
// Setup perspective projection, with aspect ratio matches viewport
gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix
gl.glLoadIdentity(); // Reset projection matrix
// Use perspective projection
angle = 60;
//calculate the angle to adjust the screen resolution
//float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealheight = idealwidth/(float)w*(float)h;
angle = (float)(Math.atan2(idealheight/2.f, Math.abs(zfar))*2.f*180.f/Math.PI);
SetBackgroundPosition();
GLU.gluPerspective(gl, angle, aspect, 0.1f, zfar);
MinMovedist = w*ratio/3.f*0.15f;
float r = (float)w/(float)h;
float size = (float)(0.1*Math.tan(angle/2.0/180.0*Math.PI));
Matrix.setIdentityM(pro_matrix, 0);
Matrix.frustumM(pro_matrix, 0, -size*r, size*r, -size , size, 0.1f, zfar);
gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
gl.glLoadIdentity(); // Reset
/* // You OpenGL|ES display re-sizing code here
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
//float []lightparam = {0.6f, 0.2f, 0.2f, 0.6f, 0.2f, 0.2f, 0, 0, 10};
float []lightparam = {1f, 1f, 1f, 3f, 1f, 1f, 0, 0, 5};
gl.glEnable(GL10.GL_LIGHTING);
// ���û�����
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightparam, 0);
// ���������
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightparam, 3);
// ���þ��淴��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightparam, 3);
// ���ù�Դλ��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightparam, 6);
// ������Դ
gl.glEnable(GL10.GL_LIGHT0);
*/
// �������
//gl.glEnable(GL10.GL_BLEND);
if( this.stateListener != null )
{
stateListener.OnStateChanged(OnStateListener.LOADED);
}
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black
gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest
gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal
gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view
gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color
gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance
// You OpenGL|ES initialization code here
//Initial the cubes
magiccube.LoadTexture(gl, context);
//this.MessUp(50);
LoadBgTexture(gl);
}
public void SetMessageSender(MessageSender messageSender)
{
this.messageSender = messageSender;
}
protected void DrawScene(GL10 gl)
{
this.DrawBg(gl);
if( !DrawCube)
{
return;
}
if(Resetting)
{
//Resetting = false;
//reset();
}
if(HasCommand)
{
Command command = commands.firstElement();
if( CommandLoop == 0 && messageSender != null)
{
messageSender.SendMessage(command.toString());
}
int nsteps = command.N*this.nStep; //rotate nsteps
if(CommandLoop%nStep == 0 && CommandLoop != nsteps)
{
MusicPlayThread musicPlayThread = new MusicPlayThread(context, R.raw.move2, volume);
musicPlayThread.start();
}
if(command.Type == Command.ROTATE_ROW)
{
magiccube.RotateRow(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else if(command.Type == Command.ROTATE_COL)
{
magiccube.RotateCol(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else
{
magiccube.RotateFace(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
CommandLoop++;
if(CommandLoop==nsteps)
{
CommandLoop = 0;
if(commands.size() > 1)
{
//Log.e("full", "full"+commands.size());
}
this.CmdStrAfter += command.toString() + " ";
commands.removeElementAt(0);
//Log.e("e", commands.size()+"");
if( commands.size() <= 0)
{
HasCommand = false;
}
if( stepListener != null)
{
stepListener.AddStep();
}
//this.ReportFaces();
//Log.e("state", this.GetState());
if(Finished && !this.IsComplete())
{
Finished = false;
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
}
if(this.stateListener != null && this.IsComplete())
{
if( !Finished )
{
Finished = true;
stateListener.OnStateChanged(OnStateListener.FINISH);
stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
}
DrawCubes(gl);
}
protected void DrawCubes(GL10 gl)
{
gl.glPushMatrix();
gl.glRotatef(rx, 1, 0, 0); //rotate
gl.glRotatef(ry, 0, 1, 0);
// Log.e("rxry", rx + " " + ry);
if(this.HasCommand)
{
magiccube.Draw(gl);
}
else
{
magiccube.DrawSimple(gl);
}
gl.glPopMatrix();
}
public void SetOnStateListener(OnStateListener stateListener)
{
this.stateListener = stateListener;
}
public void SetOnStepListnener(OnStepListener stepListener)
{
this.stepListener = stepListener;
}
public boolean GetPos(float[] point, int[] Pos)
{
//deal with the touch-point is out of the cube
if( true)
{
//return false;
}
if( rx > 0 && rx < 90.f)
{
}
return ROTATE;
}
public String SetCommand(Command command)
{
HasCommand = true;
this.commands.add(command);
this.commandsForward.clear();
this.commandsBack.add(command.Reverse());
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
return command.CmdToCmdStr();
}
public void SetForwardCommand(String CmdStr)
{
//Log.e("cmdstr", CmdStr);
this.commandsForward = Reverse(Command.CmdStrsToCmd(CmdStr));
}
public String SetCommand(int ColOrRowOrFace, int ID, int Direction)
{
solved = false;
return SetCommand(new Command(ColOrRowOrFace, ID, Direction));
}
public boolean IsSolved()
{
return solved;
}
public String MoveBack()
{
if( this.commandsBack.size() <= 0)
{
return null;
}
Command command = commandsBack.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.remove(this.commandsBack.size()-1);
if(this.commandsBack.size() <= 0 && stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
}
if( solved)
{
this.commandsAuto.add(command.Reverse());
}
else
{
this.commandsForward.add(command.Reverse());
if(stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEFORWARD);
}
}
return command.CmdToCmdStr();
}
public String MoveForward()
{
if( this.commandsForward.size() <= 0)
{
return null;
}
Command command = commandsForward.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsForward.remove(commandsForward.size()-1);
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return command.CmdToCmdStr();
}
public int MoveForward2()
{
if( this.commandsForward.size() <= 0)
{
return 0;
}
int n = commandsForward.size();
HasCommand = true;
this.commands.addAll(Reverse(commandsForward));
for( int i=commandsForward.size()-1; i>=0; i--)
{
this.commandsBack.add(commandsForward.get(i).Reverse());
}
this.commandsForward.clear();
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return n;
}
public int IsInCubeArea(float []Win)
{
int[] HitedFaceIndice = new int[6];
int HitNumber = 0;
for(int i=0; i<6; i++)
{
if(IsInQuad3D(magiccube.faces[i], Win))
{
HitedFaceIndice[HitNumber] = i;
HitNumber++;
}
}
if( HitNumber <=0)
{
return -1;
}
else
{
if( HitNumber == 1)
{
return HitedFaceIndice[0];
}
else //if more than one hitted, then choose the max z-value face as the hitted one
{
float maxzvalue = -1000.f;
int maxzindex = -1;
for( int i = 0; i< HitNumber; i++)
{
float thisz = this.GetCenterZ(magiccube.faces[HitedFaceIndice[i]]);
if( thisz > maxzvalue)
{
maxzvalue = thisz;
maxzindex = HitedFaceIndice[i];
}
}
return maxzindex;
}
}
}
private float GetLength2D(float []P1, float []P2)
{
float dx = P1[0]-P2[0];
float dy = P1[1]-P2[1];
return (float)Math.sqrt(dx*dx + dy*dy);
}
private boolean IsInQuad3D(Face f, float []Win)
{
return IsInQuad3D(f.P1, f.P2, f.P3, f.P4, Win);
}
private boolean IsInQuad3D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float[] Win1 = new float[2];
float[] Win2 = new float[2];
float[] Win3 = new float[2];
float[] Win4 = new float[2];
Project(Point1, Win1);
Project(Point2, Win2);
Project(Point3, Win3);
Project(Point4, Win4);
/* Log.e("P1", Win1[0] + " " + Win1[1]);
Log.e("P2", Win2[0] + " " + Win2[1]);
Log.e("P3", Win3[0] + " " + Win3[1]);
Log.e("P4", Win4[0] + " " + Win4[1]);*/
float []WinXY = new float[2];
WinXY[0] = Win[0];
WinXY[1] = this.view_matrix[3] - Win[1];
//Log.e("WinXY", WinXY[0] + " " + WinXY[1]);
return IsInQuad2D(Win1, Win2, Win3, Win4, WinXY);
}
private boolean IsInQuad2D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float angle = 0.f;
final float ZERO = 0.0001f;
angle += GetAngle(Win, Point1, Point2);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point2, Point3);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point3, Point4);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point4, Point1);
//Log.e("angle" , angle + " ");
if( Math.abs(angle-Math.PI*2.f) <= ZERO )
{
return true;
}
return false;
}
public String CalcCommand(float [] From, float [] To, int faceindex)
{
float [] from = new float[2];
float [] to = new float[2];
float angle, angleVertical, angleHorizon;
from[0] = From[0];
from[1] = this.view_matrix[3] - From[1];
to[0] = To[0];
to[1] = this.view_matrix[3] - To[1];
angle = GetAngle(from, to);//(float)Math.atan((to[1]-from[1])/(to[0]-from[0]))/(float)Math.PI*180.f;
//calc horizon angle
float ObjFrom[] = new float[3];
float ObjTo[] = new float[3];
float WinFrom[] = new float[2];
float WinTo[] = new float[2];
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P4[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P2[i] + magiccube.faces[faceindex].P3[i])/2.f;
}
//Log.e("obj", ObjFrom[0]+" "+ObjFrom[1]+" "+ObjFrom[2]);
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleHorizon = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//calc vertical angle
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P2[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P3[i] + magiccube.faces[faceindex].P4[i])/2.f;
}
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleVertical = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//Log.e("angle", angle +" " + angleHorizon + " " + angleVertical);
float dangle = DeltaAngle(angleHorizon, angleVertical);
float threshold = Math.min(dangle/2.f, 90.f-dangle/2.f)*0.75f; //this...........
if( DeltaAngle(angle, angleHorizon) < threshold || DeltaAngle(angle, (angleHorizon+180.f)%360.f) < threshold) //the direction
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
}
}
else if( DeltaAngle(angle, angleVertical) < threshold || DeltaAngle(angle, (angleVertical+180.f)%360.f) < threshold)
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
}
}
return null;
}
private float GetAngle(float[] From, float[] To)
{
float angle = (float)Math.atan((To[1]-From[1])/(To[0]-From[0]))/(float)Math.PI*180.f;
float dy = To[1]-From[1];
float dx = To[0]-From[0];
if( dy >= 0.f && dx > 0.f)
{
angle = (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dx == 0.f)
{
if( dy > 0.f)
{
angle = 90.f;
}
else
{
angle = 270.f;
}
}
else if( dy >= 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dy < 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if(dy <0.f && dx > 0.f)
{
angle = 360.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
return angle;
}
private float DeltaAngle(float angle1, float angle2)
{
float a1 = Math.max(angle1, angle2);
float a2 = Math.min(angle1, angle2);
float delta = a1 - a2;
if( delta >= 180.f )
{
delta = 360.f - delta;
}
return delta;
}
private float GetCenterZ(Face f)
{
float zvalue = 0.f;
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = f.P1[0];
xyz[1] = f.P1[1];
xyz[2] = f.P1[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P2[0];
xyz[1] = f.P2[1];
xyz[2] = f.P2[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P3[0];
xyz[1] = f.P3[1];
xyz[2] = f.P3[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P4[0];
xyz[1] = f.P4[1];
xyz[2] = f.P4[2];
Transform(matrix, xyz);
zvalue += xyz[2];
return zvalue/4.f;
}
private float GetAngle(float []Point0, float []Point1, float[]Point2)
{
float cos_value = (Point2[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point2[1]-Point0[1]);
cos_value /= Math.sqrt((Point2[0]-Point0[0])*(Point2[0]-Point0[0]) + (Point2[1]-Point0[1])*(Point2[1]-Point0[1]))
* Math.sqrt((Point1[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point1[1]-Point0[1]));
return (float)Math.acos(cos_value);
}
private void Project(float[] ObjXYZ, float [] WinXY)
{
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = ObjXYZ[0];
xyz[1] = ObjXYZ[1];
xyz[2] = ObjXYZ[2];
Transform(matrix, xyz);
//Log.e("xyz", xyz[0] + " " + xyz[1] + " " + xyz[2]);
float []Win = new float[3];
GLU.gluProject(xyz[0], xyz[1], xyz[2], mod_matrix, 0, pro_matrix, 0, view_matrix, 0, Win, 0);
WinXY[0] = Win[0];
WinXY[1] = Win[1];
}
private void Transform(float[]matrix, float[]Point)
{
float w = 1.f;
float x, y, z, ww;
x = matrix[0]*Point[0] + matrix[4]*Point[1] + matrix[8]*Point[2] + matrix[12]*w;
y = matrix[1]*Point[0] + matrix[5]*Point[1] + matrix[9]*Point[2] + matrix[13]*w;
z = matrix[2]*Point[0] + matrix[6]*Point[1] + matrix[10]*Point[2] + matrix[14]*w;
ww = matrix[3]*Point[0] + matrix[7]*Point[1] + matrix[11]*Point[2] + matrix[15]*w;
Point[0] = x/ww;
Point[1] = y/ww;
Point[2] = z/ww;
}
public boolean IsComplete()
{
boolean r = true;
for( int i=0; i<6; i++)
{
r = r&&magiccube.faces[i].IsSameColor();
}
return magiccube.IsComplete();
}
public String MessUp(int nStep)
{
this.solved = false;
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
return magiccube.MessUp(nStep);
}
public void MessUp(String cmdstr)
{
this.solved = false;
magiccube.MessUp(cmdstr);
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
public boolean IsMoveValid(float[]From, float []To)
{
return this.GetLength2D(From, To) > this.MinMovedist;
}
public void SetCommands(String cmdStr)
{
this.commands = Command.CmdStrsToCmd(cmdStr);
this.HasCommand = true;
}
public String SetCommand(String cmdStr)
{
return SetCommand(Command.CmdStrToCmd(cmdStr));
}
public void AutoSolve(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
this.commandsAuto = Reverse(Command.CmdStrsToCmd(SolveCmd));
this.solved = true;
}
else if(commandsAuto.size() > 0)
{
Command command = commandsAuto.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsAuto.remove(commandsAuto.size()-1);
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
}
}
public void AutoSolve2(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
public void AutoSolve3(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
commands.remove(commands.size()-1);
commands.remove(commands.size()-1);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
private Vector<Command> Reverse(Vector<Command> v)
{
Vector<Command> v2 = new Vector<Command>(v.size());
for(int i=v.size()-1; i>=0; i--)
{
v2.add(v.elementAt(i));
}
return v2;
}
public void Reset()
{
Resetting = true;
reset();
}
private void reset()
{
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
Finished = false;
this.CommandLoop = 0;
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.CmdStrAfter = "";
this.CmdStrBefore = "";
magiccube.Reset();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
this.stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
public String GetCmdStrBefore()
{
return this.CmdStrBefore;
}
public void SetCmdStrBefore(String CmdStrBefore)
{
this.CmdStrBefore = CmdStrBefore;
}
public void SetCmdStrAfter(String CmdStrAfter)
{
this.CmdStrAfter = CmdStrAfter;
}
public String GetCmdStrAfter()
{
return this.CmdStrAfter;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
| flexwang/HappyRubik | src/flex/android/magiccube/MagicCubeRender.java | Java | apache-2.0 | 40,437 |
package sagex.phoenix.remote.services;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptException;
import sagex.phoenix.util.PhoenixScriptEngine;
public class JSMethodInvocationHandler implements InvocationHandler {
private PhoenixScriptEngine eng;
private Map<String, String> methodMap = new HashMap<String, String>();
public JSMethodInvocationHandler(PhoenixScriptEngine eng, String interfaceMethod, String jsMethod) {
this.eng = eng;
methodMap.put(interfaceMethod, jsMethod);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class == method.getDeclaringClass()) {
String name = method.getName();
if ("equals".equals(name)) {
return proxy == args[0];
} else if ("hashCode".equals(name)) {
return System.identityHashCode(proxy);
} else if ("toString".equals(name)) {
return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy))
+ ", with InvocationHandler " + this;
} else {
throw new IllegalStateException(String.valueOf(method));
}
}
String jsMethod = methodMap.get(method.getName());
if (jsMethod == null) {
throw new NoSuchMethodException("No Javascript Method for " + method.getName());
}
Invocable inv = (Invocable) eng.getEngine();
try {
return inv.invokeFunction(jsMethod, args);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("The Java Method: " + method.getName() + " maps to a Javascript Method " + jsMethod
+ " that does not exist.");
} catch (ScriptException e) {
throw e;
}
}
}
| stuckless/sagetv-phoenix-core | src/main/java/sagex/phoenix/remote/services/JSMethodInvocationHandler.java | Java | apache-2.0 | 1,998 |
package io.izenecloud.larser.framework;
import io.izenecloud.conf.Configuration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.StringOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LaserArgument {
private static final Logger LOG = LoggerFactory
.getLogger(LaserArgument.class);
public static final Set<String> VALID_ARGUMENTS = new HashSet<String>(
Arrays.asList("-configure"));
@Option(name = "-configure", required = true, handler = StringOptionHandler.class)
private String configure;
public String getConfigure() {
return configure;
}
public static void parseArgs(String[] args) throws CmdLineException,
IOException {
ArrayList<String> argsList = new ArrayList<String>(Arrays.asList(args));
for (int i = 0; i < args.length; i++) {
if (i % 2 == 0 && !LaserArgument.VALID_ARGUMENTS.contains(args[i])) {
argsList.remove(args[i]);
argsList.remove(args[i + 1]);
}
}
final LaserArgument laserArgument = new LaserArgument();
new CmdLineParser(laserArgument).parseArgument(argsList
.toArray(new String[argsList.size()]));
Configuration conf = Configuration.getInstance();
LOG.info("Load configure, {}", laserArgument.getConfigure());
Path path = new Path(laserArgument.getConfigure());
FileSystem fs = FileSystem
.get(new org.apache.hadoop.conf.Configuration());
conf.load(path, fs);
}
}
| izenecloud/laser | src/main/java/io/izenecloud/larser/framework/LaserArgument.java | Java | apache-2.0 | 1,698 |
package com.nagopy.android.disablemanager2;
import android.os.Build;
import com.android.uiautomator.core.UiSelector;
@SuppressWarnings("unused")
public class UiSelectorBuilder {
private UiSelector uiSelector;
public UiSelector build() {
return uiSelector;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder() {
uiSelector = new UiSelector();
}
/**
* @since API Level 16
*/
public UiSelectorBuilder text(String text) {
uiSelector = uiSelector.text(text);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder textMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.textMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textStartsWith(String text) {
uiSelector = uiSelector.textStartsWith(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textContains(String text) {
uiSelector = uiSelector.textContains(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder className(String className) {
uiSelector = uiSelector.className(className);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder classNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.classNameMatches(regex);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder className(Class<?> type) {
uiSelector = uiSelector.className(type.getName());
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder description(String desc) {
uiSelector = uiSelector.description(desc);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder descriptionMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.descriptionMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionStartsWith(String desc) {
uiSelector = uiSelector.descriptionStartsWith(desc);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionContains(String desc) {
uiSelector = uiSelector.descriptionContains(desc);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceId(String id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceId(id);
}
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceIdMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceIdMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder index(final int index) {
uiSelector = uiSelector.index(index);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder instance(final int instance) {
uiSelector = uiSelector.instance(instance);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder enabled(boolean val) {
uiSelector = uiSelector.enabled(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focused(boolean val) {
uiSelector = uiSelector.focused(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focusable(boolean val) {
uiSelector = uiSelector.focusable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder scrollable(boolean val) {
uiSelector = uiSelector.scrollable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder selected(boolean val) {
uiSelector = uiSelector.selected(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder checked(boolean val) {
uiSelector = uiSelector.checked(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder clickable(boolean val) {
uiSelector = uiSelector.clickable(val);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder checkable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.checkable(val);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder longClickable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.longClickable(val);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder childSelector(UiSelector selector) {
uiSelector = uiSelector.childSelector(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder fromParent(UiSelector selector) {
uiSelector = uiSelector.fromParent(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder packageName(String name) {
uiSelector = uiSelector.packageName(name);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder packageNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.packageNameMatches(regex);
}
return this;
}
}
| 75py/DisableManager | uiautomator/src/main/java/com/nagopy/android/disablemanager2/UiSelectorBuilder.java | Java | apache-2.0 | 6,177 |
package com.salesmanager.shop.model.entity;
import java.io.Serializable;
public abstract class ReadableList implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int totalPages;//totalPages
private int number;//number of record in current page
private long recordsTotal;//total number of records in db
private int recordsFiltered;
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalCount) {
this.totalPages = totalCount;
}
public long getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
} | shopizer-ecommerce/shopizer | sm-shop-model/src/main/java/com/salesmanager/shop/model/entity/ReadableList.java | Java | apache-2.0 | 950 |
/*
* @(#)file SASLOutputStream.java
* @(#)author Sun Microsystems, Inc.
* @(#)version 1.10
* @(#)lastedit 07/03/08
* @(#)build @BUILD_TAG_PLACEHOLDER@
*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and
* Distribution License("CDDL")(collectively, the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy of the
* License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the
* LEGAL_NOTICES folder that accompanied this code. See the License for the
* specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file found at
* http://opendmk.dev.java.net/legal_notices/licenses.txt
* or in the LEGAL_NOTICES folder that accompanied this code.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.
*
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
*
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding
*
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license."
*
* If you don't indicate a single choice of license, a recipient has the option
* to distribute your version of this file under either the CDDL or the GPL
* Version 2, or to extend the choice of license to its licensees as provided
* above. However, if you add GPL Version 2 code and therefore, elected the
* GPL Version 2 license, then the option applies only if the new code is made
* subject to such option by the copyright holder.
*
*/
package com.sun.jmx.remote.opt.security;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslServer;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.jmx.remote.opt.util.ClassLogger;
public class SASLOutputStream extends OutputStream {
private int rawSendSize = 65536;
private byte[] lenBuf = new byte[4]; // buffer for storing length
private OutputStream out; // underlying output stream
private SaslClient sc;
private SaslServer ss;
public SASLOutputStream(SaslClient sc, OutputStream out)
throws IOException {
super();
this.out = out;
this.sc = sc;
this.ss = null;
String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public SASLOutputStream(SaslServer ss, OutputStream out)
throws IOException {
super();
this.out = out;
this.ss = ss;
this.sc = null;
String str = (String) ss.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public void write(int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte)b;
write(buffer, 0, 1);
}
public void write(byte[] buffer, int offset, int total) throws IOException {
int count;
byte[] wrappedToken, saslBuffer;
// "Packetize" buffer to be within rawSendSize
if (logger.traceOn()) {
logger.trace("write", "Total size: " + total);
}
for (int i = 0; i < total; i += rawSendSize) {
// Calculate length of current "packet"
count = (total - i) < rawSendSize ? (total - i) : rawSendSize;
// Generate wrapped token
if (sc != null)
wrappedToken = sc.wrap(buffer, offset+i, count);
else
wrappedToken = ss.wrap(buffer, offset+i, count);
// Write out length
intToNetworkByteOrder(wrappedToken.length, lenBuf, 0, 4);
if (logger.traceOn()) {
logger.trace("write", "sending size: " + wrappedToken.length);
}
out.write(lenBuf, 0, 4);
// Write out wrapped token
out.write(wrappedToken, 0, wrappedToken.length);
}
}
public void close() throws IOException {
if (sc != null)
sc.dispose();
else
ss.dispose();
out.close();
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
private void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more " +
"than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "SASLOutputStream");
}
| nickman/heliosutils | src/main/java/com/sun/jmx/remote/opt/security/SASLOutputStream.java | Java | apache-2.0 | 5,384 |
/*******************************************************************************
* Copyright © 2012-2015 eBay Software Foundation
* This program is dual licensed under the MIT and Apache 2.0 licenses.
* Please see LICENSE for more information.
*******************************************************************************/
package com.ebay.pulsar.analytics.metricstore.druid.query.sql;
/**
*
* @author mingmwang
*
*/
public class HllConstants {
public static final String HLLPREFIX = "hllhaving_";
}
| pulsarIO/pulsar-reporting-api | pulsarquery-druid/src/main/java/com/ebay/pulsar/analytics/metricstore/druid/query/sql/HllConstants.java | Java | apache-2.0 | 514 |
/**************************************************************************
* Mask.java is part of Touch4j 4.0. Copyright 2012 Emitrom 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.emitrom.touch4j.client.ui;
import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.config.Attribute;
import com.emitrom.touch4j.client.core.config.Event;
import com.emitrom.touch4j.client.core.config.XType;
import com.emitrom.touch4j.client.core.handlers.CallbackRegistration;
import com.emitrom.touch4j.client.core.handlers.mask.MaskTapHandler;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A simple class used to mask any Container. This should rarely be used
* directly, instead look at the Container.mask configuration.
*
* @see <a href=http://docs.sencha.com/touch/2-0/#!/api/Ext.Mask>Ext.Mask</a>
*/
public class Mask extends Component {
@Override
protected native void init()/*-{
var c = new $wnd.Ext.Mask();
this.@com.emitrom.touch4j.client.core.Component::configPrototype = c.initialConfig;
}-*/;
@Override
public String getXType() {
return XType.MASK.getValue();
}
@Override
protected native JavaScriptObject create(JavaScriptObject config) /*-{
return new $wnd.Ext.Mask(config);
}-*/;
public Mask() {
}
protected Mask(JavaScriptObject jso) {
super(jso);
}
/**
* True to make this mask transparent.
*
* Defaults to: false
*
* @param value
*/
public void setTransparent(String value) {
setAttribute(Attribute.TRANSPARENT.getValue(), value, true);
}
/**
* A tap event fired when a user taps on this mask
*
* @param handler
*/
public CallbackRegistration addTapHandler(MaskTapHandler handler) {
return this.addWidgetListener(Event.TAP.getValue(), handler.getJsoPeer());
}
}
| paulvi/touch4j | src/com/emitrom/touch4j/client/ui/Mask.java | Java | apache-2.0 | 2,495 |
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util.trace.uploader.launcher;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.env.BuckClasspath;
import com.facebook.buck.util.trace.uploader.types.CompressionType;
import com.google.common.base.Strings;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
/** Utility to upload chrome trace in background. */
public class UploaderLauncher {
private static final Logger LOG = Logger.get(UploaderLauncher.class);
/** Upload chrome trace in background process which runs even after current process dies. */
public static void uploadInBackground(
BuildId buildId,
Path traceFilePath,
String traceFileKind,
URI traceUploadUri,
Path logFile,
CompressionType compressionType) {
LOG.debug("Uploading build trace in the background. Upload will log to %s", logFile);
String buckClasspath = BuckClasspath.getBuckClasspathFromEnvVarOrNull();
if (Strings.isNullOrEmpty(buckClasspath)) {
LOG.error(
BuckClasspath.ENV_VAR_NAME + " env var is not set. Will not upload the trace file.");
return;
}
try {
String[] args = {
"java",
"-cp",
buckClasspath,
"com.facebook.buck.util.trace.uploader.Main",
"--buildId",
buildId.toString(),
"--traceFilePath",
traceFilePath.toString(),
"--traceFileKind",
traceFileKind,
"--baseUrl",
traceUploadUri.toString(),
"--log",
logFile.toString(),
"--compressionType",
compressionType.name(),
};
Runtime.getRuntime().exec(args);
} catch (IOException e) {
LOG.error(e, e.getMessage());
}
}
}
| LegNeato/buck | src/com/facebook/buck/util/trace/uploader/launcher/UploaderLauncher.java | Java | apache-2.0 | 2,379 |
/*
* Copyright 2013, Google Inc.
* 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 Google 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
* 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.jf.dexlib2.builder;
import org.jf.dexlib2.*;
import org.jf.dexlib2.builder.instruction.*;
import org.jf.dexlib2.iface.instruction.*;
import java.util.*;
import javax.annotation.*;
public abstract class BuilderSwitchPayload extends BuilderInstruction implements SwitchPayload {
@Nullable
MethodLocation referrer;
protected BuilderSwitchPayload(@Nonnull Opcode opcode) {
super(opcode);
}
@Nonnull
public MethodLocation getReferrer() {
if (referrer == null) {
throw new IllegalStateException("The referrer has not been set yet");
}
return referrer;
}
@Nonnull
@Override
public abstract List<? extends BuilderSwitchElement> getSwitchElements();
}
| nao20010128nao/show-java | app/src/main/java/org/jf/dexlib2/builder/BuilderSwitchPayload.java | Java | apache-2.0 | 2,310 |
package nodeAST.relational;
import java.util.Map;
import nodeAST.BinaryExpr;
import nodeAST.Expression;
import nodeAST.Ident;
import nodeAST.literals.Literal;
import types.BoolType;
import types.Type;
import visitor.ASTVisitor;
import visitor.IdentifiersTypeMatcher;
public class NEq extends BinaryExpr {
public NEq(Expression leftHandOperand, Expression rightHandOperand) {
super(leftHandOperand,rightHandOperand);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this, this.leftHandOperand, this.rightHandOperand);
}
@Override
public String toString() {
return this.leftHandOperand.toString() + "!=" + this.rightHandOperand.toString();
}
@Override
public Type getType(IdentifiersTypeMatcher typeMatcher) {
return new BoolType();
}
@Override
public boolean areOperandsTypeValid(IdentifiersTypeMatcher typeMatcher) {
Type t1=this.leftHandOperand.getType(typeMatcher);
Type t2=this.rightHandOperand.getType(typeMatcher);
return t1.isCompatibleWith(t2) &&
(t1.isArithmetic() || t1.isBoolean() || t1.isRelational() || t1.isString() );
}
@Override
public Literal compute(Map<Ident, Expression> identifiers) {
return this.leftHandOperand.compute(identifiers).neq(
this.rightHandOperand.compute(identifiers)
);
}
}
| software-engineering-amsterdam/poly-ql | GeorgePachitariu/ANTLR-First/src/nodeAST/relational/NEq.java | Java | apache-2.0 | 1,336 |
package edu.ptu.javatest._60_dsa;
import org.junit.Test;
import java.util.TreeMap;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldBool;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldObj;
public class _35_TreeMapTest {
@Test
public void testPrintTreeMap() {
TreeMap hashMapTest = new TreeMap<>();
for (int i = 0; i < 6; i++) {
hashMapTest.put(new TMHashObj(1,i*2 ), i*2 );
}
Object table = getRefFieldObj(hashMapTest, hashMapTest.getClass(), "root");
printTreeMapNode(table);
hashMapTest.put(new TMHashObj(1,9), 9);
printTreeMapNode(table);
System.out.println();
}
public static int getTreeDepth(Object rootNode) {
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return 0;
return rootNode == null ? 0 : (1 + Math.max(getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "left")), getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "right"))));
}
public static void printTreeMapNode(Object rootNode) {//转化为堆
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return;
int treeDepth = getTreeDepth(rootNode);
Object[] objects = new Object[(int) (Math.pow(2, treeDepth) - 1)];
objects[0] = rootNode;
// objects[0]=rootNode;
// objects[1]=getRefFieldObj(objects,objects.getClass(),"left");
// objects[2]=getRefFieldObj(objects,objects.getClass(),"right");
//
// objects[3]=getRefFieldObj(objects[1],objects[1].getClass(),"left");
// objects[4]=getRefFieldObj(objects[1],objects[1].getClass(),"right");
// objects[5]=getRefFieldObj(objects[2],objects[3].getClass(),"left");
// objects[6]=getRefFieldObj(objects[2],objects[4].getClass(),"right");
for (int i = 1; i < objects.length; i++) {//数组打印
int index = (i - 1) / 2;//parent
if (objects[index] != null) {
if (i % 2 == 1)
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "left");
else
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "right");
}
}
StringBuilder sb = new StringBuilder();
StringBuilder outSb = new StringBuilder();
String space = " ";
for (int i = 0; i < treeDepth + 1; i++) {
sb.append(space);
}
int nextlineIndex = 0;
for (int i = 0; i < objects.length; i++) {//new line: 0,1 ,3,7
//print space
//print value
if (nextlineIndex == i) {
outSb.append("\n\n");
if (sb.length() >= space.length()) {
sb.delete(0, space.length());
}
nextlineIndex = i * 2 + 1;
}
outSb.append(sb.toString());
if (objects[i] != null) {
Object value = getRefFieldObj(objects[i], objects[i].getClass(), "value");
boolean red = !getRefFieldBool(objects[i], objects[i].getClass(), "color");// BLACK = true;
String result = "" + value + "(" + (red ? "r" : "b") + ")";
outSb.append(result);
} else {
outSb.append("nil");
}
}
System.out.println(outSb.toString());
}
public static class TMHashObj implements Comparable{
int hash;
int value;
TMHashObj(int hash, int value) {
this.hash = hash;
this.value = value;
}
@Override
public int hashCode() {
return hash;
}
@Override
public int compareTo(Object o) {
if (o instanceof TMHashObj){
return this.value-((TMHashObj) o).value;
}
return value-o.hashCode();
}
}
}
| rickgit/Test | JavaTest/src/main/java/edu/ptu/javatest/_60_dsa/_35_TreeMapTest.java | Java | apache-2.0 | 4,084 |
package com.cisco.axl.api._8;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LPhoneSecurityProfile complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LPhoneSecurityProfile">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="phoneType" type="{http://www.cisco.com/AXL/API/8.0}XModel" minOccurs="0"/>
* <element name="protocol" type="{http://www.cisco.com/AXL/API/8.0}XDeviceProtocol" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="deviceSecurityMode" type="{http://www.cisco.com/AXL/API/8.0}XDeviceSecurityMode" minOccurs="0"/>
* <element name="authenticationMode" type="{http://www.cisco.com/AXL/API/8.0}XAuthenticationMode" minOccurs="0"/>
* <element name="keySize" type="{http://www.cisco.com/AXL/API/8.0}XKeySize" minOccurs="0"/>
* <element name="tftpEncryptedConfig" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="nonceValidityTime" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="transportType" type="{http://www.cisco.com/AXL/API/8.0}XTransport" minOccurs="0"/>
* <element name="sipPhonePort" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="enableDigestAuthentication" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="excludeDigestCredentials" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* </sequence>
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LPhoneSecurityProfile", propOrder = {
"phoneType",
"protocol",
"name",
"description",
"deviceSecurityMode",
"authenticationMode",
"keySize",
"tftpEncryptedConfig",
"nonceValidityTime",
"transportType",
"sipPhonePort",
"enableDigestAuthentication",
"excludeDigestCredentials"
})
public class LPhoneSecurityProfile {
protected String phoneType;
protected String protocol;
protected String name;
protected String description;
protected String deviceSecurityMode;
protected String authenticationMode;
protected String keySize;
protected String tftpEncryptedConfig;
protected String nonceValidityTime;
protected String transportType;
protected String sipPhonePort;
protected String enableDigestAuthentication;
protected String excludeDigestCredentials;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the phoneType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhoneType() {
return phoneType;
}
/**
* Sets the value of the phoneType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhoneType(String value) {
this.phoneType = value;
}
/**
* Gets the value of the protocol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocol() {
return protocol;
}
/**
* Sets the value of the protocol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocol(String value) {
this.protocol = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the deviceSecurityMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDeviceSecurityMode() {
return deviceSecurityMode;
}
/**
* Sets the value of the deviceSecurityMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeviceSecurityMode(String value) {
this.deviceSecurityMode = value;
}
/**
* Gets the value of the authenticationMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationMode() {
return authenticationMode;
}
/**
* Sets the value of the authenticationMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationMode(String value) {
this.authenticationMode = value;
}
/**
* Gets the value of the keySize property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeySize() {
return keySize;
}
/**
* Sets the value of the keySize property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeySize(String value) {
this.keySize = value;
}
/**
* Gets the value of the tftpEncryptedConfig property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTftpEncryptedConfig() {
return tftpEncryptedConfig;
}
/**
* Sets the value of the tftpEncryptedConfig property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTftpEncryptedConfig(String value) {
this.tftpEncryptedConfig = value;
}
/**
* Gets the value of the nonceValidityTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNonceValidityTime() {
return nonceValidityTime;
}
/**
* Sets the value of the nonceValidityTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNonceValidityTime(String value) {
this.nonceValidityTime = value;
}
/**
* Gets the value of the transportType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportType() {
return transportType;
}
/**
* Sets the value of the transportType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportType(String value) {
this.transportType = value;
}
/**
* Gets the value of the sipPhonePort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSipPhonePort() {
return sipPhonePort;
}
/**
* Sets the value of the sipPhonePort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSipPhonePort(String value) {
this.sipPhonePort = value;
}
/**
* Gets the value of the enableDigestAuthentication property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEnableDigestAuthentication() {
return enableDigestAuthentication;
}
/**
* Sets the value of the enableDigestAuthentication property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEnableDigestAuthentication(String value) {
this.enableDigestAuthentication = value;
}
/**
* Gets the value of the excludeDigestCredentials property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExcludeDigestCredentials() {
return excludeDigestCredentials;
}
/**
* Sets the value of the excludeDigestCredentials property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExcludeDigestCredentials(String value) {
this.excludeDigestCredentials = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/LPhoneSecurityProfile.java | Java | apache-2.0 | 10,171 |
package pokemon.vue;
import pokemon.launcher.PokemonCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.*;
public class MyActor extends Actor {
public Texture s=new Texture(Gdx.files.internal("crosshair.png"));
SpriteBatch b=new SpriteBatch();
float x,y;
public MyActor (float x, float y) {
this.x=x;
this.y=y;
System.out.print(PokemonCore.m.getCities().get(0).getX());
this.setBounds(x+PokemonCore.m.getCities().get(0).getX(),y+PokemonCore.m.getCities().get(0).getY(),s.getWidth(),s.getHeight());
/* RepeatAction action = new RepeatAction();
action.setCount(RepeatAction.FOREVER);
action.setAction(Actions.fadeOut(2f));*/
this.addAction(Actions.repeat(RepeatAction.FOREVER,Actions.sequence(Actions.fadeOut(1f),Actions.fadeIn(1f))));
//posx=this.getX();
//posy=this.getY();
//this.addAction(action);
//this.addAction(Actions.sequence(Actions.alpha(0),Actions.fadeIn(2f)));
System.out.println("Actor constructed");
b.getProjectionMatrix().setToOrtho2D(0, 0,640,360);
}
@Override
public void draw (Batch batch, float parentAlpha) {
b.begin();
Color color = getColor();
b.setColor(color.r, color.g, color.b, color.a * parentAlpha);
b.draw(s,this.getX()-15,this.getY()-15,30,30);
b.setColor(color);
b.end();
//System.out.println("Called");
//batch.draw(t,this.getX(),this.getY(),t.getWidth(),t.getHeight());
//batch.draw(s,this.getX()+Minimap.BourgPalette.getX(),this.getY()+Minimap.BourgPalette.getY(),30,30);
}
public void setPosition(float x, float y){
this.setX(x+this.x);
this.setY(y+this.y);
}
}
| yongaro/Pokemon | Pokemon-core/src/main/java/pokemon/vue/MyActor.java | Java | apache-2.0 | 2,197 |
package org.tiltedwindmills.fantasy.mfl.services;
import org.tiltedwindmills.fantasy.mfl.model.LoginResponse;
/**
* Interface defining operations required for logging into an MFL league.
*/
public interface LoginService {
/**
* Login.
*
* @param leagueId the league id
* @param serverId the server id
* @param year the year
* @param franchiseId the franchise id
* @param password the password
* @return the login response
*/
LoginResponse login(int leagueId, int serverId, int year, String franchiseId, String password);
}
| tiltedwindmills/mfl-api | src/main/java/org/tiltedwindmills/fantasy/mfl/services/LoginService.java | Java | apache-2.0 | 571 |
package org.ns.vk.cachegrabber.ui;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import org.ns.func.Callback;
import org.ns.ioc.IoC;
import org.ns.vk.cachegrabber.api.Application;
import org.ns.vk.cachegrabber.api.vk.Audio;
import org.ns.vk.cachegrabber.api.vk.VKApi;
/**
*
* @author stupak
*/
public class TestAction extends AbstractAction {
public TestAction() {
super("Test action");
}
@Override
public void actionPerformed(ActionEvent e) {
VKApi vkApi = IoC.get(Application.class).getVKApi();
String ownerId = "32659923";
String audioId = "259636837";
vkApi.getById(ownerId, audioId, new Callback<Audio>() {
@Override
public void call(Audio audio) {
Logger.getLogger(TestAction.class.getName()).log(Level.INFO, "loaded audio: {0}", audio);
}
});
}
}
| nikolaas/vk-cache-grabber | src/main/java/org/ns/vk/cachegrabber/ui/TestAction.java | Java | apache-2.0 | 994 |
package com.mapswithme.maps.maplayer.traffic;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@MainThread
public enum TrafficManager
{
INSTANCE;
private final static String TAG = TrafficManager.class.getSimpleName();
@NonNull
private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.TRAFFIC);
@NonNull
private final TrafficState.StateChangeListener mStateChangeListener = new TrafficStateListener();
@NonNull
private TrafficState mState = TrafficState.DISABLED;
@NonNull
private final List<TrafficCallback> mCallbacks = new ArrayList<>();
private boolean mInitialized = false;
public void initialize()
{
mLogger.d(TAG, "Initialization of traffic manager and setting the listener for traffic state changes");
TrafficState.nativeSetListener(mStateChangeListener);
mInitialized = true;
}
public void toggle()
{
checkInitialization();
if (isEnabled())
disable();
else
enable();
}
private void enable()
{
mLogger.d(TAG, "Enable traffic");
TrafficState.nativeEnable();
}
private void disable()
{
checkInitialization();
mLogger.d(TAG, "Disable traffic");
TrafficState.nativeDisable();
}
public boolean isEnabled()
{
checkInitialization();
return TrafficState.nativeIsEnabled();
}
public void attach(@NonNull TrafficCallback callback)
{
checkInitialization();
if (mCallbacks.contains(callback))
{
throw new IllegalStateException("A callback '" + callback
+ "' is already attached. Check that the 'detachAll' method was called.");
}
mLogger.d(TAG, "Attach callback '" + callback + "'");
mCallbacks.add(callback);
postPendingState();
}
private void postPendingState()
{
mStateChangeListener.onTrafficStateChanged(mState.ordinal());
}
public void detachAll()
{
checkInitialization();
if (mCallbacks.isEmpty())
{
mLogger.w(TAG, "There are no attached callbacks. Invoke the 'detachAll' method " +
"only when it's really needed!", new Throwable());
return;
}
for (TrafficCallback callback : mCallbacks)
mLogger.d(TAG, "Detach callback '" + callback + "'");
mCallbacks.clear();
}
private void checkInitialization()
{
if (!mInitialized)
throw new AssertionError("Traffic manager is not initialized!");
}
public void setEnabled(boolean enabled)
{
checkInitialization();
if (isEnabled() == enabled)
return;
if (enabled)
enable();
else
disable();
}
private class TrafficStateListener implements TrafficState.StateChangeListener
{
@Override
@MainThread
public void onTrafficStateChanged(int index)
{
TrafficState newTrafficState = TrafficState.values()[index];
mLogger.d(TAG, "onTrafficStateChanged current state = " + mState
+ " new value = " + newTrafficState);
if (mState == newTrafficState)
return;
mState = newTrafficState;
mState.activate(mCallbacks);
}
}
public interface TrafficCallback
{
void onEnabled();
void onDisabled();
void onWaitingData();
void onOutdated();
void onNetworkError();
void onNoData();
void onExpiredData();
void onExpiredApp();
}
}
| rokuz/omim | android/src/com/mapswithme/maps/maplayer/traffic/TrafficManager.java | Java | apache-2.0 | 3,514 |
package brennus.asm;
import static brennus.model.ExistingType.VOID;
import static brennus.model.ExistingType.existing;
import static brennus.model.Protection.PUBLIC;
import static junit.framework.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import brennus.Builder;
import brennus.MethodBuilder;
import brennus.SwitchBuilder;
import brennus.ThenBuilder;
import brennus.asm.TestGeneration.DynamicClassLoader;
import brennus.model.FutureType;
import brennus.printer.TypePrinter;
import org.junit.Test;
public class TestGoto {
abstract public static class FSA {
private List<String> states = new ArrayList<String>();
abstract public void exec();
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
abstract public static class FSA2 {
private List<String> states = new ArrayList<String>();
abstract public void exec(Iterator<Integer> it);
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
@Test
public void testGoto() throws Exception {
FutureType testClass = new Builder()
.startClass("brennus.asm.TestGoto$TestClass", existing(FSA.class))
.startMethod(PUBLIC, VOID, "exec")
.label("a")
.exec().callOnThis("state").literal("a").endCall().endExec()
.gotoLabel("c")
.label("b")
.exec().callOnThis("state").literal("b").endCall().endExec()
.gotoLabel("end")
.label("c")
.exec().callOnThis("state").literal("c").endCall().endExec()
.gotoLabel("b")
.label("end")
.endMethod()
.endClass();
// new TypePrinter().print(testClass);
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass");
FSA fsa = (FSA)generated.newInstance();
fsa.exec();
assertEquals(Arrays.asList("a", "c", "b"), fsa.getStates());
}
@Test
public void testFSA() throws Exception {
int[][] fsa = {
{0,1,2,3},
{0,1,2,3},
{0,1,2,3},
{0,1,2,3}
};
MethodBuilder m = new Builder()
.startClass("brennus.asm.TestGoto$TestClass2", existing(FSA2.class))
.startMethod(PUBLIC, VOID, "exec").param(existing(Iterator.class), "it")
.gotoLabel("start")
.label("start");
for (int i = 0; i < fsa.length; i++) {
m = m.label("s_"+i)
.exec().callOnThis("state").literal("s_"+i).endCall().endExec();
SwitchBuilder<ThenBuilder<MethodBuilder>> s = m.ifExp().get("it").callNoParam("hasNext").thenBlock()
.switchOn().get("it").callNoParam("next").switchBlock();
for (int j = 0; j < fsa[i].length; j++) {
int to = fsa[i][j];
s = s.caseBlock(j)
.gotoLabel("s_"+to)
.endCase();
}
m = s.endSwitch()
.elseBlock()
.gotoLabel("end")
.endIf();
}
FutureType testClass = m.label("end").endMethod().endClass();
new TypePrinter().print(testClass);
Logger.getLogger("brennus").setLevel(Level.FINEST);
Logger.getLogger("brennus").addHandler(new Handler() {
public void publish(LogRecord record) {
System.out.println(record.getMessage());
}
public void flush() {
System.out.flush();
}
public void close() throws SecurityException {
System.out.flush();
}
});
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass2");
FSA2 compiledFSA = (FSA2)generated.newInstance();
compiledFSA.exec(Arrays.asList(3,2,1).iterator());
assertEquals(Arrays.asList("s_0", "s_3", "s_2", "s_1"), compiledFSA.getStates());
}
}
| julienledem/brennus | brennus-asm/src/test/java/brennus/asm/TestGoto.java | Java | apache-2.0 | 4,143 |
/*-
* #%L
* Simmetrics - Examples
* %%
* Copyright (C) 2014 - 2021 Simmetrics 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.
* #L%
*/
package com.github.mpkorstanje.simmetrics.example;
import static com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder.with;
import com.github.mpkorstanje.simmetrics.StringDistance;
import com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder;
import com.github.mpkorstanje.simmetrics.metrics.EuclideanDistance;
import com.github.mpkorstanje.simmetrics.metrics.StringDistances;
import com.github.mpkorstanje.simmetrics.tokenizers.Tokenizers;
/**
* The StringDistances utility class contains a predefined list of well
* known distance metrics for strings.
*/
final class StringDistanceExample {
/**
* Two strings can be compared using a predefined distance metric.
*/
static float example01() {
String str1 = "This is a sentence. It is made of words";
String str2 = "This sentence is similar. It has almost the same words";
StringDistance metric = StringDistances.levenshtein();
return metric.distance(str1, str2); // 30.0000
}
/**
* A tokenizer is included when the metric is a set or list metric. For the
* euclidean distance, it is a whitespace tokenizer.
*
* Note that most predefined metrics are setup with a whitespace tokenizer.
*/
static float example02() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric = StringDistances.euclideanDistance();
return metric.distance(str1, str2); // 2.0000
}
/**
* Using the string distance builder distance metrics can be customized.
* Instead of a whitespace tokenizer a q-gram tokenizer is used.
*
* For more examples see StringDistanceBuilderExample.
*/
static float example03() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric =
StringDistanceBuilder.with(new EuclideanDistance<>())
.tokenize(Tokenizers.qGram(3))
.build();
return metric.distance(str1, str2); // 4.8989
}
}
| mpkorstanje/simmetrics | simmetrics-example/src/main/java/com/github/mpkorstanje/simmetrics/example/StringDistanceExample.java | Java | apache-2.0 | 2,695 |
/**
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hdodenhof.androidstatemachine;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
/**
* <p>The state machine defined here is a hierarchical state machine which processes messages
* and can have states arranged hierarchically.</p>
*
* <p>A state is a <code>State</code> object and must implement
* <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
* The enter/exit methods are equivalent to the construction and destruction
* in Object Oriented programming and are used to perform initialization and
* cleanup of the state respectively. The <code>getName</code> method returns the
* name of the state the default implementation returns the class name it may be
* desirable to have this return the name of the state instance name instead.
* In particular if a particular state class has multiple instances.</p>
*
* <p>When a state machine is created <code>addState</code> is used to build the
* hierarchy and <code>setInitialState</code> is used to identify which of these
* is the initial state. After construction the programmer calls <code>start</code>
* which initializes and starts the state machine. The first action the StateMachine
* is to the invoke <code>enter</code> for all of the initial state's hierarchy,
* starting at its eldest parent. The calls to enter will be done in the context
* of the StateMachines Handler not in the context of the call to start and they
* will be invoked before any messages are processed. For example, given the simple
* state machine below mP1.enter will be invoked and then mS1.enter. Finally,
* messages sent to the state machine will be processed by the current state,
* in our simple state machine below that would initially be mS1.processMessage.</p>
<code>
mP1
/ \
mS2 mS1 ----> initial state
</code>
* <p>After the state machine is created and started, messages are sent to a state
* machine using <code>sendMessage</code> and the messages are created using
* <code>obtainMessage</code>. When the state machine receives a message the
* current state's <code>processMessage</code> is invoked. In the above example
* mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
* to change the current state to a new state</p>
*
* <p>Each state in the state machine may have a zero or one parent states and if
* a child state is unable to handle a message it may have the message processed
* by its parent by returning false or NOT_HANDLED. If a message is never processed
* <code>unhandledMessage</code> will be invoked to give one last chance for the state machine
* to process the message.</p>
*
* <p>When all processing is completed a state machine may choose to call
* <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
* returns the state machine will transfer to an internal <code>HaltingState</code>
* and invoke <code>halting</code>. Any message subsequently received by the state
* machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
*
* <p>If it is desirable to completely stop the state machine call <code>quit</code> or
* <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
* call <code>onQuiting</code> and then exit Thread/Loopers.</p>
*
* <p>In addition to <code>processMessage</code> each <code>State</code> has
* an <code>enter</code> method and <code>exit</code> method which may be overridden.</p>
*
* <p>Since the states are arranged in a hierarchy transitioning to a new state
* causes current states to be exited and new states to be entered. To determine
* the list of states to be entered/exited the common parent closest to
* the current state is found. We then exit from the current state and its
* parent's up to but not including the common parent state and then enter all
* of the new states below the common parent down to the destination state.
* If there is no common parent all states are exited and then the new states
* are entered.</p>
*
* <p>Two other methods that states can use are <code>deferMessage</code> and
* <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
* a message but places it on the front of the queue rather than the back. The
* <code>deferMessage</code> causes the message to be saved on a list until a
* transition is made to a new state. At which time all of the deferred messages
* will be put on the front of the state machine queue with the oldest message
* at the front. These will then be processed by the new current state before
* any other messages that are on the queue or might be added later. Both of
* these are protected and may only be invoked from within a state machine.</p>
*
* <p>To illustrate some of these properties we'll use state machine with an 8
* state hierarchy:</p>
<code>
mP0
/ \
mP1 mS0
/ \
mS2 mS1
/ \ \
mS3 mS4 mS5 ---> initial state
</code>
* <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
* So the order of calling processMessage when a message is received is mS5,
* mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
* message by returning false or NOT_HANDLED.</p>
*
* <p>Now assume mS5.processMessage receives a message it can handle, and during
* the handling determines the machine should change states. It could call
* transitionTo(mS4) and return true or HANDLED. Immediately after returning from
* processMessage the state machine runtime will find the common parent,
* which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
* mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
* when the next message is received mS4.processMessage will be invoked.</p>
*
* <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
* It responds with "Hello World" being printed to the log for every message.</p>
<code>
class HelloWorld extends StateMachine {
HelloWorld(String name) {
super(name);
addState(mState1);
setInitialState(mState1);
}
public static HelloWorld makeHelloWorld() {
HelloWorld hw = new HelloWorld("hw");
hw.start();
return hw;
}
class State1 extends State {
@Override public boolean processMessage(Message message) {
log("Hello World");
return HANDLED;
}
}
State1 mState1 = new State1();
}
void testHelloWorld() {
HelloWorld hw = makeHelloWorld();
hw.sendMessage(hw.obtainMessage());
}
</code>
* <p>A more interesting state machine is one with four states
* with two independent parent states.</p>
<code>
mP1 mP2
/ \
mS2 mS1
</code>
* <p>Here is a description of this state machine using pseudo code.</p>
<code>
state mP1 {
enter { log("mP1.enter"); }
exit { log("mP1.exit"); }
on msg {
CMD_2 {
send(CMD_3);
defer(msg);
transitonTo(mS2);
return HANDLED;
}
return NOT_HANDLED;
}
}
INITIAL
state mS1 parent mP1 {
enter { log("mS1.enter"); }
exit { log("mS1.exit"); }
on msg {
CMD_1 {
transitionTo(mS1);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mS2 parent mP1 {
enter { log("mS2.enter"); }
exit { log("mS2.exit"); }
on msg {
CMD_2 {
send(CMD_4);
return HANDLED;
}
CMD_3 {
defer(msg);
transitionTo(mP2);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mP2 {
enter {
log("mP2.enter");
send(CMD_5);
}
exit { log("mP2.exit"); }
on msg {
CMD_3, CMD_4 { return HANDLED; }
CMD_5 {
transitionTo(HaltingState);
return HANDLED;
}
return NOT_HANDLED;
}
}
</code>
* <p>The implementation is below and also in StateMachineTest:</p>
<code>
class Hsm1 extends StateMachine {
public static final int CMD_1 = 1;
public static final int CMD_2 = 2;
public static final int CMD_3 = 3;
public static final int CMD_4 = 4;
public static final int CMD_5 = 5;
public static Hsm1 makeHsm1() {
log("makeHsm1 E");
Hsm1 sm = new Hsm1("hsm1");
sm.start();
log("makeHsm1 X");
return sm;
}
Hsm1(String name) {
super(name);
log("ctor E");
// Add states, use indentation to show hierarchy
addState(mP1);
addState(mS1, mP1);
addState(mS2, mP1);
addState(mP2);
// Set the initial state
setInitialState(mS1);
log("ctor X");
}
class P1 extends State {
@Override public void enter() {
log("mP1.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mP1.processMessage what=" + message.what);
switch(message.what) {
case CMD_2:
// CMD_2 will arrive in mS2 before CMD_3
sendMessage(obtainMessage(CMD_3));
deferMessage(message);
transitionTo(mS2);
retVal = HANDLED;
break;
default:
// Any message we don't understand in this state invokes unhandledMessage
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mP1.exit");
}
}
class S1 extends State {
@Override public void enter() {
log("mS1.enter");
}
@Override public boolean processMessage(Message message) {
log("S1.processMessage what=" + message.what);
if (message.what == CMD_1) {
// Transition to ourself to show that enter/exit is called
transitionTo(mS1);
return HANDLED;
} else {
// Let parent process all other messages
return NOT_HANDLED;
}
}
@Override public void exit() {
log("mS1.exit");
}
}
class S2 extends State {
@Override public void enter() {
log("mS2.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mS2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_2):
sendMessage(obtainMessage(CMD_4));
retVal = HANDLED;
break;
case(CMD_3):
deferMessage(message);
transitionTo(mP2);
retVal = HANDLED;
break;
default:
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mS2.exit");
}
}
class P2 extends State {
@Override public void enter() {
log("mP2.enter");
sendMessage(obtainMessage(CMD_5));
}
@Override public boolean processMessage(Message message) {
log("P2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_3):
break;
case(CMD_4):
break;
case(CMD_5):
transitionToHaltingState();
break;
}
return HANDLED;
}
@Override public void exit() {
log("mP2.exit");
}
}
@Override
void onHalting() {
log("halting");
synchronized (this) {
this.notifyAll();
}
}
P1 mP1 = new P1();
S1 mS1 = new S1();
S2 mS2 = new S2();
P2 mP2 = new P2();
}
</code>
* <p>If this is executed by sending two messages CMD_1 and CMD_2
* (Note the synchronize is only needed because we use hsm.wait())</p>
<code>
Hsm1 hsm = makeHsm1();
synchronize(hsm) {
hsm.sendMessage(obtainMessage(hsm.CMD_1));
hsm.sendMessage(obtainMessage(hsm.CMD_2));
try {
// wait for the messages to be handled
hsm.wait();
} catch (InterruptedException e) {
loge("exception while waiting " + e.getMessage());
}
}
</code>
* <p>The output is:</p>
<code>
D/hsm1 ( 1999): makeHsm1 E
D/hsm1 ( 1999): ctor E
D/hsm1 ( 1999): ctor X
D/hsm1 ( 1999): mP1.enter
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): makeHsm1 X
D/hsm1 ( 1999): mS1.processMessage what=1
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): mS1.processMessage what=2
D/hsm1 ( 1999): mP1.processMessage what=2
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS2.enter
D/hsm1 ( 1999): mS2.processMessage what=2
D/hsm1 ( 1999): mS2.processMessage what=3
D/hsm1 ( 1999): mS2.exit
D/hsm1 ( 1999): mP1.exit
D/hsm1 ( 1999): mP2.enter
D/hsm1 ( 1999): mP2.processMessage what=3
D/hsm1 ( 1999): mP2.processMessage what=4
D/hsm1 ( 1999): mP2.processMessage what=5
D/hsm1 ( 1999): mP2.exit
D/hsm1 ( 1999): halting
</code>
*/
public class StateMachine {
// Name of the state machine and used as logging tag
private String mName;
/** Message.what value when quitting */
private static final int SM_QUIT_CMD = -1;
/** Message.what value when initializing */
private static final int SM_INIT_CMD = -2;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was processed and is not to be
* processed by parent states
*/
public static final boolean HANDLED = true;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was NOT processed and is to be
* processed by parent states
*/
public static final boolean NOT_HANDLED = false;
/**
* StateMachine logging record.
*/
public static class LogRec {
private StateMachine mSm;
private long mTime;
private int mWhat;
private String mInfo;
private IState mState;
private IState mOrgState;
private IState mDstState;
/**
* Constructor
*
* @param msg
* @param state the state which handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*/
LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState transToState) {
update(sm, msg, info, state, orgState, transToState);
}
/**
* Update the information in the record.
* @param state that handled the message
* @param orgState is the first state the received the message
* @param dstState is the state that was the transition target when logging
*/
public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState dstState) {
mSm = sm;
mTime = System.currentTimeMillis();
mWhat = (msg != null) ? msg.what : 0;
mInfo = info;
mState = state;
mOrgState = orgState;
mDstState = dstState;
}
/**
* @return time stamp
*/
public long getTime() {
return mTime;
}
/**
* @return msg.what
*/
public long getWhat() {
return mWhat;
}
/**
* @return the command that was executing
*/
public String getInfo() {
return mInfo;
}
/**
* @return the state that handled this message
*/
public IState getState() {
return mState;
}
/**
* @return the state destination state if a transition is occurring or null if none.
*/
public IState getDestState() {
return mDstState;
}
/**
* @return the original state that received the message.
*/
public IState getOriginalState() {
return mOrgState;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("time=");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(mTime);
sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
sb.append(" processed=");
sb.append(mState == null ? "<null>" : mState.getName());
sb.append(" org=");
sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
sb.append(" dest=");
sb.append(mDstState == null ? "<null>" : mDstState.getName());
sb.append(" what=");
String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
if (TextUtils.isEmpty(what)) {
sb.append(mWhat);
sb.append("(0x");
sb.append(Integer.toHexString(mWhat));
sb.append(")");
} else {
sb.append(what);
}
if (!TextUtils.isEmpty(mInfo)) {
sb.append(" ");
sb.append(mInfo);
}
return sb.toString();
}
}
/**
* A list of log records including messages recently processed by the state machine.
*
* The class maintains a list of log records including messages
* recently processed. The list is finite and may be set in the
* constructor or by calling setSize. The public interface also
* includes size which returns the number of recent records,
* count which is the number of records processed since the
* the last setSize, get which returns a record and
* add which adds a record.
*/
private static class LogRecords {
private static final int DEFAULT_SIZE = 20;
private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
private int mMaxSize = DEFAULT_SIZE;
private int mOldestIndex = 0;
private int mCount = 0;
private boolean mLogOnlyTransitions = false;
/**
* private constructor use add
*/
private LogRecords() {
}
/**
* Set size of messages to maintain and clears all current records.
*
* @param maxSize number of records to maintain at anyone time.
*/
synchronized void setSize(int maxSize) {
mMaxSize = maxSize;
mCount = 0;
mLogRecVector.clear();
}
synchronized void setLogOnlyTransitions(boolean enable) {
mLogOnlyTransitions = enable;
}
synchronized boolean logOnlyTransitions() {
return mLogOnlyTransitions;
}
/**
* @return the number of recent records.
*/
synchronized int size() {
return mLogRecVector.size();
}
/**
* @return the total number of records processed since size was set.
*/
synchronized int count() {
return mCount;
}
/**
* Clear the list of records.
*/
synchronized void cleanup() {
mLogRecVector.clear();
}
/**
* @return the information on a particular record. 0 is the oldest
* record and size()-1 is the newest record. If the index is to
* large null is returned.
*/
synchronized LogRec get(int index) {
int nextIndex = mOldestIndex + index;
if (nextIndex >= mMaxSize) {
nextIndex -= mMaxSize;
}
if (nextIndex >= size()) {
return null;
} else {
return mLogRecVector.get(nextIndex);
}
}
/**
* Add a processed message.
*
* @param msg
* @param messageInfo to be stored
* @param state that handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*
*/
synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
IState orgState, IState transToState) {
mCount += 1;
if (mLogRecVector.size() < mMaxSize) {
mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
} else {
LogRec pmi = mLogRecVector.get(mOldestIndex);
mOldestIndex += 1;
if (mOldestIndex >= mMaxSize) {
mOldestIndex = 0;
}
pmi.update(sm, msg, messageInfo, state, orgState, transToState);
}
}
}
private static class SmHandler extends Handler {
/** true if StateMachine has quit */
private boolean mHasQuit = false;
/** The debug flag */
private boolean mDbg = false;
/** The SmHandler object, identifies that message is internal */
private static final Object mSmHandlerObj = new Object();
/** The current message */
private Message mMsg;
/** A list of log records including messages this state machine has processed */
private LogRecords mLogRecords = new LogRecords();
/** true if construction of the state machine has not been completed */
private boolean mIsConstructionCompleted;
/** Stack used to manage the current hierarchy of states */
private StateInfo mStateStack[];
/** Top of mStateStack */
private int mStateStackTopIndex = -1;
/** A temporary stack used to manage the state stack */
private StateInfo mTempStateStack[];
/** The top of the mTempStateStack */
private int mTempStateStackCount;
/** State used when state machine is halted */
private HaltingState mHaltingState = new HaltingState();
/** State used when state machine is quitting */
private QuittingState mQuittingState = new QuittingState();
/** Reference to the StateMachine */
private StateMachine mSm;
/**
* Information about a state.
* Used to maintain the hierarchy.
*/
private class StateInfo {
/** The state */
State state;
/** The parent of this state, null if there is no parent */
StateInfo parentStateInfo;
/** True when the state has been entered and on the stack */
boolean active;
/**
* Convert StateInfo to string
*/
@Override
public String toString() {
return "state=" + state.getName() + ",active=" + active + ",parent="
+ ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
}
}
/** The map of all of the states in the state machine */
private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
/** The initial state that will process the first message */
private State mInitialState;
/** The destination state when transitionTo has been invoked */
private State mDestState;
/** The list of deferred messages */
private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
/**
* State entered when transitionToHaltingState is called.
*/
private class HaltingState extends State {
@Override
public boolean processMessage(Message msg) {
mSm.haltedProcessMessage(msg);
return true;
}
}
/**
* State entered when a valid quit message is handled.
*/
private class QuittingState extends State {
@Override
public boolean processMessage(Message msg) {
return NOT_HANDLED;
}
}
/**
* Handle messages sent to the state machine by calling
* the current state's processMessage. It also handles
* the enter/exit calls and placing any deferred messages
* back onto the queue when transitioning to a new state.
*/
@Override
public final void handleMessage(Message msg) {
if (!mHasQuit) {
if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
/** Save the current message */
mMsg = msg;
/** State that processed the message */
State msgProcessedState = null;
if (mIsConstructionCompleted) {
/** Normal path */
msgProcessedState = processMsg(msg);
} else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
&& (mMsg.obj == mSmHandlerObj)) {
/** Initial one time path. */
mIsConstructionCompleted = true;
invokeEnterMethods(0);
} else {
throw new RuntimeException("StateMachine.handleMessage: "
+ "The start method not called, received msg: " + msg);
}
performTransitions(msgProcessedState, msg);
// We need to check if mSm == null here as we could be quitting.
if (mDbg && mSm != null) mSm.log("handleMessage: X");
}
}
/**
* Do any transitions
* @param msgProcessedState is the state that processed the message
*/
private void performTransitions(State msgProcessedState, Message msg) {
/**
* If transitionTo has been called, exit and then enter
* the appropriate states. We loop on this to allow
* enter and exit methods to use transitionTo.
*/
State orgState = mStateStack[mStateStackTopIndex].state;
/**
* Record whether message needs to be logged before we transition and
* and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
* always set msg.obj to the handler.
*/
boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj);
if (mLogRecords.logOnlyTransitions()) {
/** Record only if there is a transition */
if (mDestState != null) {
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
orgState, mDestState);
}
} else if (recordLogMsg) {
/** Record message */
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
mDestState);
}
State destState = mDestState;
if (destState != null) {
/**
* Process the transitions including transitions in the enter/exit methods
*/
while (true) {
if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
/**
* Determine the states to exit and enter and return the
* common ancestor state of the enter/exit states. Then
* invoke the exit methods then the enter methods.
*/
StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
invokeExitMethods(commonStateInfo);
int stateStackEnteringIndex = moveTempStateStackToStateStack();
invokeEnterMethods(stateStackEnteringIndex);
/**
* Since we have transitioned to a new state we need to have
* any deferred messages moved to the front of the message queue
* so they will be processed before any other messages in the
* message queue.
*/
moveDeferredMessageAtFrontOfQueue();
if (destState != mDestState) {
// A new mDestState so continue looping
destState = mDestState;
} else {
// No change in mDestState so we're done
break;
}
}
mDestState = null;
}
/**
* After processing all transitions check and
* see if the last transition was to quit or halt.
*/
if (destState != null) {
if (destState == mQuittingState) {
/**
* Call onQuitting to let subclasses cleanup.
*/
mSm.onQuitting();
cleanupAfterQuitting();
} else if (destState == mHaltingState) {
/**
* Call onHalting() if we've transitioned to the halting
* state. All subsequent messages will be processed in
* in the halting state which invokes haltedProcessMessage(msg);
*/
mSm.onHalting();
}
}
}
/**
* Cleanup all the static variables and the looper after the SM has been quit.
*/
private final void cleanupAfterQuitting() {
if (mSm.mSmThread != null) {
// If we made the thread then quit looper which stops the thread.
getLooper().quit();
mSm.mSmThread = null;
}
mSm.mSmHandler = null;
mSm = null;
mMsg = null;
mLogRecords.cleanup();
mStateStack = null;
mTempStateStack = null;
mStateInfo.clear();
mInitialState = null;
mDestState = null;
mDeferredMessages.clear();
mHasQuit = true;
}
/**
* Complete the construction of the state machine.
*/
private final void completeConstruction() {
if (mDbg) mSm.log("completeConstruction: E");
/**
* Determine the maximum depth of the state hierarchy
* so we can allocate the state stacks.
*/
int maxDepth = 0;
for (StateInfo si : mStateInfo.values()) {
int depth = 0;
for (StateInfo i = si; i != null; depth++) {
i = i.parentStateInfo;
}
if (maxDepth < depth) {
maxDepth = depth;
}
}
if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
mStateStack = new StateInfo[maxDepth];
mTempStateStack = new StateInfo[maxDepth];
setupInitialStateStack();
/** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));
if (mDbg) mSm.log("completeConstruction: X");
}
/**
* Process the message. If the current state doesn't handle
* it, call the states parent and so on. If it is never handled then
* call the state machines unhandledMessage method.
* @return the state that processed the message
*/
private final State processMsg(Message msg) {
StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
if (isQuit(msg)) {
transitionTo(mQuittingState);
} else {
while (!curStateInfo.state.processMessage(msg)) {
/**
* Not processed
*/
curStateInfo = curStateInfo.parentStateInfo;
if (curStateInfo == null) {
/**
* No parents left so it's not handled
*/
mSm.unhandledMessage(msg);
break;
}
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
}
}
return (curStateInfo != null) ? curStateInfo.state : null;
}
/**
* Call the exit method for each state from the top of stack
* up to the common ancestor state.
*/
private final void invokeExitMethods(StateInfo commonStateInfo) {
while ((mStateStackTopIndex >= 0)
&& (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
State curState = mStateStack[mStateStackTopIndex].state;
if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
curState.exit();
mStateStack[mStateStackTopIndex].active = false;
mStateStackTopIndex -= 1;
}
}
/**
* Invoke the enter method starting at the entering index to top of state stack
*/
private final void invokeEnterMethods(int stateStackEnteringIndex) {
for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
mStateStack[i].state.enter();
mStateStack[i].active = true;
}
}
/**
* Move the deferred message to the front of the message queue.
*/
private final void moveDeferredMessageAtFrontOfQueue() {
/**
* The oldest messages on the deferred list must be at
* the front of the queue so start at the back, which
* as the most resent message and end with the oldest
* messages at the front of the queue.
*/
for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
Message curMsg = mDeferredMessages.get(i);
if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
sendMessageAtFrontOfQueue(curMsg);
}
mDeferredMessages.clear();
}
/**
* Move the contents of the temporary stack to the state stack
* reversing the order of the items on the temporary stack as
* they are moved.
*
* @return index into mStateStack where entering needs to start
*/
private final int moveTempStateStackToStateStack() {
int startingIndex = mStateStackTopIndex + 1;
int i = mTempStateStackCount - 1;
int j = startingIndex;
while (i >= 0) {
if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
mStateStack[j] = mTempStateStack[i];
j += 1;
i -= 1;
}
mStateStackTopIndex = j - 1;
if (mDbg) {
mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
+ ",startingIndex=" + startingIndex + ",Top="
+ mStateStack[mStateStackTopIndex].state.getName());
}
return startingIndex;
}
/**
* Setup the mTempStateStack with the states we are going to enter.
*
* This is found by searching up the destState's ancestors for a
* state that is already active i.e. StateInfo.active == true.
* The destStae and all of its inactive parents will be on the
* TempStateStack as the list of states to enter.
*
* @return StateInfo of the common ancestor for the destState and
* current state or null if there is no common parent.
*/
private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
/**
* Search up the parent list of the destination state for an active
* state. Use a do while() loop as the destState must always be entered
* even if it is active. This can happen if we are exiting/entering
* the current state.
*/
mTempStateStackCount = 0;
StateInfo curStateInfo = mStateInfo.get(destState);
do {
mTempStateStack[mTempStateStackCount++] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
} while ((curStateInfo != null) && !curStateInfo.active);
if (mDbg) {
mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
+ mTempStateStackCount + ",curStateInfo: " + curStateInfo);
}
return curStateInfo;
}
/**
* Initialize StateStack to mInitialState.
*/
private final void setupInitialStateStack() {
if (mDbg) {
mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
}
StateInfo curStateInfo = mStateInfo.get(mInitialState);
for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
mTempStateStack[mTempStateStackCount] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
}
// Empty the StateStack
mStateStackTopIndex = -1;
moveTempStateStackToStateStack();
}
/**
* @return current message
*/
private final Message getCurrentMessage() {
return mMsg;
}
/**
* @return current state
*/
private final IState getCurrentState() {
return mStateStack[mStateStackTopIndex].state;
}
/**
* Add a new state to the state machine. Bottom up addition
* of states is allowed but the same state may only exist
* in one hierarchy.
*
* @param state the state to add
* @param parent the parent of state
* @return stateInfo for this state
*/
private final StateInfo addState(State state, State parent) {
if (mDbg) {
mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
+ ((parent == null) ? "" : parent.getName()));
}
StateInfo parentStateInfo = null;
if (parent != null) {
parentStateInfo = mStateInfo.get(parent);
if (parentStateInfo == null) {
// Recursively add our parent as it's not been added yet.
parentStateInfo = addState(parent, null);
}
}
StateInfo stateInfo = mStateInfo.get(state);
if (stateInfo == null) {
stateInfo = new StateInfo();
mStateInfo.put(state, stateInfo);
}
// Validate that we aren't adding the same state in two different hierarchies.
if ((stateInfo.parentStateInfo != null)
&& (stateInfo.parentStateInfo != parentStateInfo)) {
throw new RuntimeException("state already added");
}
stateInfo.state = state;
stateInfo.parentStateInfo = parentStateInfo;
stateInfo.active = false;
if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
return stateInfo;
}
/**
* Constructor
*
* @param looper for dispatching messages
* @param sm the hierarchical state machine
*/
private SmHandler(Looper looper, StateMachine sm) {
super(looper);
mSm = sm;
addState(mHaltingState, null);
addState(mQuittingState, null);
}
/** @see StateMachine#setInitialState(State) */
private final void setInitialState(State initialState) {
if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
mInitialState = initialState;
}
/** @see StateMachine#transitionTo(IState) */
private final void transitionTo(IState destState) {
mDestState = (State) destState;
if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
}
/** @see StateMachine#deferMessage(Message) */
private final void deferMessage(Message msg) {
if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
/* Copy the "msg" to "newMsg" as "msg" will be recycled */
Message newMsg = obtainMessage();
newMsg.copyFrom(msg);
mDeferredMessages.add(newMsg);
}
/** @see StateMachine#quit() */
private final void quit() {
if (mDbg) mSm.log("quit:");
sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** @see StateMachine#quitNow() */
private final void quitNow() {
if (mDbg) mSm.log("quitNow:");
sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** Validate that the message was sent by quit or quitNow. */
private final boolean isQuit(Message msg) {
return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj);
}
/** @see StateMachine#isDbg() */
private final boolean isDbg() {
return mDbg;
}
/** @see StateMachine#setDbg(boolean) */
private final void setDbg(boolean dbg) {
mDbg = dbg;
}
}
private SmHandler mSmHandler;
private HandlerThread mSmThread;
/**
* Initialize.
*
* @param looper for this state machine
* @param name of the state machine
*/
private void initStateMachine(String name, Looper looper) {
mName = name;
mSmHandler = new SmHandler(looper, this);
}
/**
* Constructor creates a StateMachine with its own thread.
*
* @param name of the state machine
*/
protected StateMachine(String name) {
mSmThread = new HandlerThread(name);
mSmThread.start();
Looper looper = mSmThread.getLooper();
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the looper.
*
* @param name of the state machine
*/
protected StateMachine(String name, Looper looper) {
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the handler.
*
* @param name of the state machine
*/
protected StateMachine(String name, Handler handler) {
initStateMachine(name, handler.getLooper());
}
/**
* Add a new state to the state machine
* @param state the state to add
* @param parent the parent of state
*/
protected final void addState(State state, State parent) {
mSmHandler.addState(state, parent);
}
/**
* Add a new state to the state machine, parent will be null
* @param state to add
*/
protected final void addState(State state) {
mSmHandler.addState(state, null);
}
/**
* Set the initial state. This must be invoked before
* and messages are sent to the state machine.
*
* @param initialState is the state which will receive the first message.
*/
protected final void setInitialState(State initialState) {
mSmHandler.setInitialState(initialState);
}
/**
* @return current message
*/
protected final Message getCurrentMessage() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentMessage();
}
/**
* @return current state
*/
protected final IState getCurrentState() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentState();
}
/**
* transition to destination state. Upon returning
* from processMessage the current state's exit will
* be executed and upon the next message arriving
* destState.enter will be invoked.
*
* this function can also be called inside the enter function of the
* previous transition target, but the behavior is undefined when it is
* called mid-way through a previous transition (for example, calling this
* in the enter() routine of a intermediate node when the current transition
* target is one of the nodes descendants).
*
* @param destState will be the state that receives the next message.
*/
protected final void transitionTo(IState destState) {
mSmHandler.transitionTo(destState);
}
/**
* transition to halt state. Upon returning
* from processMessage we will exit all current
* states, execute the onHalting() method and then
* for all subsequent messages haltedProcessMessage
* will be called.
*/
protected final void transitionToHaltingState() {
mSmHandler.transitionTo(mSmHandler.mHaltingState);
}
/**
* Defer this message until next state transition.
* Upon transitioning all deferred messages will be
* placed on the queue and reprocessed in the original
* order. (i.e. The next state the oldest messages will
* be processed first)
*
* @param msg is deferred until the next transition.
*/
protected final void deferMessage(Message msg) {
mSmHandler.deferMessage(msg);
}
/**
* Called when message wasn't handled
*
* @param msg that couldn't be handled.
*/
protected void unhandledMessage(Message msg) {
if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
}
/**
* Called for any message that is received after
* transitionToHalting is called.
*/
protected void haltedProcessMessage(Message msg) {
}
/**
* This will be called once after handling a message that called
* transitionToHalting. All subsequent messages will invoke
* {@link StateMachine#haltedProcessMessage(Message)}
*/
protected void onHalting() {
}
/**
* This will be called once after a quit message that was NOT handled by
* the derived StateMachine. The StateMachine will stop and any subsequent messages will be
* ignored. In addition, if this StateMachine created the thread, the thread will
* be stopped after this method returns.
*/
protected void onQuitting() {
}
/**
* @return the name
*/
public final String getName() {
return mName;
}
/**
* Set number of log records to maintain and clears all current records.
*
* @param maxSize number of messages to maintain at anyone time.
*/
public final void setLogRecSize(int maxSize) {
mSmHandler.mLogRecords.setSize(maxSize);
}
/**
* Set to log only messages that cause a state transition
*
* @param enable {@code true} to enable, {@code false} to disable
*/
public final void setLogOnlyTransitions(boolean enable) {
mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
}
/**
* @return number of log records
*/
public final int getLogRecSize() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.size();
}
/**
* @return the total number of records processed
*/
public final int getLogRecCount() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.count();
}
/**
* @return a log record, or null if index is out of range
*/
public final LogRec getLogRec(int index) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.mLogRecords.get(index);
}
/**
* @return a copy of LogRecs as a collection
*/
public final Collection<LogRec> copyLogRecs() {
Vector<LogRec> vlr = new Vector<LogRec>();
SmHandler smh = mSmHandler;
if (smh != null) {
for (LogRec lr : smh.mLogRecords.mLogRecVector) {
vlr.add(lr);
}
}
return vlr;
}
/**
* Add the string to LogRecords.
*
* @param string
*/
protected void addLogRec(String string) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
}
/**
* @return true if msg should be saved in the log, default is true.
*/
protected boolean recordLogRec(Message msg) {
return true;
}
/**
* Return a string to be logged by LogRec, default
* is an empty string. Override if additional information is desired.
*
* @param msg that was processed
* @return information to be logged as a String
*/
protected String getLogRecString(Message msg) {
return "";
}
/**
* @return the string for msg.what
*/
protected String getWhatToString(int what) {
return null;
}
/**
* @return Handler, maybe null if state machine has quit.
*/
public final Handler getHandler() {
return mSmHandler;
}
/**
* Get a message and set Message.target state machine handler.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @return A Message object from the global pool
*/
public final Message obtainMessage() {
return Message.obtain(mSmHandler);
}
/**
* Get a message and set Message.target state machine handler, what.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what) {
return Message.obtain(mSmHandler, what);
}
/**
* Get a message and set Message.target state machine handler,
* what and obj.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @param obj is assigned to Message.obj.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(mSmHandler, what, obj);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1) {
// use this obtain so we don't match the obtain(h, what, Object) method
return Message.obtain(mSmHandler, what, arg1, 0);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2) {
return Message.obtain(mSmHandler, what, arg1, arg2);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1, arg2 and obj
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @param obj is assigned to Message.obj
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
return Message.obtain(mSmHandler, what, arg1, arg2, obj);
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(msg);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, Object obj, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, Object obj,
long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(Message msg, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(msg, delayMillis);
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(msg);
}
/**
* Removes a message from the message queue.
* Protected, may only be called by instances of StateMachine.
*/
protected final void removeMessages(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.removeMessages(what);
}
/**
* Validate that the message was sent by
* {@link StateMachine#quit} or {@link StateMachine#quitNow}.
* */
protected final boolean isQuit(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return msg.what == SM_QUIT_CMD;
return smh.isQuit(msg);
}
/**
* Quit the state machine after all currently queued up messages are processed.
*/
protected final void quit() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quit();
}
/**
* Quit the state machine immediately all currently queued messages will be discarded.
*/
protected final void quitNow() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quitNow();
}
/**
* @return if debugging is enabled
*/
public boolean isDbg() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return false;
return smh.isDbg();
}
/**
* Set debug enable/disabled.
*
* @param dbg is true to enable debugging.
*/
public void setDbg(boolean dbg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.setDbg(dbg);
}
/**
* Start the state machine.
*/
public void start() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
/** Send the complete construction message */
smh.completeConstruction();
}
/**
* Dump the current state.
*
* @param fd
* @param pw
* @param args
*/
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println(getName() + ":");
pw.println(" total records=" + getLogRecCount());
for (int i = 0; i < getLogRecSize(); i++) {
pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString());
pw.flush();
}
pw.println("curState=" + getCurrentState().getName());
}
/**
* Log with debug and add to the LogRecords.
*
* @param s is string log
*/
protected void logAndAddLogRec(String s) {
addLogRec(s);
log(s);
}
/**
* Log with debug
*
* @param s is string log
*/
protected void log(String s) {
Log.d(mName, s);
}
/**
* Log with debug attribute
*
* @param s is string log
*/
protected void logd(String s) {
Log.d(mName, s);
}
/**
* Log with verbose attribute
*
* @param s is string log
*/
protected void logv(String s) {
Log.v(mName, s);
}
/**
* Log with info attribute
*
* @param s is string log
*/
protected void logi(String s) {
Log.i(mName, s);
}
/**
* Log with warning attribute
*
* @param s is string log
*/
protected void logw(String s) {
Log.w(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
*/
protected void loge(String s) {
Log.e(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
* @param e is a Throwable which logs additional information.
*/
protected void loge(String s, Throwable e) {
Log.e(mName, s, e);
}
}
| hdodenhof/AndroidStateMachine | library/src/main/java/de/hdodenhof/androidstatemachine/StateMachine.java | Java | apache-2.0 | 68,024 |
/*
* Camunda BPM REST API
* OpenApi Spec for Camunda BPM REST API.
*
* The version of the OpenAPI document: 7.13.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.camunda.consulting.openapi.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for MissingAuthorizationDto
*/
public class MissingAuthorizationDtoTest {
private final MissingAuthorizationDto model = new MissingAuthorizationDto();
/**
* Model tests for MissingAuthorizationDto
*/
@Test
public void testMissingAuthorizationDto() {
// TODO: test MissingAuthorizationDto
}
/**
* Test the property 'permissionName'
*/
@Test
public void permissionNameTest() {
// TODO: test permissionName
}
/**
* Test the property 'resourceName'
*/
@Test
public void resourceNameTest() {
// TODO: test resourceName
}
/**
* Test the property 'resourceId'
*/
@Test
public void resourceIdTest() {
// TODO: test resourceId
}
}
| camunda/camunda-consulting | snippets/camunda-openapi-client/camunda-openapi-client/src/test/java/com/camunda/consulting/openapi/client/model/MissingAuthorizationDtoTest.java | Java | apache-2.0 | 1,545 |
package th.ac.kmitl.ce.ooad.cest.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import th.ac.kmitl.ce.ooad.cest.domain.Course;
import th.ac.kmitl.ce.ooad.cest.domain.Faculty;
import java.util.List;
public interface CourseRepository extends CrudRepository<Course, Long>{
Course findFirstByCourseId(String courseId);
Course findFirstByCourseName(String courseName);
List<Course> findByCourseNameContainingOrCourseIdContainingOrderByCourseNameAsc(String courseName, String courseId);
List<Course> findByFacultyOrderByCourseNameAsc(Faculty faculty);
List<Course> findByDepartmentOrderByCourseNameAsc(String department);
@Query("select c from Course c where c.department = ?2 or c.department = '' and c.faculty = ?1 order by c.courseName")
List<Course> findByFacultyAndDepartmentOrNone(Faculty faculty, String department);
}
| CE-KMITL-OOAD-2015/CE-SMART-TRACKER-DEV | CE Smart Tracker Server/src/main/java/th/ac/kmitl/ce/ooad/cest/repository/CourseRepository.java | Java | apache-2.0 | 930 |
package org.apache.lucene.facet.sampling;
import java.io.IOException;
import java.util.Collections;
import org.apache.lucene.document.Document;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.index.FacetFields;
import org.apache.lucene.facet.params.FacetIndexingParams;
import org.apache.lucene.facet.params.FacetSearchParams;
import org.apache.lucene.facet.sampling.RandomSampler;
import org.apache.lucene.facet.sampling.Sampler;
import org.apache.lucene.facet.sampling.SamplingAccumulator;
import org.apache.lucene.facet.sampling.SamplingParams;
import org.apache.lucene.facet.search.CountFacetRequest;
import org.apache.lucene.facet.search.FacetRequest;
import org.apache.lucene.facet.search.FacetResult;
import org.apache.lucene.facet.search.FacetResultNode;
import org.apache.lucene.facet.search.FacetsCollector;
import org.apache.lucene.facet.search.StandardFacetsAccumulator;
import org.apache.lucene.facet.search.FacetRequest.ResultMode;
import org.apache.lucene.facet.taxonomy.CategoryPath;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.junit.Test;
/*
* 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.
*/
public class OversampleWithDepthTest extends FacetTestCase {
@Test
public void testCountWithdepthUsingSampling() throws Exception, IOException {
Directory indexDir = newDirectory();
Directory taxoDir = newDirectory();
FacetIndexingParams fip = new FacetIndexingParams(randomCategoryListParams());
// index 100 docs, each with one category: ["root", docnum/10, docnum]
// e.g. root/8/87
index100Docs(indexDir, taxoDir, fip);
DirectoryReader r = DirectoryReader.open(indexDir);
TaxonomyReader tr = new DirectoryTaxonomyReader(taxoDir);
CountFacetRequest facetRequest = new CountFacetRequest(new CategoryPath("root"), 10);
// Setting the depth to '2', should potentially get all categories
facetRequest.setDepth(2);
facetRequest.setResultMode(ResultMode.PER_NODE_IN_TREE);
FacetSearchParams fsp = new FacetSearchParams(fip, facetRequest);
// Craft sampling params to enforce sampling
final SamplingParams params = new SamplingParams();
params.setMinSampleSize(2);
params.setMaxSampleSize(50);
params.setOversampleFactor(5);
params.setSamplingThreshold(60);
params.setSampleRatio(0.1);
FacetResult res = searchWithFacets(r, tr, fsp, params);
FacetRequest req = res.getFacetRequest();
assertEquals(facetRequest, req);
FacetResultNode rootNode = res.getFacetResultNode();
// Each node below root should also have sub-results as the requested depth was '2'
for (FacetResultNode node : rootNode.subResults) {
assertTrue("node " + node.label + " should have had children as the requested depth was '2'", node.subResults.size() > 0);
}
IOUtils.close(r, tr, indexDir, taxoDir);
}
private void index100Docs(Directory indexDir, Directory taxoDir, FacetIndexingParams fip) throws IOException {
IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, null);
IndexWriter w = new IndexWriter(indexDir, iwc);
TaxonomyWriter tw = new DirectoryTaxonomyWriter(taxoDir);
FacetFields facetFields = new FacetFields(tw, fip);
for (int i = 0; i < 100; i++) {
Document doc = new Document();
CategoryPath cp = new CategoryPath("root",Integer.toString(i / 10), Integer.toString(i));
facetFields.addFields(doc, Collections.singletonList(cp));
w.addDocument(doc);
}
IOUtils.close(tw, w);
}
/** search reader <code>r</code>*/
private FacetResult searchWithFacets(IndexReader r, TaxonomyReader tr, FacetSearchParams fsp,
final SamplingParams params) throws IOException {
// a FacetsCollector with a sampling accumulator
Sampler sampler = new RandomSampler(params, random());
StandardFacetsAccumulator sfa = new SamplingAccumulator(sampler, fsp, r, tr);
FacetsCollector fcWithSampling = FacetsCollector.create(sfa);
IndexSearcher s = new IndexSearcher(r);
s.search(new MatchAllDocsQuery(), fcWithSampling);
// there's only one expected result, return just it.
return fcWithSampling.getFacetResults().get(0);
}
}
| pkarmstr/NYBC | solr-4.2.1/lucene/facet/src/test/org/apache/lucene/facet/sampling/OversampleWithDepthTest.java | Java | apache-2.0 | 5,565 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.jsprit.core.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
public class SolutionVerifier implements AlgorithmEndsListener {
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
for (VehicleRoutingProblemSolution solution : solutions) {
Set<Job> jobsInSolution = new HashSet<Job>();
for (VehicleRoute route : solution.getRoutes()) {
jobsInSolution.addAll(route.getTourActivities().getJobs());
}
if (jobsInSolution.size() != problem.getJobs().size()) {
throw new IllegalStateException("we are at the end of the algorithm and still have not found a valid solution." +
"This cannot be.");
}
}
}
}
| balage1551/jsprit | jsprit-core/src/main/java/com/graphhopper/jsprit/core/util/SolutionVerifier.java | Java | apache-2.0 | 2,020 |
package jp.ac.keio.bio.fun.xitosbml.image;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.ByteProcessor;
/**
* The class Filler, which provides several morphological operations for filling holes in the image.
* Date Created: Feb 21, 2017
*
* @author Kaito Ii <ii@fun.bio.keio.ac.jp>
* @author Akira Funahashi <funa@bio.keio.ac.jp>
*/
public class Filler {
/** The ImageJ image object. */
private ImagePlus image;
/** The width of an image. */
private int width;
/** The height of an image. */
private int height;
/** The depth of an image. */
private int depth;
/** The width of an image including padding. */
private int lwidth;
/** The height of an image including padding. */
private int lheight;
/** The depth of an image including padding. */
private int ldepth;
/** The mask which stores the label of each pixel. */
private int[] mask;
/**
* The hashmap of pixel value. <labelnumber, pixel value>.
* The domain which has pixel value = 0 will have a label = 1.
*/
private HashMap<Integer, Byte> hashPix = new HashMap<Integer, Byte>(); // label number, pixel value
/** The raw data (1D byte array) of the image. */
private byte[] pixels;
/** The raw data (1D int array) of inverted the image. */
private int[] invert;
/**
* Fill a hole in the given image (ImagePlus object) by morphology operation,
* and returns the filled image.
*
* @param image the ImageJ image object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(ImagePlus image){
this.width = image.getWidth();
this.height = image.getHeight();
this.depth = image.getStackSize();
this.image = image;
pixels = ImgProcessUtil.copyMat(image);
invertMat();
label();
if (checkHole()) {
while (checkHole()) {
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Fill a hole in the given image ({@link SpatialImage} object) by morphology operation,
* and returns the filled image as ImageJ image object.
*
* @param spImg the SpatialImage object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(SpatialImage spImg){
this.width = spImg.getWidth();
this.height = spImg.getHeight();
this.depth = spImg.getDepth();
this.image = spImg.getImage();
this.pixels = spImg.getRaw();
invertMat();
label();
if(checkHole()){
while(checkHole()){
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Creates the stack of images from raw data (1D array) of image (pixels[]),
* and returns the stack of images.
*
* @return the stack of images
*/
private ImageStack createStack(){
ImageStack altimage = new ImageStack(width, height);
for(int d = 0 ; d < depth ; d++){
byte[] matrix = new byte[width * height];
System.arraycopy(pixels, d * height * width, matrix, 0, matrix.length);
altimage.addSlice(new ByteProcessor(width,height,matrix,null));
}
return altimage;
}
/**
* Create an inverted 1D array of an image (invert[]) from 1D array of an image (pixels[]).
* Each pixel value will be inverted (0 -> 1, otherwise -> 0). For example, the Black and White
* binary image will be converted to a White and Black binary image.
*/
private void invertMat(){
lwidth = width + 2;
lheight = height + 2;
if(depth < 3) ldepth = depth;
else ldepth = depth + 2;
invert = new int[lwidth * lheight * ldepth];
mask = new int[lwidth * lheight * ldepth];
if (ldepth > depth) { // 3D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if (d == 0 || d == ldepth - 1 || h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1) {
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[(d - 1) * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if(h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1){
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[d * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
}
}
/** The label count. */
private int labelCount;
/**
* Assign a label (label number) to each pixel.
* The label number will be stored in mask[] array.
* The domain which has pixel value = 0 will have a label = 1.
*/
public void label(){
hashPix.put(1, (byte)0);
labelCount = 2;
if (ldepth > depth) {
for (int d = 1; d < ldepth - 1; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[(d-1) * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}
}
}
}
}else{
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[d * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}
}
}
}
}
}
/**
* Check whether a hole exists in the hashmap of pixels (HashMap<label number, pixel value>).
*
* @return true, if a hole exists
*/
public boolean checkHole(){
if(Collections.frequency(hashPix.values(), (byte) 0) > 1)
return true;
else
return false;
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The fill operation will be applied to each domain (which has unique label number).
*/
public void fillHole(){
for(Entry<Integer, Byte> e : hashPix.entrySet()){
if(!e.getKey().equals(1) && e.getValue().equals((byte)0)){
fill(e.getKey());
}
}
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The hole will be filled with the pixel value of adjacent pixel.
*
* @param labelNum the label number
*/
public void fill(int labelNum){
if (ldepth > depth) { // 3D image
for (int d = 1; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[(d-1) * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[d * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
}
}
/**
* Check adjacent pixels whether it contains the given label (labelNum).
* If all the adjacent pixels have same label with given label, then return 0.
* If the adjacent pixels contain different labels, then returns the pixel
* value of most enclosing adjacent domain.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param labelNum the label number
* @return the pixel value of most enclosing adjacent domain if different domain exists, otherwise 0
*/
public byte checkAdjacentsLabel(int w, int h, int d, int labelNum){
List<Byte> adjVal = new ArrayList<Byte>();
//check right
if(mask[d * lheight * lwidth + h * lwidth + w + 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w + 1]));
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]));
//check down
if(mask[d * lheight * lwidth + (h+1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h+1) * lwidth + w]));
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]));
//check above
if(d != depth - 1 && mask[(d+1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d+1) * lheight * lwidth + h * lwidth + w]));
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d - 1) * lheight * lwidth + h * lwidth + w]));
if(adjVal.isEmpty())
return 0;
int max = 0;
int count = 0;
int freq, temp; Byte val = 0;
for(int n = 0 ; n < adjVal.size() ; n++){
val = adjVal.get(n);
if(val == 0)
continue;
freq = Collections.frequency(adjVal, val);
temp = val & 0xFF;
if(freq > count){
max = temp;
count = freq;
}
if(freq == count && max < temp){
max = temp;
count = freq;
}
}
return (byte) max;
}
/**
* Sets the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) == (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
rewriteLabel(d, min, adjVal.get(i));
hashPix.remove(adjVal.get(i));
}
return min;
}
/**
* Sets back the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the non-zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setbackLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) != (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
hashPix.remove(adjVal.get(i));
rewriteLabel(d, min, adjVal.get(i));
}
return min;
}
/**
* Replace the label of pixels in the spatial image which has "before" to "after".
*
* @param dEnd the end of the depth
* @param after the label to set by this replacement
* @param before the label to be replaced
*/
private void rewriteLabel(int dEnd, int after, int before){
if (ldepth > depth) {
for (int d = 1; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}else{
for (int d = 0; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}
}
}
| spatialsimulator/XitoSBML | src/main/java/jp/ac/keio/bio/fun/xitosbml/image/Filler.java | Java | apache-2.0 | 14,320 |
/*
* Copyright 2015 Adaptris 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.adaptris.core;
import com.adaptris.annotation.Removal;
import com.adaptris.core.stubs.UpgradedToJunit4;
import com.adaptris.interlok.junit.scaffolding.ExampleConfigGenerator;
@Deprecated
@Removal(version = "4.0.0",
message = "moved to com.adaptris.interlok.junit.scaffolding")
public abstract class ExampleConfigCase extends ExampleConfigGenerator implements UpgradedToJunit4 {
}
| adaptris/interlok | interlok-core/src/test/java/com/adaptris/core/ExampleConfigCase.java | Java | apache-2.0 | 997 |
package org.ak.gitanalyzer.http.processor;
import org.ak.gitanalyzer.util.writer.CSVWriter;
import org.ak.gitanalyzer.util.writer.HTMLWriter;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* Created by Andrew on 02.12.2016.
*/
public class ProcessorMock extends BaseAnalysisProcessor {
public ProcessorMock(NumberFormat nf) {
super(nf);
}
@Override
public <T> String getCSVForReport(String[] headers, Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getCSVForReport(headers, collection, consumer);
}
@Override
public <T> String getJSONForTable(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONForTable(collection, consumer);
}
@Override
public <T> String getJSONFor2D(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONFor2D(collection, consumer);
}
@Override
public <T> String getJSONForGraph(Collection<T> collection, Function<T, Integer> nodeIdSupplier, TriConsumer<T, StringBuilder, Integer> consumer) {
return super.getJSONForGraph(collection, nodeIdSupplier, consumer);
}
@Override
public String getTypeString(double weight, double thickThreshold, double normalThreshold) {
return super.getTypeString(weight, thickThreshold, normalThreshold);
}
public HTMLWriter getHtmlWriter() {
return htmlWriter;
}
public CSVWriter getCsvWriter() {
return csvWriter;
}
}
| AndreyKunin/git-analyzer | src/test/java/org/ak/gitanalyzer/http/processor/ProcessorMock.java | Java | apache-2.0 | 1,622 |
package com.yezi.text.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import com.yezi.text.activity.AdapterSampleActivity;
import com.yezi.text.activity.AnimatorSampleActivity;
import com.yezi.text.R;
public class MyRecycleview extends AppCompatActivity {
private boolean enabledGrid = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycycleview);
findViewById(R.id.btn_animator_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AnimatorSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
findViewById(R.id.btn_adapter_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AdapterSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
((SwitchCompat) findViewById(R.id.grid)).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enabledGrid = isChecked;
}
});
}
}
| qwertyezi/Test | text/app/src/main/java/com/yezi/text/widget/MyRecycleview.java | Java | apache-2.0 | 1,720 |
/*
* Copyright 2008 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.datalint.open.shared.xml;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import com.datalint.open.shared.xml.impl.XMLParserImpl;
/**
* This class represents the client interface to XML parsing.
*/
public class XMLParser {
private static final XMLParserImpl impl = XMLParserImpl.getInstance();
/**
* This method creates a new document, to be manipulated by the DOM API.
*
* @return the newly created document
*/
public static Document createDocument() {
return impl.createDocument();
}
/**
* This method parses a new document from the supplied string, throwing a
* <code>DOMParseException</code> if the parse fails.
*
* @param contents the String to be parsed into a <code>Document</code>
* @return the newly created <code>Document</code>
*/
public static Document parse(String contents) {
return impl.parse(contents);
}
// Update on 2020-05-10, does not work with XPath.
public static Document parseReadOnly(String contents) {
return impl.parseReadOnly(contents);
}
/**
* This method removes all <code>Text</code> nodes which are made up of only
* white space.
*
* @param n the node which is to have all of its whitespace descendents removed.
*/
public static void removeWhitespace(Node n) {
removeWhitespaceInner(n, null);
}
/**
* This method determines whether the browser supports {@link CDATASection} as
* distinct entities from <code>Text</code> nodes.
*
* @return true if the browser supports {@link CDATASection}, otherwise
* <code>false</code>.
*/
public static boolean supportsCDATASection() {
return impl.supportsCDATASection();
}
/*
* The inner recursive method for removeWhitespace
*/
private static void removeWhitespaceInner(Node n, Node parent) {
// This n is removed from the parent if n is a whitespace node
if (parent != null && n instanceof Text && (!(n instanceof CDATASection))) {
Text t = (Text) n;
if (t.getData().matches("[ \t\n]*")) {
parent.removeChild(t);
}
}
if (n.hasChildNodes()) {
int length = n.getChildNodes().getLength();
List<Node> toBeProcessed = new ArrayList<Node>();
// We collect all the nodes to iterate as the child nodes will
// change upon removal
for (int i = 0; i < length; i++) {
toBeProcessed.add(n.getChildNodes().item(i));
}
// This changes the child nodes, but the iterator of nodes never
// changes meaning that this is safe
for (Node childNode : toBeProcessed) {
removeWhitespaceInner(childNode, n);
}
}
}
/**
* Not instantiable.
*/
private XMLParser() {
}
}
| datalint/open | Open/src/main/java/com/datalint/open/shared/xml/XMLParser.java | Java | apache-2.0 | 3,302 |
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.api;
import static org.assertj.core.util.Lists.newArrayList;
import org.junit.Rule;
import org.junit.Test;
public class JUnitBDDSoftAssertionsSuccessTest {
@Rule
public final JUnitBDDSoftAssertions softly = new JUnitBDDSoftAssertions();
@Test
public void all_assertions_should_pass() throws Throwable {
softly.then(1).isEqualTo(1);
softly.then(newArrayList(1, 2)).containsOnly(1, 2);
}
}
| dorzey/assertj-core | src/test/java/org/assertj/core/api/JUnitBDDSoftAssertionsSuccessTest.java | Java | apache-2.0 | 1,039 |
/*******************************************************************************
* Copyright 2013-2015 alladin-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.
******************************************************************************/
package at.alladin.rmbt.controlServer;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.naming.NamingException;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.engine.header.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.Options;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import at.alladin.rmbt.db.DbConnection;
import at.alladin.rmbt.shared.ResourceManager;
import at.alladin.rmbt.util.capability.Capabilities;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class ServerResource extends org.restlet.resource.ServerResource
{
protected Connection conn;
protected ResourceBundle labels;
protected ResourceBundle settings;
protected Capabilities capabilities = new Capabilities();
public static class MyDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime>
{
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context)
{
return new JsonPrimitive(src.toString());
}
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
public void readCapabilities(final JSONObject request) throws JSONException {
if (request != null) {
if (request.has("capabilities")) {
capabilities = new Gson().fromJson(request.get("capabilities").toString(), Capabilities.class);
}
}
}
public static Gson getGson(boolean prettyPrint)
{
GsonBuilder gb = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new MyDateTimeAdapter());
if (prettyPrint)
gb = gb.setPrettyPrinting();
return gb.create();
}
@Override
public void doInit() throws ResourceException
{
super.doInit();
settings = ResourceManager.getCfgBundle();
// Set default Language for System
Locale.setDefault(new Locale(settings.getString("RMBT_DEFAULT_LANGUAGE")));
labels = ResourceManager.getSysMsgBundle();
try {
if (getQuery().getNames().contains("capabilities")) {
capabilities = new Gson().fromJson(getQuery().getValues("capabilities"), Capabilities.class);
}
} catch (final Exception e) {
e.printStackTrace();
}
// Get DB-Connection
try
{
conn = DbConnection.getConnection();
}
catch (final NamingException e)
{
e.printStackTrace();
}
catch (final SQLException e)
{
System.out.println(labels.getString("ERROR_DB_CONNECTION_FAILED"));
e.printStackTrace();
}
}
@Override
protected void doRelease() throws ResourceException
{
try
{
if (conn != null)
conn.close();
}
catch (final SQLException e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
protected void addAllowOrigin()
{
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Series<>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
responseHeaders.add("Access-Control-Allow-Credentials", "false");
responseHeaders.add("Access-Control-Max-Age", "60");
}
@Options
public void doOptions(final Representation entity)
{
addAllowOrigin();
}
@SuppressWarnings("unchecked")
public String getIP()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realIp = headers.getFirstValue("X-Real-IP", true);
if (realIp != null)
return realIp;
else
return getRequest().getClientInfo().getAddress();
}
@SuppressWarnings("unchecked")
public Reference getURL()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realURL = headers.getFirstValue("X-Real-URL", true);
if (realURL != null)
return new Reference(realURL);
else
return getRequest().getOriginalRef();
}
protected String getSetting(String key, String lang)
{
if (conn == null)
return null;
try (final PreparedStatement st = conn.prepareStatement(
"SELECT value"
+ " FROM settings"
+ " WHERE key=? AND (lang IS NULL OR lang = ?)"
+ " ORDER BY lang NULLS LAST LIMIT 1");)
{
st.setString(1, key);
st.setString(2, lang);
try (final ResultSet rs = st.executeQuery();)
{
if (rs != null && rs.next())
return rs.getString("value");
}
return null;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
}
}
| alladin-IT/open-rmbt | RMBTControlServer/src/at/alladin/rmbt/controlServer/ServerResource.java | Java | apache-2.0 | 7,059 |
package io.github.marktony.reader.qsbk;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import io.github.marktony.reader.R;
import io.github.marktony.reader.adapter.QsbkArticleAdapter;
import io.github.marktony.reader.data.Qiushibaike;
import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener;
import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener;
/**
* Created by Lizhaotailang on 2016/8/4.
*/
public class QsbkFragment extends Fragment
implements QsbkContract.View {
private QsbkContract.Presenter presenter;
private QsbkArticleAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
public QsbkFragment() {
// requires empty constructor
}
public static QsbkFragment newInstance(int page) {
return new QsbkFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_list_fragment, container, false);
initViews(view);
presenter.loadArticle(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.loadArticle(true);
adapter.notifyDataSetChanged();
if (refreshLayout.isRefreshing()){
refreshLayout.setRefreshing(false);
}
}
});
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 获取最后一个完全显示的itemposition
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部并且是向下滑动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
presenter.loadMore();
}
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
isSlidingToLast = dy > 0;
}
});
return view;
}
@Override
public void setPresenter(QsbkContract.Presenter presenter) {
if (presenter != null) {
this.presenter = presenter;
}
}
@Override
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
}
@Override
public void showResult(ArrayList<Qiushibaike.Item> articleList) {
if (adapter == null) {
adapter = new QsbkArticleAdapter(getActivity(), articleList);
recyclerView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.setOnItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void OnClick(View v, int position) {
presenter.shareTo(position);
}
});
adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() {
@Override
public void OnLongClick(View view, int position) {
presenter.copyToClipboard(position);
}
});
}
@Override
public void startLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}
@Override
public void stopLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
});
}
@Override
public void showLoadError() {
Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT)
.setAction("重试", new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadArticle(false);
}
}).show();
}
@Override
public void onResume() {
super.onResume();
presenter.start();
}
}
| HeJianF/iReader | app/src/main/java/io/github/marktony/reader/qsbk/QsbkFragment.java | Java | apache-2.0 | 5,506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.