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 Intellectual Reserve, 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 org.gedcomx.build.enunciate;
import org.codehaus.enunciate.main.ClasspathHandler;
import org.codehaus.enunciate.main.ClasspathResource;
import org.codehaus.enunciate.main.Enunciate;
import org.gedcomx.test.Recipe;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ryan Heaton
*/
public class RecipeClasspathHandler implements ClasspathHandler {
private final Enunciate enunciate;
private final List<Recipe> recipes = new ArrayList<Recipe>();
private final Unmarshaller unmarshaller;
public RecipeClasspathHandler(Enunciate enunciate) {
this.enunciate = enunciate;
try {
unmarshaller = JAXBContext.newInstance(Recipe.class).createUnmarshaller();
}
catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public List<Recipe> getRecipes() {
return recipes;
}
@Override
public void startPathEntry(File pathEntry) {
}
@Override
public void handleResource(ClasspathResource resource) {
if (resource.getPath().endsWith(".recipe.xml")) {
try {
this.recipes.add((Recipe) unmarshaller.unmarshal(resource.read()));
}
catch (Exception e) {
this.enunciate.error("Unable to unmarshal recipe %s: %s.", resource.getPath(), e.getMessage());
}
}
}
@Override
public boolean endPathEntry(File pathEntry) {
return false;
}
}
| brenthale/gedcomx-java | enunciate-gedcomx-support/src/main/java/org/gedcomx/build/enunciate/RecipeClasspathHandler.java | Java | apache-2.0 | 2,169 |
/*
* 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.devicefarm.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a specific warning or failure.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/Problem" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Problem implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Information about the associated run.
* </p>
*/
private ProblemDetail run;
/**
* <p>
* Information about the associated job.
* </p>
*/
private ProblemDetail job;
/**
* <p>
* Information about the associated suite.
* </p>
*/
private ProblemDetail suite;
/**
* <p>
* Information about the associated test.
* </p>
*/
private ProblemDetail test;
/**
* <p>
* Information about the associated device.
* </p>
*/
private Device device;
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*/
private String result;
/**
* <p>
* A message about the problem's result.
* </p>
*/
private String message;
/**
* <p>
* Information about the associated run.
* </p>
*
* @param run
* Information about the associated run.
*/
public void setRun(ProblemDetail run) {
this.run = run;
}
/**
* <p>
* Information about the associated run.
* </p>
*
* @return Information about the associated run.
*/
public ProblemDetail getRun() {
return this.run;
}
/**
* <p>
* Information about the associated run.
* </p>
*
* @param run
* Information about the associated run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withRun(ProblemDetail run) {
setRun(run);
return this;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @param job
* Information about the associated job.
*/
public void setJob(ProblemDetail job) {
this.job = job;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @return Information about the associated job.
*/
public ProblemDetail getJob() {
return this.job;
}
/**
* <p>
* Information about the associated job.
* </p>
*
* @param job
* Information about the associated job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withJob(ProblemDetail job) {
setJob(job);
return this;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @param suite
* Information about the associated suite.
*/
public void setSuite(ProblemDetail suite) {
this.suite = suite;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @return Information about the associated suite.
*/
public ProblemDetail getSuite() {
return this.suite;
}
/**
* <p>
* Information about the associated suite.
* </p>
*
* @param suite
* Information about the associated suite.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withSuite(ProblemDetail suite) {
setSuite(suite);
return this;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @param test
* Information about the associated test.
*/
public void setTest(ProblemDetail test) {
this.test = test;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @return Information about the associated test.
*/
public ProblemDetail getTest() {
return this.test;
}
/**
* <p>
* Information about the associated test.
* </p>
*
* @param test
* Information about the associated test.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withTest(ProblemDetail test) {
setTest(test);
return this;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @param device
* Information about the associated device.
*/
public void setDevice(Device device) {
this.device = device;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @return Information about the associated device.
*/
public Device getDevice() {
return this.device;
}
/**
* <p>
* Information about the associated device.
* </p>
*
* @param device
* Information about the associated device.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withDevice(Device device) {
setDevice(device);
return this;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public void setResult(String result) {
this.result = result;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @return The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public String getResult() {
return this.result;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionResult
*/
public Problem withResult(String result) {
setResult(result);
return this;
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @see ExecutionResult
*/
public void setResult(ExecutionResult result) {
withResult(result);
}
/**
* <p>
* The problem's result.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* </ul>
*
* @param result
* The problem's result.</p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* PENDING
* </p>
* </li>
* <li>
* <p>
* PASSED
* </p>
* </li>
* <li>
* <p>
* WARNED
* </p>
* </li>
* <li>
* <p>
* FAILED
* </p>
* </li>
* <li>
* <p>
* SKIPPED
* </p>
* </li>
* <li>
* <p>
* ERRORED
* </p>
* </li>
* <li>
* <p>
* STOPPED
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see ExecutionResult
*/
public Problem withResult(ExecutionResult result) {
this.result = result.toString();
return this;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @param message
* A message about the problem's result.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @return A message about the problem's result.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* A message about the problem's result.
* </p>
*
* @param message
* A message about the problem's result.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Problem withMessage(String message) {
setMessage(message);
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 (getRun() != null)
sb.append("Run: ").append(getRun()).append(",");
if (getJob() != null)
sb.append("Job: ").append(getJob()).append(",");
if (getSuite() != null)
sb.append("Suite: ").append(getSuite()).append(",");
if (getTest() != null)
sb.append("Test: ").append(getTest()).append(",");
if (getDevice() != null)
sb.append("Device: ").append(getDevice()).append(",");
if (getResult() != null)
sb.append("Result: ").append(getResult()).append(",");
if (getMessage() != null)
sb.append("Message: ").append(getMessage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Problem == false)
return false;
Problem other = (Problem) obj;
if (other.getRun() == null ^ this.getRun() == null)
return false;
if (other.getRun() != null && other.getRun().equals(this.getRun()) == false)
return false;
if (other.getJob() == null ^ this.getJob() == null)
return false;
if (other.getJob() != null && other.getJob().equals(this.getJob()) == false)
return false;
if (other.getSuite() == null ^ this.getSuite() == null)
return false;
if (other.getSuite() != null && other.getSuite().equals(this.getSuite()) == false)
return false;
if (other.getTest() == null ^ this.getTest() == null)
return false;
if (other.getTest() != null && other.getTest().equals(this.getTest()) == false)
return false;
if (other.getDevice() == null ^ this.getDevice() == null)
return false;
if (other.getDevice() != null && other.getDevice().equals(this.getDevice()) == false)
return false;
if (other.getResult() == null ^ this.getResult() == null)
return false;
if (other.getResult() != null && other.getResult().equals(this.getResult()) == false)
return false;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRun() == null) ? 0 : getRun().hashCode());
hashCode = prime * hashCode + ((getJob() == null) ? 0 : getJob().hashCode());
hashCode = prime * hashCode + ((getSuite() == null) ? 0 : getSuite().hashCode());
hashCode = prime * hashCode + ((getTest() == null) ? 0 : getTest().hashCode());
hashCode = prime * hashCode + ((getDevice() == null) ? 0 : getDevice().hashCode());
hashCode = prime * hashCode + ((getResult() == null) ? 0 : getResult().hashCode());
hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
return hashCode;
}
@Override
public Problem clone() {
try {
return (Problem) 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.devicefarm.model.transform.ProblemMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/Problem.java | Java | apache-2.0 | 19,577 |
package lesson.types;
public class Classes {
public static void main(String[] args) {
JustClass one = new JustClass();
JustClass two = new JustClass(123, "sdf");
System.out.println(one);
System.out.println(two);
}
}
class JustClass {
private int number;
private String name;
public JustClass() { }
public JustClass(int number, String name) {
this.number = number;
this.name = name;
}
@Override
public String toString() {
return String
.format("JustClass {%s, %d}", name,number);
}
}
| nesterione/JavaTrainings | src/lesson/types/Classes.java | Java | apache-2.0 | 602 |
/**
* Utility classes for converting between granularities of SI (power-of-ten) and IEC (power-of-two)
* byte units and bit units.
* <p>
* <h3>Example Usage</h3>
* What's the difference in hard drive space between perception and actual?
* <pre><code>
* long perception = BinaryByteUnit.TEBIBYTES.toBytes(2);
* long usable = DecimalByteUnit.TERABYTES.toBytes(2);
* long lost = BinaryByteUnit.BYTES.toGibibytes(perception - usable);
* System.out.println(lost + " GiB lost on a 2TB drive.");
* </code></pre>
* <p>
* Method parameter for specifying a resource size.
* <pre><code>
* public void installDiskCache(long count, ByteUnit unit) {
* long size = unit.toBytes(count);
* // TODO Install disk cache of 'size' bytes.
* }
* </code></pre>
*/
package com.jakewharton.byteunits;
| JakeWharton/byteunits | src/main/java/com/jakewharton/byteunits/package-info.java | Java | apache-2.0 | 799 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.experimental.logical.relational;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.util.Pair;
/**
* Schema, from a logical perspective.
*/
public class LogicalSchema {
public static class LogicalFieldSchema {
public String alias;
public byte type;
public long uid;
public LogicalSchema schema;
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type) {
this(alias, schema, type, -1);
}
public LogicalFieldSchema(String alias, LogicalSchema schema, byte type, long uid) {
this.alias = alias;
this.type = type;
this.schema = schema;
this.uid = uid;
}
/**
* Equality is defined as having the same type and either the same schema
* or both null schema. Alias and uid are not checked.
*/
public boolean isEqual(Object other) {
if (other instanceof LogicalFieldSchema) {
LogicalFieldSchema ofs = (LogicalFieldSchema)other;
if (type != ofs.type) return false;
if (schema == null && ofs.schema == null) return true;
if (schema == null) return false;
else return schema.isEqual(ofs.schema);
} else {
return false;
}
}
public String toString() {
if( type == DataType.BAG ) {
if( schema == null ) {
return ( alias + "#" + uid + ":bag{}#" );
}
return ( alias + "#" + uid + ":bag{" + schema.toString() + "}" );
} else if( type == DataType.TUPLE ) {
if( schema == null ) {
return ( alias + "#" + uid + ":tuple{}" );
}
return ( alias + "#" + uid + ":tuple(" + schema.toString() + ")" );
}
return ( alias + "#" + uid + ":" + DataType.findTypeName(type) );
}
}
private List<LogicalFieldSchema> fields;
private Map<String, Pair<Integer, Boolean>> aliases;
public LogicalSchema() {
fields = new ArrayList<LogicalFieldSchema>();
aliases = new HashMap<String, Pair<Integer, Boolean>>();
}
/**
* Add a field to this schema.
* @param field to be added to the schema
*/
public void addField(LogicalFieldSchema field) {
fields.add(field);
if (field.alias != null && !field.alias.equals("")) {
// put the full name of this field into aliases map
// boolean in the pair indicates if this alias is full name
aliases.put(field.alias, new Pair<Integer, Boolean>(fields.size()-1, true));
int index = 0;
// check and put short names into alias map if there is no conflict
while(index != -1) {
index = field.alias.indexOf("::", index);
if (index != -1) {
String a = field.alias.substring(index+2);
if (aliases.containsKey(a)) {
// remove conflict if the conflict is not full name
// we can never remove full name
if (!aliases.get(a).second) {
aliases.remove(a);
}
}else{
// put alias into map and indicate it is a short name
aliases.put(a, new Pair<Integer, Boolean>(fields.size()-1, false));
}
index = index +2;
}
}
}
}
/**
* Fetch a field by alias
* @param alias
* @return field associated with alias, or null if no such field
*/
public LogicalFieldSchema getField(String alias) {
Pair<Integer, Boolean> p = aliases.get(alias);
if (p == null) {
return null;
}
return fields.get(p.first);
}
/**
* Fetch a field by field number
* @param fieldNum field number to fetch
* @return field
*/
public LogicalFieldSchema getField(int fieldNum) {
return fields.get(fieldNum);
}
/**
* Get all fields
* @return list of all fields
*/
public List<LogicalFieldSchema> getFields() {
return fields;
}
/**
* Get the size of the schema.
* @return size
*/
public int size() {
return fields.size();
}
/**
* Two schemas are equal if they are of equal size and their fields
* schemas considered in order are equal.
*/
public boolean isEqual(Object other) {
if (other != null && other instanceof LogicalSchema) {
LogicalSchema os = (LogicalSchema)other;
if (size() != os.size()) return false;
for (int i = 0; i < size(); i++) {
if (!getField(i).isEqual(os.getField(i))) return false;
}
return true;
} else {
return false;
}
}
/**
* Look for the index of the field that contains the specified uid
* @param uid the uid to look for
* @return the index of the field, -1 if not found
*/
public int findField(long uid) {
for(int i=0; i< size(); i++) {
LogicalFieldSchema f = getField(i);
// if this field has the same uid, then return this field
if (f.uid == uid) {
return i;
}
// if this field has a schema, check its schema
if (f.schema != null) {
if (f.schema.findField(uid) != -1) {
return i;
}
}
}
return -1;
}
/**
* Merge two schemas.
* @param s1
* @param s2
* @return a merged schema, or null if the merge fails
*/
public static LogicalSchema merge(LogicalSchema s1, LogicalSchema s2) {
// TODO
return null;
}
public String toString() {
StringBuilder str = new StringBuilder();
for( LogicalFieldSchema field : fields ) {
str.append( field.toString() + "," );
}
if( fields.size() != 0 ) {
str.deleteCharAt( str.length() -1 );
}
return str.toString();
}
}
| hirohanin/pig7hadoop21 | src/org/apache/pig/experimental/logical/relational/LogicalSchema.java | Java | apache-2.0 | 7,432 |
package com.github.nikolaymakhonin.android_app_example.di.factories;
import android.content.Context;
import android.support.annotation.NonNull;
import com.github.nikolaymakhonin.android_app_example.di.components.AppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerAppComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.DaggerServiceComponent;
import com.github.nikolaymakhonin.android_app_example.di.components.ServiceComponent;
import com.github.nikolaymakhonin.common_di.modules.service.ServiceModuleBase;
public final class ComponentsFactory {
public static AppComponent buildAppComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = buildServiceComponent(appContext);
AppComponent appComponent = DaggerAppComponent.builder()
.serviceComponent(serviceComponent)
.build();
return appComponent;
}
public static ServiceComponent buildServiceComponent(@NonNull Context appContext) {
ServiceComponent serviceComponent = DaggerServiceComponent.builder()
.serviceModuleBase(new ServiceModuleBase(appContext))
.build();
return serviceComponent;
}
}
| NikolayMakhonin/AndroidAppExample | AndroidAppExample/AppExample/src/main/java/com/github/nikolaymakhonin/android_app_example/di/factories/ComponentsFactory.java | Java | apache-2.0 | 1,243 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.objectdiagram.command;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.objectdiagram.AbstractClassOrObjectDiagram;
import net.sourceforge.plantuml.skin.VisibilityModifier;
import net.sourceforge.plantuml.ugraphic.color.NoSuchColorException;
public class CommandAddData extends SingleLineCommand2<AbstractClassOrObjectDiagram> {
public CommandAddData() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandAddData.class.getName(), RegexLeaf.start(), //
new RegexLeaf("NAME", "([%pLN_.]+)"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf(":"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf("DATA", "(.*)"), RegexLeaf.end()); //
}
@Override
protected CommandExecutionResult executeArg(AbstractClassOrObjectDiagram diagram, LineLocation location,
RegexResult arg) throws NoSuchColorException {
final String name = arg.get("NAME", 0);
final IEntity entity = diagram.getOrCreateLeaf(diagram.buildLeafIdent(name),
diagram.buildCode(name), null, null);
final String field = arg.get("DATA", 0);
if (field.length() > 0 && VisibilityModifier.isVisibilityCharacter(field)) {
diagram.setVisibilityModifierPresent(true);
}
entity.getBodier().addFieldOrMethod(field);
return CommandExecutionResult.ok();
}
}
| talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/objectdiagram/command/CommandAddData.java | Java | apache-2.0 | 2,860 |
/**
* 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.xml.security.test.stax.c14n;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_Excl;
import org.junit.Before;
import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclOmitCommentsTransformer;
import org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_ExclWithCommentsTransformer;
import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author $Author: coheigea $
* @version $Revision: 1721336 $ $Date: 2015-12-22 10:45:18 +0000 (Tue, 22 Dec 2015) $
*/
public class Canonicalizer20010315ExclusiveTest extends org.junit.Assert {
private XMLInputFactory xmlInputFactory;
@Before
public void setUp() throws Exception {
this.xmlInputFactory = XMLInputFactory.newInstance();
this.xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
}
@org.junit.Test
public void test221excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
XMLEventReader xmlSecEventReader = xmlInputFactory.createXMLEventReader(
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_1.xml")
);
XMLSecEvent xmlSecEvent = null;
while (xmlSecEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
}
while (xmlSecEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlSecEventReader.nextEvent();
}
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test222excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_2_2.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void test24excl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/example2_4.xml"),
new QName("http://example.net", "elem2")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testComplexDocexcl() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer();
c.setOutputStream(baos);
canonicalize(c,
this.getClass().getClassLoader().getResourceAsStream(
"org/apache/xml/security/c14n/inExcl/plain-soap-1.1.xml"),
new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body", "env")
);
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/plain-soap-c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
if (!equals) {
System.out.println("Expected:\n" + new String(reference, "UTF-8"));
System.out.println("");
System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
}
assertTrue(equals);
}
@org.junit.Test
public void testNodeSet() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("env");
inclusiveNamespaces.add("ns0");
inclusiveNamespaces.add("xsi");
inclusiveNamespaces.add("wsu");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
/**
* Method test24Aexcl - a testcase for SANTUARIO-263
* "Canonicalizer can't handle dynamical created DOM correctly"
* https://issues.apache.org/jira/browse/SANTUARIO-263
*/
@org.junit.Test
public void test24Aexcl() throws Exception {
Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
Element local = doc.createElementNS("foo:bar", "dsig:local");
Element test = doc.createElementNS("http://example.net", "etsi:test");
Element elem2 = doc.createElementNS("http://example.net", "etsi:elem2");
Element stuff = doc.createElementNS("foo:bar", "dsig:stuff");
elem2.appendChild(stuff);
test.appendChild(elem2);
local.appendChild(test);
doc.appendChild(local);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
t.transform(new DOMSource(doc), streamResult);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
Canonicalizer20010315_ExclWithCommentsTransformer c =
new Canonicalizer20010315_ExclWithCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(stringWriter.toString()), new QName("http://example.net", "elem2"));
byte[] reference =
getBytesFromResource(this.getClass().getClassLoader().getResource(
"org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
assertTrue(equals);
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"http://example.com\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML1 =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
final String c14nXML2 =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML1);
}
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML2);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList3() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns=\"\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testDefaultNSInInclusiveNamespacePrefixList4() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
{
//exactly the same outcome is expected if #default is not set:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("xsi");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
}
/**
* Test default namespace behavior if its in the InclusiveNamespace prefix list.
*
* @throws Exception
*/
@org.junit.Test
public void testPropagateDefaultNs1() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs2() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs3() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xmlns=\"\" xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs4() throws Exception {
final String XML =
"<Envelope"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</Envelope>";
final String c14nXML =
"<env:Body"
+ " xmlns=\"\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ " wsu:Id=\"body\">"
+ "<ns0:Ping xmlns:ns0=\"http://xmlsoap.org/Ping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
@org.junit.Test
public void testPropagateDefaultNs5() throws Exception {
final String XML =
"<env:Envelope"
+ " xmlns=\"http://example.com\""
+ " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ "<env:Body xmlns=\"\" wsu:Id=\"body\">"
+ "<ns0:Ping xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>"
+ "</env:Body>"
+ "</env:Envelope>";
final String c14nXML =
"<ns0:Ping xmlns=\"\" xmlns:ns0=\"http://xmlsoap.org/Ping\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"ns0:ping\">"
+ "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ "</ns0:Ping>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
List<String> inclusiveNamespaces = new ArrayList<String>();
inclusiveNamespaces.add("#default");
Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer();
Map<String, Object> transformerProperties = new HashMap<String, Object>();
transformerProperties.put(Canonicalizer20010315_Excl.INCLUSIVE_NAMESPACES_PREFIX_LIST, inclusiveNamespaces);
transformerProperties.put(Canonicalizer20010315_Excl.PROPAGATE_DEFAULT_NAMESPACE, Boolean.TRUE);
c.setProperties(transformerProperties);
c.setOutputStream(baos);
canonicalize(c, new StringReader(XML), new QName("http://xmlsoap.org/Ping", "Ping"));
assertEquals(new String(baos.toByteArray(), "UTF-8"), c14nXML);
}
private void canonicalize(
Canonicalizer20010315_Excl c, InputStream inputStream, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(inputStream), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, Reader reader, QName elementName)
throws XMLStreamException {
canonicalize(c, xmlInputFactory.createXMLEventReader(reader), elementName);
}
private void canonicalize(
Canonicalizer20010315_Excl c, XMLEventReader xmlEventReader, QName elementName)
throws XMLStreamException {
XMLSecEvent xmlSecEvent = null;
while (xmlEventReader.hasNext()) {
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
if (xmlSecEvent.isStartElement() && xmlSecEvent.asStartElement().getName().equals(elementName)) {
break;
}
}
while (xmlEventReader.hasNext()) {
c.transform(xmlSecEvent);
if (xmlSecEvent.isEndElement() && xmlSecEvent.asEndElement().getName().equals(elementName)) {
break;
}
xmlSecEvent = (XMLSecEvent) xmlEventReader.nextEvent();
}
}
public static byte[] getBytesFromResource(URL resource) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = resource.openStream();
try {
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
} finally {
inputStream.close();
}
}
} | Legostaev/xmlsec-gost | src/test/java/org/apache/xml/security/test/stax/c14n/Canonicalizer20010315ExclusiveTest.java | Java | apache-2.0 | 40,733 |
/*
* Copyright 2015 OpenCB
*
* 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.opencb.biodata.formats.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractFormatReader<T> {
protected Path path;
protected Logger logger;
protected AbstractFormatReader() {
path = null;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
protected AbstractFormatReader(Path f) throws IOException {
Files.exists(f);
this.path = f;
logger = LoggerFactory.getLogger(AbstractFormatReader.class);
// logger.setLevel(Logger.DEBUG_LEVEL);
}
public abstract int size() throws IOException, FileFormatException;
public abstract T read() throws FileFormatException;
public abstract T read(String regexFilter) throws FileFormatException;
public abstract List<T> read(int size) throws FileFormatException;
public abstract List<T> readAll() throws FileFormatException, IOException;
public abstract List<T> readAll(String pattern) throws FileFormatException;
public abstract void close() throws IOException;
}
| kalyanreddyemani/biodata | biodata-formats/src/main/java/org/opencb/biodata/formats/io/AbstractFormatReader.java | Java | apache-2.0 | 1,817 |
package org.ovirt.engine.ui.uicommonweb.models.configure.roles_ui;
import java.util.ArrayList;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.common.SelectionTreeNodeModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
@SuppressWarnings("unused")
public class RoleTreeView
{
public static ArrayList<SelectionTreeNodeModel> GetRoleTreeView(boolean isReadOnly, boolean isAdmin)
{
RoleNode tree = initTreeView();
ArrayList<ActionGroup> userActionGroups = null;
if (isAdmin == false)
{
userActionGroups = GetUserActionGroups();
}
ArrayList<SelectionTreeNodeModel> roleTreeView = new ArrayList<SelectionTreeNodeModel>();
SelectionTreeNodeModel firstNode = null, secondNode = null, thirdNode = null;
for (RoleNode first : tree.getLeafRoles())
{
firstNode = new SelectionTreeNodeModel();
firstNode.setTitle(first.getName());
firstNode.setDescription(first.getName());
firstNode.setIsChangable(!isReadOnly);
for (RoleNode second : first.getLeafRoles())
{
secondNode = new SelectionTreeNodeModel();
secondNode.setTitle(second.getName());
secondNode.setDescription(second.getName());
secondNode.setIsChangable(!isReadOnly);
secondNode.setTooltip(second.getTooltip());
for (RoleNode third : second.getLeafRoles())
{
thirdNode = new SelectionTreeNodeModel();
thirdNode.setTitle(third.getName());
thirdNode.setDescription(third.getDesc());
thirdNode.setIsSelectedNotificationPrevent(true);
// thirdNode.IsSelected =
// attachedActions.Contains((VdcActionType) Enum.Parse(typeof (VdcActionType), name)); //TODO:
// suppose to be action group
thirdNode.setIsChangable(!isReadOnly);
thirdNode.setIsSelectedNullable(false);
thirdNode.setTooltip(third.getTooltip());
if (!isAdmin)
{
if (userActionGroups.contains(ActionGroup.valueOf(thirdNode.getTitle())))
{
secondNode.getChildren().add(thirdNode);
}
}
else
{
secondNode.getChildren().add(thirdNode);
}
}
if (secondNode.getChildren().size() > 0)
{
firstNode.getChildren().add(secondNode);
}
}
if (firstNode.getChildren().size() > 0)
{
roleTreeView.add(firstNode);
}
}
return roleTreeView;
}
private static ArrayList<ActionGroup> GetUserActionGroups() {
ArrayList<ActionGroup> array = new ArrayList<ActionGroup>();
array.add(ActionGroup.CREATE_VM);
array.add(ActionGroup.DELETE_VM);
array.add(ActionGroup.EDIT_VM_PROPERTIES);
array.add(ActionGroup.VM_BASIC_OPERATIONS);
array.add(ActionGroup.CHANGE_VM_CD);
array.add(ActionGroup.MIGRATE_VM);
array.add(ActionGroup.CONNECT_TO_VM);
array.add(ActionGroup.CONFIGURE_VM_NETWORK);
array.add(ActionGroup.CONFIGURE_VM_STORAGE);
array.add(ActionGroup.MOVE_VM);
array.add(ActionGroup.MANIPULATE_VM_SNAPSHOTS);
array.add(ActionGroup.CREATE_TEMPLATE);
array.add(ActionGroup.EDIT_TEMPLATE_PROPERTIES);
array.add(ActionGroup.DELETE_TEMPLATE);
array.add(ActionGroup.COPY_TEMPLATE);
array.add(ActionGroup.CONFIGURE_TEMPLATE_NETWORK);
array.add(ActionGroup.CREATE_VM_POOL);
array.add(ActionGroup.EDIT_VM_POOL_CONFIGURATION);
array.add(ActionGroup.DELETE_VM_POOL);
array.add(ActionGroup.VM_POOL_BASIC_OPERATIONS);
array.add(ActionGroup.MANIPULATE_PERMISSIONS);
array.add(ActionGroup.CREATE_DISK);
array.add(ActionGroup.ATTACH_DISK);
array.add(ActionGroup.DELETE_DISK);
array.add(ActionGroup.CONFIGURE_DISK_STORAGE);
array.add(ActionGroup.EDIT_DISK_PROPERTIES);
array.add(ActionGroup.LOGIN);
array.add(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES);
array.add(ActionGroup.PORT_MIRRORING);
return array;
}
private static RoleNode initTreeView()
{
RoleNode tree =
new RoleNode(ConstantsManager.getInstance().getConstants().rootRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance().getConstants().systemRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureSystemRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.MANIPULATE_USERS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveUsersFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_PERMISSIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemovePermissionsForUsersOnObjectsInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_ROLES,
ConstantsManager.getInstance()
.getConstants()
.allowToDefineConfigureRolesInTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.LOGIN,
ConstantsManager.getInstance()
.getConstants()
.allowToLoginToTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_ENGINE,
ConstantsManager.getInstance()
.getConstants()
.allowToGetOrSetSystemConfigurationRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().dataCenterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureDataCenterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveDataCenterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyDataCenterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_STORAGE_POOL_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureLogicalNetworkPerDataCenterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().storageDomainRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureStorageDomainRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_STORAGE_DOMAIN_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToModifyStorageDomainPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_STORAGE_DOMAIN,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeStorageDomainStatusRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().clusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureClusterRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_CLUSTER,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_CLUSTER_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditClusterPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_CLUSTER_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveLogicalNetworksForTheClusterRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().glusterRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureVolumesRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateGlusterVolumesRoleTree()),
new RoleNode(ActionGroup.MANIPULATE_GLUSTER_VOLUME,
ConstantsManager.getInstance()
.getConstants()
.allowToManipulateGlusterVolumesRoleTree()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().hostRoleTree(),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.configureHostRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToAddNewHostToTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingHostFromTheClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_HOST_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToEditHostPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPUTLATE_HOST,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeHostStatusRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_HOST_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureHostsNetworkPhysicalInterfacesRoleTreeTooltip()) })),
new RoleNode(ConstantsManager.getInstance().getConstants().templateRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_TEMPLATE_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangeTemplatePropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_TEMPLATE_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureTemlateNetworkRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveExistingTemplateRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.COPY_TEMPLATE,
ConstantsManager.getInstance()
.getConstants()
.allowToCopyTemplateBetweenStorageDomainsRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] {
new RoleNode(ActionGroup.VM_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowBasicVmOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CD,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachCdToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.CONNECT_TO_VM,
ConstantsManager.getInstance()
.getConstants()
.allowViewingTheVmConsoleScreenRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.EDIT_VM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowChangeVmPropertiesRoleTreeTooltip()),
new RoleNode(ActionGroup.CREATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateNewVmsRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToRemoveVmsFromTheSystemRoleTreeTooltip()),
new RoleNode(ActionGroup.IMPORT_EXPORT_VM,
ConstantsManager.getInstance()
.getConstants()
.allowImportExportOperationsRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_NETWORK,
ConstantsManager.getInstance()
.getConstants()
.allowToConfigureVMsNetworkRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_VM_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToAddRemoveDiskToTheVmRoleTreeTooltip()),
new RoleNode(ActionGroup.MANIPULATE_VM_SNAPSHOTS,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDeleteSnapshotsOfTheVmRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.administrationOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatDcOrEqualRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.MOVE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveVmImageToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.MIGRATE_VM,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowMigratingVmBetweenHostsInClusterRoleTreeTooltip()),
new RoleNode(ActionGroup.PORT_MIRRORING,
ConstantsManager.getInstance()
.getConstants()
.allowVmNetworkPortMirroringRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().vmPoolRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.basicOperationsRoleTree(),
new RoleNode[] { new RoleNode(ActionGroup.VM_POOL_BASIC_OPERATIONS,
ConstantsManager.getInstance()
.getConstants()
.allowToRunPauseStopVmFromVmPoolRoleTreeTooltip()) }),
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainigTheseOperationsShuoldAssociatSdOrAboveRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_VM_POOL,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteVmPoolRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_VM_POOL_CONFIGURATION,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheVmPoolRoleTreeTooltip()) }) }),
new RoleNode(ConstantsManager.getInstance().getConstants().diskRoleTree(),
new RoleNode[] {
new RoleNode(ConstantsManager.getInstance()
.getConstants()
.provisioningOperationsRoleTree(),
ConstantsManager.getInstance()
.getConstants()
.notePermissionsContainingOperationsRoleTreeTooltip(),
new RoleNode[] {
new RoleNode(ActionGroup.CREATE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToCreateDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.DELETE_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToDeleteDiskRoleTreeTooltip()),
new RoleNode(ActionGroup.CONFIGURE_DISK_STORAGE,
ConstantsManager.getInstance()
.getConstants()
.allowToMoveDiskToAnotherStorageDomainRoleTreeTooltip()),
new RoleNode(ActionGroup.ATTACH_DISK,
ConstantsManager.getInstance()
.getConstants()
.allowToAttachDiskToVmRoleTreeTooltip()),
new RoleNode(ActionGroup.EDIT_DISK_PROPERTIES,
ConstantsManager.getInstance()
.getConstants()
.allowToChangePropertiesOfTheDiskRoleTreeTooltip()) }) }) });
// nothing to filter
if (!ApplicationModeHelper.getUiMode().equals(ApplicationMode.AllModes)) {
ApplicationModeHelper.filterActionGroupTreeByApplictionMode(tree);
}
return tree;
}
}
| derekhiggins/ovirt-engine | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/configure/roles_ui/RoleTreeView.java | Java | apache-2.0 | 34,814 |
package com.jpattern.core.command;
import com.jpattern.core.IProvider;
import com.jpattern.core.exception.NullProviderException;
import com.jpattern.logger.ILogger;
import com.jpattern.logger.SystemOutLoggerFactory;
/**
*
* @author Francesco Cina'
*
* 11/set/2011
*/
public abstract class ACommand<T extends IProvider> {
private ICommandExecutor commandExecutor;
private IOnExceptionStrategy onExceptionStrategy;
private T provider;
private ILogger logger = null;
private boolean executed = false;
private boolean rolledback = false;
/**
* This method launch the execution of the command (or chain of commands) using the default
* default Executor and catching every runtime exception.
* This command is the same of:
* exec(provider, true);
* @return the result of the execution
*/
public final ACommandResult exec(T provider) {
return exec(provider, new DefaultCommandExecutor());
}
/**
* This method launch the execution of the command (or chain of commands).
* Every command in the chain will be managed by an ICommandExecutor object.
* This command is the same of:
* exec(commandExecutor, true);
* @param aCommandExecutor the pool in which the command will runs
* @return the result of the execution
*/
public final ACommandResult exec(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return exec( commandExecutor, new CommandResult());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using the default
* default Executor and catching every runtime exception.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider) {
return rollback(provider, new DefaultCommandExecutor());
}
/**
* This method launch the rollback of the command execution (or chain of commands) using a custom command executor.
* The rollback is effectively performed only if the command has been executed with a positive result, otherwise
* the command is intended as "not executed" then no rollback will be performed.
* This command is the same of:
* rollback(provider, commandExecutor, true);
* @return the result of the rollback
*/
public final ACommandResult rollback(T provider, ICommandExecutor commandExecutor) {
visit(provider);
return rollback(commandExecutor, new CommandResult());
}
void visit(T provider) {
this.provider = provider;
}
protected final ACommandResult exec(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().execute(this, commandResult);
return commandResult;
}
protected final ACommandResult rollback(ICommandExecutor commandExecutor, ACommandResult commandResult) {
this.commandExecutor = commandExecutor;
commandResult.setExecutionStart(this);
getCommandExecutor().rollback(this, commandResult);
return commandResult;
}
protected final ICommandExecutor getCommandExecutor() {
if (commandExecutor==null) {
commandExecutor = new DefaultCommandExecutor();
}
return commandExecutor;
}
protected final T getProvider() {
if (provider==null) {
throw new NullProviderException();
}
return provider;
}
protected final ILogger getLogger() {
if (logger == null) {
if (provider == null) {
logger = new SystemOutLoggerFactory().logger(getClass());
} else {
logger = getProvider().getLoggerService().logger(this.getClass());
}
}
return logger;
}
public void setOnExceptionStrategy(IOnExceptionStrategy onExceptionStrategy) {
this.onExceptionStrategy = onExceptionStrategy;
}
public IOnExceptionStrategy getOnExceptionStrategy() {
if (onExceptionStrategy == null) {
onExceptionStrategy = new CatchOnExceptionStrategy();
}
return onExceptionStrategy;
}
protected final void doExec(ACommandResult commandResult) {
try {
int errorSize = commandResult.getErrorMessages().size();
executed = false;
rolledback = false;
execute(commandResult);
executed = commandResult.getErrorMessages().size() == errorSize;
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown");
} finally {
try {
postExecute(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
void postExecute(ACommandResult commandResult) {
}
void postRollback(ACommandResult commandResult) {
}
protected final void doRollback(ACommandResult commandResult) {
try {
if (executed && !rolledback) {
rollback(commandResult);
rolledback = true;
}
} catch (RuntimeException e) {
getOnExceptionStrategy().onException(e, getLogger(), commandResult, "RuntimeException thrown while rollbacking");
} finally {
try {
postRollback(commandResult);
} finally {
commandResult.setExecutionEnd(this);
}
}
}
protected abstract void execute(ACommandResult commandResult);
protected abstract void rollback(ACommandResult commandResult);
void setExecuted(boolean executed) {
this.executed = executed;
}
boolean isExecuted() {
return executed;
}
void setRolledback(boolean rolledback) {
this.rolledback = rolledback;
}
boolean isRolledback() {
return rolledback;
}
}
| ufoscout/jpattern | core/src/main/java/com/jpattern/core/command/ACommand.java | Java | apache-2.0 | 5,668 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.internal.hash;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Output stream decorator that hashes data written to the stream.
* Inspired by the Google Guava project.
*/
public final class HashingOutputStream extends FilterOutputStream {
private final Hasher hasher;
public HashingOutputStream(HashFunction hashFunction, OutputStream out) {
super(checkNotNull(out));
this.hasher = checkNotNull(hashFunction.newHasher());
}
@Override
public void write(int b) throws IOException {
hasher.putByte((byte) b);
out.write(b);
}
@Override
public void write(byte[] bytes, int off, int len) throws IOException {
hasher.putBytes(bytes, off, len);
out.write(bytes, off, len);
}
public HashCode hash() {
return hasher.hash();
}
@Override
public void close() throws IOException {
out.close();
}
}
| gstevey/gradle | subprojects/base-services/src/main/java/org/gradle/internal/hash/HashingOutputStream.java | Java | apache-2.0 | 1,665 |
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.agent;
import com.spotify.docker.client.ContainerNotFoundException;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.helios.common.descriptors.Goal;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.servicescommon.DefaultReactor;
import com.spotify.helios.servicescommon.Reactor;
import com.spotify.helios.servicescommon.statistics.MetricsContext;
import com.spotify.helios.servicescommon.statistics.SupervisorMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPED;
import static com.spotify.helios.common.descriptors.TaskStatus.State.STOPPING;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Supervises docker containers for a single job.
*/
public class Supervisor {
public interface Listener {
void stateChanged(Supervisor supervisor);
}
private static final Logger log = LoggerFactory.getLogger(Supervisor.class);
private final DockerClient docker;
private final Job job;
private final RestartPolicy restartPolicy;
private final SupervisorMetrics metrics;
private final Reactor reactor;
private final Listener listener;
private final TaskRunnerFactory runnerFactory;
private final StatusUpdater statusUpdater;
private final TaskMonitor monitor;
private final Sleeper sleeper;
private volatile Goal goal;
private volatile String containerId;
private volatile TaskRunner runner;
private volatile Command currentCommand;
private volatile Command performedCommand;
public Supervisor(final Builder builder) {
this.job = checkNotNull(builder.job, "job");
this.docker = checkNotNull(builder.dockerClient, "docker");
this.restartPolicy = checkNotNull(builder.restartPolicy, "restartPolicy");
this.metrics = checkNotNull(builder.metrics, "metrics");
this.listener = checkNotNull(builder.listener, "listener");
this.currentCommand = new Nop();
this.containerId = builder.existingContainerId;
this.runnerFactory = checkNotNull(builder.runnerFactory, "runnerFactory");
this.statusUpdater = checkNotNull(builder.statusUpdater, "statusUpdater");
this.monitor = checkNotNull(builder.monitor, "monitor");
this.reactor = new DefaultReactor("supervisor-" + job.getId(), new Update(),
SECONDS.toMillis(30));
this.reactor.startAsync();
statusUpdater.setContainerId(containerId);
this.sleeper = builder.sleeper;
}
public void setGoal(final Goal goal) {
if (this.goal == goal) {
return;
}
log.debug("Supervisor {}: setting goal: {}", job.getId(), goal);
this.goal = goal;
statusUpdater.setGoal(goal);
switch (goal) {
case START:
currentCommand = new Start();
reactor.signal();
metrics.supervisorStarted();
break;
case STOP:
case UNDEPLOY:
currentCommand = new Stop();
reactor.signal();
metrics.supervisorStopped();
break;
}
}
/**
* Close this supervisor. The actual container is left as-is.
*/
public void close() {
reactor.stopAsync();
if (runner != null) {
runner.stopAsync();
}
metrics.supervisorClosed();
monitor.close();
}
/**
* Wait for supervisor to stop after closing it.
*/
public void join() {
reactor.awaitTerminated();
if (runner != null) {
// Stop the runner again in case it was rewritten by the reactor before it terminated.
runner.stopAsync();
runner.awaitTerminated();
}
}
/**
* Check if the current command is start.
* @return True if current command is start, otherwise false.
*/
public boolean isStarting() {
return currentCommand instanceof Start;
}
/**
* Check if the current command is stop.
* @return True if current command is stop, otherwise false.
*/
public boolean isStopping() {
return currentCommand instanceof Stop;
}
/**
* Check whether the last start/stop command is done.
* @return True if last start/stop command is done, otherwise false.
*/
public boolean isDone() {
return currentCommand == performedCommand;
}
/**
* Get the current container id
* @return The container id.
*/
public String containerId() {
return containerId;
}
private class Update implements Reactor.Callback {
@Override
public void run(final boolean timeout) throws InterruptedException {
final Command command = currentCommand;
final boolean done = performedCommand == command;
log.debug("Supervisor {}: update: performedCommand={}, command={}, done={}",
job.getId(), performedCommand, command, done);
command.perform(done);
if (!done) {
performedCommand = command;
fireStateChanged();
}
}
}
private void fireStateChanged() {
log.debug("Supervisor {}: state changed", job.getId());
try {
listener.stateChanged(this);
} catch (Exception e) {
log.error("Listener threw exception", e);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private Builder() {
}
private Job job;
private String existingContainerId;
private DockerClient dockerClient;
private RestartPolicy restartPolicy;
private SupervisorMetrics metrics;
private Listener listener = new NopListener();
private TaskRunnerFactory runnerFactory;
private StatusUpdater statusUpdater;
private TaskMonitor monitor;
private Sleeper sleeper = new ThreadSleeper();
public Builder setJob(final Job job) {
this.job = job;
return this;
}
public Builder setExistingContainerId(final String existingContainerId) {
this.existingContainerId = existingContainerId;
return this;
}
public Builder setRestartPolicy(final RestartPolicy restartPolicy) {
this.restartPolicy = restartPolicy;
return this;
}
public Builder setDockerClient(final DockerClient dockerClient) {
this.dockerClient = dockerClient;
return this;
}
public Builder setMetrics(SupervisorMetrics metrics) {
this.metrics = metrics;
return this;
}
public Builder setListener(final Listener listener) {
this.listener = listener;
return this;
}
public Builder setRunnerFactory(final TaskRunnerFactory runnerFactory) {
this.runnerFactory = runnerFactory;
return this;
}
public Builder setStatusUpdater(final StatusUpdater statusUpdater) {
this.statusUpdater = statusUpdater;
return this;
}
public Builder setMonitor(final TaskMonitor monitor) {
this.monitor = monitor;
return this;
}
public Builder setSleeper(final Sleeper sleeper) {
this.sleeper = sleeper;
return this;
}
public Supervisor build() {
return new Supervisor(this);
}
private class NopListener implements Listener {
@Override
public void stateChanged(final Supervisor supervisor) {
}
}
}
private interface Command {
/**
* Perform the command. Although this is declared to throw InterruptedException, this will only
* happen when the supervisor is being shut down. During normal operations, the operation will
* be allowed to run until it's done.
* @param done Flag indicating if operation is done.
* @throws InterruptedException If thread is interrupted.
*/
void perform(final boolean done) throws InterruptedException;
}
/**
* Starts a container and attempts to keep it up indefinitely, restarting it when it exits.
*/
private class Start implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (runner == null) {
// There's no active runner, start it to bring up the container.
startAfter(0);
return;
}
if (runner.isRunning()) {
// There's an active runner, brought up by this or another Start command previously.
return;
}
// Check if the runner exited normally or threw an exception
final Result<Integer> result = runner.result();
if (!result.isSuccess()) {
// Runner threw an exception, inspect it.
final Throwable t = result.getException();
if (t instanceof InterruptedException || t instanceof InterruptedIOException) {
// We're probably shutting down, remove the runner and bail.
log.debug("task runner interrupted");
runner = null;
reactor.signal();
return;
} else if (t instanceof DockerException) {
log.error("docker error", t);
} else {
log.error("task runner threw exception", t);
}
}
// Restart the task
startAfter(restartPolicy.delay(monitor.throttle()));
}
private void startAfter(final long delay) {
log.debug("starting job (delay={}): {}", delay, job);
runner = runnerFactory.create(delay, containerId, new TaskListener());
runner.startAsync();
runner.resultFuture().addListener(reactor.signalRunnable(), directExecutor());
}
}
/**
* Stops a container, making sure that the runner spawned by {@link Start} is stopped and the
* container is not running.
*/
private class Stop implements Command {
@Override
public void perform(final boolean done) throws InterruptedException {
if (done) {
return;
}
final Integer gracePeriod = job.getGracePeriod();
if (gracePeriod != null && gracePeriod > 0) {
log.info("Unregistering from service discovery for {} seconds before stopping",
gracePeriod);
statusUpdater.setState(STOPPING);
statusUpdater.update();
if (runner.unregister()) {
log.info("Unregistered. Now sleeping for {} seconds.", gracePeriod);
sleeper.sleep(TimeUnit.MILLISECONDS.convert(gracePeriod, TimeUnit.SECONDS));
}
}
log.info("stopping job: {}", job);
// Stop the runner
if (runner != null) {
runner.stop();
runner = null;
}
final RetryScheduler retryScheduler = BoundedRandomExponentialBackoff.newBuilder()
.setMinIntervalMillis(SECONDS.toMillis(1))
.setMaxIntervalMillis(SECONDS.toMillis(30))
.build().newScheduler();
// Kill the container after stopping the runner
while (!containerNotRunning()) {
killContainer();
Thread.sleep(retryScheduler.nextMillis());
}
statusUpdater.setState(STOPPED);
statusUpdater.setContainerError(containerError());
statusUpdater.update();
}
private void killContainer() throws InterruptedException {
if (containerId == null) {
return;
}
try {
docker.killContainer(containerId);
} catch (DockerException e) {
log.error("failed to kill container {}", containerId, e);
}
}
private boolean containerNotRunning()
throws InterruptedException {
if (containerId == null) {
return true;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return true;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return false;
}
return !containerInfo.state().running();
}
private String containerError() throws InterruptedException {
if (containerId == null) {
return null;
}
final ContainerInfo containerInfo;
try {
containerInfo = docker.inspectContainer(containerId);
} catch (ContainerNotFoundException e) {
return null;
} catch (DockerException e) {
log.error("failed to query container {}", containerId, e);
return null;
}
return containerInfo.state().error();
}
}
private static class Nop implements Command {
@Override
public void perform(final boolean done) {
}
}
@Override
public String toString() {
return "Supervisor{" +
"job=" + job +
", currentCommand=" + currentCommand +
", performedCommand=" + performedCommand +
'}';
}
private class TaskListener extends TaskRunner.NopListener {
private MetricsContext pullContext;
@Override
public void failed(final Throwable t, final String containerError) {
metrics.containersThrewException();
}
@Override
public void pulling() {
pullContext = metrics.containerPull();
}
@Override
public void pullFailed() {
if (pullContext != null) {
pullContext.failure();
}
}
@Override
public void pulled() {
if (pullContext != null) {
pullContext.success();
}
}
@Override
public void created(final String createdContainerId) {
containerId = createdContainerId;
}
}
}
| gtonic/helios | helios-services/src/main/java/com/spotify/helios/agent/Supervisor.java | Java | apache-2.0 | 14,062 |
package de.saxsys.mvvmfx.examples.contacts.model;
public class Subdivision {
private final String name;
private final String abbr;
private final Country country;
public Subdivision(String name, String abbr, Country country) {
this.name = name;
this.abbr = abbr;
this.country = country;
}
public String getName() {
return name;
}
public String getAbbr() {
return abbr;
}
public Country getCountry() {
return country;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Subdivision that = (Subdivision) o;
if (!abbr.equals(that.abbr)) {
return false;
}
if (!country.equals(that.country)) {
return false;
}
if (!name.equals(that.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + abbr.hashCode();
result = 31 * result + country.hashCode();
return result;
}
}
| sialcasa/mvvmFX | examples/contacts-example/src/main/java/de/saxsys/mvvmfx/examples/contacts/model/Subdivision.java | Java | apache-2.0 | 1,010 |
package fr.jmini.asciidoctorj.testcases;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.ast.Block;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.Title;
public class ShowTitleTrueTestCase implements AdocTestCase {
public static final String ASCIIDOC = "" +
"= My page\n" +
"\n" +
"Some text\n" +
"";
@Override
public String getAdocInput() {
return ASCIIDOC;
}
@Override
public Map<String, Object> getInputOptions() {
AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
.showTitle(true);
return OptionsBuilder.options()
.attributes(attributesBuilder)
.asMap();
}
// tag::expected-html[]
public static final String EXPECTED_HTML = "" +
"<h1>My page</h1>\n" +
"<div class=\"paragraph\">\n" +
"<p>Some text</p>\n" +
"</div>";
// end::expected-html[]
@Override
public String getHtmlOutput() {
return EXPECTED_HTML;
}
@Override
// tag::assert-code[]
public void checkAst(Document astDocument) {
Document document1 = astDocument;
assertThat(document1.getId()).isNull();
assertThat(document1.getNodeName()).isEqualTo("document");
assertThat(document1.getParent()).isNull();
assertThat(document1.getContext()).isEqualTo("document");
assertThat(document1.getDocument()).isSameAs(document1);
assertThat(document1.isInline()).isFalse();
assertThat(document1.isBlock()).isTrue();
assertThat(document1.getAttributes()).containsEntry("doctitle", "My page")
.containsEntry("doctype", "article")
.containsEntry("example-caption", "Example")
.containsEntry("figure-caption", "Figure")
.containsEntry("filetype", "html")
.containsEntry("notitle", "")
.containsEntry("prewrap", "")
.containsEntry("showtitle", true)
.containsEntry("table-caption", "Table");
assertThat(document1.getRoles()).isNullOrEmpty();
assertThat(document1.isReftext()).isFalse();
assertThat(document1.getReftext()).isNull();
assertThat(document1.getCaption()).isNull();
assertThat(document1.getTitle()).isNull();
assertThat(document1.getStyle()).isNull();
assertThat(document1.getLevel()).isEqualTo(0);
assertThat(document1.getContentModel()).isEqualTo("compound");
assertThat(document1.getSourceLocation()).isNull();
assertThat(document1.getSubstitutions()).isNullOrEmpty();
assertThat(document1.getBlocks()).hasSize(1);
Block block1 = (Block) document1.getBlocks()
.get(0);
assertThat(block1.getId()).isNull();
assertThat(block1.getNodeName()).isEqualTo("paragraph");
assertThat(block1.getParent()).isSameAs(document1);
assertThat(block1.getContext()).isEqualTo("paragraph");
assertThat(block1.getDocument()).isSameAs(document1);
assertThat(block1.isInline()).isFalse();
assertThat(block1.isBlock()).isTrue();
assertThat(block1.getAttributes()).isNullOrEmpty();
assertThat(block1.getRoles()).isNullOrEmpty();
assertThat(block1.isReftext()).isFalse();
assertThat(block1.getReftext()).isNull();
assertThat(block1.getCaption()).isNull();
assertThat(block1.getTitle()).isNull();
assertThat(block1.getStyle()).isNull();
assertThat(block1.getLevel()).isEqualTo(0);
assertThat(block1.getContentModel()).isEqualTo("simple");
assertThat(block1.getSourceLocation()).isNull();
assertThat(block1.getSubstitutions()).containsExactly("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements");
assertThat(block1.getBlocks()).isNullOrEmpty();
assertThat(block1.getLines()).containsExactly("Some text");
assertThat(block1.getSource()).isEqualTo("Some text");
Title title1 = document1.getStructuredDoctitle();
assertThat(title1.getMain()).isEqualTo("My page");
assertThat(title1.getSubtitle()).isNull();
assertThat(title1.getCombined()).isEqualTo("My page");
assertThat(title1.isSanitized()).isFalse();
assertThat(document1.getDoctitle()).isEqualTo("My page");
assertThat(document1.getOptions()).containsEntry("header_footer", false);
}
// end::assert-code[]
@Override
// tag::mock-code[]
public Document createMock() {
Document mockDocument1 = mock(Document.class);
when(mockDocument1.getId()).thenReturn(null);
when(mockDocument1.getNodeName()).thenReturn("document");
when(mockDocument1.getParent()).thenReturn(null);
when(mockDocument1.getContext()).thenReturn("document");
when(mockDocument1.getDocument()).thenReturn(mockDocument1);
when(mockDocument1.isInline()).thenReturn(false);
when(mockDocument1.isBlock()).thenReturn(true);
Map<String, Object> map1 = new HashMap<>();
map1.put("doctitle", "My page");
map1.put("doctype", "article");
map1.put("example-caption", "Example");
map1.put("figure-caption", "Figure");
map1.put("filetype", "html");
map1.put("notitle", "");
map1.put("prewrap", "");
map1.put("showtitle", true);
map1.put("table-caption", "Table");
when(mockDocument1.getAttributes()).thenReturn(map1);
when(mockDocument1.getRoles()).thenReturn(Collections.emptyList());
when(mockDocument1.isReftext()).thenReturn(false);
when(mockDocument1.getReftext()).thenReturn(null);
when(mockDocument1.getCaption()).thenReturn(null);
when(mockDocument1.getTitle()).thenReturn(null);
when(mockDocument1.getStyle()).thenReturn(null);
when(mockDocument1.getLevel()).thenReturn(0);
when(mockDocument1.getContentModel()).thenReturn("compound");
when(mockDocument1.getSourceLocation()).thenReturn(null);
when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList());
Block mockBlock1 = mock(Block.class);
when(mockBlock1.getId()).thenReturn(null);
when(mockBlock1.getNodeName()).thenReturn("paragraph");
when(mockBlock1.getParent()).thenReturn(mockDocument1);
when(mockBlock1.getContext()).thenReturn("paragraph");
when(mockBlock1.getDocument()).thenReturn(mockDocument1);
when(mockBlock1.isInline()).thenReturn(false);
when(mockBlock1.isBlock()).thenReturn(true);
when(mockBlock1.getAttributes()).thenReturn(Collections.emptyMap());
when(mockBlock1.getRoles()).thenReturn(Collections.emptyList());
when(mockBlock1.isReftext()).thenReturn(false);
when(mockBlock1.getReftext()).thenReturn(null);
when(mockBlock1.getCaption()).thenReturn(null);
when(mockBlock1.getTitle()).thenReturn(null);
when(mockBlock1.getStyle()).thenReturn(null);
when(mockBlock1.getLevel()).thenReturn(0);
when(mockBlock1.getContentModel()).thenReturn("simple");
when(mockBlock1.getSourceLocation()).thenReturn(null);
when(mockBlock1.getSubstitutions()).thenReturn(Arrays.asList("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements"));
when(mockBlock1.getBlocks()).thenReturn(Collections.emptyList());
when(mockBlock1.getLines()).thenReturn(Collections.singletonList("Some text"));
when(mockBlock1.getSource()).thenReturn("Some text");
when(mockDocument1.getBlocks()).thenReturn(Collections.singletonList(mockBlock1));
Title mockTitle1 = mock(Title.class);
when(mockTitle1.getMain()).thenReturn("My page");
when(mockTitle1.getSubtitle()).thenReturn(null);
when(mockTitle1.getCombined()).thenReturn("My page");
when(mockTitle1.isSanitized()).thenReturn(false);
when(mockDocument1.getStructuredDoctitle()).thenReturn(mockTitle1);
when(mockDocument1.getDoctitle()).thenReturn("My page");
Map<Object, Object> map2 = new HashMap<>();
map2.put("attributes", "{\"showtitle\"=>true}");
map2.put("header_footer", false);
when(mockDocument1.getOptions()).thenReturn(map2);
return mockDocument1;
}
// end::mock-code[]
} | jmini/asciidoctorj-experiments | test-cases/adoc-test-cases/src/main/java/fr/jmini/asciidoctorj/testcases/ShowTitleTrueTestCase.java | Java | apache-2.0 | 8,764 |
package fr.sii.ogham.sms.message;
import fr.sii.ogham.core.util.EqualsBuilder;
import fr.sii.ogham.core.util.HashCodeBuilder;
/**
* Represents a phone number. It wraps a simple string. The aim is to abstracts
* the concept and to be able to provide other fields latter if needed.
*
* @author Aurélien Baudet
*
*/
public class PhoneNumber {
/**
* The phone number as string
*/
private String number;
/**
* Initialize the phone number with the provided number.
*
* @param number
* the phone number
*/
public PhoneNumber(String number) {
super();
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return number;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(number).hashCode();
}
@Override
public boolean equals(Object obj) {
return new EqualsBuilder(this, obj).appendFields("number").isEqual();
}
}
| groupe-sii/ogham | ogham-core/src/main/java/fr/sii/ogham/sms/message/PhoneNumber.java | Java | apache-2.0 | 1,017 |
package org.fastnate.generator.converter;
import java.time.Duration;
import org.fastnate.generator.context.GeneratorContext;
import org.fastnate.generator.statements.ColumnExpression;
import org.fastnate.generator.statements.PrimitiveColumnExpression;
/**
* Converts a {@link Duration} to an SQL expression.
*
* @author Tobias Liefke
*/
public class DurationConverter implements ValueConverter<Duration> {
@Override
public ColumnExpression getExpression(final Duration value, final GeneratorContext context) {
return PrimitiveColumnExpression.create(value.toNanos(), context.getDialect());
}
@Override
public ColumnExpression getExpression(final String defaultValue, final GeneratorContext context) {
return getExpression(Duration.parse(defaultValue), context);
}
}
| liefke/org.fastnate | fastnate-generator/src/main/java/org/fastnate/generator/converter/DurationConverter.java | Java | apache-2.0 | 786 |
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802
// Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2014.10.23 alle 11:27:04 AM CEST
//
package org.cumulus.certificate.model;
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>Classe Java per HistoryStateType complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="HistoryStateType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="stateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="refersToStateId" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HistoryStateType")
public class HistoryStateType {
@XmlAttribute(name = "stateId", required = true)
protected String stateId;
@XmlAttribute(name = "refersToStateId", required = true)
protected String refersToStateId;
/**
* Recupera il valore della proprietà stateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStateId() {
return stateId;
}
/**
* Imposta il valore della proprietà stateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStateId(String value) {
this.stateId = value;
}
/**
* Recupera il valore della proprietà refersToStateId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRefersToStateId() {
return refersToStateId;
}
/**
* Imposta il valore della proprietà refersToStateId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefersToStateId(String value) {
this.refersToStateId = value;
}
}
| fgaudenzi/testManager | testManager/XMLRepository/CertificationModel/org/cumulus/certificate/model/HistoryStateType.java | Java | apache-2.0 | 2,497 |
/*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.serverhealth;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.CruiseConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class ServerHealthService implements ApplicationContextAware {
private static final Logger LOG = LoggerFactory.getLogger(ServerHealthService.class);
private HashMap<ServerHealthState, Set<String>> pipelinesWithErrors;
private Map<HealthStateType, ServerHealthState> serverHealth;
private ApplicationContext applicationContext;
public ServerHealthService() {
this.serverHealth = new ConcurrentHashMap<>();
this.pipelinesWithErrors = new HashMap<>();
}
public void removeByScope(HealthStateScope scope) {
for (HealthStateType healthStateType : entryKeys()) {
if (healthStateType.isSameScope(scope)) {
serverHealth.remove(healthStateType);
}
}
}
private Set<HealthStateType> entryKeys() {
return new HashSet<>(serverHealth.keySet());
}
public List<ServerHealthState> filterByScope(HealthStateScope scope) {
List<ServerHealthState> filtered = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
HealthStateType type = entry.getKey();
if (type.isSameScope(scope)) {
filtered.add(entry.getValue());
}
}
return filtered;
}
public HealthStateType update(ServerHealthState serverHealthState) {
HealthStateType type = serverHealthState.getType();
if (serverHealthState.getLogLevel() == HealthStateLevel.OK) {
if (serverHealth.containsKey(type)) {
serverHealth.remove(type);
}
return null;
} else {
serverHealth.put(type, serverHealthState);
return type;
}
}
// called from spring timer
public synchronized void onTimer() {
CruiseConfig currentConfig = applicationContext.getBean(CruiseConfigProvider.class).getCurrentConfig();
purgeStaleHealthMessages(currentConfig);
LOG.debug("Recomputing material to pipeline mappings.");
HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) {
erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig));
}
pipelinesWithErrors = erroredPipelines;
LOG.debug("Done recomputing material to pipeline mappings.");
}
public Set<String> getPipelinesWithErrors(ServerHealthState serverHealthState) {
return pipelinesWithErrors.get(serverHealthState);
}
void purgeStaleHealthMessages(CruiseConfig cruiseConfig) {
removeMessagesForElementsNoLongerInConfig(cruiseConfig);
removeExpiredMessages();
}
@Deprecated(forRemoval = true) // Remove once we get rid of SpringJUnitTestRunner
public void removeAllLogs() {
serverHealth.clear();
}
private void removeMessagesForElementsNoLongerInConfig(CruiseConfig cruiseConfig) {
for (HealthStateType type : entryKeys()) {
if (type.isRemovedFromConfig(cruiseConfig)) {
this.removeByScope(type);
}
}
}
private void removeExpiredMessages() {
for (Map.Entry<HealthStateType, ServerHealthState> entry : new HashSet<>(serverHealth.entrySet())) {
ServerHealthState value = entry.getValue();
if (value.hasExpired()) {
serverHealth.remove(entry.getKey());
}
}
}
private void removeByScope(HealthStateType type) {
removeByScope(type.getScope());
}
public ServerHealthStates logs() {
ArrayList<ServerHealthState> logs = new ArrayList<>();
for (Map.Entry<HealthStateType, ServerHealthState> entry : sortedEntries()) {
logs.add(entry.getValue());
}
return new ServerHealthStates(logs);
}
private List<Map.Entry<HealthStateType, ServerHealthState>> sortedEntries() {
List<Map.Entry<HealthStateType, ServerHealthState>> entries = new ArrayList<>(serverHealth.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getKey));
return entries;
}
public String getLogsAsText() {
StringBuilder text = new StringBuilder();
for (ServerHealthState state : logs()) {
text.append(state.getDescription());
text.append("\n\t");
text.append(state.getMessage());
text.append("\n");
}
return text.toString();
}
public boolean containsError(HealthStateType type, HealthStateLevel level) {
ServerHealthStates allLogs = logs();
for (ServerHealthState log : allLogs) {
if (log.getType().equals(type) && log.getLogLevel() == level) {
return true;
}
}
return false;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| GaneshSPatil/gocd | common/src/main/java/com/thoughtworks/go/serverhealth/ServerHealthService.java | Java | apache-2.0 | 6,153 |
package gov.ic.geoint.spreadsheet;
/**
*
*/
public interface ICell extends Hashable {
/**
*
* @return
*/
public int getColumnNum();
/**
*
* @return
*/
public int getRowNum();
/**
*
* @return
*/
public String getValue();
}
| GEOINT/spreadsheetDiff | src/main/java/gov/ic/geoint/spreadsheet/ICell.java | Java | apache-2.0 | 298 |
package sdk.chat.demo.examples.api;
import io.reactivex.functions.Consumer;
import sdk.guru.common.DisposableMap;
public class BaseExample implements Consumer<Throwable> {
// Add the disposables to a map so you can dispose of them all at one time
protected DisposableMap dm = new DisposableMap();
@Override
public void accept(Throwable throwable) throws Exception {
// Handle exception
}
}
| chat-sdk/chat-sdk-android | chat-sdk-demo/src/main/java/sdk/chat/demo/examples/api/BaseExample.java | Java | apache-2.0 | 423 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.core.api.query;
// NOT_PUBLISHED
public interface ISuggestionQuery extends ISourceQuery {
String getKeyword();
}
| eENVplus/tf-exploitation-server | TF_Exploitation_Server_core/src/main/java/net/disy/eenvplus/tfes/core/api/query/ISuggestionQuery.java | Java | apache-2.0 | 201 |
package com.jwetherell.algorithms.data_structures.interfaces;
/**
* A tree can be defined recursively (locally) as a collection of nodes (starting at a root node),
* where each node is a data structure consisting of a value, together with a list of nodes (the "children"),
* with the constraints that no node is duplicated. A tree can be defined abstractly as a whole (globally)
* as an ordered tree, with a value assigned to each node.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public interface ITree<T> {
/**
* Add value to the tree. Tree can contain multiple equal values.
*
* @param value to add to the tree.
* @return True if successfully added to tree.
*/
public boolean add(T value);
/**
* Remove first occurrence of value in the tree.
*
* @param value to remove from the tree.
* @return T value removed from tree.
*/
public T remove(T value);
/**
* Clear the entire stack.
*/
public void clear();
/**
* Does the tree contain the value.
*
* @param value to locate in the tree.
* @return True if tree contains value.
*/
public boolean contains(T value);
/**
* Get number of nodes in the tree.
*
* @return Number of nodes in the tree.
*/
public int size();
/**
* Validate the tree according to the invariants.
*
* @return True if the tree is valid.
*/
public boolean validate();
/**
* Get Tree as a Java compatible Collection
*
* @return Java compatible Collection
*/
public java.util.Collection<T> toCollection();
}
| phishman3579/java-algorithms-implementation | src/com/jwetherell/algorithms/data_structures/interfaces/ITree.java | Java | apache-2.0 | 1,766 |
/*
* Copyright 2014, The Sporting Exchange Limited
* Copyright 2014, Simon Matić Langford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.exemel.disco.transport.jetty;
import uk.co.exemel.disco.DiscoVersion;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.junit.Test;
import java.util.Collections;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link uk.co.exemel.disco.transport.jetty.CrossOriginHandler}
*/
public class CrossOriginHandlerTest {
@Test
public void testHandlerSetsServerHeaderInTheResponse() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(res, times(1)).setHeader(eq("Server"), eq("Disco 2 - " + DiscoVersion.getVersion()));
}
@Test
public void testHandlerMarksRequestAsHandledByDefault() throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler("betfair.com", "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
victim.handle("/", req, req, res);
verify(req, times(1)).setHandled(eq(true));
verify(req, times(1)).setHandled(eq(false));
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainExplicitDomain() throws Exception {
testHandlesCrossOriginRequest("betfair.com", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainAllDomains() throws Exception {
testHandlesCrossOriginRequest("*", true);
}
@Test
public void testHandlerUnmarksRequestAsHandledIfFilterContinuesTheChainNoDomains() throws Exception {
testHandlesCrossOriginRequest("", false);
}
private void testHandlesCrossOriginRequest(String domains, boolean wantHandled) throws Exception {
final CrossOriginHandler victim = new CrossOriginHandler(domains, "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
final MockJettyRequest req = mock(MockJettyRequest.class);
final MockJettyResponse res = mock(MockJettyResponse.class);
when(req.getMethod()).thenReturn("OPTIONS");
when(req.getHeader("Origin")).thenReturn("betfair.com");
when(req.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER)).thenReturn("PUT");
when(req.getHeaders("Connection")).thenReturn(Collections.<String>emptyEnumeration());
victim.handle("/", req, req, res);
// this is always called
verify(req, times(1)).setHandled(eq(true));
if (wantHandled) {
verify(req, never()).setHandled(eq(false));
}
else {
verify(req, times(1)).setHandled(eq(false));
}
}
}
| eswdd/disco | disco-framework/jetty-transport/src/test/java/uk/co/exemel/disco/transport/jetty/CrossOriginHandlerTest.java | Java | apache-2.0 | 3,706 |
package org.nd4j.linalg.indexing;
import com.google.common.base.Function;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.MatchCondition;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndReplace;
import org.nd4j.linalg.api.ops.impl.transforms.comparison.CompareAndSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.conditions.AbsValueGreaterThan;
import org.nd4j.linalg.indexing.conditions.Condition;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.indexing.functions.Value;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* @author raver119@gmail.com
*/
@RunWith(Parameterized.class)
public class BooleanIndexingTest extends BaseNd4jTest {
public BooleanIndexingTest(Nd4jBackend backend) {
super(backend);
}
/*
1D array checks
*/
@Test
public void testAnd1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThan(0.5f)));
}
@Test
public void testAnd2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.and(array, Conditions.lessThan(6.0f)));
}
@Test
public void testAnd3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(5.0f)));
}
@Test
public void testAnd4() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(4.0f)));
}
@Test
public void testAnd5() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.greaterThanOrEqual(1e-5f)));
}
@Test
public void testAnd6() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertFalse(BooleanIndexing.and(array, Conditions.lessThan(1e-5f)));
}
@Test
public void testAnd7() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f, 1e-5f, 1e-5f});
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-5f)));
}
@Test
public void testOr1() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(3.0f)));
}
@Test
public void testOr2() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertTrue(BooleanIndexing.or(array, Conditions.lessThan(3.0f)));
}
@Test
public void testOr3() throws Exception {
INDArray array = Nd4j.create(new float[] {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
assertFalse(BooleanIndexing.or(array, Conditions.greaterThan(6.0f)));
}
@Test
public void testApplyWhere1() throws Exception {
INDArray array = Nd4j.create(new float[] {-1f, -1f, -1f, -1f, -1f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(Nd4j.EPS_THRESHOLD), new Value(Nd4j.EPS_THRESHOLD));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(Nd4j.EPS_THRESHOLD)));
}
@Test
public void testApplyWhere2() throws Exception {
INDArray array = Nd4j.create(new float[] {0f, 0f, 0f, 0f, 0f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1.0f), new Value(1.0f));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1.0f)));
}
@Test
public void testApplyWhere3() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, 1e-18f, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
@Test
public void testApplyWhere4() throws Exception {
INDArray array = Nd4j.create(new float[] {1e-18f, Float.NaN, 1e-18f, 1e-18f, 1e-18f});
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-12f), new Value(1e-12f));
//System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.isNan(), new Value(1e-16f));
System.out.println("Array contains: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.or(array, Conditions.isNan()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-16f)));
}
/*
2D array checks
*/
@Test
public void test2dAnd1() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
assertTrue(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd2() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
System.out.println(array);
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void test2dAnd3() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertFalse(BooleanIndexing.and(array, Conditions.greaterThan(0f)));
}
@Test
public void test2dAnd4() throws Exception {
INDArray array = Nd4j.zeros(10, 10);
array.slice(4).putScalar(2, 1e-5f);
assertTrue(BooleanIndexing.or(array, Conditions.greaterThan(1e-6f)));
}
@Test
public void test2dApplyWhere1() throws Exception {
INDArray array = Nd4j.ones(4, 4);
array.slice(3).putScalar(2, 1e-5f);
//System.out.println("Array before: " + Arrays.toString(array.data().asFloat()));
BooleanIndexing.applyWhere(array, Conditions.lessThan(1e-4f), new Value(1e-12f));
//System.out.println("Array after 1: " + Arrays.toString(array.data().asFloat()));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1e-12f)));
assertTrue(BooleanIndexing.or(array, Conditions.equals(1.0f)));
assertFalse(BooleanIndexing.and(array, Conditions.equals(1e-12f)));
}
/**
* This test fails, because it highlights current mechanics on SpecifiedIndex stuff.
* Internally there's
*
* @throws Exception
*/
@Test
public void testSliceAssign1() throws Exception {
INDArray array = Nd4j.zeros(4, 4);
INDArray patch = Nd4j.create(new float[] {1e-5f, 1e-5f, 1e-5f});
INDArray slice = array.slice(1);
int[] idx = new int[] {0, 1, 3};
INDArrayIndex[] range = new INDArrayIndex[] {new SpecifiedIndex(idx)};
INDArray subarray = slice.get(range);
System.out.println("Subarray: " + Arrays.toString(subarray.data().asFloat()) + " isView: " + subarray.isView());
slice.put(range, patch);
System.out.println("Array after being patched: " + Arrays.toString(array.data().asFloat()));
assertFalse(BooleanIndexing.and(array, Conditions.equals(0f)));
}
@Test
public void testConditionalAssign1() throws Exception {
INDArray array1 = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7});
INDArray array2 = Nd4j.create(new double[] {7, 6, 5, 4, 3, 2, 1});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 3, 2, 1});
BooleanIndexing.replaceWhere(array1, array2, Conditions.greaterThan(4));
assertEquals(comp, array1);
}
@Test
public void testCaSTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3, Conditions.equals(0)));
assertEquals(comp, array);
}
@Test
public void testCaSTransform2() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {3, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, 3.0, Conditions.lessThan(2)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(array, comp, Conditions.lessThan(5)));
assertEquals(comp, array);
}
@Test
public void testCaRPairwiseTransform1() throws Exception {
INDArray array = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(array, comp, Conditions.lessThan(1)));
assertEquals(comp, array);
}
@Test
public void testCaSPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 0, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndSet(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform2() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 0, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.epsNotEquals(0.0)));
assertEquals(comp, x);
}
@Test
public void testCaSPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 4, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(4)));
assertEquals(comp, x);
}
@Test
public void testCaRPairwiseTransform3() throws Exception {
INDArray x = Nd4j.create(new double[] {1, 2, 0, 4, 5});
INDArray y = Nd4j.create(new double[] {2, 4, 3, 4, 5});
INDArray comp = Nd4j.create(new double[] {2, 2, 3, 4, 5});
Nd4j.getExecutioner().exec(new CompareAndReplace(x, y, Conditions.lessThan(2)));
assertEquals(comp, x);
}
@Test
public void testMatchConditionAllDimensions1() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.lessThan(5)), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(5, val);
}
@Test
public void testMatchConditionAllDimensions2() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NaN, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner().exec(new MatchCondition(array, Conditions.isNan()), Integer.MAX_VALUE)
.getDouble(0);
assertEquals(1, val);
}
@Test
public void testMatchConditionAllDimensions3() throws Exception {
INDArray array = Nd4j.create(new double[] {0, 1, 2, 3, Double.NEGATIVE_INFINITY, 5, 6, 7, 8, 9});
int val = (int) Nd4j.getExecutioner()
.exec(new MatchCondition(array, Conditions.isInfinite()), Integer.MAX_VALUE).getDouble(0);
assertEquals(1, val);
}
@Test
public void testAbsValueGreaterThan() {
final double threshold = 2;
Condition absValueCondition = new AbsValueGreaterThan(threshold);
Function<Number, Number> clipFn = new Function<Number, Number>() {
@Override
public Number apply(Number number) {
System.out.println("Number: " + number.doubleValue());
return (number.doubleValue() > threshold ? threshold : -threshold);
}
};
Nd4j.getRandom().setSeed(12345);
INDArray orig = Nd4j.rand(1, 20).muli(6).subi(3); //Random numbers: -3 to 3
INDArray exp = orig.dup();
INDArray after = orig.dup();
for (int i = 0; i < exp.length(); i++) {
double d = exp.getDouble(i);
if (d > threshold) {
exp.putScalar(i, threshold);
} else if (d < -threshold) {
exp.putScalar(i, -threshold);
}
}
BooleanIndexing.applyWhere(after, absValueCondition, clipFn);
System.out.println(orig);
System.out.println(exp);
System.out.println(after);
assertEquals(exp, after);
}
@Test
public void testMatchConditionAlongDimension1() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0);
boolean result[] = BooleanIndexing.and(array, Conditions.equals(0.0), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension2() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
System.out.println("Array: " + array);
boolean result[] = BooleanIndexing.or(array, Conditions.lessThan(0.9), 1);
boolean comp[] = new boolean[] {false, false, true};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testMatchConditionAlongDimension3() throws Exception {
INDArray array = Nd4j.ones(3, 10);
array.getRow(2).assign(0.0).putScalar(0, 1.0);
boolean result[] = BooleanIndexing.and(array, Conditions.lessThan(0.0), 1);
boolean comp[] = new boolean[] {false, false, false};
System.out.println("Result: " + Arrays.toString(result));
assertArrayEquals(comp, result);
}
@Test
public void testConditionalUpdate() {
INDArray arr = Nd4j.linspace(-2, 2, 5);
INDArray ones = Nd4j.ones(5);
INDArray exp = Nd4j.create(new double[] {1, 1, 0, 1, 1});
Nd4j.getExecutioner().exec(new CompareAndSet(ones, arr, ones, Conditions.equals(0.0)));
assertEquals(exp, ones);
}
@Test
public void testFirstIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(2, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.lessThan(3));
assertEquals(0, result.getDouble(0), 0.0);
}
@Test
public void testLastIndex1() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(3));
assertEquals(8, result.getDouble(0), 0.0);
}
@Test
public void testFirstIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 9}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.firstIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {1, 2, 0});
assertEquals(exp, result);
}
@Test
public void testLastIndex2D() {
INDArray arr = Nd4j.create(new double[] {1, 2, 3, 0, 1, 3, 7, 8, 0}).reshape('c', 3, 3);
INDArray result = BooleanIndexing.lastIndex(arr, Conditions.greaterThanOrEqual(2), 1);
INDArray exp = Nd4j.create(new double[] {2, 2, 1});
assertEquals(exp, result);
}
@Test
public void testEpsEquals1() throws Exception {
INDArray array = Nd4j.create(new double[]{-1, -1, -1e-8, 1e-8, 1, 1});
MatchCondition condition = new MatchCondition(array, Conditions.epsEquals(0.0));
int numZeroes = Nd4j.getExecutioner().exec(condition, Integer.MAX_VALUE).getInt(0);
assertEquals(2, numZeroes);
}
@Override
public char ordering() {
return 'c';
}
}
| huitseeker/nd4j | nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/indexing/BooleanIndexingTest.java | Java | apache-2.0 | 17,052 |
package com.xiaojinzi.component.error;
public class ServiceRepeatCreateException extends RuntimeException {
public ServiceRepeatCreateException() {
}
public ServiceRepeatCreateException(String message) {
super(message);
}
public ServiceRepeatCreateException(String message, Throwable cause) {
super(message, cause);
}
public ServiceRepeatCreateException(Throwable cause) {
super(cause);
}
}
| xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/error/ServiceRepeatCreateException.java | Java | apache-2.0 | 453 |
package de.uniulm.omi.cloudiator.sword.multicloud.service;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import de.uniulm.omi.cloudiator.sword.domain.Cloud;
import de.uniulm.omi.cloudiator.sword.domain.Pricing;
import de.uniulm.omi.cloudiator.sword.multicloud.pricing.PricingSupplierFactory;
import de.uniulm.omi.cloudiator.sword.service.PricingService;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
public class MultiCloudPricingService implements PricingService {
private final CloudRegistry cloudRegistry;
@Inject
private PricingSupplierFactory pricingSupplierFactory;
@Inject
public MultiCloudPricingService(CloudRegistry cloudRegistry) {
this.cloudRegistry = checkNotNull(cloudRegistry, "cloudRegistry is null");
}
@Override
public Iterable<Pricing> listPricing() {
/*final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
Optional<Cloud> awsCloud = cloudRegistry.list().stream().filter(cloud -> cloud.api().providerName().equals("aws-ec2")).findFirst();
if(awsCloud.isPresent()) {
Supplier<Set<Pricing>> awsPricingSupplier = pricingSupplierFactory.createAWSPricingSupplier(awsCloud.get().credential());
builder.addAll(awsPricingSupplier.get());
}
return builder.build();*/
final ImmutableSet.Builder<Pricing> builder = ImmutableSet.builder();
cloudRegistry
.list()
.stream()
.filter(cloud -> cloud.api().providerName().equals("aws-ec2"))
.findFirst()
.ifPresent(cloud -> builder.addAll(pricingSupplierFactory.createAWSPricingSupplier(cloud.credential()).get()));
return builder.build();
}
}
| cloudiator/sword | multicloud/src/main/java/de/uniulm/omi/cloudiator/sword/multicloud/service/MultiCloudPricingService.java | Java | apache-2.0 | 1,844 |
/*
* Copyright 2011-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.transform;
import java.lang.reflect.Constructor;
import com.amazonaws.AmazonServiceException;
public abstract class AbstractErrorUnmarshaller<T> implements Unmarshaller<AmazonServiceException, T> {
/**
* The type of AmazonServiceException that will be instantiated. Subclasses
* specialized for a specific type of exception can control this through the
* protected constructor.
*/
protected final Class<? extends AmazonServiceException> exceptionClass;
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into AmazonServiceException objects.
*/
public AbstractErrorUnmarshaller() {
this(AmazonServiceException.class);
}
/**
* Constructs a new error unmarshaller that will unmarshall error responses
* into objects of the specified class, extending AmazonServiceException.
*
* @param exceptionClass
* The subclass of AmazonServiceException which will be
* instantiated and populated by this class.
*/
public AbstractErrorUnmarshaller(Class<? extends AmazonServiceException> exceptionClass) {
this.exceptionClass = exceptionClass;
}
/**
* Constructs a new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @param message
* The error message to set in the new exception object.
*
* @return A new exception object of the type specified in this class's
* constructor and sets the specified error message.
*
* @throws Exception
* If there are any problems using reflection to invoke the
* exception class's constructor.
*/
protected AmazonServiceException newException(String message) throws Exception {
Constructor<? extends AmazonServiceException> constructor = exceptionClass.getConstructor(String.class);
return constructor.newInstance(message);
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/transform/AbstractErrorUnmarshaller.java | Java | apache-2.0 | 2,633 |
package com.icfcc.cache.support;
import com.icfcc.cache.Cache;
import java.util.Collection;
/**
* Simple cache manager working against a given collection of caches.
* Useful for testing or simple caching declarations.
*
* @author Costin Leau
* @since 3.1
*/
public class SimpleCacheManager extends AbstractCacheManager {
private Collection<? extends Cache> caches;
/**
* Specify the collection of Cache instances to use for this CacheManager.
*/
public void setCaches(Collection<? extends Cache> caches) {
this.caches = caches;
}
@Override
protected Collection<? extends Cache> loadCaches() {
return this.caches;
}
} | Gitpiece/spring-cache-project | spring-cache/src/main/java/com/icfcc/cache/support/SimpleCacheManager.java | Java | apache-2.0 | 684 |
package fr.fablabmars.model;
import java.util.ArrayList;
import fr.fablabmars.observer.Observable;
import fr.fablabmars.observer.Observer;
/**
* Observable contenant le menu courant.
*
* @author Guillaume Perouffe
* @see Observable
*/
public class CardMenu implements Observable {
/**
* Liste des observateurs de cet observable.
*/
private ArrayList<Observer> listObserver = new ArrayList<Observer>();
/**
* Indice du menu courant
*/
private int panel;
/**
* Constructeur de l'observable
* <p>
* On initialise le menu sur le 'panel' par défaut,
* d'indice 0.
* </p>
*
* @see CardMenu#panel
*/
public CardMenu(){
panel = 0;
}
/**
* Change le panneau courant et notifie les observateurs.
*
* @param panel
* Indice du nouveau menu.
*
* @see CardMenu#panel
* @see Observable#notifyObservers()
*/
public void setPanel(int panel){
this.panel = panel;
notifyObservers();
}
@Override
public void addObserver(Observer obs) {
listObserver.add(obs);
}
@Override
public void removeObserver(Observer obs) {
listObserver.remove(obs);
}
@Override
public void notifyObservers() {
for(Observer obs:listObserver){
obs.update(this);
}
}
/**
* Retourne le menu courant
*
* @return Menu courant
*
* @see CardMenu#panel
*/
@Override
public int getState(){
return panel;
}
}
| gperouffe/FabLabUsers | src/fr/fablabmars/model/CardMenu.java | Java | apache-2.0 | 1,473 |
package ru.job4j.collections.tree;
/**
* Бинарное дерево .
*
* @author Hincu Andrei (andreih1981@gmail.com) by 20.10.17;
* @version $Id$
* @since 0.1
* @param <E> тип данных.
*/
public class BinaryTree<E extends Comparable<E>> extends Tree<E> {
/**
* Корень дерева.
*/
private Node<E> node;
/**
* Размер дерева.
*/
private int size;
/**
* Узел дерева.
* @param <E> значение.
*/
private class Node<E> {
/**
* Значение.
*/
private E value;
/**
* левый сын.
*/
private Node<E> left;
/**
* правый сын.
*/
private Node<E> right;
/**
* Конструктор.
* @param value значение узла.
*/
private Node(E value) {
this.value = value;
}
}
/**
* Добавляем новый элемент или корень дерева.
* @param e значение.
*/
public void add(E e) {
if (node == null) {
node = new Node<>(e);
size++;
} else {
addNewElement(e, node);
}
}
/**
* Метод для поиска места вставки.
* @param e значение.
* @param n текуший узел дерева.
*/
private void addNewElement(E e, Node<E> n) {
if (e.compareTo(n.value) < 0) {
if (n.left == null) {
n.left = new Node<>(e);
size++;
} else {
addNewElement(e, n.left);
}
} else if (e.compareTo(n.value) > 0) {
if (n.right == null) {
n.right = new Node<>(e);
size++;
} else {
addNewElement(e, n.right);
}
}
}
/**
* геттер.
* @return размер дерева.
*/
public int getSize() {
return size;
}
}
| andreiHi/hincuA | chapter_005/src/main/java/ru/job4j/collections/tree/BinaryTree.java | Java | apache-2.0 | 2,101 |
/**
* 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.pinot.core.startree.v2.store;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.pinot.common.segment.ReadMode;
import org.apache.pinot.core.segment.index.column.ColumnIndexContainer;
import org.apache.pinot.core.segment.index.metadata.SegmentMetadataImpl;
import org.apache.pinot.core.segment.memory.PinotDataBuffer;
import org.apache.pinot.core.startree.v2.StarTreeV2;
import org.apache.pinot.core.startree.v2.StarTreeV2Constants;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexKey;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexValue;
/**
* The {@code StarTreeIndexContainer} class contains the indexes for multiple star-trees.
*/
public class StarTreeIndexContainer implements Closeable {
private final PinotDataBuffer _dataBuffer;
private final List<StarTreeV2> _starTrees;
public StarTreeIndexContainer(File segmentDirectory, SegmentMetadataImpl segmentMetadata,
Map<String, ColumnIndexContainer> indexContainerMap, ReadMode readMode)
throws ConfigurationException, IOException {
File indexFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_FILE_NAME);
if (readMode == ReadMode.heap) {
_dataBuffer = PinotDataBuffer
.loadFile(indexFile, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
} else {
_dataBuffer = PinotDataBuffer
.mapFile(indexFile, true, 0, indexFile.length(), ByteOrder.LITTLE_ENDIAN, "Star-tree V2 data buffer");
}
File indexMapFile = new File(segmentDirectory, StarTreeV2Constants.INDEX_MAP_FILE_NAME);
List<Map<IndexKey, IndexValue>> indexMapList =
StarTreeIndexMapUtils.loadFromFile(indexMapFile, segmentMetadata.getStarTreeV2MetadataList().size());
_starTrees = StarTreeLoaderUtils.loadStarTreeV2(_dataBuffer, indexMapList, segmentMetadata, indexContainerMap);
}
public List<StarTreeV2> getStarTrees() {
return _starTrees;
}
@Override
public void close()
throws IOException {
_dataBuffer.close();
}
}
| linkedin/pinot | pinot-core/src/main/java/org/apache/pinot/core/startree/v2/store/StarTreeIndexContainer.java | Java | apache-2.0 | 3,059 |
/*
Copyright 2010-2011 Zhengmao HU (James)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.sf.jabb.util.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Given a text string to be tested, and list of matching strings, find out which matching string the
* text string starts with.<br>
* 给定一个待检查的文本字符串,以及一批开头匹配字符串,看看待检查的文本字符串以哪个匹配字符串开头。
* <p>
* The matching is case sensitive.
* If one matching string starts with another,
* and the text string starts with them, then the longer one will be considered to be matched.
* <p>
* 匹配时对大小写敏感。如果匹配字符串之间互相饱含,则匹配其中最长的。
*
* <p>
* If the matching need to be checked upon number segments (start number ~ end number) represented
* as strings, {@link #expandNumberMatchingRange(Map, String, String, Object)} method can be used to
* expand number segments to heading number strings.
* <p>
* 如果需要对代表数字号码(开始号码~结束号码)的字符串进行匹配,可使用
* {@link #expandNumberMatchingRange(Map, String, String, Object)} 方法
* 将号码段字符串(一个开始号码,一个结束号码)转换为号码头字符串。
*
* @author Zhengmao HU (James)
*
*/
public class StringStartWithMatcher extends StartWithMatcher {
private static final long serialVersionUID = -2501231925022032723L;
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
* <p>
* When initializing internal data structure, choose to consume more memory for better matching speed.
* <p>
* 在创建内部数据结构的时候,选择占用更多内存,而换取速度上的提升。
*
* @param headingDefinitions Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.<p>
* Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions) {
super(normalizeMatchingDefinitions(headingDefinitions));
}
/**
* Create a new instance according to heading strings and their corresponding attachment objects.<br>
* 根据开头匹配字符串、开头匹配字符串所对应的附件对象,创建一个新的实例。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @param moreSpaceForSpeed 是否占用更多内存,而换取速度上的提升。
* <p>Whether or not to consume
* more memory for better matching speed.
*/
public StringStartWithMatcher(Map<String, ? extends Object> headingDefinitions, boolean moreSpaceForSpeed) {
super(normalizeMatchingDefinitions(headingDefinitions), moreSpaceForSpeed);
}
/**
* Create a copy, the copy will have exactly the same matching
* definitions as the original copy.<br>
* 创建一个副本,这个副本与原先的对象具有完全相同匹配方式。
*
* @param toBeCopied 原本。<br>The original copy.
*/
public StringStartWithMatcher(StringStartWithMatcher toBeCopied) {
super(toBeCopied);
}
/**
* Normalize matching definitions according to requirements of {@link StartWithMatcher}.<br>
* 根据{@link StartWithMatcher}的需要来规范化匹配条件定义。
*
* @param headingDefinitions Key是匹配字符串,Value是附件对象。
* 当进行匹配检查的时候,返回附件对象来标识哪一个匹配字符串被匹配上了。
* <p>
* Key is the heading string, Value is its associated attachment object.
* When the heading string is matched, the attachment object will be returned
* as identifier.
* @return {@link StartWithMatcher}所需的匹配条件定义。
* <br>Matching definitions for usage of {@link StartWithMatcher}.
*/
static protected List<MatchingDefinition> normalizeMatchingDefinitions(Map<String, ? extends Object> headingDefinitions){
// exactMatchExample自动设置为与regularExpression相同
List<MatchingDefinition> l = new ArrayList<MatchingDefinition>(headingDefinitions.size());
for (Map.Entry<String, ? extends Object> e: headingDefinitions.entrySet()){
MatchingDefinition c = new MatchingDefinition();
c.setRegularExpression(escapeForRegExp(e.getKey()));
c.setAttachment(e.getValue());
c.setExactMatchExample(e.getKey());
l.add(c);
}
return l;
}
/**
* Expand number segments (such as 138000~138999 or 138000~138029) into number headings
* (such as 138 or {13800,13801,13802}).<br>
* 把号码段(类似:138000~138999或138000~138029)展开成号码头(类似:138或13800,13801,13802)。
*
* @param headingDefinitions 可用来对{@link StringStartWithMatcher}进行初始化的展开后的匹配条件
* 会被放到这个Map里。
* <br> Equivalent heading definitions that could be used to
* create instance of {@link StringStartWithMatcher} will be put into this Map.
* @param start 起始号码 <br> first/starting number
* @param end 结束号码 <br> last/ending number
* @param attachment 匹配附件<br>attachment to identify that the segment matches a string
*/
public static <T> void expandNumberMatchingRange(Map<String, T> headingDefinitions, String start, String end, T attachment){
int firstDiff; //第一个不相同字符的位置
int lastDiff; //末尾0:9对应段开始的位置
// 先强行保证起始号码与结束号码长度相同
if (start.length() > end.length()){
StringBuilder sb = new StringBuilder(end);
while (start.length() > sb.length()){
sb.append("9");
}
end = sb.toString();
} else if (end.length() > start.length()){
StringBuilder sb = new StringBuilder(start);
while (end.length() > sb.length()){
sb.append("0");
}
start = sb.toString();
}
// 然后寻找第一个不相同字符的位置
for (firstDiff = 0; firstDiff < start.length(); firstDiff++){
if (start.charAt(firstDiff) != end.charAt(firstDiff)){
break;
}
}
// 再寻找末尾0:9对应段开始的位置
for (lastDiff = start.length() - 1; lastDiff >= 0; lastDiff--){
if (start.charAt(lastDiff) != '0' || end.charAt(lastDiff) != '9'){
break;
}
}
lastDiff++;
if (firstDiff == lastDiff){ // 则表示可合并为一条
headingDefinitions.put(start.substring(0, firstDiff), attachment);
} else { // 则表示要扩展为多条
int j = Integer.parseInt(start.substring(firstDiff, lastDiff));
int k = Integer.parseInt(end.substring(firstDiff, lastDiff));
String head = start.substring(0, firstDiff);
String f = "%" + (lastDiff-firstDiff) + "d";
StringBuilder sb = new StringBuilder();
for (int i = j; i <= k; i++){
sb.setLength(0);
sb.append(head);
sb.append(String.format(f, i));
headingDefinitions.put(sb.toString(), attachment);
}
}
}
}
| james-hu/jabb-core | src/main/java/net/sf/jabb/util/text/StringStartWithMatcher.java | Java | apache-2.0 | 8,259 |
package com.dexvis.simple.transform;
import javafx.scene.web.HTMLEditor;
import org.simpleframework.xml.transform.Transform;
public class HTMLEditorTransform implements Transform<HTMLEditor>
{
public HTMLEditor read(String value) throws Exception
{
HTMLEditor editor = new HTMLEditor();
editor.setHtmlText(value);
return editor;
}
@Override
public String write(HTMLEditor value) throws Exception
{
return value.getHtmlText();
}
}
| PatMartin/Dex | src/com/dexvis/simple/transform/HTMLEditorTransform.java | Java | apache-2.0 | 485 |
package ecologylab.bigsemantics.service.crawler;
import java.io.IOException;
/**
* A general framework for crawling resources.
*
* @author quyin
*/
public interface ResourceCrawler<T>
{
/**
* Queue a resource with the given URI.
*
* @param uri
*/
void queue(String uri);
/**
* If the crawler has more resources to crawl.
*
* @return true if there are still resources to crawl.
*/
boolean hasNext();
/**
* Retrieve the next resource.
*
* @return The next crawled resource.
* @throws IOException
* If the resource cannot be accessed.
*/
T next() throws IOException;
/**
* Expand a given resource.
*
* @param resource
*/
void expand(T resource);
/**
* @return The number of resources queued.
*/
int countQueued();
/**
* @return The number of resources that are to be crawled.
*/
int countWaiting();
/**
* @return The number of resources that have been accessed.
*/
int countAccessed();
/**
* @return The number of resources that have been accessed successfully.
*/
int countSuccess();
/**
* @return The number of resources that have been accessed unsuccessfully.
*/
int countFailure();
} | ecologylab/BigSemanticsService | BasicCrawler/src/ecologylab/bigsemantics/service/crawler/ResourceCrawler.java | Java | apache-2.0 | 1,304 |
package net.sf.anpr.rcp.widget;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class JCanvasPanel extends JLabel {
private static final long serialVersionUID = 1L;
private Rectangle focusArea=new Rectangle();
private BufferedImage image;
public JCanvasPanel() {
super();
this.setVerticalAlignment(SwingConstants.TOP);
this.setHorizontalAlignment(SwingConstants.LEFT);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(focusArea==null) return ;
if (focusArea.width >= 0 && focusArea.height >= 0) {
Color c = g.getColor();
g.setColor(Color.RED);
g.drawRect(focusArea.x, focusArea.y, focusArea.width, focusArea.height);
g.setColor(c);
}
g.dispose();
}
protected void setImage(BufferedImage image){
this.image=image;
this.setIcon(new ImageIcon(image));
}
public void setFocusArea(Rectangle focusArea) {
this.focusArea = focusArea;
}
protected BufferedImage getImage() {
return image;
}
}
| alexmao86/swing-rcp | src/main/java/net/sf/anpr/rcp/widget/JCanvasPanel.java | Java | apache-2.0 | 1,173 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.app.standalone.about;
import org.eclipse.jface.action.IAction;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionDelegate;
public class AboutBoxAction extends ActionDelegate
{
private IWorkbenchWindow window;
public AboutBoxAction(IWorkbenchWindow window) {
this.window = window;
}
@Override
public void run(IAction action)
{
// new AboutDialog(window.getShell()).open();
AboutBoxDialog dialog = new AboutBoxDialog(window.getShell());
dialog.open();
}
} | dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui.app.standalone/src/org/jkiss/dbeaver/ui/app/standalone/about/AboutBoxAction.java | Java | apache-2.0 | 1,230 |
package com.action.design.pattern.chain;
/**
* 创建不同类型的记录器。赋予它们不同的错误级别,并在每个记录器中设置下一个记录器。每个记录器中的下一个记录器代表的是链的一部分。
* Created by wuyunfeng on 2017/6/15.
*/
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG,
"This is an debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR,
"This is an error information.");
}
}
| pearpai/java_action | src/main/java/com/action/design/pattern/chain/ChainPatternDemo.java | Java | apache-2.0 | 1,140 |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.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 boofcv.alg.descriptor;
import boofcv.struct.feature.TupleDesc_B;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("ResultOfMethodCallIgnored") @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
@State(Scope.Benchmark)
@Fork(value = 1)
public class BenchmarkDescriptorDistance {
static int NUM_FEATURES = 10000;
List<TupleDesc_B> binaryA = new ArrayList<>();
List<TupleDesc_B> binaryB = new ArrayList<>();
HammingTable16 table = new HammingTable16();
@Setup public void setup() {
Random rand = new Random(234234);
binaryA = new ArrayList<>();
binaryB = new ArrayList<>();
for (int i = 0; i < NUM_FEATURES; i++) {
binaryA.add(randomFeature(rand));
binaryB.add(randomFeature(rand));
}
}
@Benchmark public void hammingTable() {
for (int i = 0; i < binaryA.size(); i++) {
tableScore(binaryA.get(i), binaryB.get(i));
}
}
private int tableScore( TupleDesc_B a, TupleDesc_B b ) {
int score = 0;
for (int i = 0; i < a.data.length; i++) {
int dataA = a.data[i];
int dataB = b.data[i];
score += table.lookup((short)dataA, (short)dataB);
score += table.lookup((short)(dataA >> 16), (short)(dataB >> 16));
}
return score;
}
@Benchmark public void equationOld() {
for (int i = 0; i < binaryA.size(); i++) {
ExperimentalDescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
@Benchmark public void equation() {
for (int i = 0; i < binaryA.size(); i++) {
DescriptorDistance.hamming(binaryA.get(i), binaryB.get(i));
}
}
private TupleDesc_B randomFeature( Random rand ) {
TupleDesc_B feat = new TupleDesc_B(512);
for (int j = 0; j < feat.data.length; j++) {
feat.data[j] = rand.nextInt();
}
return feat;
}
public static void main( String[] args ) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkDescriptorDistance.class.getSimpleName())
.warmupTime(TimeValue.seconds(1))
.measurementTime(TimeValue.seconds(1))
.build();
new Runner(opt).run();
}
}
| lessthanoptimal/BoofCV | main/boofcv-feature/src/benchmark/java/boofcv/alg/descriptor/BenchmarkDescriptorDistance.java | Java | apache-2.0 | 3,105 |
package adamin90.com.wpp.model.mostsearch;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class MostSearchData {
@SerializedName("data")
@Expose
private List<Datum> data = new ArrayList<Datum>();
@SerializedName("code")
@Expose
private Integer code;
/**
*
* @return
* The data
*/
public List<Datum> getData() {
return data;
}
/**
*
* @param data
* The data
*/
public void setData(List<Datum> data) {
this.data = data;
}
/**
*
* @return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* @param code
* The code
*/
public void setCode(Integer code) {
this.code = code;
}
}
| adamin1990/MaterialWpp | wpp/app/src/main/java/adamin90/com/wpp/model/mostsearch/MostSearchData.java | Java | apache-2.0 | 971 |
package com.hangon.saying.viewPager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.example.fd.ourapplication.R;
import com.hangon.common.Constants;
import com.hangon.common.MyApplication;
import com.hangon.common.ViewHolder;
import com.hangon.common.VolleyBitmapCache;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/5/31.
*/
public class GradAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
Context context;
List list = new ArrayList();
private static ImageLoader mImageLoader; // imageLoader对象,用来初始化NetworkImageView
/**
* 记录每个子项的高度。
*/
private int mItemHeight = 0;
GradAdapter(Context context, List list) {
this.context = context;
this.list = list;
mImageLoader = new ImageLoader(MyApplication.queues, new VolleyBitmapCache()); // 初始化一个loader对象,可以进行自定义配置
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
ViewGradHolder gradHolder;
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
gradHolder = new ViewGradHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.carlife_grade_content, null);
gradHolder.img = (ImageView) convertView.findViewById(R.id.item_grida_image);
convertView.setTag(gradHolder);
} else {
gradHolder = (ViewGradHolder) convertView.getTag();
}
NetworkImageView networkImageView = (NetworkImageView) gradHolder.img;
// 设置默认的图片
networkImageView.setDefaultImageResId(R.drawable.default_photo);
// 设置图片加载失败后显示的图片
networkImageView.setErrorImageResId(R.drawable.error_photo);
if (list.get(position) != null && !list.get(position).equals("")) {
//getImag(list.get(position).toString());
// 开始加载网络图片
networkImageView.setImageUrl(Constants.LOAD_SAYING_IMG_URL + list.get(position), mImageLoader);
}
return convertView;
}
class ViewGradHolder {
ImageView img;
}
private void getImag(String path) {
String url = Constants.LOAD_SAYING_IMG_URL + path;
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
gradHolder.img.setImageBitmap(bitmap);
}
}, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(context, "说说图片加载失败", Toast.LENGTH_SHORT).show();
}
});
MyApplication.getHttpQueues().add(request);
}
/**
* 设置item子项的高度。
*/
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
notifyDataSetChanged();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// 仅当GridView静止时才去下载图片,GridView滑动时取消所有正在下载的任务
if (scrollState == SCROLL_STATE_IDLE) {
// loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
} else {
// cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
| TangZuopeng/OurApplication | app/src/main/java/com/hangon/saying/viewPager/GradAdapter.java | Java | apache-2.0 | 4,468 |
/**
* Copyright 2013 Agustín Miura <"agustin.miura@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 ar.com.imperium.common.security;
import org.springframework.stereotype.Component;
@Component("dummyHashService")
public class DummyHashServiceImpl implements IHashService
{
@Override
public String hashString(String input) throws Exception
{
return input;
}
}
| agustinmiura/imperium | src/main/java/ar/com/imperium/common/security/DummyHashServiceImpl.java | Java | apache-2.0 | 925 |
package com.sadc.game.gameobject.trackobject;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.sadc.game.GameConstants;
import com.sadc.game.gameobject.GameUtils;
import com.sadc.game.gameobject.Player;
/**
* @author f536985 (Tom Farello)
*/
public class Wall extends TrackObject {
public Wall(float distance, float angle) {
setActive(true);
setDistance(distance);
setAngle(angle);
setWidth(22);
setTexture(new Texture("brickWall.png"));
}
@Override
public void update(float delta, Player player) {
if (collide(player)) {
player.crash();
setActive(false);
}
}
@Override
public void draw(float delta, float playerDistance, SpriteBatch spriteBatch) {
float drawDistance = (float)Math.pow(2 , playerDistance - (getDistance()));
GameUtils.setColorByDrawDistance(drawDistance, spriteBatch);
spriteBatch.draw(getTexture(), GameConstants.SCREEN_WIDTH / 2 - 50, 15,
50, GameConstants.SCREEN_HEIGHT / 2 - 15, 100, 70, drawDistance, drawDistance, getAngle(), 0, 0, 100, 70, false, false);
}
}
| jlturner85/libgdx-gradle-template | core/src/main/java/com/sadc/game/gameobject/trackobject/Wall.java | Java | apache-2.0 | 1,196 |
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.sql.functions.coll;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This operator can work as aggregate or inline. If only one argument is passed than aggregates,
* otherwise executes, and returns, the SYMMETRIC DIFFERENCE between the collections received as
* parameters. Works also with no collection values.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class OSQLFunctionSymmetricDifference extends OSQLFunctionMultiValueAbstract<Set<Object>> {
public static final String NAME = "symmetricDifference";
private Set<Object> rejected;
public OSQLFunctionSymmetricDifference() {
super(NAME, 1, -1);
}
private static void addItemToResult(Object o, Set<Object> accepted, Set<Object> rejected) {
if (!accepted.contains(o) && !rejected.contains(o)) {
accepted.add(o);
} else {
accepted.remove(o);
rejected.add(o);
}
}
private static void addItemsToResult(
Collection<Object> co, Set<Object> accepted, Set<Object> rejected) {
for (Object o : co) {
addItemToResult(o, accepted, rejected);
}
}
@SuppressWarnings("unchecked")
public Object execute(
Object iThis,
OIdentifiable iCurrentRecord,
Object iCurrentResult,
final Object[] iParams,
OCommandContext iContext) {
if (iParams[0] == null) return null;
Object value = iParams[0];
if (iParams.length == 1) {
// AGGREGATION MODE (STATEFUL)
if (context == null) {
context = new HashSet<Object>();
rejected = new HashSet<Object>();
}
if (value instanceof Collection<?>) {
addItemsToResult((Collection<Object>) value, context, rejected);
} else {
addItemToResult(value, context, rejected);
}
return null;
} else {
// IN-LINE MODE (STATELESS)
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object iParameter : iParams) {
if (iParameter instanceof Collection<?>) {
addItemsToResult((Collection<Object>) iParameter, result, rejected);
} else {
addItemToResult(iParameter, result, rejected);
}
}
return result;
}
}
@Override
public Set<Object> getResult() {
if (returnDistributedResult()) {
final Map<String, Object> doc = new HashMap<String, Object>();
doc.put("result", context);
doc.put("rejected", rejected);
return Collections.<Object>singleton(doc);
} else {
return super.getResult();
}
}
public String getSyntax() {
return "difference(<field>*)";
}
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
if (returnDistributedResult()) {
final Set<Object> result = new HashSet<Object>();
final Set<Object> rejected = new HashSet<Object>();
for (Object item : resultsToMerge) {
rejected.addAll(unwrap(item, "rejected"));
}
for (Object item : resultsToMerge) {
addItemsToResult(unwrap(item, "result"), result, rejected);
}
return result;
}
if (!resultsToMerge.isEmpty()) return resultsToMerge.get(0);
return null;
}
@SuppressWarnings("unchecked")
private Set<Object> unwrap(Object obj, String field) {
final Set<Object> objAsSet = (Set<Object>) obj;
final Map<String, Object> objAsMap = (Map<String, Object>) objAsSet.iterator().next();
final Set<Object> objAsField = (Set<Object>) objAsMap.get(field);
return objAsField;
}
}
| orientechnologies/orientdb | core/src/main/java/com/orientechnologies/orient/core/sql/functions/coll/OSQLFunctionSymmetricDifference.java | Java | apache-2.0 | 4,574 |
/*
* Copyright 2012-2017 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.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* An empty element returned on a successful request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetReceiptRulePosition" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetReceiptRulePositionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SetReceiptRulePositionResult == false)
return false;
SetReceiptRulePositionResult other = (SetReceiptRulePositionResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public SetReceiptRulePositionResult clone() {
try {
return (SetReceiptRulePositionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| dagnir/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/SetReceiptRulePositionResult.java | Java | apache-2.0 | 2,365 |
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.daisy.pipeline.client.PipelineClient;
import org.daisy.pipeline.webservice.jaxb.job.Job;
import org.daisy.pipeline.webservice.jaxb.job.JobStatus;
import org.daisy.pipeline.webservice.jaxb.job.Messages;
import org.daisy.pipeline.webservice.jaxb.request.Callback;
import org.daisy.pipeline.webservice.jaxb.request.CallbackType;
import org.daisy.pipeline.webservice.jaxb.request.Input;
import org.daisy.pipeline.webservice.jaxb.request.Item;
import org.daisy.pipeline.webservice.jaxb.request.JobRequest;
import org.daisy.pipeline.webservice.jaxb.request.ObjectFactory;
import org.daisy.pipeline.webservice.jaxb.request.Script;
import org.daisy.pipeline.webservice.jaxb.request.Priority;
import org.junit.Assert;
import org.junit.Test;
public class TestPushNotifications extends Base {
private static final PipelineClient client = newClient(TestClientJobs.CREDS_DEF.clientId, TestClientJobs.CREDS_DEF.secret);
@Override
protected PipelineClient client() {
return client;
}
@Override
protected Properties systemProperties() {
Properties p = super.systemProperties();
// client authentication is required for push notifications
p.setProperty("org.daisy.pipeline.ws.authentication", "true");
p.setProperty("org.daisy.pipeline.ws.authentication.key", TestClientJobs.CREDS_DEF.clientId);
p.setProperty("org.daisy.pipeline.ws.authentication.secret", TestClientJobs.CREDS_DEF.secret);
return p;
}
@Test
public void testPushNotifications() throws Exception {
AbstractCallback testStatusAndMessages = new AbstractCallback() {
JobStatus lastStatus = null;
BigDecimal lastProgress = BigDecimal.ZERO;
Iterator<BigDecimal> mustSee = stream(".25", ".375", ".5", ".55", ".675", ".8", ".9").map(d -> new BigDecimal(d)).iterator();
BigDecimal mustSeeNext = mustSee.next();
List<BigDecimal> seen = new ArrayList<BigDecimal>();
@Override
void handleStatus(JobStatus status) {
lastStatus = status;
}
@Override
void handleMessages(Messages messages) {
BigDecimal progress = messages.getProgress();
if (progress.compareTo(lastProgress) != 0) {
Assert.assertTrue("Progress must be monotonic non-decreasing", progress.compareTo(lastProgress) >= 0);
if (mustSeeNext != null) {
if (progress.compareTo(mustSeeNext) == 0) {
seen.clear();
mustSeeNext = mustSee.hasNext() ? mustSee.next() : null;
} else {
seen.add(progress);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, progress.compareTo(mustSeeNext) < 0);
}
}
lastProgress = progress;
}
}
@Override
void finalTest() {
Assert.assertEquals(JobStatus.SUCCESS, lastStatus);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, mustSeeNext == null);
}
};
HttpServer server; {
server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/notify", testStatusAndMessages);
server.setExecutor(null);
server.start();
}
try {
JobRequest req; {
ObjectFactory oFactory = new ObjectFactory();
req = oFactory.createJobRequest();
Script script = oFactory.createScript(); {
Optional<String> href = getScriptHref("mock-messages-script");
Assert.assertTrue(href.isPresent());
script.setHref(href.get());
}
req.getScriptOrNicenameOrPriority().add(script);
Input input = oFactory.createInput(); {
Item source = oFactory.createItem();
source.setValue(getResource("hello.xml").toURI().toString());
input.getItem().add(source);
input.setName("source");
}
req.getScriptOrNicenameOrPriority().add(input);
req.getScriptOrNicenameOrPriority().add(oFactory.createNicename("NICE_NAME"));
req.getScriptOrNicenameOrPriority().add(oFactory.createPriority(Priority.LOW));
Callback callback = oFactory.createCallback(); {
callback.setType(CallbackType.MESSAGES);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
callback = oFactory.createCallback(); {
callback.setType(CallbackType.STATUS);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
}
Job job = client().sendJob(req);
deleteAfterTest(job);
waitForStatus(JobStatus.SUCCESS, job, 10000);
// wait until all updates have been pushed
Thread.sleep(1000);
testStatusAndMessages.finalTest();
} finally {
server.stop(1);
}
}
public static abstract class AbstractCallback implements HttpHandler {
abstract void handleStatus(JobStatus status);
abstract void handleMessages(Messages messages);
abstract void finalTest();
@Override
public void handle(HttpExchange t) throws IOException {
Job job; {
try {
job = (Job)JAXBContext.newInstance(Job.class).createUnmarshaller().unmarshal(t.getRequestBody());
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
handleStatus(job.getStatus());
Optional<Messages> messages = getMessages(job);
if (messages.isPresent())
handleMessages(messages.get());
String response = "got it";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static Optional<Messages> getMessages(Job job) {
return Optional.fromNullable(
Iterables.getOnlyElement(
Iterables.filter(
job.getNicenameOrBatchIdOrScript(),
Messages.class),
null));
}
static <T> Stream<T> stream(T... array) {
return Arrays.<T>stream(array);
}
}
| daisy/pipeline-issues | framework/webservice/src/test/java/TestPushNotifications.java | Java | apache-2.0 | 6,214 |
/*
* Copyright 2012-2016 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 jetbrains.jetpad.base.edt;
public class BufferingEdtManager extends RunningEdtManager {
public BufferingEdtManager() {
super();
}
public BufferingEdtManager(String name) {
super(name);
}
@Override
protected void doSchedule(Runnable r) {
addTaskToQueue(r);
}
@Override
public String toString() {
return "BufferingEdtManager@" + Integer.toHexString(hashCode()) +
("".equals(getName()) ? "" : " (" + getName()+ ")");
}
} | timzam/jetpad-mapper | util/base/src/test/java/jetbrains/jetpad/base/edt/BufferingEdtManager.java | Java | apache-2.0 | 1,075 |
/*
* Copyright 2016
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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.tudarmstadt.ukp.experiments.argumentation.sequence.io.filters;
import de.tudarmstadt.ukp.experiments.argumentation.sequence.DocumentRegister;
import org.apache.uima.jcas.JCas;
import java.util.HashSet;
import java.util.Set;
/**
* Filter wrt document register
*
* @author Ivan Habernal
*/
public class DocumentRegisterFilter
implements DocumentCollectionFilter
{
private final Set<DocumentRegister> documentRegisters = new HashSet<>();
public DocumentRegisterFilter(String documentRegistersString)
{
// parse document registers
if (!documentRegistersString.isEmpty()) {
for (String documentDomainSplit : documentRegistersString.split(" ")) {
String domain = documentDomainSplit.trim();
if (!domain.isEmpty()) {
documentRegisters.add(DocumentRegister.fromString(domain));
}
}
}
}
@Override
public boolean removeFromCollection(JCas jCas)
{
DocumentRegister register = DocumentRegister.fromJCas(jCas);
return !documentRegisters.isEmpty() && !documentRegisters.contains(register);
}
@Override
public boolean applyFilter()
{
return !documentRegisters.isEmpty();
}
}
| habernal/emnlp2015 | code/experiments/src/main/java/de/tudarmstadt/ukp/experiments/argumentation/sequence/io/filters/DocumentRegisterFilter.java | Java | apache-2.0 | 1,948 |
package es.npatarino.android.gotchallenge.chat.message.viewmodel;
import android.net.Uri;
import es.npatarino.android.gotchallenge.chat.message.model.Payload;
public class StickerPayLoad implements Payload {
private String stickerFilePath;
public StickerPayLoad(String stickerFilePath) {
this.stickerFilePath = stickerFilePath;
}
public String getStickerFilePath() {
return stickerFilePath;
}
public Uri getSticker() {
return Uri.parse(stickerFilePath);
}
}
| tonilopezmr/Game-of-Thrones | app/src/main/java/es/npatarino/android/gotchallenge/chat/message/viewmodel/StickerPayLoad.java | Java | apache-2.0 | 490 |
/* */ package com.hundsun.network.gates.wulin.biz.service.pojo.auction;
/* */
/* */ import com.hundsun.network.gates.luosi.biz.security.ServiceException;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumActiveStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumBidCheckStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumBidPriceStatus;
/* */ import com.hundsun.network.gates.luosi.common.enums.EnumOperatorType;
/* */ import com.hundsun.network.gates.luosi.common.remote.ServiceResult;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.enums.EnumAuctionErrors;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.request.AuctionMulitBidRequest;
/* */ import com.hundsun.network.gates.luosi.wulin.reomte.request.SystemMessageRequest;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionBidderDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionFreeBidDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionHallDAO;
/* */ import com.hundsun.network.gates.wulin.biz.dao.auction.AuctionLogDAO;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionBidder;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionFreeBid;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionLog;
/* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionMulitBidProject;
/* */ import com.hundsun.network.gates.wulin.biz.domain.query.AuctionMulitBidProjectQuery;
/* */ import com.hundsun.network.gates.wulin.biz.domain.query.MulitAuctionReviewQuery;
/* */ import com.hundsun.network.gates.wulin.biz.service.BaseService;
/* */ import com.hundsun.network.gates.wulin.biz.service.auction.MulitAuctionService;
/* */ import com.hundsun.network.gates.wulin.biz.service.message.SystemMessageService;
/* */ import com.hundsun.network.gates.wulin.biz.service.project.ProjectListingService;
/* */ import com.hundsun.network.melody.common.util.StringUtil;
/* */ import java.io.IOException;
/* */ import java.util.ArrayList;
/* */ import java.util.HashMap;
/* */ import java.util.List;
/* */ import java.util.Locale;
/* */ import org.apache.commons.logging.Log;
/* */ import org.codehaus.jackson.map.ObjectMapper;
/* */ import org.springframework.beans.factory.annotation.Autowired;
/* */ import org.springframework.context.MessageSource;
/* */ import org.springframework.stereotype.Service;
/* */ import org.springframework.transaction.TransactionStatus;
/* */ import org.springframework.transaction.support.TransactionCallback;
/* */ import org.springframework.transaction.support.TransactionTemplate;
/* */
/* */ @Service("mulitAuctionService")
/* */ public class MulitAuctionServiceImpl extends BaseService
/* */ implements MulitAuctionService
/* */ {
/* */
/* */ @Autowired
/* */ private ProjectListingService projectListingService;
/* */
/* */ @Autowired
/* */ private AuctionFreeBidDAO auctionFreeBidDAO;
/* */
/* */ @Autowired
/* */ private AuctionBidderDAO auctionBidderDAO;
/* */
/* */ @Autowired
/* */ private AuctionLogDAO auctionLogDAO;
/* */
/* */ @Autowired
/* */ private MessageSource messageSource;
/* */
/* */ @Autowired
/* */ private AuctionHallDAO auctionHallDAO;
/* */
/* */ @Autowired
/* */ private SystemMessageService systemMessageService;
/* */
/* */ public ServiceResult review(final AuctionMulitBidRequest request)
/* */ {
/* 70 */ ServiceResult serviceResult = new ServiceResult();
/* */
/* 72 */ if ((null == request) || (StringUtil.isEmpty(request.getBidderAccount())) || (StringUtil.isEmpty(request.getReviewer())) || (StringUtil.isEmpty(request.getProjectCode())) || (StringUtil.isEmpty(request.getRemark())))
/* */ {
/* 76 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.PARAMETER_ERROR.getValue()), EnumAuctionErrors.PARAMETER_ERROR.getInfo());
/* */
/* 78 */ return serviceResult;
/* */ }
/* 80 */ AuctionMulitBidProjectQuery query = new AuctionMulitBidProjectQuery();
/* 81 */ query.setReviewer(request.getReviewer());
/* 82 */ query.setProjectCode(request.getProjectCode());
/* 83 */ List projectList = this.projectListingService.queryAuctionMulitBidProjectUncheckedByProjectCode(query);
/* */
/* 86 */ if ((null == projectList) || (projectList.size() <= 0)) {
/* 87 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.CHECK_PROJECT_LISTING_NULL.getValue()), EnumAuctionErrors.CHECK_PROJECT_LISTING_NULL.getInfo());
/* */
/* 89 */ return serviceResult;
/* */ }
/* */
/* 92 */ AuctionFreeBid auctionFreeBid = queryTopUncheckFreeBid(request.getProjectCode(), request.getBidderAccount());
/* */
/* 94 */ if (null == auctionFreeBid) {
/* 95 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.PARAMETER_ERROR.getValue()), EnumAuctionErrors.PARAMETER_ERROR.getInfo());
/* */
/* 97 */ return serviceResult;
/* */ }
/* */
/* 100 */ AuctionBidder auctionBidder = this.auctionBidderDAO.selectNormalByBidderAccount(request.getProjectCode(), request.getBidderAccount());
/* */
/* 102 */ if (null == auctionBidder) {
/* 103 */ serviceResult.setErrorNOInfo(Integer.valueOf(EnumAuctionErrors.CHECK_BIDDER_NULL.getValue()), EnumAuctionErrors.CHECK_BIDDER_NULL.getInfo());
/* */
/* 105 */ return serviceResult;
/* */ }
/* 107 */ ObjectMapper mapper = new ObjectMapper();
/* 108 */ String auctionBidderJson = "";
/* */ try {
/* 110 */ auctionBidderJson = mapper.writeValueAsString(auctionBidder);
/* */ } catch (IOException e) {
/* 112 */ if (this.log.isErrorEnabled()) {
/* 113 */ this.log.error("convert auctionBidder to json format fail,", e);
/* */ }
/* */ }
/* 116 */ final String fAuctionBidderJson = auctionBidderJson;
/* 117 */ final AuctionFreeBid fAuctionFreeBid = auctionFreeBid;
/* 118 */ final String logRemark = getMessage("project.auction.mulitbid.review.log.remark", new String[] { request.getReviewer(), auctionBidder.getBidderAccount() });
/* */
/* 120 */ final AuctionBidder fAuctionBidder = auctionBidder;
/* 121 */ final AuctionMulitBidProject fAuctionMulitBidProject = (AuctionMulitBidProject)projectList.get(0);
/* */
/* 123 */ serviceResult = (ServiceResult)this.transactionTemplate.execute(new TransactionCallback() {
/* */ public ServiceResult doInTransaction(TransactionStatus status) {
/* 125 */ ServiceResult result = new ServiceResult();
/* 126 */ Object savePoint = status.createSavepoint();
/* */ try
/* */ {
/* 129 */ AuctionFreeBid auctionFreeBid = new AuctionFreeBid();
/* 130 */ auctionFreeBid.setBidderAccount(fAuctionFreeBid.getBidderAccount());
/* 131 */ auctionFreeBid.setBidderTrademark(fAuctionFreeBid.getBidderTrademark());
/* 132 */ auctionFreeBid.setBidOperatorAccount(fAuctionFreeBid.getBidOperatorAccount());
/* 133 */ auctionFreeBid.setCheckRemark(request.getRemark());
/* 134 */ auctionFreeBid.setCheckStatus(EnumBidCheckStatus.Fail.getValue());
/* 135 */ auctionFreeBid.setIp(fAuctionFreeBid.getIp());
/* 136 */ auctionFreeBid.setOperator(request.getOperator());
/* 137 */ auctionFreeBid.setPrice(fAuctionFreeBid.getPrice());
/* 138 */ auctionFreeBid.setProjectCode(request.getProjectCode());
/* 139 */ auctionFreeBid.setStatus(fAuctionFreeBid.getStatus());
/* 140 */ MulitAuctionServiceImpl.this.auctionFreeBidDAO.insert(auctionFreeBid);
/* */
/* 143 */ if (MulitAuctionServiceImpl.this.auctionBidderDAO.deleteByBidderAccount(request.getProjectCode(), request.getBidderAccount()) <= 0)
/* */ {
/* 145 */ throw new ServiceException(EnumAuctionErrors.REVIEW_DELETE_BIDDER_FAIL.getInfo(), Integer.valueOf(EnumAuctionErrors.REVIEW_DELETE_BIDDER_FAIL.getValue()));
/* */ }
/* */
/* 150 */ if (EnumActiveStatus.Yes.getValue().equals(fAuctionBidder.getIsPriority())) {
/* 151 */ HashMap actionHallMap = new HashMap();
/* 152 */ actionHallMap.put("priorityNumSub", Integer.valueOf(1));
/* 153 */ actionHallMap.put("whereProjectCode", request.getProjectCode());
/* 154 */ if (MulitAuctionServiceImpl.this.auctionHallDAO.updateByMap(actionHallMap) <= 0) {
/* 155 */ throw new ServiceException(EnumAuctionErrors.REVIEW_UPDATE_HALL_FALL.getInfo(), Integer.valueOf(EnumAuctionErrors.REVIEW_UPDATE_HALL_FALL.getValue()));
/* */ }
/* */
/* */ }
/* */
/* 172 */ SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
/* 173 */ systemMessageRequest.setSendAccount(EnumOperatorType.SYSTEM.getValue());
/* 174 */ systemMessageRequest.setContent(MulitAuctionServiceImpl.this.getMessage("project.auction.mulitbid.review.message.content", new String[] { fAuctionMulitBidProject.getProjectTitle(), request.getRemark() }));
/* */
/* 177 */ systemMessageRequest.setTitle(MulitAuctionServiceImpl.this.getMessage("project.auction.mulitbid.review.message.title", new String[0]));
/* */
/* 179 */ List userAccountList = new ArrayList();
/* 180 */ userAccountList.add(fAuctionBidder.getBidderAccount());
/* 181 */ systemMessageRequest.setUserAccountList(userAccountList);
/* 182 */ MulitAuctionServiceImpl.this.systemMessageService.sendSystemMessage(systemMessageRequest);
/* */
/* 185 */ AuctionLog auctionLog = new AuctionLog();
/* 186 */ auctionLog.setDataJson(fAuctionBidderJson);
/* 187 */ auctionLog.setProjectCode(request.getProjectCode());
/* 188 */ auctionLog.setRemark(logRemark);
/* 189 */ auctionLog.setOperatorType(EnumOperatorType.REVIEWER.getValue());
/* 190 */ auctionLog.setOperator(request.getReviewer());
/* 191 */ MulitAuctionServiceImpl.this.auctionLogDAO.insert(auctionLog);
/* */ }
/* */ catch (ServiceException e) {
/* 194 */ status.rollbackToSavepoint(savePoint);
/* 195 */ MulitAuctionServiceImpl.this.log.error("MulitAuctionServiceImpl review fail", e);
/* 196 */ result.setErrorNO(e.getErrorNO());
/* 197 */ result.setErrorInfo(e.getErrorInfo());
/* */ } catch (Exception e) {
/* 199 */ status.rollbackToSavepoint(savePoint);
/* 200 */ MulitAuctionServiceImpl.this.log.error("MulitAuctionServiceImpl review error", e);
/* 201 */ result.setErrorNO(Integer.valueOf(EnumAuctionErrors.INTERNAL_ERROR.getValue()));
/* 202 */ result.setErrorInfo(EnumAuctionErrors.INTERNAL_ERROR.getInfo());
/* */ }
/* 204 */ return result;
/* */ }
/* */ });
/* 208 */ return serviceResult;
/* */ }
/* */
/* */ public AuctionFreeBid queryTopUncheckFreeBid(String projectCode, String bidderAccount)
/* */ {
/* 213 */ MulitAuctionReviewQuery query = new MulitAuctionReviewQuery();
/* 214 */ query.setBidderAccount(bidderAccount);
/* 215 */ query.setCheckStatus(EnumBidCheckStatus.Pass);
/* 216 */ query.setProjectCode(projectCode);
/* 217 */ query.setStatus(EnumBidPriceStatus.EFFECTIVE);
/* 218 */ return this.auctionFreeBidDAO.selectTopByMulitAuctionReviewQuery(query);
/* */ }
/* */
/* */ protected String getMessage(String code, String[] args) {
/* 222 */ return this.messageSource.getMessage(code, args, Locale.CHINA);
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.wulin.biz.service.pojo.auction.MulitAuctionServiceImpl
* JD-Core Version: 0.6.0
*/ | hnccfr/ccfrweb | basecore/src/com/hundsun/network/gates/wulin/biz/service/pojo/auction/MulitAuctionServiceImpl.java | Java | apache-2.0 | 12,488 |
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.utn.dacs2017.compraventa.vendedor;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Grego Dadone
*/
@Controller
class VendedorController {
private final VendedorRepository vendedores;
@Autowired
public VendedorController(VendedorRepository vendedorService) {
this.vendedores = vendedorService;
}
@RequestMapping(value = { "/vendedores.html" })
public String showVendedorList(Map<String, Object> model) {
Vendedores vendedores = new Vendedores();
vendedores.getVendedorList().addAll(this.vendedores.findAll());
model.put("vendedores", vendedores);
return "vendedores/vendedorList";
}
@RequestMapping(value = { "/vendedores.json", "/vendedores.xml" })
public @ResponseBody Vendedores showResourcesVendedorList() {
Vendedores vendedores = new Vendedores();
vendedores.getVendedorList().addAll(this.vendedores.findAll());
return vendedores;
}
}
| gregodadone/spring-compraventa | src/main/java/org/utn/dacs2017/compraventa/vendedor/VendedorController.java | Java | apache-2.0 | 1,812 |
package com.afollestad.breadcrumb;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Aidan Follestad (afollestad)
*/
public class LinearBreadcrumb extends HorizontalScrollView implements View.OnClickListener {
public static class Crumb implements Serializable {
public Crumb(String path,String attachMsg) {
mPath = path;
mAttachMsg = attachMsg;
}
private final String mPath;
private final String mAttachMsg;
private int mScrollY;
private int mScrollOffset;
public int getScrollY() {
return mScrollY;
}
public int getScrollOffset() {
return mScrollOffset;
}
public void setScrollY(int scrollY) {
this.mScrollY = scrollY;
}
public void setScrollOffset(int scrollOffset) {
this.mScrollOffset = scrollOffset;
}
public String getPath() {
return mPath;
}
public String getTitle() {
return (!TextUtils.isEmpty(mAttachMsg)) ? mAttachMsg : mPath;
}
public String getmAttachMsg() {
return mAttachMsg;
}
@Override
public boolean equals(Object o) {
return (o instanceof Crumb) && ((Crumb) o).getPath().equals(getPath());
}
@Override
public String toString() {
return "Crumb{" +
"mAttachMsg='" + mAttachMsg + '\'' +
", mPath='" + mPath + '\'' +
", mScrollY=" + mScrollY +
", mScrollOffset=" + mScrollOffset +
'}';
}
}
public interface SelectionCallback {
void onCrumbSelection(Crumb crumb, String absolutePath, int count, int index);
}
public LinearBreadcrumb(Context context) {
super(context);
init();
}
public LinearBreadcrumb(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LinearBreadcrumb(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private List<Crumb> mCrumbs;
private List<Crumb> mOldCrumbs;
private LinearLayout mChildFrame;
private int mActive;
private SelectionCallback mCallback;
private void init() {
setMinimumHeight((int) getResources().getDimension(R.dimen.breadcrumb_height));
setClipToPadding(false);
mCrumbs = new ArrayList<>();
mChildFrame = new LinearLayout(getContext());
addView(mChildFrame, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setAlpha(View view, int alpha) {
if (view instanceof ImageView && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
((ImageView) view).setImageAlpha(alpha);
} else {
ViewCompat.setAlpha(view, alpha);
}
}
public void addCrumb(@NonNull Crumb crumb, boolean refreshLayout) {
LinearLayout view = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.bread_crumb, this, false);
view.setTag(mCrumbs.size());
view.setClickable(true);
view.setFocusable(true);
view.setOnClickListener(this);
mChildFrame.addView(view, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mCrumbs.add(crumb);
if (refreshLayout) {
mActive = mCrumbs.size() - 1;
requestLayout();
}
invalidateActivatedAll();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
//RTL works fine like this
View child = mChildFrame.getChildAt(mActive);
if (child != null)
smoothScrollTo(child.getLeft(), 0);
}
public Crumb findCrumb(@NonNull String forDir) {
for (int i = 0; i < mCrumbs.size(); i++) {
if (mCrumbs.get(i).getPath().equals(forDir))
return mCrumbs.get(i);
}
return null;
}
public void clearCrumbs() {
try {
mOldCrumbs = new ArrayList<>(mCrumbs);
mCrumbs.clear();
mChildFrame.removeAllViews();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
public Crumb getCrumb(int index) {
return mCrumbs.get(index);
}
public void setCallback(SelectionCallback callback) {
mCallback = callback;
}
public boolean setActive(Crumb newActive) {
mActive = mCrumbs.indexOf(newActive);
for(int i = size()-1;size()>mActive+1;i--){
removeCrumbAt(i);
}
((LinearLayout)mChildFrame.getChildAt(mActive)).getChildAt(1).setVisibility(View.GONE);
boolean success = mActive > -1;
if (success)
requestLayout();
return success;
}
private void invalidateActivatedAll() {
for (int i = 0; i < mCrumbs.size(); i++) {
Crumb crumb = mCrumbs.get(i);
invalidateActivated(mChildFrame.getChildAt(i), mActive == mCrumbs.indexOf(crumb),
i < mCrumbs.size() - 1).setText(crumb.getTitle());
}
}
public void removeCrumbAt(int index) {
mCrumbs.remove(index);
mChildFrame.removeViewAt(index);
}
private void updateIndices() {
for (int i = 0; i < mChildFrame.getChildCount(); i++)
mChildFrame.getChildAt(i).setTag(i);
}
private boolean isValidPath(String path) {
return path == null;
}
public int size() {
return mCrumbs.size();
}
private TextView invalidateActivated(View view, boolean isActive, boolean isShowSeparator) {
LinearLayout child = (LinearLayout) view;
if (isShowSeparator)
child.getChildAt(1).setVisibility(View.VISIBLE);
return (TextView) child.getChildAt(0);
}
public int getActiveIndex() {
return mActive;
}
@Override
public void onClick(View v) {
if (mCallback != null) {
int index = (Integer) v.getTag();
if (index >= 0 && index < (size()-1)) {
setActive(mCrumbs.get(index));
mCallback.onCrumbSelection(mCrumbs.get(index),
getAbsolutePath(mCrumbs.get(index), "/"), mCrumbs.size(), index);
}
}
}
public static class SavedStateWrapper implements Serializable {
public final int mActive;
public final List<Crumb> mCrumbs;
public final int mVisibility;
public SavedStateWrapper(LinearBreadcrumb view) {
mActive = view.mActive;
mCrumbs = view.mCrumbs;
mVisibility = view.getVisibility();
}
}
public SavedStateWrapper getStateWrapper() {
return new SavedStateWrapper(this);
}
public void restoreFromStateWrapper(SavedStateWrapper mSavedState, Activity context) {
if (mSavedState != null) {
mActive = mSavedState.mActive;
for (Crumb c : mSavedState.mCrumbs) {
addCrumb(c, false);
}
requestLayout();
setVisibility(mSavedState.mVisibility);
}
}
public String getAbsolutePath(Crumb crumb, @NonNull String separator) {
StringBuilder builder = new StringBuilder();
if (size() > 1 && !crumb.equals(mCrumbs.get(0))) {
List<Crumb> crumbs = mCrumbs.subList(1, size());
for (Crumb mCrumb : crumbs) {
builder.append(mCrumb.getPath());
builder.append(separator);
if (mCrumb.equals(crumb)) {
break;
}
}
String path = builder.toString();
return path.substring(0, path.length() -1);
} else {
return null;
}
}
public String getCurAbsolutePath(@NonNull String separator){
return getAbsolutePath(getCrumb(mActive),separator);
}
public void addRootCrumb() {
clearCrumbs();
addCrumb(new Crumb("/","root"), true);
}
public void addPath(@NonNull String path,@NonNull String sha, @NonNull String separator) {
clearCrumbs();
addCrumb(new Crumb("",""), false);
String[] paths = path.split(separator);
Crumb lastCrumb = null;
for (String splitPath : paths) {
lastCrumb = new Crumb(splitPath,sha);
addCrumb(lastCrumb, false);
}
if (lastCrumb != null) {
setActive(lastCrumb);
}
}
} | jbm714060/Github | breadcrumb/src/main/java/com/afollestad/breadcrumb/LinearBreadcrumb.java | Java | apache-2.0 | 9,519 |
/*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.orc.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.orc.CompressionKind;
import org.apache.orc.OrcConf;
import org.apache.orc.OrcFile;
import org.apache.orc.Reader;
import org.apache.orc.RecordReader;
import org.apache.orc.TypeDescription;
import org.apache.orc.Writer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestOrcLargeStripe {
private Path workDir = new Path(System.getProperty("test.tmp.dir", "target" + File.separator + "test"
+ File.separator + "tmp"));
Configuration conf;
FileSystem fs;
private Path testFilePath;
@Rule
public TestName testCaseName = new TestName();
@Before
public void openFileSystem() throws Exception {
conf = new Configuration();
fs = FileSystem.getLocal(conf);
testFilePath = new Path(workDir, "TestOrcFile." + testCaseName.getMethodName() + ".orc");
fs.delete(testFilePath, false);
}
@Mock
private FSDataInputStream mockDataInput;
static class RangeBuilder {
BufferChunkList result = new BufferChunkList();
RangeBuilder range(long offset, int length) {
result.add(new BufferChunk(offset, length));
return this;
}
BufferChunkList build() {
return result;
}
}
@Test
public void testZeroCopy() throws Exception {
BufferChunkList ranges = new RangeBuilder().range(1000, 3000).build();
HadoopShims.ZeroCopyReaderShim mockZcr = mock(HadoopShims.ZeroCopyReaderShim.class);
when(mockZcr.readBuffer(anyInt(), anyBoolean()))
.thenAnswer(invocation -> ByteBuffer.allocate(1000));
RecordReaderUtils.readDiskRanges(mockDataInput, mockZcr, ranges, true);
verify(mockDataInput).seek(1000);
verify(mockZcr).readBuffer(3000, false);
verify(mockZcr).readBuffer(2000, false);
verify(mockZcr).readBuffer(1000, false);
}
@Test
public void testRangeMerge() throws Exception {
BufferChunkList rangeList = new RangeBuilder()
.range(100, 1000)
.range(1000, 10000)
.range(3000, 30000).build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput).readFully(eq(100L), any(), eq(0), eq(32900));
}
@Test
public void testRangeSkip() throws Exception {
BufferChunkList rangeList = new RangeBuilder()
.range(1000, 1000)
.range(2000, 1000)
.range(4000, 1000)
.range(4100, 100)
.range(8000, 1000).build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput).readFully(eq(1000L), any(), eq(0), eq(2000));
verify(mockDataInput).readFully(eq(4000L), any(), eq(0), eq(1000));
verify(mockDataInput).readFully(eq(8000L), any(), eq(0), eq(1000));
}
@Test
public void testEmpty() throws Exception {
BufferChunkList rangeList = new RangeBuilder().build();
RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false);
verify(mockDataInput, never()).readFully(anyLong(), any(), anyInt(), anyInt());
}
@Test
public void testConfigMaxChunkLimit() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.getLocal(conf);
TypeDescription schema = TypeDescription.createTimestamp();
testFilePath = new Path(workDir, "TestOrcLargeStripe." +
testCaseName.getMethodName() + ".orc");
fs.delete(testFilePath, false);
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf).setSchema(schema).stripeSize(100000).bufferSize(10000)
.version(OrcFile.Version.V_0_11).fileSystem(fs));
writer.close();
OrcFile.ReaderOptions opts = OrcFile.readerOptions(conf);
Reader reader = OrcFile.createReader(testFilePath, opts);
RecordReader recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE));
assertTrue(recordReader instanceof RecordReaderImpl);
assertEquals(Integer.MAX_VALUE - 1024, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit());
conf = new Configuration();
conf.setInt(OrcConf.ORC_MAX_DISK_RANGE_CHUNK_LIMIT.getHiveConfName(), 1000);
opts = OrcFile.readerOptions(conf);
reader = OrcFile.createReader(testFilePath, opts);
recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE));
assertTrue(recordReader instanceof RecordReaderImpl);
assertEquals(1000, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit());
}
@Test
public void testStringDirectGreaterThan2GB() throws IOException {
final Runtime rt = Runtime.getRuntime();
assumeTrue(rt.maxMemory() > 4_000_000_000L);
TypeDescription schema = TypeDescription.createString();
conf.setDouble("hive.exec.orc.dictionary.key.size.threshold", 0.0);
Writer writer = OrcFile.createWriter(
testFilePath,
OrcFile.writerOptions(conf).setSchema(schema)
.compress(CompressionKind.NONE));
// 5000 is the lower bound for a stripe
int size = 5000;
int width = 500_000;
// generate a random string that is width characters long
Random random = new Random(123);
char[] randomChars= new char[width];
int posn = 0;
for(int length = 0; length < width && posn < randomChars.length; ++posn) {
char cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT);
// make sure we get a valid, non-surrogate
while (Character.isSurrogate(cp)) {
cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT);
}
// compute the length of the utf8
length += cp < 0x80 ? 1 : (cp < 0x800 ? 2 : 3);
randomChars[posn] = cp;
}
// put the random characters in as a repeating value.
VectorizedRowBatch batch = schema.createRowBatch();
BytesColumnVector string = (BytesColumnVector) batch.cols[0];
string.setVal(0, new String(randomChars, 0, posn).getBytes(StandardCharsets.UTF_8));
string.isRepeating = true;
for(int rows=size; rows > 0; rows -= batch.size) {
batch.size = Math.min(rows, batch.getMaxSize());
writer.addRowBatch(batch);
}
writer.close();
try {
Reader reader = OrcFile.createReader(testFilePath,
OrcFile.readerOptions(conf).filesystem(fs));
RecordReader rows = reader.rows();
batch = reader.getSchema().createRowBatch();
int rowsRead = 0;
while (rows.nextBatch(batch)) {
rowsRead += batch.size;
}
assertEquals(size, rowsRead);
} finally {
fs.delete(testFilePath, false);
}
}
}
| omalley/orc | java/core/src/test/org/apache/orc/impl/TestOrcLargeStripe.java | Java | apache-2.0 | 8,450 |
/*
* Solo - A small and beautiful blogging system written in Java.
* Copyright (c) 2010-present, b3log.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.b3log.solo.processor;
import org.apache.commons.lang.StringUtils;
import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.MockHttpServletRequest;
import org.b3log.solo.MockHttpServletResponse;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* {@link ErrorProcessor} test case.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.3, Feb 22, 2019
* @since 1.7.0
*/
@Test(suiteName = "processor")
public class ErrorProcessorTestCase extends AbstractTestCase {
/**
* Init.
*
* @throws Exception exception
*/
@Test
public void init() throws Exception {
super.init();
}
/**
* showErrorPage.
*/
@Test(dependsOnMethods = "init")
public void showErrorPage() {
final MockHttpServletRequest request = mockRequest();
request.setRequestURI("/error/403");
final MockHttpServletResponse response = mockResponse();
mockDispatcherServletService(request, response);
final String content = response.body();
Assert.assertTrue(StringUtils.contains(content, "<title>403 Forbidden! - Solo 的个人博客</title>"));
}
}
| b3log/b3log-solo | src/test/java/org/b3log/solo/processor/ErrorProcessorTestCase.java | Java | apache-2.0 | 1,972 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.impl.cmd;
import java.io.Serializable;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.api.FlowableObjectNotFoundException;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.form.TaskFormData;
import org.flowable.engine.impl.form.FormEngine;
import org.flowable.engine.impl.form.TaskFormHandler;
import org.flowable.engine.impl.persistence.entity.TaskEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.FormHandlerUtil;
import org.flowable.engine.task.Task;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class GetRenderedTaskFormCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String formEngineName;
public GetRenderedTaskFormCmd(String taskId, String formEngineName) {
this.taskId = taskId;
this.formEngineName = formEngineName;
}
public Object execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("Task id should not be null");
}
TaskEntity task = CommandContextUtil.getTaskEntityManager(commandContext).findById(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Task '" + taskId + "' not found", Task.class);
}
TaskFormHandler taskFormHandler = FormHandlerUtil.getTaskFormHandlder(task);
if (taskFormHandler != null) {
FormEngine formEngine = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormEngines().get(formEngineName);
if (formEngine == null) {
throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration");
}
TaskFormData taskForm = taskFormHandler.createTaskForm(task);
return formEngine.renderTaskForm(taskForm);
}
return null;
}
}
| stephraleigh/flowable-engine | modules/flowable-engine/src/main/java/org/flowable/engine/impl/cmd/GetRenderedTaskFormCmd.java | Java | apache-2.0 | 2,774 |
package com.stdnull.v2api.model;
import android.os.Bundle;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chen on 2017/8/20.
*/
public class V2MainFragModel {
private static final String KEY_V2EXBEAN = "KEY_V2EXBEAN";
private List<V2ExBean> mContentListModel = new ArrayList<>();
public List<V2ExBean> getContentListModel() {
return mContentListModel;
}
public void addContentListModel(List<V2ExBean> contentListModel) {
if(contentListModel != null) {
this.mContentListModel.addAll(contentListModel);
}
}
public boolean isModelEmpty(){
return mContentListModel.isEmpty() ;
}
public void clearModel(){
mContentListModel.clear();
}
public void save(Bundle bundle){
bundle.putParcelableArrayList(KEY_V2EXBEAN, (ArrayList<? extends Parcelable>) mContentListModel);
}
public boolean restore(Bundle bundle){
if(bundle == null){
return false;
}
mContentListModel = bundle.getParcelableArrayList(KEY_V2EXBEAN);
return mContentListModel != null && !mContentListModel.isEmpty();
}
}
| stdnull/RunMap | v2api/src/main/java/com/stdnull/v2api/model/V2MainFragModel.java | Java | apache-2.0 | 1,194 |
/*
* Solo - A small and beautiful blogging system written in Java.
* Copyright (c) 2010-present, b3log.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.b3log.solo.model;
/**
* This class defines all link model relevant keys.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.2, Oct 31, 2011
* @since 0.3.1
*/
public final class Link {
/**
* Link.
*/
public static final String LINK = "link";
/**
* Links.
*/
public static final String LINKS = "links";
/**
* Key of title.
*/
public static final String LINK_TITLE = "linkTitle";
/**
* Key of address.
*/
public static final String LINK_ADDRESS = "linkAddress";
/**
* Key of description.
*/
public static final String LINK_DESCRIPTION = "linkDescription";
/**
* Key of order.
*/
public static final String LINK_ORDER = "linkOrder";
/**
* Private constructor.
*/
private Link() {
}
}
| b3log/b3log-solo | src/main/java/org/b3log/solo/model/Link.java | Java | apache-2.0 | 1,646 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.management;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.TabularData;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.util.StringHelper;
import org.junit.Ignore;
/**
* @version
*/
public class ManagedCamelContextTest extends ManagementTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
// to force a different management name than the camel id
context.getManagementNameStrategy().setNamePattern("19-#name#");
return context;
}
public void testManagedCamelContext() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertTrue("Should be registered", mbeanServer.isRegistered(on));
String name = (String) mbeanServer.getAttribute(on, "CamelId");
assertEquals("camel-1", name);
String managementName = (String) mbeanServer.getAttribute(on, "ManagementName");
assertEquals("19-camel-1", managementName);
String uptime = (String) mbeanServer.getAttribute(on, "Uptime");
assertNotNull(uptime);
String status = (String) mbeanServer.getAttribute(on, "State");
assertEquals("Started", status);
Boolean messageHistory = (Boolean) mbeanServer.getAttribute(on, "MessageHistory");
assertEquals(Boolean.TRUE, messageHistory);
Integer total = (Integer) mbeanServer.getAttribute(on, "TotalRoutes");
assertEquals(2, total.intValue());
Integer started = (Integer) mbeanServer.getAttribute(on, "StartedRoutes");
assertEquals(2, started.intValue());
// invoke operations
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mbeanServer.invoke(on, "sendBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"});
assertMockEndpointsSatisfied();
resetMocks();
mock.expectedBodiesReceived("Hello World");
mbeanServer.invoke(on, "sendStringBody", new Object[]{"direct:start", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"});
assertMockEndpointsSatisfied();
Object reply = mbeanServer.invoke(on, "requestBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.Object"});
assertEquals("Bye World", reply);
reply = mbeanServer.invoke(on, "requestStringBody", new Object[]{"direct:foo", "Hello World"}, new String[]{"java.lang.String", "java.lang.String"});
assertEquals("Bye World", reply);
resetMocks();
mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("foo", 123);
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("foo", 123);
mbeanServer.invoke(on, "sendBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"});
assertMockEndpointsSatisfied();
resetMocks();
mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("foo", 123);
reply = mbeanServer.invoke(on, "requestBodyAndHeaders", new Object[]{"direct:start", "Hello World", headers}, new String[]{"java.lang.String", "java.lang.Object", "java.util.Map"});
assertEquals("Hello World", reply);
assertMockEndpointsSatisfied();
// test can send
Boolean can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"direct:start"}, new String[]{"java.lang.String"});
assertEquals(true, can.booleanValue());
can = (Boolean) mbeanServer.invoke(on, "canSendToEndpoint", new Object[]{"timer:foo"}, new String[]{"java.lang.String"});
assertEquals(false, can.booleanValue());
// stop Camel
mbeanServer.invoke(on, "stop", null, null);
}
public void testManagedCamelContextCreateEndpoint() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertNull(context.hasEndpoint("seda:bar"));
// create a new endpoint
Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.TRUE, reply);
assertNotNull(context.hasEndpoint("seda:bar"));
ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\"");
boolean registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
// create it again
reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.FALSE, reply);
registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
}
public void testManagedCamelContextRemoveEndpoint() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertNull(context.hasEndpoint("seda:bar"));
// create a new endpoint
Object reply = mbeanServer.invoke(on, "createEndpoint", new Object[]{"seda:bar"}, new String[]{"java.lang.String"});
assertEquals(Boolean.TRUE, reply);
assertNotNull(context.hasEndpoint("seda:bar"));
ObjectName seda = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=endpoints,name=\"seda://bar\"");
boolean registered = mbeanServer.isRegistered(seda);
assertTrue("Should be registered " + seda, registered);
// remove it
Object num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"});
assertEquals(1, num);
assertNull(context.hasEndpoint("seda:bar"));
registered = mbeanServer.isRegistered(seda);
assertFalse("Should not be registered " + seda, registered);
// remove it again
num = mbeanServer.invoke(on, "removeEndpoints", new Object[]{"seda:*"}, new String[]{"java.lang.String"});
assertEquals(0, num);
assertNull(context.hasEndpoint("seda:bar"));
registered = mbeanServer.isRegistered(seda);
assertFalse("Should not be registered " + seda, registered);
}
public void testFindComponentsInClasspath() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
assertTrue("Should be registered", mbeanServer.isRegistered(on));
@SuppressWarnings("unchecked")
Map<String, Properties> info = (Map<String, Properties>) mbeanServer.invoke(on, "findComponents", null, null);
assertNotNull(info);
assertTrue(info.size() > 20);
Properties prop = info.get("seda");
assertNotNull(prop);
assertEquals("seda", prop.get("name"));
assertEquals("org.apache.camel", prop.get("groupId"));
assertEquals("camel-core", prop.get("artifactId"));
}
public void testManagedCamelContextCreateRouteStaticEndpointJson() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "createRouteStaticEndpointJson", null, null);
assertNotNull(json);
assertEquals(7, StringHelper.countChar(json, '{'));
assertEquals(7, StringHelper.countChar(json, '}'));
assertTrue(json.contains("{ \"uri\": \"direct://start\" }"));
assertTrue(json.contains("{ \"uri\": \"direct://foo\" }"));
}
public void testManagedCamelContextExplainEndpointUri() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "explainEndpointJson", new Object[]{"log:foo?groupDelay=2000&groupSize=5", false},
new String[]{"java.lang.String", "boolean"});
assertNotNull(json);
assertEquals(5, StringHelper.countChar(json, '{'));
assertEquals(5, StringHelper.countChar(json, '}'));
assertTrue(json.contains("\"groupDelay\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Long\", \"deprecated\": \"false\", \"value\": \"2000\","
+ " \"description\": \"Set the initial delay for stats (in millis)\" },"));
assertTrue(json.contains("\"groupSize\": { \"kind\": \"parameter\", \"type\": \"integer\", \"javaType\": \"java.lang.Integer\", \"deprecated\": \"false\", \"value\": \"5\","
+ " \"description\": \"An integer that specifies a group size for throughput logging.\" }"));
assertTrue(json.contains("\"loggerName\": { \"kind\": \"path\", \"type\": \"string\", \"javaType\": \"java.lang.String\", \"deprecated\": \"false\","
+ " \"value\": \"foo\", \"description\": \"The logger name to use\" }"));
}
public void testManagedCamelContextExplainEip() throws Exception {
// JMX tests dont work well on AIX CI servers (hangs them)
if (isPlatform("aix")) {
return;
}
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=19-camel-1,type=context,name=\"camel-1\"");
// get the json
String json = (String) mbeanServer.invoke(on, "explainEipJson", new Object[]{"transform", false}, new String[]{"java.lang.String", "boolean"});
assertNotNull(json);
assertTrue(json.contains("\"label\": \"transformation\""));
assertTrue(json.contains("\"expression\": { \"kind\": \"element\", \"required\": \"true\", \"type\": \"object\""));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("mock:result");
from("direct:foo").transform(constant("Bye World"));
}
};
}
}
| logzio/camel | camel-core/src/test/java/org/apache/camel/management/ManagedCamelContextTest.java | Java | apache-2.0 | 12,715 |
/*
* 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.search.aggregations.metrics.stats;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.SearchContext;
import java.io.IOException;
import java.util.Map;
public class StatsAggregationBuilder extends ValuesSourceAggregationBuilder.LeafOnly<ValuesSource.Numeric, StatsAggregationBuilder> {
public static final String NAME = "stats";
private static final ObjectParser<StatsAggregationBuilder, Void> PARSER;
static {
PARSER = new ObjectParser<>(StatsAggregationBuilder.NAME);
ValuesSourceParserHelper.declareNumericFields(PARSER, true, true, false);
}
public static AggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException {
return PARSER.parse(parser, new StatsAggregationBuilder(aggregationName), null);
}
public StatsAggregationBuilder(String name) {
super(name, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
protected StatsAggregationBuilder(StatsAggregationBuilder clone,
Builder factoriesBuilder, Map<String, Object> metaData) {
super(clone, factoriesBuilder, metaData);
}
@Override
public AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metaData) {
return new StatsAggregationBuilder(this, factoriesBuilder, metaData);
}
/**
* Read from a stream.
*/
public StatsAggregationBuilder(StreamInput in) throws IOException {
super(in, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
@Override
protected void innerWriteTo(StreamOutput out) {
// Do nothing, no extra state to write to stream
}
@Override
protected StatsAggregatorFactory innerBuild(SearchContext context, ValuesSourceConfig<Numeric> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
return new StatsAggregatorFactory(name, config, context, parent, subFactoriesBuilder, metaData);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
return builder;
}
@Override
protected int innerHashCode() {
return 0;
}
@Override
protected boolean innerEquals(Object obj) {
return true;
}
@Override
public String getType() {
return NAME;
}
}
| jprante/elasticsearch-server | server/src/main/java/org/elasticsearch/search/aggregations/metrics/stats/StatsAggregationBuilder.java | Java | apache-2.0 | 4,154 |
package jenkins.plugins.hygieia;
public class DefaultHygieiaServiceStub extends DefaultHygieiaService {
// private HttpClientStub httpClientStub;
public DefaultHygieiaServiceStub(String host, String token, String name) {
super(host, token, name);
}
// @Override
// public HttpClientStub getHttpClient() {
// return httpClientStub;
// }
// public void setHttpClient(HttpClientStub httpClientStub) {
// this.httpClientStub = httpClientStub;
// }
}
| tabladrum/hygieia-jenkins-plugin | src/test/java/jenkins/plugins/hygieia/DefaultHygieiaServiceStub.java | Java | apache-2.0 | 499 |
package cn.aezo.demo.rabbitmq.c05_model_topic;
import cn.aezo.demo.rabbitmq.util.RabbitmqU;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
/**
* 测试 topic 类型消息模型
*
* 结果如下:
* consumer1收到消息:[aezo.order.vip] 这是 0 条消息
* consumer2收到消息:[smalle.vip] 这是 2 条消息
* consumer1收到消息:[aezo.user] 这是 1 条消息
* consumer1收到消息:[smalle.vip] 这是 2 条消息
* consumer1收到消息:[aezo.order.vip] 这是 3 条消息
* consumer1收到消息:[aezo.user] 这是 4 条消息
*
* @author smalle
* @date 2020-08-29 16:31
*/
public class Consumer {
private static final String EXCHANGE_NAME = "topic_logs";
public static void main(String[] args) throws IOException {
consumer1();
consumer2();
}
public static void consumer1() throws IOException {
Connection connection = RabbitmqU.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
// 获取一个临时队列。管理后台的Queues-Features会增加"AD"(autoDelete)和"Excl"(exclusive)标识
String queueName = channel.queueDeclare().getQueue();
// **将临时队列和交换机绑定,并订阅某些类型的消息**
channel.queueBind(queueName, EXCHANGE_NAME, "aezo.#"); // *匹配一个单词,#匹配多个单词
channel.queueBind(queueName, EXCHANGE_NAME, "*.vip");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer1收到消息:" + new String(body, "UTF-8"));
}
});
}
public static void consumer2() throws IOException {
Connection connection = RabbitmqU.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
// * 表示一个单词。此时无法匹配 aezo.order.vip 和 aezo.vip.hello 等
channel.queueBind(queueName, EXCHANGE_NAME, "*.vip");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumer2收到消息:" + new String(body, "UTF-8"));
}
});
}
}
| oldinaction/smjava | rabbitmq/src/main/java/cn/aezo/demo/rabbitmq/c05_model_topic/Consumer.java | Java | apache-2.0 | 2,828 |
/*
* Copyright 2016 The Simple File Server Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sfs.integration.java;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.logging.Logger;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.sfs.RunBootedTestOnContextRx;
import org.sfs.Server;
import org.sfs.TestSubscriber;
import org.sfs.VertxContext;
import rx.Observable;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import static io.vertx.core.logging.LoggerFactory.getLogger;
@RunWith(VertxUnitRunner.class)
public class BaseTestVerticle {
private static final Logger LOGGER = getLogger(BaseTestVerticle.class);
@Rule
public RunBootedTestOnContextRx runTestOnContext = new RunBootedTestOnContextRx();
public VertxContext<Server> vertxContext() {
return runTestOnContext.getVertxContext();
}
public HttpClient httpClient() {
return runTestOnContext.getHttpClient();
}
public Vertx vertx() {
return vertxContext().vertx();
}
public Path tmpDir() {
return runTestOnContext.getTmpDir();
}
public void runOnServerContext(TestContext testContext, RunnableWithException callable) {
Async async = testContext.async();
Context c = vertxContext().verticle().getContext();
c.runOnContext(event -> {
try {
callable.run();
async.complete();
} catch (Exception e) {
testContext.fail(e);
}
});
}
public void runOnServerContext(TestContext testContext, Callable<Observable<Void>> callable) {
Async async = testContext.async();
Context c = vertxContext().verticle().getContext();
c.runOnContext(event -> {
try {
callable.call().subscribe(new TestSubscriber(testContext, async));
} catch (Exception e) {
testContext.fail(e);
}
});
}
public interface RunnableWithException {
void run() throws Exception;
}
}
| pitchpoint-solutions/sfs | sfs-server/src/test/java/org/sfs/integration/java/BaseTestVerticle.java | Java | apache-2.0 | 2,779 |
/*
* Core Utils - Common Utilities.
* Copyright 2015-2016 GRyCAP (Universitat Politecnica de Valencia)
*
* 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 product combines work with different licenses. See the "NOTICE" text
* file for details on the various modules and licenses.
*
* The "NOTICE" text file is part of the distribution. Any derivative works
* that you distribute must include a readable copy of the "NOTICE" text file.
*/
package es.upv.grycap.coreutils.common;
import com.google.common.collect.Range;
/**
* Hard-coded configuration limits.
* @author Erik Torres
* @since 0.2.0
*/
public interface CoreutilsLimits {
public static final int NUM_AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
public static final Range<Long> TRY_LOCK_TIMEOUT_RANGE = Range.closed(1l, 2000l);
public static final Range<Integer> MAX_POOL_SIZE_RANGE = Range.closed(Math.min(2, NUM_AVAILABLE_PROCESSORS), Math.max(128, NUM_AVAILABLE_PROCESSORS));
public static final Range<Long> KEEP_ALIVE_TIME_RANGE = Range.closed(60000l, 3600000l);
public static final Range<Long> WAIT_TERMINATION_TIMEOUT_RANGE = Range.closed(1000l, 60000l);
} | grycap/coreutils | coreutils-common/src/main/java/es/upv/grycap/coreutils/common/CoreutilsLimits.java | Java | apache-2.0 | 1,687 |
/*
* Copyright (c) 2016 Ni YueMing<niyueming@163.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 net.nym.napply.library.cookie.store;
/**
* Created by zhy on 16/3/10.
*/
public interface HasCookieStore
{
CookieStore getCookieStore();
}
| niyueming/NApply | library/src/main/java/net/nym/napply/library/cookie/store/HasCookieStore.java | Java | apache-2.0 | 754 |
/*
* Copyright 2012-2017 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.kinesisfirehose.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ProcessingConfiguration JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProcessingConfigurationJsonUnmarshaller implements Unmarshaller<ProcessingConfiguration, JsonUnmarshallerContext> {
public ProcessingConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
ProcessingConfiguration processingConfiguration = new ProcessingConfiguration();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Enabled", targetDepth)) {
context.nextToken();
processingConfiguration.setEnabled(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("Processors", targetDepth)) {
context.nextToken();
processingConfiguration.setProcessors(new ListUnmarshaller<Processor>(ProcessorJsonUnmarshaller.getInstance()).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return processingConfiguration;
}
private static ProcessingConfigurationJsonUnmarshaller instance;
public static ProcessingConfigurationJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ProcessingConfigurationJsonUnmarshaller();
return instance;
}
}
| dagnir/aws-sdk-java | aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/transform/ProcessingConfigurationJsonUnmarshaller.java | Java | apache-2.0 | 3,132 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonCallableFactory;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshotCallable;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.Operation;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST callable factory implementation for the Routes service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
@BetaApi
public class HttpJsonRoutesCallableFactory
implements HttpJsonStubCallableFactory<Operation, GlobalOperationsStub> {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createUnaryCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createPagedCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createBatchingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
HttpJsonCallSettings<RequestT, Operation> httpJsonCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
GlobalOperationsStub operationsStub) {
UnaryCallable<RequestT, Operation> innerCallable =
HttpJsonCallableFactory.createBaseUnaryCallable(
httpJsonCallSettings, callSettings.getInitialCallSettings(), clientContext);
HttpJsonOperationSnapshotCallable<RequestT, Operation> initialCallable =
new HttpJsonOperationSnapshotCallable<RequestT, Operation>(
innerCallable,
httpJsonCallSettings.getMethodDescriptor().getOperationSnapshotFactory());
return HttpJsonCallableFactory.createOperationCallable(
callSettings, clientContext, operationsStub.longRunningClient(), initialCallable);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createServerStreamingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
}
| googleapis/java-compute | google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonRoutesCallableFactory.java | Java | apache-2.0 | 4,575 |
/*
Copyright 2013 Semantic Discovery, Inc. (www.semanticdiscovery.com)
This file is part of the Semantic Discovery Toolkit.
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sd.token;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.sd.nlp.NormalizedString;
/**
* An nlp.NormalizedString implementation based on this package's tokenization.
* <p>
* @author Spence Koehler
*/
public class TokenizerNormalizedString implements NormalizedString {
private TokenizerBasedNormalizer normalizer;
private StandardTokenizer tokenizer;
private boolean lowerCaseFlag;
private boolean computed;
private Normalization _normalization;
/**
* Construct with default case-sensitive settings.
*/
public TokenizerNormalizedString(String string) {
this(TokenizerBasedNormalizer.CASE_SENSITIVE_INSTANCE, new StandardTokenizer(string, TokenizerBasedNormalizer.DEFAULT_TOKENIZER_OPTIONS), false);
}
/**
* Construct with the given settings.
*/
public TokenizerNormalizedString(TokenizerBasedNormalizer normalizer, StandardTokenizer tokenizer, boolean lowerCaseFlag) {
this.normalizer = normalizer;
this.tokenizer = tokenizer;
this.lowerCaseFlag = lowerCaseFlag;
this.computed = false;
reset();
}
public StandardTokenizer getTokenizer() {
return tokenizer;
}
public void setLowerCaseFlag(boolean lowerCaseFlag) {
if (lowerCaseFlag != this.lowerCaseFlag) {
this.lowerCaseFlag = lowerCaseFlag;
reset();
}
}
public boolean getLowerCaseFlag() {
return lowerCaseFlag;
}
/**
* Set a flag indicating whether to split on camel-casing.
*/
public void setSplitOnCamelCase(boolean splitOnCamelCase) {
final Break curBreak = tokenizer.getOptions().getLowerUpperBreak();
final Break nextBreak = splitOnCamelCase ? Break.ZERO_WIDTH_SOFT_BREAK : Break.NO_BREAK;
if (curBreak != nextBreak) {
final StandardTokenizerOptions newOptions = new StandardTokenizerOptions(tokenizer.getOptions());
newOptions.setLowerUpperBreak(nextBreak);
this.tokenizer = new StandardTokenizer(tokenizer.getText(), newOptions);
reset();
}
}
private final void reset() {
this.computed = false;
}
/**
* Get the flag indicating whether to split on camel-casing.
*/
public boolean getSplitOnCamelCase() {
return tokenizer.getOptions().getLowerUpperBreak() != Break.NO_BREAK;
}
/**
* Get the length of the normalized string.
*/
public int getNormalizedLength() {
return getNormalized().length();
}
/**
* Get the normalized string.
* <p>
* Note that the normalized string may apply to only a portion of the full
* original string.
*/
public String getNormalized() {
return getNormalization().getNormalized();
}
public String toString() {
return getNormalized();
}
/**
* Get the normalized string from the start (inclusive) to end (exclusive).
* <p>
* Note that the normalized string may apply to only a portion of the full
* original string.
*/
public String getNormalized(int startPos, int endPos) {
return getNormalized().substring(startPos, endPos);
}
/**
* Get the original string that applies to the normalized string.
*/
public String getOriginal() {
return tokenizer.getText();
}
/**
* Get the original string that applies to the normalized string from the
* given index for the given number of normalized characters.
*/
public String getOriginal(int normalizedStartIndex, int normalizedLength) {
final int origStartIdx = getOriginalIndex(normalizedStartIndex);
final int origEndIdx = getOriginalIndex(normalizedStartIndex + normalizedLength);
return getOriginal().substring(origStartIdx, origEndIdx);
}
/**
* Get the index in the original string corresponding to the normalized index.
*/
public int getOriginalIndex(int normalizedIndex) {
final Integer result = getNormalization().getOriginalIndex(normalizedIndex);
return result == null ? -1 : result;
}
/**
* Get a new normalized string for the portion of this normalized string
* preceding the normalized start index (exclusive). Remove extra whitespace
* at the end of the returned string. Ensure that the returned string ends
* on an end token boundary.
*
* @return the preceding normalized string or null if empty (after skipping white).
*/
public NormalizedString getPreceding(int normalizedStartIndex) {
return getPreceding(normalizedStartIndex, true);
}
/**
* Get a new normalized string for the portion of this normalized string
* preceding the normalized start index (exclusive). Remove extra whitespace
* at the end of the returned string.
*
* @param normalizedStartIndex a token start position in the normalized string beyond the result
* @param checkEndBreak when true, skip back over non breaking chars to ensure result ends at a break.
*
* @return the preceding normalized string or null if empty (after skipping white).
*/
public NormalizedString getPreceding(int normalizedStartIndex, boolean checkEndBreak) {
NormalizedString result = null;
final int origIdx = getOriginalIndex(normalizedStartIndex);
if (origIdx >= 0) {
final Token token = tokenizer.getToken(origIdx);
if (token != null) {
final String priorText =
checkEndBreak ? tokenizer.getPriorText(token) :
tokenizer.getText().substring(0, token.getStartIndex()).trim();
if (!"".equals(priorText)) {
result = normalizer.normalize(priorText);
}
}
}
return result;
}
/**
* Find the (normalized) index of the nth token preceding the normalizedPos.
* <p>
* If normalizedPos is -1, start from the end of the string.
* If the beginning of the string is fewer than numTokens prior to normalizedPos,
* return the beginning of the string.
*/
public int getPrecedingIndex(int normalizedPos, int numTokens) {
int result = normalizedPos < 0 ? getNormalization().getNormalizedLength() : normalizedPos;
// skip back to the numTokens-th start break.
int numStarts = 0;
for (; result > 0 && numStarts < numTokens; result = findPrecedingTokenStart(result)) {
++numStarts;
}
return result;
}
/**
* Find the start of the token before the normalizedPos.
* <p>
* If normalizedPos is at a token start, the prior token (or -1 if there is
* no prior token) will be returned; otherwise, the start of the token of
* which normalizedPos is a part will be returned.
*/
public int findPrecedingTokenStart(int normalizedPos) {
final Integer priorStart = getNormalization().getBreaks().lower(normalizedPos);
return priorStart == null ? -1 : priorStart;
}
/**
* Get a new normalized string for the portion of this normalized string
* following the normalized start index (inclusive). Remove extra whitespace
* at the beginning of the returned string.
*
* @return the following normalized string or null if empty (after skipping white).
*/
public NormalizedString getRemaining(int normalizedStartIndex) {
NormalizedString result = null;
final int origIdx = getOriginalIndex(normalizedStartIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origIdx < origLen) {
final String remainingText = origText.substring(origIdx).trim();
if (!"".equals(remainingText)) {
result = normalizer.normalize(remainingText);
}
}
}
return result;
}
/**
* Build a normalized string from this using the given normalized index range.
*/
public NormalizedString buildNormalizedString(int normalizedStartIndex, int normalizedEndIndex) {
NormalizedString result = null;
final int origStartIdx = getOriginalIndex(normalizedStartIndex);
if (origStartIdx >= 0) {
final int origEndIdx = getOriginalIndex(normalizedEndIndex);
if (origEndIdx > origStartIdx) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origStartIdx < origLen) {
final String string = origText.substring(origStartIdx, Math.min(origEndIdx, origLen));
result = normalizer.normalize(string);
}
}
}
return result;
}
/**
* Lowercase the normalized form in this instance.
*
* @return this instance.
*/
public NormalizedString toLowerCase() {
getNormalization().toLowerCase();
return this;
}
/**
* Get the normalized string's chars.
*/
public char[] getNormalizedChars() {
return getNormalization().getNormalizedChars();
}
/**
* Get the normalized char at the given (normalized) index.
* <p>
* NOTE: Bounds checking is left up to the caller.
*/
public char getNormalizedChar(int index) {
return getNormalization().getNormalizedChars()[index];
}
/**
* Get the original code point corresponding to the normalized char at the
* (normalized) index.
* <p>
* NOTE: Bounds checking is left up to the caller.
*/
public int getOriginalCodePoint(int nIndex) {
int result = 0;
final int origIdx = getOriginalIndex(nIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
if (origIdx < origLen) {
result = origText.codePointAt(origIdx);
}
}
return result;
}
/**
* Determine whether the original character corresponding to the normalized
* index is a letter or digit.
*/
public boolean isLetterOrDigit(int nIndex) {
return Character.isLetterOrDigit(getOriginalCodePoint(nIndex));
}
/**
* Get the ORIGINAL index of the first symbol (non-letter, digit, or white
* character) prior to the NORMALIZED index in the full original string.
*
* @return -1 if no symbol is found or the index of the found symbol in the
* original input string.
*/
public int findPreviousSymbolIndex(int nIndex) {
int result = -1;
final int origIdx = getOriginalIndex(nIndex);
if (origIdx >= 0) {
final String origText = tokenizer.getText();
final int origLen = origText.length();
for (result = Math.min(origIdx, origLen) - 1; result >= 0; --result) {
final int cp = origText.codePointAt(result);
if (cp != ' ' && !Character.isLetterOrDigit(cp)) break;
}
}
return result;
}
/**
* Determine whether the normalized string has a digit between the normalized
* start (inclusive) and end (exclusive).
*/
public boolean hasDigit(int nStartIndex, int nEndIndex) {
boolean result = false;
final char[] nchars = getNormalization().getNormalizedChars();
nEndIndex = Math.min(nEndIndex, nchars.length);
for (int idx = Math.max(nStartIndex, 0); idx < nEndIndex; ++idx) {
final char c = nchars[idx];
if (c <= '9' && c >= '0') {
result = true;
break;
}
}
return result;
}
/**
* Count the number of normalized words in the given range.
*/
public int numWords(int nStartIndex, int nEndIndex) {
int result = 0;
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
nEndIndex = Math.min(nEndIndex, nLen);
for (int idx = Math.max(nStartIndex, 0); idx < nEndIndex && idx >= 0; idx = breaks.higher(idx)) {
if (idx == nEndIndex - 1) break; // nEndIdex as at the beginning of a word -- doesn't count
++result;
}
return result;
}
/**
* Determine whether there is a break before the normalized startIndex.
*/
public boolean isStartBreak(int startIndex) {
return getNormalization().isBreak(startIndex - 1);
}
/**
* Determine whether there is a break after the normalized endIndex.
*/
public boolean isEndBreak(int endIndex) {
return getNormalization().isBreak(endIndex + 1);
}
/**
* Get (first) the normalized index that best corresponds to the original index.
*/
public int getNormalizedIndex(int originalIndex) {
return getNormalization().getNormalizedIndex(originalIndex);
}
/**
* Split into normalized token strings.
*/
public String[] split() {
return getNormalization().getNormalized().split("\\s+");
}
/**
* Split into normalized token strings, removing stopwords.
*/
public String[] split(Set<String> stopwords) {
final List<String> result = new ArrayList<String>();
for (NormalizedToken token = getToken(0, true); token != null; token = token.getNext(true)) {
final String ntoken = token.getNormalized();
if (stopwords == null || !stopwords.contains(ntoken)) {
result.add(ntoken);
}
}
return result.toArray(new String[result.size()]);
}
/**
* Split this normalized string into tokens.
*/
public NormalizedToken[] tokenize() {
final List<NormalizedToken> result = new ArrayList<NormalizedToken>();
for (NormalizedToken token = getToken(0, true); token != null; token = token.getNext(true)) {
result.add(token);
}
return result.toArray(new NormalizedToken[result.size()]);
}
/**
* Get the token starting from the start position, optionally skipping to a
* start break first.
*
* @return the token or null if there are no tokens to get.
*/
public NormalizedToken getToken(int startPos, boolean skipToBreak) {
NormalizedToken result = null;
startPos = getTokenStart(startPos, skipToBreak);
if (startPos < getNormalization().getNormalizedLength()) {
final int endPos = getTokenEnd(startPos);
result = new NormalizedToken(this, startPos, endPos);
}
return result;
}
/**
* Get the token after the given token, optionally skipping to a start
* break first.
*/
public NormalizedToken getNextToken(NormalizedToken curToken, boolean skipToBreak) {
NormalizedToken result = null;
if (curToken != null) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
int curEndPos = curToken.getEndPos();
if (skipToBreak && !normalization.isBreak(curEndPos)) {
final Integer nextBreak = breaks.higher(curEndPos);
curEndPos = (nextBreak == null) ? nLen : nextBreak;
}
if (curEndPos < nLen) {
final int startPos = getTokenStart(curEndPos + 1, true);
if (startPos < nLen) {
final int nextEndPos = getTokenEnd(startPos);
result = new NormalizedToken(this, startPos, nextEndPos);
}
}
}
return result;
}
/**
* Get the normalized token start pos at or after (normalized) startPos
* after optionally skipping to a token start position (if not already
* at one.)
*/
private final int getTokenStart(int startPos, boolean skipToBreak) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
if (skipToBreak && !isStartBreak(startPos)) {
final Integer nextBreak = breaks.ceiling(startPos);
startPos = nextBreak == null ? nLen : nextBreak + 1;
}
return startPos;
}
/**
* Get the normalized index just after the token starting at (normalized) startPos.
*/
private final int getTokenEnd(int startPos) {
final Normalization normalization = getNormalization();
final TreeSet<Integer> breaks = normalization.getBreaks();
final int nLen = normalization.getNormalizedLength();
final Integer endPos = breaks.higher(startPos);
return endPos == null ? nLen : endPos;
}
protected final Normalization getNormalization() {
if (!computed) {
computeNormalization();
}
return _normalization;
}
private final void computeNormalization() {
this._normalization = buildNewNormalization(tokenizer, lowerCaseFlag);
for (Token token = tokenizer.getToken(0); token != null; token = token.getNextToken()) {
_normalization.updateWithToken(token);
}
this.computed = true;
}
protected Normalization buildNewNormalization(StandardTokenizer tokenizer, boolean lowerCaseFlag) {
return new Normalization(tokenizer, lowerCaseFlag);
}
public static class Normalization {
private StandardTokenizer tokenizer;
private boolean lowerCaseFlag;
private StringBuilder normalized;
private Map<Integer, Integer> norm2orig;
private TreeSet<Integer> breaks;
private char[] _nchars;
public Normalization(StandardTokenizer tokenizer, boolean lowerCaseFlag) {
this.tokenizer = tokenizer;
this.lowerCaseFlag = lowerCaseFlag;
this.normalized = new StringBuilder();
this.norm2orig = new HashMap<Integer, Integer>();
this.breaks = new TreeSet<Integer>();
this._nchars = null;
}
public final StandardTokenizer getTokenizer() {
return tokenizer;
}
public final boolean getLowerCaseFlag() {
return lowerCaseFlag;
}
/** Get original input. */
public final String getInput() {
return tokenizer.getText();
}
/** Get the normalized string. */
public final String getNormalized() {
return normalized.toString();
}
public final char[] getNormalizedChars() {
if (_nchars == null) {
_nchars = normalized.toString().toCharArray();
}
return _nchars;
}
public final int getNormalizedLength() {
return normalized.length();
}
public final int getOriginalIndex(int normalizedIndex) {
final Integer result =
(normalizedIndex == normalized.length()) ?
tokenizer.getText().length() :
norm2orig.get(normalizedIndex);
return result == null ? -1 : result;
}
public final int getNormalizedIndex(int originalIndex) {
int result = -1;
for (Map.Entry<Integer, Integer> entry : norm2orig.entrySet()) {
final int normIdx = entry.getKey();
final int origIdx = entry.getValue();
if (originalIndex == origIdx) {
// maps to normalized char
result = normIdx;
break;
}
else if (originalIndex > origIdx) {
// maps back to normalized white (break)
result = normIdx - 1;
break;
}
}
return result;
}
/**
* Determine whether there is a break at the given index.
*/
public final boolean isBreak(int normalizedIndex) {
return !norm2orig.containsKey(normalizedIndex);
}
/** Get the normalized break positions (not including string start or end). */
public final TreeSet<Integer> getBreaks() {
return breaks;
}
/** Lowercase this instance's normalized chars. */
public final void toLowerCase() {
final String newNorm = normalized.toString().toLowerCase();
this.normalized.setLength(0);
this.normalized.append(newNorm);
this._nchars = null;
}
/**
* Build the next normalized chars from the given token using
* the "appendX" method calls.
*/
protected void updateWithToken(Token token) {
final String tokenText = lowerCaseFlag ? token.getText().toLowerCase() : token.getText();
appendNormalizedText(token.getStartIndex(), tokenText, true);
}
/**
* Append each normalized character originally starting at startIdx.
*/
protected final void appendNormalizedText(int startIdx, String normalizedTokenText) {
appendNormalizedText(startIdx, normalizedTokenText, true);
}
/**
* Append each normalized character originally starting at startIdx.
*/
protected final void appendNormalizedText(int startIdx, String normalizedTokenText, boolean addWhite) {
final int len = normalizedTokenText.length();
for (int i = 0; i < len; ++i) {
final char c = normalizedTokenText.charAt(i);
appendNormalizedChar(startIdx++, c, addWhite && i == 0);
}
}
/**
* Append the normalized character originally starting at origIdx.
*/
protected final void appendNormalizedChar(int origIdx, char c, boolean addWhite) {
int normIdx = normalized.length();
if (normIdx > 0 && addWhite) {
normalized.append(' ');
breaks.add(normIdx++);
}
norm2orig.put(normIdx, origIdx);
normalized.append(c);
_nchars = null;
}
/**
* Append the normalized characters all expanding from the originalIdx.
*/
protected final void appendExpandedText(int origIdx, String chars) {
appendExpandedText(origIdx, chars, true);
}
/**
* Append the normalized characters all expanding from the originalIdx.
*/
protected final void appendExpandedText(int origIdx, String chars, boolean addWhite) {
final int len = chars.length();
for (int i = 0; i < chars.length(); ++i) {
final char c = chars.charAt(i);
appendNormalizedChar(origIdx, c, addWhite && i == 0);
}
}
}
}
| KoehlerSB747/sd-tools | src/main/java/org/sd/token/TokenizerNormalizedString.java | Java | apache-2.0 | 22,049 |
package lodVader.spring.REST.models.degree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import org.junit.Test;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import lodVader.mongodb.DBSuperClass2;
import lodVader.mongodb.collections.DatasetDB;
import lodVader.mongodb.collections.DatasetLinksetDB;
import lodVader.mongodb.collections.LinksetDB;
import lodVader.mongodb.collections.ResourceDB;
public class IndegreeDatasetModel {
public StringBuilder result = new StringBuilder();
public boolean isVocabulary = true;
public boolean isDeadLinks = false;
/**
* MapReduce functions for indegree linksets
*/
public String mapindegreeWithVocabs;
public String mapindegreeNoVocabs;
public String reduceinDegree;
class Result implements Comparator<Result>, Comparable<Result> {
int targetDataset;
int links = 0;
HashSet<Integer> sourceDatasetList = new HashSet<>();
@Override
public int compare(Result o1, Result o2) {
return o1.links - o2.links;
}
@Override
public int compareTo(Result o) {
return this.sourceDatasetList.size() - o.sourceDatasetList.size();
}
}
HashMap<Integer, Result> tmpResults = new HashMap<Integer, Result>();
ArrayList<Result> finalList = new ArrayList<Result>();
@Test
public void calc() {
/**
* MapReduce to find indegree with vocabularies
*/
result.append("===============================================================\n");
result.append("Comparing with vocabularies\n");
result.append("===============================================================\n\n");
DBCollection collection = DBSuperClass2.getDBInstance().getCollection(DatasetLinksetDB.COLLECTION_NAME);
DBCursor instances;
if(!isDeadLinks){
BasicDBList and = new BasicDBList();
// and.add(new BasicDBObject(DatasetLinksetDB.LINKS, new BasicDBObject("$gt", 0)));
// and.add(new BasicDBObject(DatasetLinksetDB.DATASET_SOURCE, new BasicDBObject("$ne", DatasetLinksetDB.DATASET_TARGET)));
instances = collection.find( new BasicDBObject(DatasetLinksetDB.LINKS, new BasicDBObject("$gt", 0)));
}
else{
BasicDBList and = new BasicDBList();
// and.add(new BasicDBObject(DatasetLinksetDB.DEAD_LINKS, new BasicDBObject("$gt", 0)));
// and.add(new BasicDBObject(DatasetLinksetDB.DATASET_SOURCE, new BasicDBObject("$ne", DatasetLinksetDB.DATASET_TARGET)));
// instances = collection.find( new BasicDBObject("$and", and));
instances = collection.find(new BasicDBObject(DatasetLinksetDB.DEAD_LINKS, new BasicDBObject("$gt", 0)));
}
for (DBObject object : instances) {
DatasetLinksetDB linkset = new DatasetLinksetDB(object);
if (linkset.getDistributionTargetIsVocabulary() == isVocabulary) {
Result result = tmpResults.get(linkset.getDatasetTarget());
if (result == null) {
result = new Result();
}
if (isDeadLinks)
result.links = result.links + linkset.getDeadLinks();
else
result.links = result.links + linkset.getLinks();
result.sourceDatasetList.add(linkset.getDatasetSource());
result.targetDataset = linkset.getDatasetTarget();
tmpResults.put(linkset.getDatasetTarget(), result);
}
}
for (Integer r : tmpResults.keySet()) {
finalList.add(tmpResults.get(r));
}
result.append("\n===== Sorted by links=======");
Collections.sort(finalList, new Result());
printTableindegree();
result.append("\n===== Sorted by number of datasets=======");
Collections.sort(finalList);
printTableindegree();
result.append("\n\n\n\n===============================================================\n");
result.append("Comparing without vocabularies\n");
result.append("===============================================================\n\n");
tmpResults = new HashMap<Integer, Result>();
finalList = new ArrayList<Result>();
isVocabulary = false;
for (DBObject object : instances) {
DatasetLinksetDB linkset = new DatasetLinksetDB(object);
if (linkset.getDistributionTargetIsVocabulary() == isVocabulary) {
Result result = tmpResults.get(linkset.getDatasetTarget());
if (result == null) {
result = new Result();
}
if (isDeadLinks)
result.links = result.links + linkset.getDeadLinks();
else
result.links = result.links + linkset.getLinks();
result.sourceDatasetList.add(linkset.getDatasetSource());
result.targetDataset = linkset.getDatasetTarget();
tmpResults.put(linkset.getDatasetTarget(), result);
}
}
for (Integer r : tmpResults.keySet()) {
finalList.add(tmpResults.get(r));
}
result.append("\n===== Sorted by links=======");
Collections.sort(finalList, new Result());
printTableindegree();
result.append("\n===== Sorted by number of datasets=======");
Collections.sort(finalList);
printTableindegree();
}
private void printTableindegree() {
result.append("\n\nName\t indegree \t Links \n");
DatasetDB tmpDataset;
for (Result r : finalList) {
tmpDataset = new DatasetDB(r.targetDataset);
result.append(tmpDataset.getTitle());
result.append("\t" + r.sourceDatasetList.size());
result.append("\t" + r.links);
result.append("\n");
}
result.append("\n\n\n");
}
}
| AKSW/LODVader | src/main/java/lodVader/spring/REST/models/degree/IndegreeDatasetModel.java | Java | apache-2.0 | 5,358 |
package no.api.regurgitator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegurgitatorConfiguration extends Configuration {
@Valid
@NotNull
@JsonProperty
private int proxyPort;
@Valid
@JsonProperty
private String archivedFolder;
@Valid
@NotNull
@JsonProperty
private Boolean recordOnStart;
@Valid
@NotNull
@JsonProperty
private String storageManager;
public int getProxyPort() {
return proxyPort;
}
public String getStorageManager() {
return storageManager;
}
public Boolean getRecordOnStart() {
return recordOnStart;
}
public String getArchivedFolder() {
return archivedFolder;
}
}
| amedia/regurgitator | regurgitator-service/src/main/java/no/api/regurgitator/RegurgitatorConfiguration.java | Java | apache-2.0 | 958 |
package org.minimalj.example.petclinic.frontend;
import org.minimalj.backend.Backend;
import org.minimalj.example.petclinic.model.Vet;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.editor.Editor.NewObjectEditor;
import org.minimalj.frontend.form.Form;
public class AddVetEditor extends NewObjectEditor<Vet> {
@Override
protected Form<Vet> createForm() {
Form<Vet> form = new Form<>();
form.line(Vet.$.person.firstName);
form.line(Vet.$.person.lastName);
form.line(Vet.$.specialties);
return form;
}
@Override
protected Vet save(Vet owner) {
return Backend.save(owner);
}
@Override
protected void finished(Vet newVet) {
Frontend.show(new VetTablePage());
}
}
| BrunoEberhard/minimal-j | example/007_PetClinic/src/org/minimalj/example/petclinic/frontend/AddVetEditor.java | Java | apache-2.0 | 710 |
/*
* Copyright 2019 Frederic Thevenet
*
* 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 eu.binjr.common.javafx.controls;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import javafx.scene.transform.Transform;
import javafx.stage.Screen;
public final class SnapshotUtils {
public static WritableImage outputScaleAwareSnapshot(Node node) {
return scaledSnapshot(node, 0.0,0.0);
}
public static WritableImage scaledSnapshot(Node node, double scaleX, double scaleY) {
SnapshotParameters spa = new SnapshotParameters();
spa.setTransform(Transform.scale(
scaleX == 0.0 ? Screen.getPrimary().getOutputScaleX() : scaleX,
scaleY == 0.0 ? Screen.getPrimary().getOutputScaleY() : scaleY));
return node.snapshot(spa, null);
}
}
| fthevenet/binjr | binjr-core/src/main/java/eu/binjr/common/javafx/controls/SnapshotUtils.java | Java | apache-2.0 | 1,413 |
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.jersey.types;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Simple Jersey date parameter class. Accepts either milliseconds since epoch UTC or ISO formatted dates.
* Will convert everything into UTC regardless of input timezone.
*/
public class DateParam
{
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+");
private final DateTime dateTime;
DateParam(DateTime dateTime)
{
this.dateTime = checkNotNull(dateTime, "null datetime").withZone(DateTimeZone.UTC);
}
public static DateParam valueOf(DateTime dateTime)
{
return new DateParam(dateTime);
}
public static DateParam valueOf(String string)
{
if (string == null) {
return null;
}
if (NUMBER_PATTERN.matcher(string).matches()) {
return new DateParam(new DateTime(Long.parseLong(string), DateTimeZone.UTC));
} else {
return new DateParam(new DateTime(string, DateTimeZone.UTC));
}
}
/**
* @return a DateTime if the parameter was provided, or null otherwise.
*/
// This method is static so that you can handle optional parameters as null instances.
public static DateTime getDateTime(DateParam param)
{
return param == null ? null : param.dateTime;
}
@Override
public String toString()
{
return Objects.toString(dateTime);
}
}
| NessComputing/components-ness-jersey | jersey/src/main/java/com/nesscomputing/jersey/types/DateParam.java | Java | apache-2.0 | 2,189 |
package hu.akarnokd.rxjava;
import java.util.concurrent.TimeUnit;
import rx.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;
public class TrackSubscriber1 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
RxJavaHooks.setOnObservableStart((observable, onSubscribe) -> {
if (!onSubscribe.getClass().getName().toLowerCase().contains("map")) {
return onSubscribe;
}
System.out.println("Started");
return (Observable.OnSubscribe<Object>)observer -> {
class SignalTracker extends Subscriber<Object> {
@Override public void onNext(Object o) {
// handle onNext before or aftern notifying the downstream
observer.onNext(o);
}
@Override public void onError(Throwable t) {
// handle onError
observer.onError(t);
}
@Override public void onCompleted() {
// handle onComplete
System.out.println("Completed");
observer.onCompleted();
}
}
SignalTracker t = new SignalTracker();
onSubscribe.call(t);
};
});
Observable<Integer> observable = Observable.range(1, 5)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(integer -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return integer * 3;
});
observable.subscribe(System.out::println);
Thread.sleep(6000L);
}
}
| akarnokd/akarnokd-misc | src/main/java/hu/akarnokd/rxjava/TrackSubscriber1.java | Java | apache-2.0 | 1,774 |
package tk.zielony.carbonsamples.feature;
import android.app.Activity;
import android.os.Bundle;
import tk.zielony.carbonsamples.R;
/**
* Created by Marcin on 2016-03-13.
*/
public class TextMarkerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_textmarker);
}
}
| sevoan/Carbon | samples/src/main/java/tk/zielony/carbonsamples/feature/TextMarkerActivity.java | Java | apache-2.0 | 408 |
/* */ package com.hundsun.network.gates.houchao.biz.services.pojo;
/* */
/* */ import org.springframework.context.annotation.Scope;
/* */ import org.springframework.stereotype.Service;
/* */
/* */ @Service("outFundTrans")
/* */ @Scope("prototype")
/* */ public class OutFundTrans extends InOutFundTrans
/* */ {
/* */ protected boolean isTrans()
/* */ {
/* 26 */ return true;
/* */ }
/* */
/* */ protected boolean isOutFund()
/* */ {
/* 31 */ return true;
/* */ }
/* */
/* */ protected boolean isNeedRecordUncomeFund()
/* */ {
/* 39 */ return false;
/* */ }
/* */
/* */ protected boolean isInOutTrans()
/* */ {
/* 49 */ return true;
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy16\houchao\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.houchao.biz.services.pojo.OutFundTrans
* JD-Core Version: 0.6.0
*/ | hnccfr/ccfrweb | fundcore/src/com/hundsun/network/gates/houchao/biz/services/pojo/OutFundTrans.java | Java | apache-2.0 | 1,022 |
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.support;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindingErrorProcessor;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
/**
* Convenient {@link WebBindingInitializer} for declarative configuration
* in a Spring application context. Allows for reusing pre-configured
* initializers with multiple controller/handlers.
*
* @author Juergen Hoeller
* @since 2.5
* @see #setDirectFieldAccess
* @see #setMessageCodesResolver
* @see #setBindingErrorProcessor
* @see #setValidator(Validator)
* @see #setConversionService(ConversionService)
* @see #setPropertyEditorRegistrar
*/
public class ConfigurableWebBindingInitializer implements WebBindingInitializer {
private boolean autoGrowNestedPaths = true;
private boolean directFieldAccess = false;
@Nullable
private MessageCodesResolver messageCodesResolver;
@Nullable
private BindingErrorProcessor bindingErrorProcessor;
@Nullable
private Validator validator;
@Nullable
private ConversionService conversionService;
@Nullable
private PropertyEditorRegistrar[] propertyEditorRegistrars;
/**
* Set whether a binder should attempt to "auto-grow" a nested path that contains a null value.
* <p>If "true", a null path location will be populated with a default object value and traversed
* instead of resulting in an exception. This flag also enables auto-growth of collection elements
* when accessing an out-of-bounds index.
* <p>Default is "true" on a standard DataBinder. Note that this feature is only supported
* for bean property access (DataBinder's default mode), not for field access.
* @see org.springframework.validation.DataBinder#initBeanPropertyAccess()
* @see org.springframework.validation.DataBinder#setAutoGrowNestedPaths
*/
public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) {
this.autoGrowNestedPaths = autoGrowNestedPaths;
}
/**
* Return whether a binder should attempt to "auto-grow" a nested path that contains a null value.
*/
public boolean isAutoGrowNestedPaths() {
return this.autoGrowNestedPaths;
}
/**
* Set whether to use direct field access instead of bean property access.
* <p>Default is {@code false}, using bean property access.
* Switch this to {@code true} in order to enforce direct field access.
* @see org.springframework.validation.DataBinder#initDirectFieldAccess()
* @see org.springframework.validation.DataBinder#initBeanPropertyAccess()
*/
public final void setDirectFieldAccess(boolean directFieldAccess) {
this.directFieldAccess = directFieldAccess;
}
/**
* Return whether to use direct field access instead of bean property access.
*/
public boolean isDirectFieldAccess() {
return this.directFieldAccess;
}
/**
* Set the strategy to use for resolving errors into message codes.
* Applies the given strategy to all data binders used by this controller.
* <p>Default is {@code null}, i.e. using the default strategy of
* the data binder.
* @see org.springframework.validation.DataBinder#setMessageCodesResolver
*/
public final void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) {
this.messageCodesResolver = messageCodesResolver;
}
/**
* Return the strategy to use for resolving errors into message codes.
*/
@Nullable
public final MessageCodesResolver getMessageCodesResolver() {
return this.messageCodesResolver;
}
/**
* Set the strategy to use for processing binding errors, that is,
* required field errors and {@code PropertyAccessException}s.
* <p>Default is {@code null}, that is, using the default strategy
* of the data binder.
* @see org.springframework.validation.DataBinder#setBindingErrorProcessor
*/
public final void setBindingErrorProcessor(@Nullable BindingErrorProcessor bindingErrorProcessor) {
this.bindingErrorProcessor = bindingErrorProcessor;
}
/**
* Return the strategy to use for processing binding errors.
*/
@Nullable
public final BindingErrorProcessor getBindingErrorProcessor() {
return this.bindingErrorProcessor;
}
/**
* Set the Validator to apply after each binding step.
*/
public final void setValidator(@Nullable Validator validator) {
this.validator = validator;
}
/**
* Return the Validator to apply after each binding step, if any.
*/
@Nullable
public final Validator getValidator() {
return this.validator;
}
/**
* Specify a ConversionService which will apply to every DataBinder.
* @since 3.0
*/
public final void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
/**
* Return the ConversionService which will apply to every DataBinder.
*/
@Nullable
public final ConversionService getConversionService() {
return this.conversionService;
}
/**
* Specify a single PropertyEditorRegistrar to be applied to every DataBinder.
*/
public final void setPropertyEditorRegistrar(PropertyEditorRegistrar propertyEditorRegistrar) {
this.propertyEditorRegistrars = new PropertyEditorRegistrar[] {propertyEditorRegistrar};
}
/**
* Specify multiple PropertyEditorRegistrars to be applied to every DataBinder.
*/
public final void setPropertyEditorRegistrars(@Nullable PropertyEditorRegistrar[] propertyEditorRegistrars) {
this.propertyEditorRegistrars = propertyEditorRegistrars;
}
/**
* Return the PropertyEditorRegistrars to be applied to every DataBinder.
*/
@Nullable
public final PropertyEditorRegistrar[] getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void initBinder(WebDataBinder binder) {
binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
if (this.directFieldAccess) {
binder.initDirectFieldAccess();
}
if (this.messageCodesResolver != null) {
binder.setMessageCodesResolver(this.messageCodesResolver);
}
if (this.bindingErrorProcessor != null) {
binder.setBindingErrorProcessor(this.bindingErrorProcessor);
}
if (this.validator != null && binder.getTarget() != null &&
this.validator.supports(binder.getTarget().getClass())) {
binder.setValidator(this.validator);
}
if (this.conversionService != null) {
binder.setConversionService(this.conversionService);
}
if (this.propertyEditorRegistrars != null) {
for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
propertyEditorRegistrar.registerCustomEditors(binder);
}
}
}
}
| spring-projects/spring-framework | spring-web/src/main/java/org/springframework/web/bind/support/ConfigurableWebBindingInitializer.java | Java | apache-2.0 | 7,350 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2015 AS3Boyan
* Copyright 2014-2014 Elias Ku
*
* 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 is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*;
import com.intellij.plugins.haxe.lang.psi.*;
public class HaxeMultiplicativeExpressionImpl extends HaxeExpressionImpl implements HaxeMultiplicativeExpression {
public HaxeMultiplicativeExpressionImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof HaxeVisitor) ((HaxeVisitor)visitor).visitMultiplicativeExpression(this);
else super.accept(visitor);
}
@Override
@NotNull
public List<HaxeExpression> getExpressionList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, HaxeExpression.class);
}
@Override
@Nullable
public HaxeIfStatement getIfStatement() {
return findChildByClass(HaxeIfStatement.class);
}
@Override
@Nullable
public HaxeSwitchStatement getSwitchStatement() {
return findChildByClass(HaxeSwitchStatement.class);
}
@Override
@Nullable
public HaxeTryStatement getTryStatement() {
return findChildByClass(HaxeTryStatement.class);
}
}
| yanhick/intellij-haxe-nightly-builds | gen/com/intellij/plugins/haxe/lang/psi/impl/HaxeMultiplicativeExpressionImpl.java | Java | apache-2.0 | 2,047 |
package com.yuzhou.viewer.service;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.common.eventbus.EventBus;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.yuzhou.viewer.R;
import com.yuzhou.viewer.model.GoogleImage;
import com.yuzhou.viewer.model.GoogleImageFactory;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuzhou on 2015/08/02.
*/
public class GoogleApiTask extends AsyncTask<ApiParam, Integer, List<GoogleImage>>
{
private final SyncHttpClient client = new SyncHttpClient();
private final List<GoogleImage> items = new ArrayList<>();
private final EventBus eventBus;
private final Context context;
private int errorResource;
public GoogleApiTask(EventBus eventBus, Context context)
{
this.eventBus = eventBus;
this.context = context;
}
private List<GoogleImage> interExecute(ApiParam request)
{
Log.d("VIEWER", request.toString());
client.get(request.getUrl(), request.getParams(), new JsonHttpResponseHandler()
{
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject response)
{
Log.i("VIEWER", "status code=" + statusCode + ", response=" + response + ", error=" + throwable.getMessage());
errorResource = R.string.error_unavailable_network;
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
if (response == null) {
Log.i("VIEWER", "Response no context");
errorResource = R.string.error_server_side;
return;
}
try {
int httpCode = response.getInt("responseStatus");
if (httpCode == 400) {
errorResource = R.string.error_data_not_found;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
if (httpCode != 200) {
errorResource = R.string.error_server_side;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
List<GoogleImage> images = GoogleImageFactory.create(response);
if (images.isEmpty()) {
Log.i("VIEWER", "Can not parse JSON");
Log.d("VIEWER", "response=" + response.toString());
errorResource = R.string.error_server_side;
return;
}
items.addAll(images);
} catch (JSONException e) {
Log.i("VIEWER", "Can not parse JSON");
e.printStackTrace();
}
}
});
return items;
}
@Override
protected List<GoogleImage> doInBackground(ApiParam... requests)
{
ApiParam request = requests[0];
return interExecute(request);
}
@Override
protected void onPreExecute()
{
items.clear();
}
@Override
protected void onPostExecute(List<GoogleImage> googleImages)
{
if (errorResource > 0) {
Toast.makeText(context, errorResource, Toast.LENGTH_LONG).show();
}
eventBus.post(items);
}
} | yuzhou2/android_02_grid_image_search | app/src/main/java/com/yuzhou/viewer/service/GoogleApiTask.java | Java | apache-2.0 | 3,730 |
package com.rockhoppertech.music.fx.cmn;
/*
* #%L
* rockymusic-fx
* %%
* Copyright (C) 1996 - 2013 Rockhopper Technologies
* %%
* 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.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.SceneBuilder;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <a href="http://genedelisa.com/">Gene De Lisa</a>
*
*/
public class GrandStaffApp extends Application {
private static final Logger logger = LoggerFactory
.getLogger(GrandStaffApp.class);
private Stage stage;
private Scene scene;
private Pane root;
private GrandStaffAppController controller;
public static void main(String[] args) throws Exception {
launch(args);
}
void loadRootFxml() {
String fxmlFile = "/fxml/GrandStaffPanel.fxml";
logger.debug("Loading FXML for main view from: {}", fxmlFile);
try {
FXMLLoader loader = new FXMLLoader(
GrandStaffApp.class.getResource(fxmlFile));
root = (AnchorPane) loader.load();
controller = loader.getController();
} catch (IOException e) {
logger.error(e.getLocalizedMessage(),e);
}
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
// this.staffModel = new StaffModel();
// MIDITrack track = MIDITrackBuilder
// .create()
// .noteString(
// "E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4")
// .durations(5, 4, 3, 2, 1, 1.5, .5, .75, .25, .25)
// .sequential()
// .build();
// this.staffModel.setTrack(track);
loadRootFxml();
this.scene = SceneBuilder.create()
.root(root)
.fill(Color.web("#1030F0"))
.stylesheets("/styles/grandStaffApp.css")
.build();
this.configureStage();
logger.debug("started");
}
private void configureStage() {
stage.setTitle("Music Notation");
// fullScreen();
stage.setScene(this.scene);
stage.show();
}
private void fullScreen() {
// make it full screen
stage.setX(0);
stage.setY(0);
stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());
stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
}
}
| genedelisa/rockymusic | rockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/GrandStaffApp.java | Java | apache-2.0 | 3,230 |
package org.tuxdevelop.spring.batch.lightmin.server.cluster.configuration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@Data
@ConfigurationProperties(prefix = "spring.batch.lightmin.server.cluster.infinispan")
public class InfinispanServerClusterConfigurationProperties {
@NestedConfigurationProperty
private RepositoryConfigurationProperties repository = new RepositoryConfigurationProperties();
@Data
static class RepositoryConfigurationProperties {
private Boolean initSchedulerExecutionRepository = Boolean.FALSE;
private Boolean initSchedulerConfigurationRepository = Boolean.FALSE;
}
}
| tuxdevelop/spring-batch-lightmin | spring-batch-lightmin-server/spring-batch-lightmin-server-cluster/spring-batch-lightmin-server-cluster-infinispan/src/main/java/org/tuxdevelop/spring/batch/lightmin/server/cluster/configuration/InfinispanServerClusterConfigurationProperties.java | Java | apache-2.0 | 765 |
package org.ngrinder.home.controller;
import lombok.RequiredArgsConstructor;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.home.model.PanelEntry;
import org.ngrinder.home.service.HomeService;
import org.ngrinder.infra.config.Config;
import org.ngrinder.script.handler.ScriptHandler;
import org.ngrinder.script.handler.ScriptHandlerFactory;
import org.ngrinder.user.service.UserContext;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.*;
import static java.util.Comparator.comparing;
import static org.ngrinder.common.constant.ControllerConstants.*;
import static org.ngrinder.common.util.CollectionUtils.buildMap;
import static org.ngrinder.common.util.NoOp.noOp;
/**
* Home index page api controller.
*
* @since 3.5.0
*/
@RestController
@RequestMapping("/home/api")
@RequiredArgsConstructor
public class HomeApiController {
private static final String TIMEZONE_ID_PREFIXES = "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private final HomeService homeService;
private final ScriptHandlerFactory scriptHandlerFactory;
private final UserContext userContext;
private final Config config;
private final MessageSource messageSource;
private List<TimeZone> timeZones = null;
@PostConstruct
public void init() {
timeZones = new ArrayList<>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES) && !TimeZone.getTimeZone(id).getDisplayName().contains("GMT")) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
timeZones.sort(comparing(TimeZone::getID));
}
@GetMapping("/handlers")
public List<ScriptHandler> getHandlers() {
return scriptHandlerFactory.getVisibleHandlers();
}
@GetMapping("/panel")
public Map<String, Object> getPanelEntries() {
return buildMap("leftPanelEntries", getLeftPanelEntries(), "rightPanelEntries", getRightPanelEntries());
}
@GetMapping("/timezones")
public List<TimeZone> getTimezones() {
return timeZones;
}
@GetMapping("/config")
public Map<String, Object> getCommonHomeConfig() {
return buildMap(
"askQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL)),
"seeMoreQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL)),
"seeMoreResourcesUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_MORE_URL),
"userLanguage", config.getControllerProperties().getProperty(ControllerConstants.PROP_CONTROLLER_DEFAULT_LANG));
}
private List<PanelEntry> getRightPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Get nGrinder Resource RSS
String rightPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_RSS);
return homeService.getRightPanelEntries(rightPanelRssURL);
}
return Collections.emptyList();
}
private List<PanelEntry> getLeftPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Make the i18n applied QnA panel. Depending on the user language, show the different QnA panel.
String leftPanelRssURLKey = getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS);
// Make admin configure the QnA panel.
String leftPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS,
leftPanelRssURLKey);
return homeService.getLeftPanelEntries(leftPanelRssURL);
}
return Collections.emptyList();
}
@GetMapping("/messagesources/{locale}")
public Map<String, String> getUserDefinedMessageSources(@PathVariable String locale) {
return homeService.getUserDefinedMessageSources(locale);
}
/**
* Get the message from messageSource by the given key.
*
* @param key key of message
* @return the found message. If not found, the error message will return.
*/
private String getMessages(String key) {
String userLanguage = "en";
try {
userLanguage = userContext.getCurrentUser().getUserLanguage();
} catch (Exception e) {
noOp();
}
Locale locale = new Locale(userLanguage);
return messageSource.getMessage(key, null, locale);
}
}
| naver/ngrinder | ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeApiController.java | Java | apache-2.0 | 4,677 |
package com.huawei.esdk.fusionmanager.local.model.system;
import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;
/**
* 查询计划任务详情返回信息。
* <p>
* @since eSDK Cloud V100R003C30
*/
public class QueryScheduleTaskDetailResp extends FMSDKResponse
{
/**
* 计划任务。
*/
private ScheduleTask scheduleTask;
public ScheduleTask getScheduleTask()
{
return scheduleTask;
}
public void setScheduleTask(ScheduleTask scheduleTask)
{
this.scheduleTask = scheduleTask;
}
}
| eSDK/esdk_cloud_fm_r3_native_java | source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/system/QueryScheduleTaskDetailResp.java | Java | apache-2.0 | 571 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.modules.sparql.expression;
import com.hp.hpl.jena.sparql.expr.E_LogicalAnd;
import com.hp.hpl.jena.sparql.expr.E_LogicalOr;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.syntax.ElementFilter;
// NOT_PUBLISHED
public class SparqlExpressionBuilder {
private Expr current;
private SparqlExpressionBuilder(Expr expression) {
this.current = expression;
}
public static SparqlExpressionBuilder use(Expr expression) {
return new SparqlExpressionBuilder(expression);
}
public Expr toExpr() {
return current;
}
public ElementFilter toElementFilter() {
return new ElementFilter(current);
}
public SparqlExpressionBuilder and(Expr expression) {
if (expression != null) {
current = new E_LogicalAnd(current, expression);
}
return this;
}
public SparqlExpressionBuilder and(Expr expression, boolean condition) {
if (condition) {
return and(expression);
}
return this;
}
public SparqlExpressionBuilder or(Expr expression) {
if (expression != null) {
current = new E_LogicalOr(current, expression);
}
return this;
}
}
| eENVplus/tf-exploitation-server | TF_Exploitation_Server_modules/src/main/java/net/disy/eenvplus/tfes/modules/sparql/expression/SparqlExpressionBuilder.java | Java | apache-2.0 | 1,223 |
package com.sectong.util;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
private static Logger logger = Logger.getLogger(HttpUtil.class);
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType){
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
| xaioyi/yidongyiljwj | src/main/java/com/sectong/util/HttpUtil.java | Java | apache-2.0 | 1,988 |
/*
* Copyright 2015 Matthew Timmermans
*
* 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.nobigsoftware.dfalex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import static backport.java.util.function.BackportFuncs.computeIfAbsent;
/**
* Turns an NFA into a non-minimal RawDfa by powerset construction
*/
class DfaFromNfa<RESULT> {
//inputs
private final Nfa<RESULT> m_nfa;
private final int[] m_nfaStartStates;
private final int[] m_dfaStartStates;
private final DfaAmbiguityResolver<? super RESULT> m_ambiguityResolver;
//utility
private final DfaStateSignatureCodec m_dfaSigCodec = new DfaStateSignatureCodec();
//These fields are scratch space
private final IntListKey m_tempStateSignature = new IntListKey();
private final ArrayDeque<Integer> m_tempNfaClosureList = new ArrayDeque<>();
private final HashSet<RESULT> m_tempResultSet = new HashSet<RESULT>();
//accumulators
private final HashMap<RESULT, Integer> m_acceptSetMap = new HashMap<>();
private final ArrayList<RESULT> m_acceptSets = new ArrayList<>();
private final HashMap<IntListKey, Integer> m_dfaStateSignatureMap = new HashMap<>();
private final ArrayList<IntListKey> m_dfaStateSignatures = new ArrayList<>();
private final ArrayList<DfaStateInfo> m_dfaStates = new ArrayList<>();
public DfaFromNfa(Nfa<RESULT> nfa, int[] nfaStartStates,
DfaAmbiguityResolver<? super RESULT> ambiguityResolver) {
m_nfa = nfa;
m_nfaStartStates = nfaStartStates;
m_dfaStartStates = new int[nfaStartStates.length];
m_ambiguityResolver = ambiguityResolver;
m_acceptSets.add(null);
_build();
}
public RawDfa<RESULT> getDfa() {
return new RawDfa<>(m_dfaStates, m_acceptSets, m_dfaStartStates);
}
private void _build() {
final CompactIntSubset nfaStateSet = new CompactIntSubset(m_nfa.numStates());
final ArrayList<NfaTransition> dfaStateTransitions = new ArrayList<>();
final ArrayList<NfaTransition> transitionQ = new ArrayList<>(1000);
//Create the DFA start states
for (int i = 0; i < m_dfaStartStates.length; ++i) {
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, m_nfaStartStates[i]);
m_dfaStartStates[i] = _getDfaState(nfaStateSet);
}
//Create the transitions and other DFA states.
//m_dfaStateSignatures grows as we discover new states.
//m_dfaStates grows as we complete them
for (int stateNum = 0; stateNum < m_dfaStateSignatures.size(); ++stateNum) {
final IntListKey dfaStateSig = m_dfaStateSignatures.get(stateNum);
dfaStateTransitions.clear();
//For each DFA state, combine the NFA transitions for each
//distinct character range into a DFA transiton, appending new DFA states
//as we discover them.
transitionQ.clear();
//dump all the NFA transitions for the state into the Q
DfaStateSignatureCodec.expand(dfaStateSig,
state -> m_nfa.forStateTransitions(state, transitionQ::add));
//sort all the transitions by first character
Collections.sort(transitionQ, (arg0, arg1) -> {
if (arg0.m_firstChar != arg1.m_firstChar) {
return (arg0.m_firstChar < arg1.m_firstChar ? -1 : 1);
}
return 0;
});
final int tqlen = transitionQ.size();
//first character we haven't accounted for yet
char minc = 0;
//NFA transitions at index < tqstart are no longer relevant
//NFA transitions at index >= tqstart are in first char order OR have first char <= minc
//The sequence of NFA transitions contributing the the previous DFA transition starts here
int tqstart = 0;
//make a range of NFA transitions corresponding to the next DFA transition
while (tqstart < tqlen) {
NfaTransition trans = transitionQ.get(tqstart);
if (trans.m_lastChar < minc) {
++tqstart;
continue;
}
//INVAR - trans contributes to the next DFA transition
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
char startc = trans.m_firstChar;
char endc = trans.m_lastChar;
if (startc < minc) {
startc = minc;
}
//make range of all transitions that include the start character, removing ones
//that drop out
for (int tqend = tqstart + 1; tqend < tqlen; ++tqend) {
trans = transitionQ.get(tqend);
if (trans.m_lastChar < startc) {
//remove this one
transitionQ.set(tqend, transitionQ.get(tqstart++));
continue;
}
if (trans.m_firstChar > startc) {
//this one is for the next transition
if (trans.m_firstChar <= endc) {
endc = (char) (trans.m_firstChar - 1);
}
break;
}
//this one counts
if (trans.m_lastChar < endc) {
endc = trans.m_lastChar;
}
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
}
dfaStateTransitions.add(new NfaTransition(startc, endc, _getDfaState(nfaStateSet)));
minc = (char) (endc + 1);
if (minc < endc) {
//wrapped around
break;
}
}
//INVARIANT: m_dfaStatesOut.size() == stateNum
m_dfaStates.add(_createStateInfo(dfaStateSig, dfaStateTransitions));
}
}
//Add an NFA state to m_currentNFASubset, along with the transitive
//closure over its epsilon transitions
private void _addNfaStateAndEpsilonsToSubset(CompactIntSubset dest, int stateNum) {
m_tempNfaClosureList.clear();
if (dest.add(stateNum)) {
m_tempNfaClosureList.add(stateNum);
}
Integer newNfaState;
while ((newNfaState = m_tempNfaClosureList.poll()) != null) {
m_nfa.forStateEpsilons(newNfaState, (Integer src) -> {
if (dest.add(src)) {
m_tempNfaClosureList.add(src);
}
});
}
}
private void _addNfaStateToSignatureCodec(int stateNum) {
if (m_nfa.hasTransitionsOrAccepts(stateNum)) {
m_dfaSigCodec.acceptInt(stateNum);
}
}
//Make a DFA state for a set of simultaneous NFA states
private Integer _getDfaState(CompactIntSubset nfaStateSet) {
//dump state combination into compressed form
m_tempStateSignature.clear();
m_dfaSigCodec.start(m_tempStateSignature::add, nfaStateSet.getSize(),
nfaStateSet.getRange());
nfaStateSet.dumpInOrder(this::_addNfaStateToSignatureCodec);
m_dfaSigCodec.finish();
//make sure it's in the map
Integer dfaStateNum = m_dfaStateSignatureMap.get(m_tempStateSignature);
if (dfaStateNum == null) {
dfaStateNum = m_dfaStateSignatures.size();
IntListKey newSig = new IntListKey(m_tempStateSignature);
m_dfaStateSignatures.add(newSig);
m_dfaStateSignatureMap.put(newSig, dfaStateNum);
}
return dfaStateNum;
}
@SuppressWarnings("unchecked")
private DfaStateInfo _createStateInfo(IntListKey sig, List<NfaTransition> transitions) {
//calculate the set of accepts
m_tempResultSet.clear();
DfaStateSignatureCodec.expand(sig, nfastate -> {
RESULT accept = m_nfa.getAccept(nfastate);
if (accept != null) {
m_tempResultSet.add(accept);
}
});
//and get an accept set index for it
RESULT dfaAccept = null;
if (m_tempResultSet.size() > 1) {
dfaAccept = (RESULT) m_ambiguityResolver.apply(m_tempResultSet);
} else if (!m_tempResultSet.isEmpty()) {
dfaAccept = m_tempResultSet.iterator().next();
}
int acceptSetIndex = 0;
if (dfaAccept != null) {
acceptSetIndex = computeIfAbsent(m_acceptSetMap, dfaAccept, keyset -> {
m_acceptSets.add(keyset);
return m_acceptSets.size() - 1;
});
}
return new DfaStateInfo(transitions, acceptSetIndex);
}
}
| 6thsolution/ApexNLP | dfalex/src/main/java/com/nobigsoftware/dfalex/DfaFromNfa.java | Java | apache-2.0 | 9,517 |
package com.emc.ecs.servicebroker.repository;
import com.emc.ecs.servicebroker.exception.EcsManagementClientException;
import com.emc.ecs.servicebroker.service.s3.S3Service;
import com.emc.ecs.servicebroker.model.Constants;
import com.emc.object.s3.bean.GetObjectResult;
import com.emc.object.s3.bean.ListObjectsResult;
import com.emc.object.s3.bean.S3Object;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.servicebroker.model.binding.SharedVolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeMount;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
@SuppressWarnings("unused")
public class ServiceInstanceBindingRepository {
static final Logger logger = LoggerFactory.getLogger(ServiceInstanceBindingRepository.class);
public static final String FILENAME_PREFIX = "service-instance-binding";
private final ObjectMapper objectMapper = new ObjectMapper();
{
// NOTE -- ideally we would not need this code, but for now, the VolumeMount class has
// custom serialization that is not matched with corresponding deserialization, so
// deserializing serialized volume mounts doesn't work OOTB.
SimpleModule module = new SimpleModule();
module.addDeserializer(VolumeMount.DeviceType.class, new DeviceTypeDeserializer());
module.addDeserializer(VolumeMount.Mode.class, new ModeDeserializer());
module.addDeserializer(VolumeDevice.class, new VolumeDeviceDeserializer());
objectMapper.registerModule(module);
}
@Autowired
private S3Service s3;
private static String getFilename(String id) {
return FILENAME_PREFIX + "/" + id + ".json";
}
private static boolean isCorrectFilename (String filename) {
return filename.matches(FILENAME_PREFIX + "/.*\\.json");
}
private ServiceInstanceBinding findByFilename(String filename) throws IOException {
if (!isCorrectFilename(filename)) {
String errorMessage = format("Invalid filename of service instance binding provided: %s", filename);
throw new IOException(errorMessage);
}
logger.debug("Loading service instance binding from repository file {}", filename);
GetObjectResult<InputStream> input = s3.getObject(filename);
return objectMapper.readValue(input.getObject(), ServiceInstanceBinding.class);
}
ServiceInstanceBinding removeSecretCredentials(ServiceInstanceBinding binding) {
Map<String, Object> credentials = binding.getCredentials();
credentials.remove(Constants.S3_URL);
credentials.remove(Constants.CREDENTIALS_SECRET_KEY);
binding.setCredentials(credentials);
return binding;
}
@PostConstruct
public void initialize() throws EcsManagementClientException {
logger.info("Service binding file prefix: {}", FILENAME_PREFIX);
}
public void save(ServiceInstanceBinding binding) throws IOException {
String filename = getFilename(binding.getBindingId());
String serialized = objectMapper.writeValueAsString(binding);
s3.putObject(filename, serialized);
}
public ServiceInstanceBinding find(String id) throws IOException {
String filename = getFilename(id);
return findByFilename(filename);
}
public ListServiceInstanceBindingsResponse listServiceInstanceBindings(String marker, int pageSize) throws IOException {
if (pageSize < 0) {
throw new IOException("Page size could not be negative number");
}
List<ServiceInstanceBinding> bindings = new ArrayList<>();
ListObjectsResult list = marker != null ?
s3.listObjects(FILENAME_PREFIX + "/", getFilename(marker), pageSize) :
s3.listObjects(FILENAME_PREFIX + "/", null, pageSize);
for (S3Object s3Object: list.getObjects()) {
String filename = s3Object.getKey();
if (isCorrectFilename(filename)) {
ServiceInstanceBinding binding = findByFilename(filename);
bindings.add(removeSecretCredentials(binding));
}
}
ListServiceInstanceBindingsResponse response = new ListServiceInstanceBindingsResponse(bindings);
response.setMarker(list.getMarker());
response.setPageSize(list.getMaxKeys());
response.setNextMarker(list.getNextMarker());
return response;
}
public void delete(String id) {
String filename = getFilename(id);
s3.deleteObject(filename);
}
public static class ModeDeserializer extends StdDeserializer<VolumeMount.Mode> {
ModeDeserializer() {
this(null);
}
ModeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.Mode deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
String s = node.asText();
if (s.equals("rw")) {
return VolumeMount.Mode.READ_WRITE;
} else {
return VolumeMount.Mode.READ_ONLY;
}
}
}
public static class DeviceTypeDeserializer extends StdDeserializer<VolumeMount.DeviceType> {
DeviceTypeDeserializer() {
this(null);
}
DeviceTypeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.DeviceType deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return VolumeMount.DeviceType.SHARED;
}
}
public static class VolumeDeviceDeserializer extends StdDeserializer<VolumeDevice> {
VolumeDeviceDeserializer() {
this(null);
}
VolumeDeviceDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeDevice deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return jp.getCodec().readValue(jp, SharedVolumeDevice.class);
}
}
} | emccode/ecs-cf-service-broker | src/main/java/com/emc/ecs/servicebroker/repository/ServiceInstanceBindingRepository.java | Java | apache-2.0 | 6,740 |
/*******************************************************************************
* Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation
******************************************************************************/
package com.quakearts.webapp.facelets.bootstrap.renderers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIColumn;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import com.quakearts.webapp.facelets.bootstrap.components.BootTable;
import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute;
import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager;
import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicRenderer;
import com.quakearts.webapp.facelets.util.UtilityMethods;
import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*;
public class BootTableRenderer extends HtmlBasicRenderer {
private static final Attribute[] ATTRIBUTES =
AttributeManager.getAttributes(AttributeManager.Key.DATATABLE);
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
BootTable data = (BootTable) component;
data.setRowIndex(-1);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("table", component);
writer.writeAttribute("id", component.getClientId(context),
"id");
String styleClass = data.get("styleClass");
writer.writeAttribute("class","table "+(styleClass !=null?" "+styleClass:""), "styleClass");
renderHTML5DataAttributes(context, component);
renderPassThruAttributes(context, writer, component,
ATTRIBUTES);
writer.writeText("\n", component, null);
UIComponent caption = getFacet(component, "caption");
if (caption != null) {
String captionClass = data.get("captionClass");
String captionStyle = data.get("captionStyle");
writer.startElement("caption", component);
if (captionClass != null) {
writer.writeAttribute("class", captionClass, "captionClass");
}
if (captionStyle != null) {
writer.writeAttribute("style", captionStyle, "captionStyle");
}
encodeRecursive(context, caption);
writer.endElement("caption");
}
UIComponent colGroups = getFacet(component, "colgroups");
if (colGroups != null) {
encodeRecursive(context, colGroups);
}
BootMetaInfo info = getMetaInfo(context, component);
UIComponent header = getFacet(component, "header");
if (header != null || info.hasHeaderFacets) {
String headerClass = data.get("headerClass");
writer.startElement("thead", component);
writer.writeText("\n", component, null);
if (header != null) {
writer.startElement("tr", header);
writer.startElement("th", header);
if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
writer.writeAttribute("scope", "colgroup", null);
encodeRecursive(context, header);
writer.endElement("th");
writer.endElement("tr");
writer.write("\n");
}
if (info.hasHeaderFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnHeaderClass = info.getCurrentHeaderClass();
writer.startElement("th", column);
if (columnHeaderClass != null) {
writer.writeAttribute("class", columnHeaderClass,
"columnHeaderClass");
} else if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
writer.writeAttribute("scope", "col", null);
UIComponent facet = getFacet(column, "header");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("th");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("thead");
writer.writeText("\n", component, null);
}
}
@Override
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncodeChildren(component)) {
return;
}
UIData data = (UIData) component;
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, data);
if(info.columns.isEmpty()) {
writer.startElement("tbody", component);
renderEmptyTableRow(writer, component);
writer.endElement("tbody");
return;
}
int processed = 0;
int rowIndex = data.getFirst() - 1;
int rows = data.getRows();
List<Integer> bodyRows = getBodyRows(context.getExternalContext().getApplicationMap(), data);
boolean hasBodyRows = (bodyRows != null && !bodyRows.isEmpty());
boolean wroteTableBody = false;
if (!hasBodyRows) {
writer.startElement("tbody", component);
writer.writeText("\n", component, null);
}
boolean renderedRow = false;
while (true) {
if ((rows > 0) && (++processed > rows)) {
break;
}
data.setRowIndex(++rowIndex);
if (!data.isRowAvailable()) {
break;
}
if (hasBodyRows && bodyRows.contains(data.getRowIndex())) {
if (wroteTableBody) {
writer.endElement("tbody");
}
writer.startElement("tbody", data);
wroteTableBody = true;
}
writer.startElement("tr", component);
if (info.rowClasses.length > 0) {
writer.writeAttribute("class", info.getCurrentRowClass(),
"rowClasses");
}
writer.writeText("\n", component, null);
info.newRow();
for (UIColumn column : info.columns) {
boolean isRowHeader = Boolean.TRUE.equals(column.getAttributes()
.get("rowHeader"));
if (isRowHeader) {
writer.startElement("th", column);
writer.writeAttribute("scope", "row", null);
} else {
writer.startElement("td", column);
}
String columnClass = info.getCurrentColumnClass();
if (columnClass != null) {
writer.writeAttribute("class", columnClass, "columnClasses");
}
for (Iterator<UIComponent> gkids = getChildren(column); gkids
.hasNext();) {
encodeRecursive(context, gkids.next());
}
if (isRowHeader) {
writer.endElement("th");
} else {
writer.endElement("td");
}
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
renderedRow = true;
}
if(!renderedRow) {
renderEmptyTableRow(writer, data);
}
writer.endElement("tbody");
writer.writeText("\n", component, null);
data.setRowIndex(-1);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, component);
UIComponent footer = getFacet(component, "footer");
if (footer != null || info.hasFooterFacets) {
String footerClass = (String) component.getAttributes().get("footerClass");
writer.startElement("tfoot", component);
writer.writeText("\n", component, null);
if (info.hasFooterFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnFooterClass = (String) column.getAttributes().get(
"footerClass");
writer.startElement("td", column);
if (columnFooterClass != null) {
writer.writeAttribute("class", columnFooterClass,
"columnFooterClass");
} else if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
UIComponent facet = getFacet(column, "footer");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("td");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
if (footer != null) {
writer.startElement("tr", footer);
writer.startElement("td", footer);
if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
encodeRecursive(context, footer);
writer.endElement("td");
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("tfoot");
writer.writeText("\n", component, null);
}
clearMetaInfo(context, component);
((UIData) component).setRowIndex(-1);
writer.endElement("table");
writer.writeText("\n", component, null);
}
private List<Integer> getBodyRows(Map<String, Object> appMap, UIData data) {
List<Integer> result = null;
String bodyRows = (String) data.getAttributes().get("bodyrows");
if (bodyRows != null) {
String [] rows = UtilityMethods.split(appMap, bodyRows, ",");
if (rows != null) {
result = new ArrayList<Integer>(rows.length);
for (String curRow : rows) {
result.add(Integer.valueOf(curRow));
}
}
}
return result;
}
private void renderEmptyTableRow(final ResponseWriter writer,
final UIComponent component) throws IOException {
writer.startElement("tr", component);
writer.startElement("td", component);
writer.endElement("td");
writer.endElement("tr");
}
protected BootTableRenderer.BootMetaInfo getMetaInfo(FacesContext context,
UIComponent table) {
String key = createKey(table);
Map<Object, Object> attributes = context.getAttributes();
BootMetaInfo info = (BootMetaInfo) attributes
.get(key);
if (info == null) {
info = new BootMetaInfo(table);
attributes.put(key, info);
}
return info;
}
protected void clearMetaInfo(FacesContext context, UIComponent table) {
context.getAttributes().remove(createKey(table));
}
protected String createKey(UIComponent table) {
return BootMetaInfo.KEY + '_' + table.hashCode();
}
private static class BootMetaInfo {
private static final UIColumn PLACE_HOLDER_COLUMN = new UIColumn();
private static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final String KEY = BootMetaInfo.class.getName();
public final String[] rowClasses;
public final String[] columnClasses;
public final String[] headerClasses;
public final List<UIColumn> columns;
public final boolean hasHeaderFacets;
public final boolean hasFooterFacets;
public final int columnCount;
public int columnStyleCounter;
public int headerStyleCounter;
public int rowStyleCounter;
public BootMetaInfo(UIComponent table) {
rowClasses = getRowClasses(table);
columnClasses = getColumnClasses(table);
headerClasses = getHeaderClasses(table);
columns = getColumns(table);
columnCount = columns.size();
hasHeaderFacets = hasFacet("header", columns);
hasFooterFacets = hasFacet("footer", columns);
}
public void newRow() {
columnStyleCounter = 0;
headerStyleCounter = 0;
}
public String getCurrentColumnClass() {
String style = null;
if (columnStyleCounter < columnClasses.length
&& columnStyleCounter <= columnCount) {
style = columnClasses[columnStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentHeaderClass() {
String style = null;
if (headerStyleCounter < headerClasses.length
&& headerStyleCounter <= columnCount) {
style = headerClasses[headerStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentRowClass() {
String style = rowClasses[rowStyleCounter++];
if (rowStyleCounter >= rowClasses.length) {
rowStyleCounter = 0;
}
return style;
}
private static String[] getColumnClasses(UIComponent table) {
String values = ((BootTable) table).get("columnClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static String[] getHeaderClasses(UIComponent table) {
String values = ((BootTable) table).get("headerClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static List<UIColumn> getColumns(UIComponent table) {
if (table instanceof UIData) {
int childCount = table.getChildCount();
if (childCount > 0) {
List<UIColumn> results = new ArrayList<UIColumn>(childCount);
for (UIComponent kid : table.getChildren()) {
if ((kid instanceof UIColumn) && kid.isRendered()) {
results.add((UIColumn) kid);
}
}
return results;
} else {
return Collections.emptyList();
}
} else {
int count;
Object value = table.getAttributes().get("columns");
if ((value != null) && (value instanceof Integer)) {
count = ((Integer) value);
} else {
count = 2;
}
if (count < 1) {
count = 1;
}
List<UIColumn> result = new ArrayList<UIColumn>(count);
for (int i = 0; i < count; i++) {
result.add(PLACE_HOLDER_COLUMN);
}
return result;
}
}
private static boolean hasFacet(String name, List<UIColumn> columns) {
if (!columns.isEmpty()) {
for (UIColumn column : columns) {
if (column.getFacetCount() > 0) {
if (column.getFacets().containsKey(name)) {
return true;
}
}
}
}
return false;
}
private static String[] getRowClasses(UIComponent table) {
String values = ((BootTable) table).get("rowClasses");
if (values == null) {
return (EMPTY_STRING_ARRAY);
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
}
}
| kwakutwumasi/Quakearts-JSF-Webtools | qa-boot/src/main/java/com/quakearts/webapp/facelets/bootstrap/renderers/BootTableRenderer.java | Java | apache-2.0 | 15,874 |
package info.pupcode.model.repo.test;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by fabientronche1 on 08.11.15.
*/
public class AbstractConcordionFixture {
protected SpringConfigTest springConfigTest;
protected ClassPathXmlApplicationContext applicationContext;
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
if (springConfigTest == null) {
springConfigTest = (SpringConfigTest) applicationContext.getBean(SpringConfigTest.class.getName());
}
}
}
| PUPInitiative/pup-code-poc | pup-code-domain/src/test/java/info/pupcode/model/repo/test/AbstractConcordionFixture.java | Java | apache-2.0 | 658 |
package pro.luxun.luxunanimation.presenter.adapter;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wufeiyang on 16/5/7.
*/
public abstract class BaseRecyclerAdapter<T, V extends View> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder<V>> {
protected List<T> mItems = new ArrayList<>();
@Override
public BaseViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new BaseViewHolder<>(onCreateItemView(parent, viewType));
}
@Override
public int getItemCount() {
return mItems.size();
}
@UiThread
public void refresh(List<T> datas){
mItems.clear();
add(datas);
}
@UiThread
public void add(List<T> datas){
mItems.addAll(datas);
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
V v = (V) holder.itemView;
onBindView(v, mItems.get(position));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
protected abstract void onBindView(V v, T t);
public static class BaseViewHolder<V extends View> extends RecyclerView.ViewHolder{
public BaseViewHolder(V itemView) {
super(itemView);
}
}
}
| ayaseruri/luxunPro | app/src/main/java/pro/luxun/luxunanimation/presenter/adapter/BaseRecyclerAdapter.java | Java | apache-2.0 | 1,444 |
package cn.xmut.experiment.service.impl;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import cn.xmut.experiment.dao.IExperimentDao;
import cn.xmut.experiment.dao.impl.jdbc.ExperimentDaoImpl;
import cn.xmut.experiment.domain.Experiment;
import cn.xmut.experiment.domain.ShowExperiment;
import cn.xmut.experiment.service.IExperimentService;
public class ExperimentServiceImpl implements IExperimentService {
IExperimentDao experimentDao = new ExperimentDaoImpl();
public boolean addExperiment(Experiment experiment, String docName,String dirPath, FileItem fileItem) {
return experimentDao.addExperiment(experiment, docName, dirPath, fileItem);
}
public boolean updateExperiment(Experiment experiment) {
return experimentDao.updateExperiment(experiment);
}
public String getDocPath(int experimentId) {
return experimentDao.getDocPath(experimentId);
}
public Experiment getExperiment(int experimentId) {
return experimentDao.getExperiment(experimentId);
}
public List<ShowExperiment> queryPass(Experiment experiment) {
return experimentDao.queryPass(experiment);
}
public List<ShowExperiment> queryNodistribute(Experiment experiment) {
return experimentDao.queryNodistribute(experiment);
}
public List<ShowExperiment> expertQueryNoExtimate(Experiment experiment, String expertId) {
return experimentDao.expertQueryNoExtimate(experiment, expertId);
}
public List<ShowExperiment> managerQueryNoExtimate(Experiment experiment) {
return experimentDao.managerQueryNoExtimate(experiment);
}
public List<ShowExperiment> managerQueryNoPass(Experiment experiment) {
return experimentDao.managerQueryNoPass(experiment);
}
public boolean delExperiment(Experiment experiment) {
return experimentDao.delExperiment(experiment);
}
public List<ShowExperiment> headmanQueryNoPass(Experiment experiment) {
return experimentDao.headmanQueryNoPass(experiment);
}
}
| bingoogolapple/J2EENote | experiment/src/cn/xmut/experiment/service/impl/ExperimentServiceImpl.java | Java | apache-2.0 | 1,988 |
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.collection.primitive;
public interface PrimitiveLongIntVisitor<E extends Exception>
{
/**
* Visit the given entry.
*
* @param key The key of the entry.
* @param value The value of the entry.
* @return 'true' to signal that the iteration should be stopped, 'false' to signal that the iteration should
* continue if there are more entries to look at.
* @throws E any thrown exception of type 'E' will bubble up through the 'visit' method.
*/
boolean visited( long key, int value ) throws E;
}
| HuangLS/neo4j | community/primitive-collections/src/main/java/org/neo4j/collection/primitive/PrimitiveLongIntVisitor.java | Java | apache-2.0 | 1,354 |
package org.anyline.entity;
import com.fasterxml.jackson.databind.JsonNode;
import org.anyline.util.*;
import org.anyline.util.regular.Regular;
import org.anyline.util.regular.RegularUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
public class DataSet implements Collection<DataRow>, Serializable {
private static final long serialVersionUID = 6443551515441660101L;
protected static final Logger log = LoggerFactory.getLogger(DataSet.class);
private boolean result = true; // 执行结果
private Exception exception = null; // 异常
private String message = null; // 提示信息
private PageNavi navi = null; // 分页
private List<String> head = null; // 表头
private List<DataRow> rows = null; // 数据
private List<String> primaryKeys = null; // 主键
private String datalink = null; // 数据连接
private String dataSource = null; // 数据源(表|视图|XML定义SQL)
private String schema = null;
private String table = null;
private long createTime = 0; //创建时间
private long expires = -1; //过期时间(毫秒) 从创建时刻计时expires毫秒后过期
private boolean isFromCache = false; //是否来自缓存
private boolean isAsc = false;
private boolean isDesc = false;
private Map<String, Object> queryParams = new HashMap<String, Object>();//查询条件
/**
* 创建索引
*
* @param key key
* @return return
* crateIndex("ID");
* crateIndex("ID:ASC");
*/
public DataSet creatIndex(String key) {
return this;
}
public DataSet() {
rows = new ArrayList<DataRow>();
createTime = System.currentTimeMillis();
}
public DataSet(List<Map<String, Object>> list) {
rows = new ArrayList<DataRow>();
if (null == list)
return;
for (Map<String, Object> map : list) {
DataRow row = new DataRow(map);
rows.add(row);
}
}
public static DataSet build(Collection<?> list, String ... fields) {
return parse(list, fields);
}
/**
* list解析成DataSet
* @param list list
* @param fields 如果list是二维数据
* fields 下标对应的属性(字段/key)名称 如"ID","CODE","NAME"
* 如果不输入则以下标作为DataRow的key 如row.put("0","100").put("1","A01").put("2","张三");
* 如果属性数量超出list长度,取null值存入DataRow
*
* 如果list是一组数组
* fileds对应条目的属性值 如果不输入 则以条目的属性作DataRow的key 如"USER_ID:id","USER_NM:name"
*
* @return DataSet
*/
public static DataSet parse(Collection<?> list, String ... fields) {
DataSet set = new DataSet();
if (null != list) {
for (Object obj : list) {
DataRow row = null;
if(obj instanceof Collection){
row = DataRow.parseList((Collection)obj, fields);
}else {
row = DataRow.parse(obj, fields);
}
set.add(row);
}
}
return set;
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, String json) {
if (null != json) {
try {
return parseJson(keyCase, BeanUtil.JSON_MAPPER.readTree(json));
} catch (Exception e) {
}
}
return null;
}
public static DataSet parseJson(String json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, JsonNode json) {
DataSet set = new DataSet();
if (null != json) {
if (json.isArray()) {
Iterator<JsonNode> items = json.iterator();
while (items.hasNext()) {
JsonNode item = items.next();
set.add(DataRow.parseJson(keyCase, item));
}
}
}
return set;
}
public static DataSet parseJson(JsonNode json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public DataSet Camel(){
for(DataRow row:rows){
row.Camel();
}
return this;
}
public DataSet camel(){
for(DataRow row:rows){
row.camel();
}
return this;
}
public DataSet setIsNew(boolean bol) {
for (DataRow row : rows) {
row.setIsNew(bol);
}
return this;
}
/**
* 移除每个条目中指定的key
*
* @param keys keys
* @return DataSet
*/
public DataSet remove(String... keys) {
for (DataRow row : rows) {
for (String key : keys) {
row.remove(key);
}
}
return this;
}
public DataSet trim(){
for(DataRow row:rows){
row.trim();
}
return this;
}
/**
* 添加主键
*
* @param applyItem 是否应用到集合中的DataRow 默认true
* @param pks pks
* @return return
*/
public DataSet addPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
addPrimaryKey(applyItem, list);
}
return this;
}
public DataSet addPrimaryKey(String... pks) {
return addPrimaryKey(true, pks);
}
public DataSet addPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
if (null == pks) {
return this;
}
for (String pk : pks) {
if (BasicUtil.isEmpty(pk)) {
continue;
}
pk = key(pk);
if (!primaryKeys.contains(pk)) {
primaryKeys.add(pk);
}
}
if (applyItem) {
for (DataRow row : rows) {
row.setPrimaryKey(false, primaryKeys);
}
}
return this;
}
public DataSet addPrimaryKey(Collection<String> pks) {
return addPrimaryKey(true, pks);
}
/**
* 设置主键
*
* @param applyItem applyItem
* @param pks pks
* @return return
*/
public DataSet setPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
setPrimaryKey(applyItem, list);
}
return this;
}
public DataSet setPrimaryKey(String... pks) {
return setPrimaryKey(true, pks);
}
public DataSet setPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == pks) {
return this;
}
this.primaryKeys = new ArrayList<>();
addPrimaryKey(applyItem, pks);
return this;
}
public DataSet setPrimaryKey(Collection<String> pks) {
return setPrimaryKey(true, pks);
}
public DataSet set(int index, DataRow item) {
rows.set(index, item);
return this;
}
/**
* 是否有主键
*
* @return return
*/
public boolean hasPrimaryKeys() {
if (null != primaryKeys && primaryKeys.size() > 0) {
return true;
} else {
return false;
}
}
/**
* 提取主键
*
* @return return
*/
public List<String> getPrimaryKeys() {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
return primaryKeys;
}
/**
* 添加表头
*
* @param col col
* @return return
*/
public DataSet addHead(String col) {
if (null == head) {
head = new ArrayList<>();
}
if ("ROW_NUMBER".equals(col)) {
return this;
}
if (head.contains(col)) {
return this;
}
head.add(col);
return this;
}
/**
* 表头
*
* @return return
*/
public List<String> getHead() {
return head;
}
public int indexOf(Object obj) {
return rows.indexOf(obj);
}
/**
* 从begin开始截断到end,方法执行将改变原DataSet长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet truncates(int begin, int end) {
if (!rows.isEmpty()) {
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
rows = rows.subList(begin, end);
}
return this;
}
/**
* 从begin开始截断到最后一个
*
* @param begin 开始位置
* @return DataSet
*/
public DataSet truncates(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return truncates(begin, end);
} else {
return truncates(begin, rows.size() - 1);
}
}
/**
* 从begin开始截断到最后一个并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataRow
*/
public DataRow truncate(int begin) {
return truncate(begin, rows.size() - 1);
}
/**
* 从begin开始截断到end位置并返回其中第一个DataRow
*
* @param begin 开始位置
* @param end 结束位置
* @return DataRow
*/
public DataRow truncate(int begin, int end) {
truncates(begin, end);
if (rows.size() > 0) {
return rows.get(0);
} else {
return null;
}
}
/**
* 从begin开始截取到最后一个
*
* @param begin 开始位置
* 如果输入负数则取后n个,如果造成数量不足,则取全部
* @return DataSet
*/
public DataSet cuts(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return cuts(begin, end);
} else {
return cuts(begin, rows.size() - 1);
}
}
/**
* 从begin开始截取到end位置,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet cuts(int begin, int end) {
DataSet result = new DataSet();
if (rows.isEmpty()) {
return result;
}
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
for (int i = begin; i <= end; i++) {
result.add(rows.get(i));
}
return result;
}
/**
* 从begin开始截取到最后一个,并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataSet
*/
public DataRow cut(int begin) {
return cut(begin, rows.size() - 1);
}
/**
* 从begin开始截取到end位置,并返回其中第一个DataRow,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataRow cut(int begin, int end) {
DataSet result = cuts(begin, end);
if (result.size() > 0) {
return result.getRow(0);
}
return null;
}
/**
* 记录数量
*
* @return return
*/
public int size() {
int result = 0;
if (null != rows)
result = rows.size();
return result;
}
public int getSize() {
return size();
}
/**
* 是否出现异常
*
* @return return
*/
public boolean isException() {
return null != exception;
}
public boolean isFromCache() {
return isFromCache;
}
public DataSet setIsFromCache(boolean bol) {
this.isFromCache = bol;
return this;
}
/**
* 返回数据是否为空
*
* @return return
*/
public boolean isEmpty() {
boolean result = true;
if (null == rows) {
result = true;
} else if (rows instanceof Collection) {
result = ((Collection<?>) rows).isEmpty();
}
return result;
}
/**
* 读取一行数据
*
* @param index index
* @return return
*/
public DataRow getRow(int index) {
DataRow row = null;
if (null != rows && index < rows.size()) {
row = rows.get(index);
}
if (null != row) {
row.setContainer(this);
}
return row;
}
public boolean exists(String ... params){
DataRow row = getRow(0, params);
return row != null;
}
public DataRow getRow(String... params) {
return getRow(0, params);
}
public DataRow getRow(DataRow params) {
return getRow(0, params);
}
public DataRow getRow(List<String> params) {
String[] kvs = BeanUtil.list2array(params);
return getRow(0, kvs);
}
public DataRow getRow(int begin, String... params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
public DataRow getRow(int begin, DataRow params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
/**
* 根据keys去重
*
* @param keys keys
* @return DataSet
*/
public DataSet distinct(String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
DataRow row = rows.get(i);
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public DataSet distinct(List<String> keys) {
DataSet result = new DataSet();
if (null != rows) {
for (DataRow row:rows) {
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public Object clone() {
DataSet set = new DataSet();
List<DataRow> rows = new ArrayList<DataRow>();
for (DataRow row : this.rows) {
rows.add((DataRow) row.clone());
}
set.setRows(rows);
set.cloneProperty(this);
return set;
}
private DataSet cloneProperty(DataSet from) {
return cloneProperty(from, this);
}
public static DataSet cloneProperty(DataSet from, DataSet to) {
if (null != from && null != to) {
to.exception = from.exception;
to.message = from.message;
to.navi = from.navi;
to.head = from.head;
to.primaryKeys = from.primaryKeys;
to.dataSource = from.dataSource;
to.datalink = from.datalink;
to.schema = from.schema;
to.table = from.table;
}
return to;
}
/**
* 指定key转换成number
* @param keys keys
* @return DataRow
*/
public DataSet convertNumber(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertNumber(keys);
}
}
return this;
}
public DataSet convertString(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertString(keys);
}
}
return this;
}
public DataSet skip(boolean skip){
for(DataRow row:rows){
row.skip = skip;
}
return this;
}
/**
* 筛选符合条件的集合
* 注意如果String类型 1与1.0比较不相等, 可以先调用convertNumber转换一下数据类型
* @param params key1,value1,key2:value2,key3,value3
* "NM:zh%","AGE:>20","NM","%zh%"
* @param begin begin
* @param qty 最多筛选多少个 0表示不限制
* @return return
*/
public DataSet getRows(int begin, int qty, String... params) {
DataSet set = new DataSet();
Map<String, String> kvs = new HashMap<String, String>();
int len = params.length;
int i = 0;
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对,如时间格式TIME:{10:10}
while (i < len) {
String p1 = params[i];
if (BasicUtil.isEmpty(p1)) {
i++;
continue;
} else if (p1.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(p1);
kvs.put(ks[0], ks[1]);
i++;
continue;
} else {
if (i + 1 < len) {
String p2 = params[i + 1];
if (BasicUtil.isEmpty(p2) || !p2.contains(":")) {
kvs.put(p1, p2);
i += 2;
continue;
} else if (p2.startsWith("{") && p2.endsWith("}")) {
p2 = p2.substring(1, p2.length() - 1);
kvs.put(p1, p2);
kvs.put(p1 + srcFlagTag, "true");
i += 2;
continue;
} else {
String ks[] = BeanUtil.parseKeyValue(p2);
kvs.put(ks[0], ks[1]);
i += 2;
continue;
}
}
}
i++;
}
return getRows(begin, qty, kvs);
}
public DataSet getRows(int begin, int qty, DataRow kvs) {
Map<String,String> map = new HashMap<String,String>();
for(String k:kvs.keySet()){
map.put(k, kvs.getString(k));
}
return getRows(begin, qty, map);
}
public DataSet getRows(int begin, int qty, Map<String, String> kvs) {
DataSet set = new DataSet();
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对
BigDecimal d1;
BigDecimal d2;
for (DataRow row:rows) {
if(row.skip){
continue;
}
boolean chk = true;//对比结果
for (String k : kvs.keySet()) {
boolean srcFlag = false;
if (k.endsWith(srcFlagTag)) {
continue;
} else {
String srcFlagValue = kvs.get(k + srcFlagTag);
if (BasicUtil.isNotEmpty(srcFlagValue)) {
srcFlag = true;
}
}
String v = kvs.get(k);
Object value = row.get(k);
if(!row.containsKey(k) && null == value){
//注意这里有可能是个复合key
chk = false;
break;
}
if (null == v) {
if (null != value) {
chk = false;
break;
}else{
continue;
}
} else {
if (null == value) {
chk = false;
break;
}
//与SQL.COMPARE_TYPE保持一致
int compare = 10;
if (v.startsWith("=")) {
compare = 10;
v = v.substring(1);
} else if (v.startsWith(">")) {
compare = 20;
v = v.substring(1);
} else if (v.startsWith(">=")) {
compare = 21;
v = v.substring(2);
} else if (v.startsWith("<")) {
compare = 30;
v = v.substring(1);
} else if (v.startsWith("<=")) {
compare = 31;
v = v.substring(2);
} else if (v.startsWith("%") && v.endsWith("%")) {
compare = 50;
v = v.substring(1, v.length() - 1);
} else if (v.endsWith("%")) {
compare = 51;
v = v.substring(0, v.length() - 1);
} else if (v.startsWith("%")) {
compare = 52;
v = v.substring(1);
}
if(compare <= 31 && value instanceof Number) {
try {
d1 = new BigDecimal(value.toString());
d2 = new BigDecimal(v);
int cr = d1.compareTo(d2);
if (compare == 10) {
if (cr != 0) {
chk = false;
break;
}
} else if (compare == 20) {
if (cr <= 0) {
chk = false;
break;
}
} else if (compare == 21) {
if (cr < 0) {
chk = false;
break;
}
} else if (compare == 30) {
if (cr >= 0) {
chk = false;
break;
}
} else if (compare == 31) {
if (cr > 0) {
chk = false;
break;
}
}
}catch (NumberFormatException e){
chk = false;
break;
}
}
String str = value + "";
str = str.toLowerCase();
v = v.toLowerCase();
if (srcFlag) {
v = "{" + v + "}";
}
if (compare == 10) {
if (!v.equals(str)) {
chk = false;
break;
}
} else if (compare == 50) {
if (!str.contains(v)) {
chk = false;
break;
}
} else if (compare == 51) {
if (!str.startsWith(v)) {
chk = false;
break;
}
} else if (compare == 52) {
if (!str.endsWith(v)) {
chk = false;
break;
}
}
}
}//end for kvs
if (chk) {
set.add(row);
if (qty > 0 && set.size() >= qty) {
break;
}
}
}//end for rows
set.cloneProperty(this);
return set;
}
public DataSet getRows(int begin, String... params) {
return getRows(begin, -1, params);
}
public DataSet getRows(String... params) {
return getRows(0, params);
}
public DataSet getRows(DataSet set, String key) {
String kvs[] = new String[set.size()];
int i = 0;
for (DataRow row : set) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
kvs[i++] = key + ":" + value;
}
}
return getRows(kvs);
}
public DataSet getRows(DataRow row, String... keys) {
List<String> list = new ArrayList<>();
int i = 0;
for (String key : keys) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
list.add(key + ":" + value);
}
}
String[] kvs = BeanUtil.list2array(list);
return getRows(kvs);
}
/**
* 数字格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatNumber(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatNumber(format, cols);
}
return this;
}
public DataSet numberFormat(String target, String key, String format){
for(DataRow row: rows){
numberFormat(target, key, format);
}
return this;
}
public DataSet numberFormat(String key, String format){
return numberFormat(key, key, format);
}
/**
* 日期格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatDate(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatDate(format, cols);
}
return this;
}
public DataSet dateFormat(String target, String key, String format){
for(DataRow row: rows){
dateFormat(target, key, format);
}
return this;
}
public DataSet dateFormat(String key, String format){
return dateFormat(key, key, format);
}
/**
* 提取符合指定属性值的集合
*
* @param begin begin
* @param end end
* @param key key
* @param value value
* @return return
*/
public DataSet filter(int begin, int end, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
int size = size();
if (begin < 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
tmpValue = getString(i, key, "");
if ((null == value && null == tmpValue)
|| (null != value && value.equals(tmpValue))) {
set.add(getRow(i));
}
}
set.cloneProperty(this);
return set;
}
public DataSet getRows(int fr, int to) {
DataSet set = new DataSet();
int size = this.size();
if (fr < 0) {
fr = 0;
}
for (int i = fr; i < size && i <= to; i++) {
set.addRow(getRow(i));
}
return set;
}
/**
* 合计
* @param begin 开始
* @param end 结束
* @param key key
* @return BigDecimal
*/
public BigDecimal sum(int begin, int end, String key) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (begin <= 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(getDecimal(i, key, 0));
}
}
return result;
}
public BigDecimal sum(String key) {
BigDecimal result = BigDecimal.ZERO;
result = sum(0, size() - 1, key);
return result;
}
/**
* 多列合计
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow sums(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, sum(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, sum(key));
}
}
}
return result;
}
public DataRow sums(String... keys) {
return sums(new DataRow(), keys);
}
/**
* 多列平均值
*
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key));
}
}
}
return result;
}
public DataRow avgs(String... keys) {
return avgs(new DataRow(), keys);
}
/**
* 多列平均值
* @param result 保存合计结果
* @param scale scale
* @param round round
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, int scale, int round, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key, scale, round));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key, scale, round));
}
}
}
return result;
}
public DataRow avgs(int scale, int round, String... keys) {
return avgs(new DataRow(), scale, round, keys);
}
/**
* 最大值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal maxDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) > 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal maxDecimal(String key) {
return maxDecimal(size(), key);
}
public int maxInt(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int maxInt(String key) {
return maxInt(size(), key);
}
public double maxDouble(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double maxDouble(String key) {
return maxDouble(size(), key);
}
// public BigDecimal max(int top, String key){
// BigDecimal result = maxDecimal(top, key);
// return result;
// }
// public BigDecimal max(String key){
// return maxDecimal(size(), key);
// }
/**
* 最小值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal minDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) < 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal minDecimal(String key) {
return minDecimal(size(), key);
}
public int minInt(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int minInt(String key) {
return minInt(size(), key);
}
public double minDouble(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double minDouble(String key) {
return minDouble(size(), key);
}
// public BigDecimal min(int top, String key){
// BigDecimal result = minDecimal(top, key);
// return result;
// }
// public BigDecimal min(String key){
// return minDecimal(size(), key);
// }
/**
* key对应的value最大的一行
*
* @param key key
* @return return
*/
public DataRow max(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(size - 1);
} else if (isDesc) {
row = getRow(0);
} else {
asc(key);
row = getRow(size - 1);
}
return row;
}
public DataRow min(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(0);
} else if (isDesc) {
row = getRow(size - 1);
} else {
asc(key);
row = getRow(0);
}
return row;
}
/**
* 平均值 空数据不参与加法但参与除法
*
* @param top 多少行
* @param key key
* @param scale scale
* @param round round
* @return return
*/
public BigDecimal avg(int top, String key, int scale, int round) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (size > top) {
size = top;
}
int count = 0;
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(tmp);
}
count++;
}
if (count > 0) {
result = result.divide(new BigDecimal(count), scale, round);
}
return result;
}
public BigDecimal avg(String key, int scale, int round) {
BigDecimal result = avg(size(), key, scale ,round);
return result;
}
public BigDecimal avg(String key) {
BigDecimal result = avg(size(), key, 2, BigDecimal.ROUND_HALF_UP);
return result;
}
public DataSet addRow(DataRow row) {
if (null != row) {
rows.add(row);
}
return this;
}
public DataSet addRow(int idx, DataRow row) {
if (null != row) {
rows.add(idx, row);
}
return this;
}
/**
* 合并key例的值 以connector连接
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concat(String key, String connector) {
return BasicUtil.concat(getStrings(key), connector);
}
public String concatNvl(String key, String connector) {
return BasicUtil.concat(getNvlStrings(key), connector);
}
/**
* 合并key例的值 以connector连接(不取null值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutNull(String key, String connector) {
return BasicUtil.concat(getStringsWithoutNull(key), connector);
}
/**
* 合并key例的值 以connector连接(不取空值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutEmpty(String key, String connector) {
return BasicUtil.concat(getStringsWithoutEmpty(key), connector);
}
public String concatNvl(String key) {
return BasicUtil.concat(getNvlStrings(key), ",");
}
public String concatWithoutNull(String key) {
return BasicUtil.concat(getStringsWithoutNull(key), ",");
}
public String concatWithoutEmpty(String key) {
return BasicUtil.concat(getStringsWithoutEmpty(key), ",");
}
public String concat(String key) {
return BasicUtil.concat(getStrings(key), ",");
}
/**
* 提取单列值
*
* @param key key
* @return return
*/
public List<Object> fetchValues(String key) {
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < size(); i++) {
result.add(get(i, key));
}
return result;
}
/**
* 取单列不重复的值
*
* @param key key
* @return return
*/
public List<String> fetchDistinctValue(String key) {
List<String> result = new ArrayList<>();
for (int i = 0; i < size(); i++) {
String value = getString(i, key, "");
if (result.contains(value)) {
continue;
}
result.add(value);
}
return result;
}
public List<String> fetchDistinctValues(String key) {
return fetchDistinctValue(key);
}
/**
* 分页
*
* @param link link
* @return return
*/
public String displayNavi(String link) {
String result = "";
if (null != navi) {
result = navi.getHtml();
}
return result;
}
public String navi(String link) {
return displayNavi(link);
}
public String displayNavi() {
return displayNavi(null);
}
public String navi() {
return displayNavi(null);
}
public DataSet put(int idx, String key, Object value) {
DataRow row = getRow(idx);
if (null != row) {
row.put(key, value);
}
return this;
}
public DataSet removes(String... keys) {
for (DataRow row : rows) {
row.removes(keys);
}
return this;
}
/**
* String
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getString(int index, String key) throws Exception {
return getRow(index).getString(key);
}
public String getString(int index, String key, String def) {
try {
return getString(index, key);
} catch (Exception e) {
return def;
}
}
public String getString(String key) throws Exception {
return getString(0, key);
}
public String getString(String key, String def) {
return getString(0, key, def);
}
public Object get(int index, String key) {
DataRow row = getRow(index);
if (null != row) {
return row.get(key);
}
return null;
}
public List<Object> gets(String key) {
List<Object> list = new ArrayList<Object>();
for (DataRow row : rows) {
list.add(row.getString(key));
}
return list;
}
public List<DataSet> getSets(String key) {
List<DataSet> list = new ArrayList<DataSet>();
for (DataRow row : rows) {
DataSet set = row.getSet(key);
if (null != set) {
list.add(set);
}
}
return list;
}
public List<String> getStrings(String key) {
List<String> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getString(key));
}
return result;
}
public List<Integer> getInts(String key) throws Exception {
List<Integer> result = new ArrayList<Integer>();
for (DataRow row : rows) {
result.add(row.getInt(key));
}
return result;
}
public List<Object> getObjects(String key) {
List<Object> result = new ArrayList<Object>();
for (DataRow row : rows) {
result.add(row.get(key));
}
return result;
}
public List<String> getDistinctStrings(String key) {
return fetchDistinctValue(key);
}
public List<String> getNvlStrings(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
} else {
result.add("");
}
}
return result;
}
public List<String> getStringsWithoutEmpty(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (BasicUtil.isNotEmpty(val)) {
result.add(val.toString());
}
}
return result;
}
public List<String> getStringsWithoutNull(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
}
}
return result;
}
public BigDecimal getDecimal(int idx, String key) throws Exception {
return getRow(idx).getDecimal(key);
}
public BigDecimal getDecimal(int idx, String key, double def) {
return getDecimal(idx, key, new BigDecimal(def));
}
public BigDecimal getDecimal(int idx, String key, BigDecimal def) {
try {
BigDecimal val = getDecimal(idx, key);
if (null == val) {
return def;
}
return val;
} catch (Exception e) {
return def;
}
}
/**
* 抽取指定列生成新的DataSet 新的DataSet只包括指定列的值与分页信息,不包含其他附加信息(如来源表)
* @param keys keys
* @return DataSet
*/
public DataSet extract(String ... keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
public DataSet extract(List<String> keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
/**
* html格式(未实现)
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getHtmlString(int index, String key) throws Exception {
return getString(index, key);
}
public String getHtmlString(int index, String key, String def) {
return getString(index, key, def);
}
public String getHtmlString(String key) throws Exception {
return getHtmlString(0, key);
}
/**
* escape String
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getEscapeString(int index, String key) throws Exception {
return EscapeUtil.escape(getString(index, key)).toString();
}
public String getEscapeString(int index, String key, String def) {
try {
return getEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.escape(def).toString();
}
}
public String getDoubleEscapeString(int index, String key) throws Exception {
return EscapeUtil.doubleEscape(getString(index, key));
}
public String getDoubleEscapeString(int index, String key, String def) {
try {
return getDoubleEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.doubleEscape(def);
}
}
public String getEscapeString(String key) throws Exception {
return getEscapeString(0, key);
}
public String getDoubleEscapeString(String key) throws Exception {
return getDoubleEscapeString(0, key);
}
/**
* int
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public int getInt(int index, String key) throws Exception {
return getRow(index).getInt(key);
}
public int getInt(int index, String key, int def) {
try {
return getInt(index, key);
} catch (Exception e) {
return def;
}
}
public int getInt(String key) throws Exception {
return getInt(0, key);
}
public int getInt(String key, int def) {
return getInt(0, key, def);
}
/**
* double
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public double getDouble(int index, String key) throws Exception {
return getRow(index).getDouble(key);
}
public double getDouble(int index, String key, double def) {
try {
return getDouble(index, key);
} catch (Exception e) {
return def;
}
}
public double getDouble(String key) throws Exception {
return getDouble(0, key);
}
public double getDouble(String key, double def) {
return getDouble(0, key, def);
}
/**
* 在key列基础上 +value,如果原来没有key列则默认0并put到target
* @param target 计算结果key
* @param key key
* @param value value
* @return this
*/
public DataSet add(String target, String key, int value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, double value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, short value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, float value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String key, int value){
return add(key, key, value);
}
public DataSet add(String key, double value){
return add(key, key, value);
}
public DataSet add(String key, short value){
return add(key, key, value);
}
public DataSet add(String key, float value){
return add(key, key, value);
}
public DataSet add(String key, BigDecimal value){
return add(key, key, value);
}
public DataSet subtract(String target, String key, int value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, double value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, short value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, float value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String key, int value){
return subtract(key, key, value);
}
public DataSet subtract(String key, double value){
return subtract(key, key, value);
}
public DataSet subtract(String key, short value){
return subtract(key, key, value);
}
public DataSet subtract(String key, float value){
return subtract(key, key, value);
}
public DataSet subtract(String key, BigDecimal value){
return subtract(key, key, value);
}
public DataSet multiply(String target, String key, int value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, double value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, short value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, float value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String key, int value){
return multiply(key,key,value);
}
public DataSet multiply(String key, double value){
return multiply(key,key,value);
}
public DataSet multiply(String key, short value){
return multiply(key,key,value);
}
public DataSet multiply(String key, float value){
return multiply(key,key,value);
}
public DataSet multiply(String key, BigDecimal value){
return multiply(key,key,value);
}
public DataSet divide(String target, String key, int value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, double value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, short value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, float value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, BigDecimal value, int mode){
for(DataRow row:rows){
row.divide(target, key, value, mode);
}
return this;
}
public DataSet divide(String key, int value){
return divide(key,key, value);
}
public DataSet divide(String key, double value){
return divide(key,key, value);
}
public DataSet divide(String key, short value){
return divide(key,key, value);
}
public DataSet divide(String key, float value){
return divide(key,key, value);
}
public DataSet divide(String key, BigDecimal value, int mode){
return divide(key,key, value, mode);
}
public DataSet round(String target, String key, int scale, int mode){
for (DataRow row:rows){
row.round(target, key, scale, mode);
}
return this;
}
public DataSet round(String key, int scale, int mode){
return round(key, key, scale, mode);
}
/**
* DataSet拆分成size部分
* @param page 拆成多少部分
* @return list
*/
public List<DataSet> split(int page){
List<DataSet> list = new ArrayList<>();
int size = this.size();
int vol = size / page;//每页多少行
for(int i=0; i<page; i++){
int fr = i*vol;
int to = (i+1)*vol-1;
if(i == page-1){
to = size-1;
}
DataSet set = this.cuts(fr, to);
list.add(set);
}
return list;
}
/**
* rows 列表中的数据格式化成json格式 不同与toJSON
* map.put("type", "list");
* map.put("result", result);
* map.put("message", message);
* map.put("rows", rows);
* map.put("success", result);
* map.put("navi", navi);
*/
public String toString() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", "list");
map.put("result", result);
map.put("message", message);
map.put("rows", rows);
map.put("success", result);
if(null != navi){
Map<String,Object> navi_ = new HashMap<String,Object>();
navi_.put("page", navi.getCurPage());
navi_.put("pages", navi.getTotalPage());
navi_.put("rows", navi.getTotalRow());
navi_.put("vol", navi.getPageRows());
map.put("navi", navi_);
}
return BeanUtil.map2json(map);
}
/**
* rows 列表中的数据格式化成json格式 不同与toString
*
* @return return
*/
public String toJson() {
return BeanUtil.object2json(this);
}
public String getJson() {
return toJSON();
}
public String toJSON() {
return toJson();
}
/**
* 根据指定列生成map
*
* @param key ID,{ID}_{NM}
* @return return
*/
public Map<String, DataRow> toMap(String key) {
Map<String, DataRow> maps = new HashMap<String, DataRow>();
for (DataRow row : rows) {
maps.put(row.getString(key), row);
}
return maps;
}
/**
* 子类
*
* @param idx idx
* @return return
*/
public Object getChildren(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getChildren();
}
return null;
}
public Object getChildren() {
return getChildren(0);
}
public DataSet setChildren(int idx, Object children) {
DataRow row = getRow(idx);
if (null != row) {
row.setChildren(children);
}
return this;
}
public DataSet setChildren(Object children) {
setChildren(0, children);
return this;
}
/**
* 父类
*
* @param idx idx
* @return return
*/
public Object getParent(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getParent();
}
return null;
}
public Object getParent() {
return getParent(0);
}
public DataSet setParent(int idx, Object parent) {
DataRow row = getRow(idx);
if (null != row) {
row.setParent(parent);
}
return this;
}
public DataSet setParent(Object parent) {
setParent(0, parent);
return this;
}
/**
* 转换成对象
*
* @param <T> T
* @param index index
* @param clazz clazz
* @return return
*/
public <T> T entity(int index, Class<T> clazz) {
DataRow row = getRow(index);
if (null != row) {
return row.entity(clazz);
}
return null;
}
/**
* 转换成对象集合
*
* @param <T> T
* @param clazz clazz
* @return return
*/
public <T> List<T> entity(Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (null != rows) {
for (DataRow row : rows) {
list.add(row.entity(clazz));
}
}
return list;
}
public <T> T entity(Class<T> clazz, int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.entity(clazz);
}
return null;
}
public DataSet setDataSource(String dataSource) {
if (null == dataSource) {
return this;
}
this.dataSource = dataSource;
if (dataSource.contains(".") && !dataSource.contains(":")) {
schema = dataSource.substring(0, dataSource.indexOf("."));
table = dataSource.substring(dataSource.indexOf(".") + 1);
}
for (DataRow row : rows) {
if (BasicUtil.isEmpty(row.getDataSource())) {
row.setDataSource(dataSource);
}
}
return this;
}
/**
* 合并
* @param set DataSet
* @param keys 根据keys去重
* @return DataSet
*/
public DataSet union(DataSet set, String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY");
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
if (!result.contains(item, keys)) {
result.add(item);
}
}
return result;
}
/**
* 合并合并不去重
*
* @param set set
* @return return
*/
public DataSet unionAll(DataSet set) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
result.add(item);
}
return result;
}
/**
* 是否包含这一行
*
* @param row row
* @param keys keys
* @return return
*/
public boolean contains(DataRow row, String... keys) {
if (null == rows || rows.size() == 0 || null == row) {
return false;
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY", "ID");
}
String params[] = packParam(row, keys);
return exists(params);
}
public String[] packParam(DataRow row, String... keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.length * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 根据数据与属性列表 封装kvs
* ["ID","1","CODE","A01"]
* @param row 数据 DataRow
* @param keys 属性 ID,CODE
* @return kvs
*/
public String[] packParam(DataRow row, List<String> keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.size() * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 从items中按相应的key提取数据 存入
* dispatch("children",items, "DEPAT_CD")
* dispatchs("children",items, "CD:BASE_CD")
*
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEMS";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] kvs = packParam(row, reverseKey(keys));
DataSet set = items.getRows(kvs);
if (recursion) {
set.dispatchs(field, unique, recursion, items, keys);
}
if(unique) {
set.skip(true);
}
row.put(field, set);
}
}
items.skip(false);
return this;
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, keys);
}
public DataSet dispatchs(String field, DataSet items, String... keys) {
return dispatchs(field,false, false, items, keys);
}
public DataSet dispatchs(DataSet items, String... keys) {
return dispatchs("ITEMS", items, keys);
}
public DataSet dispatchs(boolean unique, boolean recursion, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, keys);
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEM";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if(unique){
result.skip = true;
}
row.put(field, result);
}
}
items.skip(false);
return this;
}
public DataSet dispatch(String field, DataSet items, String... keys) {
return dispatch(field, false, false, items, keys);
}
public DataSet dispatch(DataSet items, String... keys) {
return dispatch("ITEM", items, keys);
}
public DataSet dispatch(boolean unique, boolean recursion, String... keys) {
return dispatch("ITEM", unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, this, keys);
}
/**
* 直接调用dispatchs
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs( unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(String field, DataSet items, String... keys) {
return dispatchs(field, items, keys);
}
@Deprecated
public DataSet dispatchItems(DataSet items, String... keys) {
return dispatchs(items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, String... keys) {
return dispatchs( unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatch(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItem(String field, DataSet items, String... keys) {
return dispatch(field, items, keys);
}
@Deprecated
public DataSet dispatchItem(DataSet items, String... keys) {
return dispatch(items, keys);
}
@Deprecated
public DataSet dispatchItem(boolean unique, boolean recursion, String... keys) {
return dispatch(unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, keys);
}
/**
* 根据keys列建立关联,并将关联出来的结果拼接到集合的条目上,如果有重复则覆盖条目
*
* @param items 被查询的集合
* @param keys 关联条件列
* @return return
*/
public DataSet join(DataSet items, String... keys) {
if (null == items || null == keys || keys.length == 0) {
return this;
}
for (DataRow row : rows) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if (null != result) {
row.copy(result, result.keys());
}
}
return this;
}
public DataSet toLowerKey() {
for (DataRow row : rows) {
row.toLowerKey();
}
return this;
}
public DataSet toUpperKey() {
for (DataRow row : rows) {
row.toUpperKey();
}
return this;
}
/**
* 按keys分组
*
* @param keys keys
* @return return
*/
public DataSet group(String... keys) {
DataSet result = distinct(keys);
result.dispatchs(true,false, this, keys);
return result;
}
public DataSet or(DataSet set, String... keys) {
return this.union(set, keys);
}
public DataSet getRows(Map<String, String> kvs) {
return getRows(0, -1, kvs);
}
/**
* 多个集合的交集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param sets 集合
* @param keys 判断依据
* @return DataSet
*/
public static DataSet intersection(boolean distinct, List<DataSet> sets, String... keys) {
DataSet result = null;
if (null != sets && sets.size() > 0) {
for (DataSet set : sets) {
if (null == result) {
result = set;
} else {
result = result.intersection(distinct, set, keys);
}
}
}
if (null == result) {
result = new DataSet();
}
return result;
}
public static DataSet intersection(List<DataSet> sets, String... keys) {
return intersection(false, sets, keys);
}
/**
* 交集
*
* @param distinct 是否根据keys抽取不重复的集合(根据keys去重)
* @param set set
* @param keys 根据keys列比较是否相等,如果列名不一致"ID:USER_ID",ID表示当前DataSet的列,USER_ID表示参数中DataSet的列
* @return return
*/
public DataSet intersection(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
if (null == set) {
return result;
}
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (set.contains(row, kv)) { //符合交集
if(!result.contains(row, kv)){//result中没有
result.add((DataRow) row.clone());
}else {
if(!distinct){//result中有但不要求distinct
result.add((DataRow) row.clone());
}
}
}
}
return result;
}
public DataSet intersection(DataSet set, String... keys) {
return intersection(false, set, keys);
}
public DataSet and(boolean distinct, DataSet set, String... keys) {
return intersection(distinct, set, keys);
}
public DataSet and(DataSet set, String... keys) {
return intersection(false, set, keys);
}
/**
* 补集
* 在this中,但不在set中
* this作为超集 set作为子集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys keys
* @return return
*/
public DataSet complement(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet complement(DataSet set, String... keys) {
return complement(false, set, keys);
}
/**
* 差集
* 从当前集合中删除set中存在的row,生成新的DataSet并不修改当前对象
* this中有 set中没有的
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys CD,"CD:WORK_CD"
* @return return
*/
public DataSet difference(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet difference(DataSet set, String... keys) {
return difference(false, set, keys);
}
/**
* 颠倒kv-vk
*
* @param keys kv
* @return String[]
*/
private String[] reverseKey(String[] keys) {
if (null == keys) {
return new String[0];
}
int size = keys.length;
String result[] = new String[size];
for (int i = 0; i < size; i++) {
String key = keys[i];
if (BasicUtil.isNotEmpty(key) && key.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(key);
key = ks[1] + ":" + ks[0];
}
result[i] = key;
}
return result;
}
/**
* 清除指定列全为空的行,如果不指定keys,则清除所有列都为空的行
*
* @param keys keys
* @return DataSet
*/
public DataSet removeEmptyRow(String... keys) {
int size = this.size();
for (int i = size - 1; i >= 0; i--) {
DataRow row = getRow(i);
if (null == keys || keys.length == 0) {
if (row.isEmpty()) {
this.remove(row);
}
} else {
boolean isEmpty = true;
for (String key : keys) {
if (row.isNotEmpty(key)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
this.remove(row);
}
}
}
return this;
}
public DataSet changeKey(String key, String target, boolean remove) {
for(DataRow row:rows){
row.changeKey(key, target, remove);
}
return this;
}
public DataSet changeKey(String key, String target) {
return changeKey(key, target, true);
}
/**
* 删除rows中的columns列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeColumn(String... columns) {
if (null != columns) {
for (String column : columns) {
for (DataRow row : rows) {
row.remove(column);
}
}
}
return this;
}
/**
* 删除rows中值为空(null|'')的列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeEmptyColumn(String... columns) {
for (DataRow row : rows) {
row.removeEmpty(columns);
}
return this;
}
/**
* NULL > ""
*
* @return DataSet
*/
public DataSet nvl() {
for (DataRow row : rows) {
row.nvl();
}
return this;
}
/* ********************************************** 实现接口 *********************************************************** */
public boolean add(DataRow e) {
return rows.add((DataRow) e);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public boolean addAll(Collection c) {
return rows.addAll(c);
}
public void clear() {
rows.clear();
}
public boolean contains(Object o) {
return rows.contains(o);
}
public boolean containsAll(Collection<?> c) {
return rows.containsAll(c);
}
public Iterator<DataRow> iterator() {
return rows.iterator();
}
public boolean remove(Object o) {
return rows.remove(o);
}
public boolean removeAll(Collection<?> c) {
return rows.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return rows.retainAll(c);
}
public Object[] toArray() {
return rows.toArray();
}
@SuppressWarnings("unchecked")
public Object[] toArray(Object[] a) {
return rows.toArray(a);
}
public String getSchema() {
return schema;
}
public DataSet setSchema(String schema) {
this.schema = schema;
return this;
}
public String getTable() {
return table;
}
public DataSet setTable(String table) {
if (null != table && table.contains(".")) {
String[] tbs = table.split("\\.");
this.table = tbs[1];
this.schema = tbs[0];
} else {
this.table = table;
}
return this;
}
/**
* 验证是否过期
* 根据当前时间与创建时间对比
* 过期返回 true
*
* @param millisecond 过期时间(毫秒) millisecond 过期时间(毫秒)
* @return boolean
*/
public boolean isExpire(int millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire(long millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire() {
if (getExpires() == -1) {
return false;
}
if (System.currentTimeMillis() - createTime > getExpires()) {
return true;
}
return false;
}
public long getCreateTime() {
return createTime;
}
public List<DataRow> getRows() {
return rows;
}
/************************** getter setter ***************************************/
/**
* 过期时间(毫秒)
*
* @return long
*/
public long getExpires() {
return expires;
}
public DataSet setExpires(long millisecond) {
this.expires = millisecond;
return this;
}
public DataSet setExpires(int millisecond) {
this.expires = millisecond;
return this;
}
public boolean isResult() {
return result;
}
public boolean isSuccess() {
return result;
}
public DataSet setResult(boolean result) {
this.result = result;
return this;
}
public Exception getException() {
return exception;
}
public DataSet setException(Exception exception) {
this.exception = exception;
return this;
}
public String getMessage() {
return message;
}
public DataSet setMessage(String message) {
this.message = message;
return this;
}
public PageNavi getNavi() {
return navi;
}
public DataSet setNavi(PageNavi navi) {
this.navi = navi;
return this;
}
public DataSet setRows(List<DataRow> rows) {
this.rows = rows;
return this;
}
public String getDataSource() {
String ds = table;
if (BasicUtil.isNotEmpty(ds) && BasicUtil.isNotEmpty(schema)) {
ds = schema + "." + ds;
}
if (BasicUtil.isEmpty(ds)) {
ds = dataSource;
}
return ds;
}
public DataSet order(final String... keys) {
return asc(keys);
}
public DataSet put(String key, Object value, boolean pk, boolean override) {
for (DataRow row : rows) {
row.put(key, value, pk, override);
}
return this;
}
public DataSet put(String key, Object value, boolean pk) {
for (DataRow row : rows) {
row.put(key, value, pk);
}
return this;
}
public DataSet put(String key, Object value) {
for (DataRow row : rows) {
row.put(key, value);
}
return this;
}
/**
* 行转列
* 表结构(编号, 姓名, 年度, 科目, 分数, 等级)
* @param pks 唯一标识key(如编号,姓名)
* @param classKeys 分类key(如年度,科目)
* @param valueKeys 取值key(如分数,等级),如果不指定key则将整行作为value
* @return
* 如果指定key
* 返回结构 [
* {编号:01,姓名:张三,2010-数学-分数:100},
* {编号:01,姓名:张三,2010-数学-等级:A},
* {编号:01,姓名:张三,2010-物理-分数:100}
* ]
* 如果只有一个valueKey则返回[
* {编号:01,姓名:张三,2010-数学:100},
* {编号:01,姓名:张三,2010-物理:90}
* ]
* 不指定valuekey则返回 [
* {编号:01,姓名:张三,2010-数学:{分数:100,等级:A}},
* {编号:01,姓名:张三,2010-物理:{分数:100,等级:A}}
* ]
*/
public DataSet pivot(List<String> pks, List<String> classKeys, List<String> valueKeys) {
DataSet result = distinct(pks);
DataSet classValues = distinct(classKeys); //[{年度:2010,科目:数学},{年度:2010,科目:物理},{年度:2011,科目:数学}]
for (DataRow row : result) {
for (DataRow classValue : classValues) {
DataRow params = new DataRow();
params.copy(row, pks).copy(classValue);
DataRow valueRow = getRow(params);
if(null != valueRow){
valueRow.skip = true;
}
String finalKey = concatValue(classValue,"-");//2010-数学
if(null != valueKeys && valueKeys.size() > 0){
if(valueKeys.size() == 1){
if (null != valueRow) {
row.put(finalKey, valueRow.get(valueKeys.get(0)));
} else {
row.put(finalKey, null);
}
}else {
for (String valueKey : valueKeys) {
//{2010-数学-分数:100;2010-数学-等级:A}
if (null != valueRow) {
row.put(finalKey + "-" + valueKey, valueRow.get(valueKey));
} else {
row.put(finalKey + "-" + valueKey, null);
}
}
}
}else{
if (null != valueRow){
row.put(finalKey, valueRow);
}else{
row.put(finalKey, null);
}
}
}
}
skip(false);
return result;
}
public DataSet pivot(String[] pks, String[] classKeys, String[] valueKeys) {
return pivot(Arrays.asList(pks),Arrays.asList(classKeys),Arrays.asList(valueKeys));
}
/**
* 行转列
* @param pk 唯一标识key(如姓名)多个key以,分隔如(编号,姓名)
* @param classKey 分类key(如科目)多个key以,分隔如(科目,年度)
* @param valueKey 取值key(如分数)多个key以,分隔如(分数,等级)
* @return
* 表结构(姓名,科目,分数)
* 返回结构 [{姓名:张三,数学:100,物理:90,英语:80},{姓名:李四,数学:100,物理:90,英语:80}]
*/
public DataSet pivot(String pk, String classKey, String valueKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>(Arrays.asList(valueKey.trim().split(",")));
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(String pk, String classKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>();
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(List<String> pks, List<String> classKeys, String ... valueKeys) {
List<String> list = new ArrayList<>();
if(null != valueKeys){
for(String item:valueKeys){
list.add(item);
}
}
return pivot(pks, classKeys, valueKeys);
}
private String concatValue(DataRow row, String split){
StringBuilder builder = new StringBuilder();
List<String> keys = row.keys();
for(String key:keys){
if(builder.length() > 0){
builder.append(split);
}
builder.append(row.getString(key));
}
return builder.toString();
}
private String[] kvs(DataRow row){
List<String> keys = row.keys();
int size = keys.size();
String[] kvs = new String[size*2];
for(int i=0; i<size; i++){
String k = keys.get(i);
String v = row.getStringNvl(k);
kvs[i*2] = k;
kvs[i*2+1] = v;
}
return kvs;
}
/**
* 排序
*
* @param keys keys
* @return DataSet
*/
public DataSet asc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return -1;
} else {
if (null == v2) {
return 1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal num1 = new BigDecimal(v1.toString());
BigDecimal num2 = new BigDecimal(v2.toString());
result = num1.compareTo(num2);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date1.compareTo(date2);
} else {
result = v1.toString().compareTo(v2.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = true;
isDesc = false;
return this;
}
public DataSet desc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return 1;
} else {
if (null == v2) {
return -1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal val1 = new BigDecimal(v1.toString());
BigDecimal val2 = new BigDecimal(v2.toString());
result = val2.compareTo(val1);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date2.compareTo(date1);
} else {
result = v2.toString().compareTo(v1.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = false;
isDesc = true;
return this;
}
public DataSet addAllUpdateColumns() {
for (DataRow row : rows) {
row.addAllUpdateColumns();
}
return this;
}
public DataSet clearUpdateColumns() {
for (DataRow row : rows) {
row.clearUpdateColumns();
}
return this;
}
public DataSet removeNull(String... keys) {
for (DataRow row : rows) {
row.removeNull(keys);
}
return this;
}
private static String key(String key) {
if (null != key && ConfigTable.IS_UPPER_KEY) {
key = key.toUpperCase();
}
return key;
}
/**
* 替换所有NULL值
*
* @param value value
* @return return
*/
public DataSet replaceNull(String value) {
for (DataRow row : rows) {
row.replaceNull(value);
}
return this;
}
/**
* 替换所有空值
*
* @param value value
* @return return
*/
public DataSet replaceEmpty(String value) {
for (DataRow row : rows) {
row.replaceEmpty(value);
}
return this;
}
/**
* 替换所有NULL值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceNull(String key, String value) {
for (DataRow row : rows) {
row.replaceNull(key, value);
}
return this;
}
/**
* 替换所有空值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceEmpty(String key, String value) {
for (DataRow row : rows) {
row.replaceEmpty(key, value);
}
return this;
}
public DataSet replace(String key, String oldChar, String newChar) {
if (null == key || null == oldChar || null == newChar) {
return this;
}
for (DataRow row : rows) {
row.replace(key, oldChar, newChar);
}
return this;
}
public DataSet replace(String oldChar, String newChar) {
for (DataRow row : rows) {
row.replace(oldChar, newChar);
}
return this;
}
/* ************************* 类sql操作 ************************************** */
/**
* 随机取一行
* @return DataRow
*/
public DataRow random() {
DataRow row = null;
int size = size();
if (size > 0) {
row = getRow(BasicUtil.getRandomNumber(0, size - 1));
}
return row;
}
/**
* 随机取qty行
* @param qty 行数
* @return DataSet
*/
public DataSet randoms(int qty) {
DataSet set = new DataSet();
int size = size();
if (qty < 0) {
qty = 0;
}
if (qty > size) {
qty = size;
}
for (int i = 0; i < qty; i++) {
while (true) {
int idx = BasicUtil.getRandomNumber(0, size - 1);
DataRow row = set.getRow(idx);
if (!set.contains(row)) {
set.add(row);
break;
}
}
}
set.cloneProperty(this);
return set;
}
/**
* 随机取min到max行
* @param min min
* @param max max
* @return DataSet
*/
public DataSet randoms(int min, int max) {
int qty = BasicUtil.getRandomNumber(min, max);
return randoms(qty);
}
public DataSet unique(String... keys) {
return distinct(keys);
}
/**
* 根据正则提取集合
* @param key key
* @param regex 正则
* @param mode 匹配方式
* @return DataSet
*/
public DataSet regex(String key, String regex, Regular.MATCH_MODE mode) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : this) {
tmpValue = row.getString(key);
if (RegularUtil.match(tmpValue, regex, mode)) {
set.add(row);
}
}
set.cloneProperty(this);
return set;
}
public DataSet regex(String key, String regex) {
return regex(key, regex, Regular.MATCH_MODE.MATCH);
}
public boolean checkRequired(String... keys) {
for (DataRow row : rows) {
if (!row.checkRequired(keys)) {
return false;
}
}
return true;
}
public Map<String, Object> getQueryParams() {
return queryParams;
}
public DataSet setQueryParams(Map<String, Object> params) {
this.queryParams = params;
return this;
}
public Object getQueryParam(String key) {
return queryParams.get(key);
}
public DataSet addQueryParam(String key, Object param) {
queryParams.put(key, param);
return this;
}
public String getDatalink() {
return datalink;
}
public void setDatalink(String datalink) {
this.datalink = datalink;
}
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
private boolean ignoreCase = true; //是否忽略大小写
/**
* 是否忽略NULL 如果设置成true 在执行equal notEqual like contains进 null与null比较返回false
* 左右出现NULL时直接返回false
* true会导致一行数据 equal notEqual都筛选不到
*/
private boolean ignoreNull = true;
public DataSet setIgnoreCase(boolean bol) {
this.ignoreCase = bol;
return DataSet.this;
}
public DataSet setIgnoreNull(boolean bol) {
this.ignoreNull = bol;
return DataSet.this;
}
/**
* 筛选key=value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet equals(String key, String value) {
return equals(DataSet.this, key, value);
}
private DataSet equals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = tmpValue.equalsIgnoreCase(value);
} else {
chk = tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key != value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet notEquals(String key, String value) {
return notEquals(DataSet.this, key, value);
}
private DataSet notEquals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = !tmpValue.equalsIgnoreCase(value);
} else {
chk = !tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值是否包含value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet contains(String key, String value) {
return contains(DataSet.this, key, value);
}
private DataSet contains(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == value) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
value = value.toLowerCase();
}
if (tmpValue.contains(value)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值like pattern的子集,pattern遵循sql通配符的规则,%表示任意个字符,_表示一个字符
*
* @param key 列
* @param pattern 表达式
* @return DataSet
*/
public DataSet like(String key, String pattern) {
return like(DataSet.this, key, pattern);
}
private DataSet like(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null != pattern) {
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
}
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet notLike(String key, String pattern) {
return notLike(DataSet.this, key, pattern);
}
private DataSet notLike(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null == pattern) {
return set;
}
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (!RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet startWith(String key, String prefix) {
return startWith(DataSet.this, key, prefix);
}
private DataSet startWith(DataSet src, String key, String prefix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == prefix) {
continue;
}
} else {
if (null == tmpValue && null == prefix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == prefix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
prefix = prefix.toLowerCase();
}
if (tmpValue.startsWith(prefix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet endWith(String key, String suffix) {
return endWith(DataSet.this, key, suffix);
}
private DataSet endWith(DataSet src, String key, String suffix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == suffix) {
continue;
}
} else {
if (null == tmpValue && null == suffix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == suffix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
suffix = suffix.toLowerCase();
}
if (tmpValue.endsWith(suffix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet in(String key, T... values) {
return in(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet in(String key, Collection<T> values) {
return in(DataSet.this, key, values);
}
private <T> DataSet in(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
for (DataRow row : src) {
if (BasicUtil.containsString(ignoreNull, ignoreCase, values, row.getString(key))) {
set.add(row);
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet notIn(String key, T... values) {
return notIn(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet notIn(String key, Collection<T> values) {
return notIn(DataSet.this, key, values);
}
private <T> DataSet notIn(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
if (null != values) {
String tmpValue = null;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull && null == tmpValue) {
continue;
}
if (!BasicUtil.containsString(ignoreNull, ignoreCase, values, tmpValue)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet isNull(String... keys) {
return isNull(DataSet.this, keys);
}
private DataSet isNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNull(set, key);
}
}
return set;
}
private DataSet isNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null == row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet isNotNull(String... keys) {
return isNotNull(DataSet.this, keys);
}
private DataSet isNotNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotNull(set, key);
}
}
return set;
}
private DataSet isNotNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null != row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet notNull(String... keys) {
return isNotNull(keys);
}
public DataSet isEmpty(String... keys) {
return isEmpty(DataSet.this, keys);
}
private DataSet isEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isEmpty(set, key);
}
}
return set;
}
private DataSet isEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet empty(String... keys) {
return isEmpty(keys);
}
public DataSet isNotEmpty(String... keys) {
return isNotEmpty(DataSet.this, keys);
}
private DataSet isNotEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotEmpty(set, key);
}
}
return set;
}
private DataSet isNotEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isNotEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet notEmpty(String... keys) {
return isNotEmpty(keys);
}
public <T> DataSet less(String key, T value) {
return less(DataSet.this, key, value);
}
private <T> DataSet less(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) < 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) < 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) < 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet lessEqual(String key, T value) {
return lessEqual(DataSet.this, key, value);
}
private <T> DataSet lessEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) <= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) <= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greater(String key, T value) {
return greater(DataSet.this, key, value);
}
private <T> DataSet greater(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) > 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) > 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) > 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greaterEqual(String key, T value) {
return greaterEqual(DataSet.this, key, value);
}
private <T> DataSet greaterEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) >= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) >= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet between(String key, T min, T max) {
return between(DataSet.this, key, min, max);
}
private <T> DataSet between(DataSet src, String key, T min, T max) {
DataSet set = greaterEqual(src, key, min);
set = lessEqual(set, key, max);
return set;
}
}
public Select select = new Select();
} | anylineorg/anyline | anyline-core/src/main/java/org/anyline/entity/DataSet.java | Java | apache-2.0 | 115,477 |
package ua.job4j.loop;
/**
* Class Класс для вычисления факториала заданного числа.
* @author vfrundin
* @since 05.11.2017
* @version 1.0
*/
public class Factorial {
/**
* Метод должен вычислять факториал поданного на вход числа.
* @param n Число для которого нужно определить факториал.
* @return result - найденный факториал числа n.
*/
public int calc(int n) {
int result = 1;
if (n != 0) {
for (int i = 1; i <= n; i++) {
result *= i;
}
}
return result;
}
}
| Krok3/junior | chapter_001/src/main/java/ua/job4j/loop/Factorial.java | Java | apache-2.0 | 728 |
/* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.graphs.base.compact;
import net.automatalib.commons.smartcollections.ResizingArrayStorage;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CompactBidiGraph<@Nullable NP, @Nullable EP> extends AbstractCompactBidiGraph<NP, EP> {
private final ResizingArrayStorage<NP> nodeProperties;
public CompactBidiGraph() {
this.nodeProperties = new ResizingArrayStorage<>(Object.class);
}
public CompactBidiGraph(int initialCapacity) {
super(initialCapacity);
this.nodeProperties = new ResizingArrayStorage<>(Object.class, initialCapacity);
}
@Override
public void setNodeProperty(int node, @Nullable NP property) {
nodeProperties.ensureCapacity(node + 1);
nodeProperties.array[node] = property;
}
@Override
public NP getNodeProperty(int node) {
return node < nodeProperties.array.length ? nodeProperties.array[node] : null;
}
}
| LearnLib/automatalib | core/src/main/java/net/automatalib/graphs/base/compact/CompactBidiGraph.java | Java | apache-2.0 | 1,632 |
package com.github.binarywang.wxpay.service.impl;
import com.github.binarywang.wxpay.bean.request.*;
import com.github.binarywang.wxpay.bean.result.*;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.testbase.ApiTestModule;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
/**
* @author chenliang
* @date 2021-08-02 6:45 下午
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxEntrustPapServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
private WxPayService payService;
/**
* 公众号纯签约
*/
@Test
public void testMpSign() {
String contractCode = "222200002222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000014", ")");
WxMpEntrustRequest wxMpEntrust = WxMpEntrustRequest.newBuilder()
.planId("142323") //模板ID:跟微信申请
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.requestSerial(6L)
//.returnWeb(1)
.version("1.0")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.outerId(displayAccount)
.build();
String url = null;
try {
url = this.payService.getWxEntrustPapService().mpSign(wxMpEntrust);
} catch (WxPayException e) {
e.printStackTrace();
}
logger.info(url);
}
/**
* 小程序纯签约
*/
@Test
public void testMaSign() {
String contractCode = "222220000022222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000001", ")");
WxMaEntrustRequest wxMaEntrustRequest = WxMaEntrustRequest.newBuilder()
.contractCode(contractCode)
.contractDisplayAccount(contractCode)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.outerId(displayAccount)
.planId("141535")
.requestSerial(2L)
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.build();
try {
String url = this.payService.getWxEntrustPapService().maSign(wxMaEntrustRequest);
logger.info(url);
} catch (WxPayException e) {
e.printStackTrace();
}
}
/**
* h5纯签约
*/
@Test
public void testH5Sign() {
String contractCode = "222111122222";
String displayAccount = Joiner.on("").join("陈*", "(", "100000000", ")");
WxH5EntrustRequest wxH5EntrustRequest = WxH5EntrustRequest.newBuilder()
.requestSerial(2L)
.clientIp("127.0.0.1")
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.planId("141535")
.returnAppid("1")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.version("1.0")
.outerId(displayAccount)
.build();
try {
WxH5EntrustResult wxH5EntrustResult = this.payService.getWxEntrustPapService().h5Sign(wxH5EntrustRequest);
logger.info(wxH5EntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPaySign() {
String contractCode = "2222211110000222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000005", ")");
String outTradeNo = "11100111101";
WxPayEntrustRequest wxPayEntrustRequest = WxPayEntrustRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractAppId(this.payService.getConfig().getAppId())
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.contractMchId(this.payService.getConfig().getMchId())
//签约回调
.contractNotifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.detail("产品是好")
.deviceInfo("oneplus 7 pro")
//.goodsTag()
//.limitPay()
//支付回调
.notifyUrl("http://domain.com/api/wxpay/pay/callback.do")
.openId("oIvLdt8Q-_aKy4Vo6f4YI6gsIhMc") //openId
.outTradeNo(outTradeNo)
.planId("141535")
//.productId()
.requestSerial(3L)
.spbillCreateIp("127.0.0.1")
//.timeExpire()
//.timeStart()
.totalFee(1)
.tradeType("MWEB")
.contractOuterId(displayAccount)
.build();
try {
WxPayEntrustResult wxPayEntrustResult = this.payService.getWxEntrustPapService().paySign(wxPayEntrustRequest);
logger.info(wxPayEntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testWithhold() {
String outTradeNo = "101010101";
WxWithholdRequest withholdRequest = WxWithholdRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractId("202011065409471222") // 微信返回的签约协议号
.detail("产品描述")
.feeType("CNY")
//.goodsTag()
.notifyUrl("http://domain.com/api/wxpay/withhold/callback.do")
.outTradeNo(outTradeNo)
.spbillCreateIp("127.0.0.1")
.totalFee(1)
.tradeType("PAP")
.build();
try {
WxWithholdResult wxWithholdResult = this.payService.getWxEntrustPapService().withhold(withholdRequest);
logger.info(wxWithholdResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPreWithhold() {
WxPreWithholdRequest.EstimateAmount estimateAmount = new WxPreWithholdRequest.EstimateAmount();
estimateAmount.setAmount(1);
estimateAmount.setCurrency("CNY");
WxPreWithholdRequest wxPreWithholdRequest = WxPreWithholdRequest.newBuilder()
.appId("wx73dssxxxxxx")
.contractId("202010275173070001")
.estimateAmount(estimateAmount)
.mchId("1600010102")
.build();
try {
String httpResponseModel = this.payService.getWxEntrustPapService().preWithhold(wxPreWithholdRequest);
logger.info(httpResponseModel);
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testQuerySign() {
String outTradeNo = "1212121212";
WxSignQueryRequest wxSignQueryRequest = WxSignQueryRequest.newBuilder()
//.contractId("202010275173073211")
.contractCode(outTradeNo)
.planId(1432112)
.version("1.0")
.build();
try {
WxSignQueryResult wxSignQueryResult = this.payService.getWxEntrustPapService().querySign(wxSignQueryRequest);
logger.info(wxSignQueryResult.toString());
} catch (WxPayException e) {
logger.info("异常码:" + e.getErrCode());
logger.info("异常:" + e);
}
}
@Test
public void testTerminationContract() {
WxTerminatedContractRequest wxTerminatedContractRequest = WxTerminatedContractRequest.newBuilder()
.contractId("202010275173070231")
.contractTerminationRemark("测试解约")
.version("1.0")
.build();
try {
WxTerminationContractResult wxTerminationContractResult = this.payService.getWxEntrustPapService().terminationContract(wxTerminatedContractRequest);
logger.info(wxTerminationContractResult.toString());
} catch (WxPayException e) {
logger.error(e.getMessage());
}
}
}
| Wechat-Group/WxJava | weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxEntrustPapServiceTest.java | Java | apache-2.0 | 7,346 |
package org.clinical3PO.common.security;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.clinical3PO.common.security.model.User;
import org.clinical3PO.common.security.service.UserService;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
User user = userService.loadUserByUsername(username);
if (user == null) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
| Clinical3PO/Platform | dev/clinical3PO/app/src/main/java/org/clinical3PO/common/security/CustomAuthenticationProvider.java | Java | apache-2.0 | 1,572 |
package com.example.mywechat.utils;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
/**
* ActivityCollector ÀàÓÃÓÚ¹ÜÀíËùÓеĻ
* @author dzhiqin
*
*/
public class ActivityCollector {
public static List<Activity> activities=new ArrayList<Activity>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity){
activities.remove(activity);
}
/**
* ¹Ø±ÕËùÓл
*/
public static void finishAll(){
for(Activity activity:activities){
if(!activity.isFinishing()){
activity.finish();
}
}
}
public ActivityCollector() {
// TODO ×Ô¶¯Éú³ÉµÄ¹¹Ô캯Êý´æ¸ù
}
}
| dzhiqin/MyWeChat | src/com/example/mywechat/utils/ActivityCollector.java | Java | apache-2.0 | 697 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Cleidimar Viana
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.seamusdawkins.tablayout.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.seamusdawkins.tablayout.R;
public class FirstFragment extends Fragment {
TextView tv;
RelativeLayout rl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
tv = (TextView) rootView.findViewById(R.id.action);
tv.setText(R.string.str_first);
return rootView;
}
}
| cleidimarviana/Tabs-Material | app/src/main/java/com/seamusdawkins/tablayout/fragments/FirstFragment.java | Java | apache-2.0 | 1,928 |
/**
* 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.gora.cassandra.store;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.serializers.ByteBufferSerializer;
import me.prettyprint.cassandra.serializers.IntegerSerializer;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.OrderedSuperRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.beans.SuperRow;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.RangeSlicesQuery;
import me.prettyprint.hector.api.query.RangeSuperSlicesQuery;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Serializer;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.util.Utf8;
import org.apache.gora.cassandra.query.CassandraQuery;
import org.apache.gora.cassandra.serializers.GenericArraySerializer;
import org.apache.gora.cassandra.serializers.GoraSerializerTypeInferer;
import org.apache.gora.cassandra.serializers.TypeUtils;
import org.apache.gora.mapreduce.GoraRecordReader;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.persistency.State;
import org.apache.gora.persistency.StatefulHashMap;
import org.apache.gora.query.Query;
import org.apache.gora.util.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CassandraClient<K, T extends PersistentBase> {
public static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
private Cluster cluster;
private Keyspace keyspace;
private Mutator<K> mutator;
private Class<K> keyClass;
private Class<T> persistentClass;
private CassandraMapping cassandraMapping = null;
private Serializer<K> keySerializer;
public void initialize(Class<K> keyClass, Class<T> persistentClass) throws Exception {
this.keyClass = keyClass;
// get cassandra mapping with persistent class
this.persistentClass = persistentClass;
this.cassandraMapping = CassandraMappingManager.getManager().get(persistentClass);
// LOG.info("persistentClass=" + persistentClass.getName() + " -> cassandraMapping=" + cassandraMapping);
this.cluster = HFactory.getOrCreateCluster(this.cassandraMapping.getClusterName(), new CassandraHostConfigurator(this.cassandraMapping.getHostName()));
// add keyspace to cluster
checkKeyspace();
// Just create a Keyspace object on the client side, corresponding to an already existing keyspace with already created column families.
this.keyspace = HFactory.createKeyspace(this.cassandraMapping.getKeyspaceName(), this.cluster);
this.keySerializer = GoraSerializerTypeInferer.getSerializer(keyClass);
this.mutator = HFactory.createMutator(this.keyspace, this.keySerializer);
}
/**
* Check if keyspace already exists.
*/
public boolean keyspaceExists() {
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
return (keyspaceDefinition != null);
}
/**
* Check if keyspace already exists. If not, create it.
* In this method, we also utilise Hector's {@ConfigurableConsistencyLevel}
* logic. It is set by passing a ConfigurableConsistencyLevel object right
* when the Keyspace is created. Currently consistency level is .ONE which
* permits consistency to wait until one replica has responded.
*/
public void checkKeyspace() {
// "describe keyspace <keyspaceName>;" query
KeyspaceDefinition keyspaceDefinition = this.cluster.describeKeyspace(this.cassandraMapping.getKeyspaceName());
if (keyspaceDefinition == null) {
List<ColumnFamilyDefinition> columnFamilyDefinitions = this.cassandraMapping.getColumnFamilyDefinitions();
// GORA-197
for (ColumnFamilyDefinition cfDef : columnFamilyDefinitions) {
cfDef.setComparatorType(ComparatorType.BYTESTYPE);
}
keyspaceDefinition = HFactory.createKeyspaceDefinition(this.cassandraMapping.getKeyspaceName(), "org.apache.cassandra.locator.SimpleStrategy", 1, columnFamilyDefinitions);
this.cluster.addKeyspace(keyspaceDefinition, true);
// LOG.info("Keyspace '" + this.cassandraMapping.getKeyspaceName() + "' in cluster '" + this.cassandraMapping.getClusterName() + "' was created on host '" + this.cassandraMapping.getHostName() + "'");
// Create a customized Consistency Level
ConfigurableConsistencyLevel configurableConsistencyLevel = new ConfigurableConsistencyLevel();
Map<String, HConsistencyLevel> clmap = new HashMap<String, HConsistencyLevel>();
// Define CL.ONE for ColumnFamily "ColumnFamily"
clmap.put("ColumnFamily", HConsistencyLevel.ONE);
// In this we use CL.ONE for read and writes. But you can use different CLs if needed.
configurableConsistencyLevel.setReadCfConsistencyLevels(clmap);
configurableConsistencyLevel.setWriteCfConsistencyLevels(clmap);
// Then let the keyspace know
HFactory.createKeyspace("Keyspace", this.cluster, configurableConsistencyLevel);
keyspaceDefinition = null;
}
else {
List<ColumnFamilyDefinition> cfDefs = keyspaceDefinition.getCfDefs();
if (cfDefs == null || cfDefs.size() == 0) {
LOG.warn(keyspaceDefinition.getName() + " does not have any column family.");
}
else {
for (ColumnFamilyDefinition cfDef : cfDefs) {
ComparatorType comparatorType = cfDef.getComparatorType();
if (! comparatorType.equals(ComparatorType.BYTESTYPE)) {
// GORA-197
LOG.warn("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName()
+ ", not BytesType. It may cause a fatal error on column validation later.");
}
else {
// LOG.info("The comparator type of " + cfDef.getName() + " column family is " + comparatorType.getTypeName() + ".");
}
}
}
}
}
/**
* Drop keyspace.
*/
public void dropKeyspace() {
// "drop keyspace <keyspaceName>;" query
this.cluster.dropKeyspace(this.cassandraMapping.getKeyspaceName());
}
/**
* Insert a field in a column.
* @param key the row key
* @param fieldName the field name
* @param value the field value.
*/
public void addColumn(K key, String fieldName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String columnName = this.cassandraMapping.getColumn(fieldName);
if (columnName == null) {
LOG.warn("Column name is null for field=" + fieldName + " with value=" + value.toString());
return;
}
synchronized(mutator) {
HectorUtils.insertColumn(mutator, key, columnFamily, columnName, byteBuffer);
}
}
/**
* Insert a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
* @param value the member value
*/
@SuppressWarnings("unchecked")
public void addSubColumn(K key, String fieldName, ByteBuffer columnName, Object value) {
if (value == null) {
return;
}
ByteBuffer byteBuffer = toByteBuffer(value);
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.insertSubColumn(mutator, key, columnFamily, superColumnName, columnName, byteBuffer);
}
}
public void addSubColumn(K key, String fieldName, String columnName, Object value) {
addSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName), value);
}
public void addSubColumn(K key, String fieldName, Integer columnName, Object value) {
addSubColumn(key, fieldName, IntegerSerializer.get().toByteBuffer(columnName), value);
}
/**
* Delete a member in a super column. This is used for map and record Avro types.
* @param key the row key
* @param fieldName the field name
* @param columnName the column name (the member name, or the index of array)
*/
@SuppressWarnings("unchecked")
public void deleteSubColumn(K key, String fieldName, ByteBuffer columnName) {
String columnFamily = this.cassandraMapping.getFamily(fieldName);
String superColumnName = this.cassandraMapping.getColumn(fieldName);
synchronized(mutator) {
HectorUtils.deleteSubColumn(mutator, key, columnFamily, superColumnName, columnName);
}
}
public void deleteSubColumn(K key, String fieldName, String columnName) {
deleteSubColumn(key, fieldName, StringSerializer.get().toByteBuffer(columnName));
}
@SuppressWarnings("unchecked")
public void addGenericArray(K key, String fieldName, GenericArray array) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Object itemValue: array) {
// TODO: hack, do not store empty arrays
if (itemValue instanceof GenericArray<?>) {
if (((GenericArray)itemValue).size() == 0) {
continue;
}
} else if (itemValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)itemValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, i++, itemValue);
}
}
else {
addColumn(key, fieldName, array);
}
}
@SuppressWarnings("unchecked")
public void addStatefulHashMap(K key, String fieldName, StatefulHashMap<Utf8,Object> map) {
if (isSuper( cassandraMapping.getFamily(fieldName) )) {
int i= 0;
for (Utf8 mapKey: map.keySet()) {
if (map.getState(mapKey) == State.DELETED) {
deleteSubColumn(key, fieldName, mapKey.toString());
continue;
}
// TODO: hack, do not store empty arrays
Object mapValue = map.get(mapKey);
if (mapValue instanceof GenericArray<?>) {
if (((GenericArray)mapValue).size() == 0) {
continue;
}
} else if (mapValue instanceof StatefulHashMap<?,?>) {
if (((StatefulHashMap)mapValue).size() == 0) {
continue;
}
}
addSubColumn(key, fieldName, mapKey.toString(), mapValue);
}
}
else {
addColumn(key, fieldName, map);
}
}
/**
* Serialize value to ByteBuffer.
* @param value the member value
* @return ByteBuffer object
*/
@SuppressWarnings("unchecked")
public ByteBuffer toByteBuffer(Object value) {
ByteBuffer byteBuffer = null;
Serializer serializer = GoraSerializerTypeInferer.getSerializer(value);
if (serializer == null) {
LOG.info("Serializer not found for: " + value.toString());
}
else {
byteBuffer = serializer.toByteBuffer(value);
}
if (byteBuffer == null) {
LOG.info("value class=" + value.getClass().getName() + " value=" + value + " -> null");
}
return byteBuffer;
}
/**
* Select a family column in the keyspace.
* @param cassandraQuery a wrapper of the query
* @param family the family name to be queried
* @return a list of family rows
*/
public List<Row<K, ByteBuffer, ByteBuffer>> execute(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
ByteBuffer[] columnNameByteBuffers = new ByteBuffer[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columnNameByteBuffers[i] = StringSerializer.get().toByteBuffer(columnNames[i]);
}
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSlicesQuery<K, ByteBuffer, ByteBuffer> rangeSlicesQuery = HFactory.createRangeSlicesQuery(this.keyspace, this.keySerializer, ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSlicesQuery.setColumnFamily(family);
rangeSlicesQuery.setKeys(startKey, endKey);
rangeSlicesQuery.setRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSlicesQuery.setRowCount(limit);
rangeSlicesQuery.setColumnNames(columnNameByteBuffers);
QueryResult<OrderedRows<K, ByteBuffer, ByteBuffer>> queryResult = rangeSlicesQuery.execute();
OrderedRows<K, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Select the families that contain at least one column mapped to a query field.
* @param query indicates the columns to select
* @return a map which keys are the family names and values the corresponding column names required to get all the query fields.
*/
public Map<String, List<String>> getFamilyMap(Query<K, T> query) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
// check if the family value was already initialized
List<String> list = map.get(family);
if (list == null) {
list = new ArrayList<String>();
map.put(family, list);
}
if (column != null) {
list.add(column);
}
}
return map;
}
/**
* Select the field names according to the column names, which format if fully qualified: "family:column"
* @param query
* @return a map which keys are the fully qualified column names and values the query fields
*/
public Map<String, String> getReverseMap(Query<K, T> query) {
Map<String, String> map = new HashMap<String, String>();
for (String field: query.getFields()) {
String family = this.cassandraMapping.getFamily(field);
String column = this.cassandraMapping.getColumn(field);
map.put(family + ":" + column, field);
}
return map;
}
public boolean isSuper(String family) {
return this.cassandraMapping.isSuper(family);
}
public List<SuperRow<K, String, ByteBuffer, ByteBuffer>> executeSuper(CassandraQuery<K, T> cassandraQuery, String family) {
String[] columnNames = cassandraQuery.getColumns(family);
Query<K, T> query = cassandraQuery.getQuery();
int limit = (int) query.getLimit();
if (limit < 1) {
limit = Integer.MAX_VALUE;
}
K startKey = query.getStartKey();
K endKey = query.getEndKey();
RangeSuperSlicesQuery<K, String, ByteBuffer, ByteBuffer> rangeSuperSlicesQuery = HFactory.createRangeSuperSlicesQuery(this.keyspace, this.keySerializer, StringSerializer.get(), ByteBufferSerializer.get(), ByteBufferSerializer.get());
rangeSuperSlicesQuery.setColumnFamily(family);
rangeSuperSlicesQuery.setKeys(startKey, endKey);
rangeSuperSlicesQuery.setRange("", "", false, GoraRecordReader.BUFFER_LIMIT_READ_VALUE);
rangeSuperSlicesQuery.setRowCount(limit);
rangeSuperSlicesQuery.setColumnNames(columnNames);
QueryResult<OrderedSuperRows<K, String, ByteBuffer, ByteBuffer>> queryResult = rangeSuperSlicesQuery.execute();
OrderedSuperRows<K, String, ByteBuffer, ByteBuffer> orderedRows = queryResult.get();
return orderedRows.getList();
}
/**
* Obtain Schema/Keyspace name
* @return Keyspace
*/
public String getKeyspaceName() {
return this.cassandraMapping.getKeyspaceName();
}
}
| prateekbansal/apache-gora-0.4 | gora-cassandra/src/main/java/org/apache/gora/cassandra/store/CassandraClient.java | Java | apache-2.0 | 17,283 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.io.sstable;
import java.io.IOException;
import java.util.Iterator;
import com.google.common.util.concurrent.RateLimiter;
import com.google.common.collect.AbstractIterator;
import org.apache.cassandra.db.DataRange;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.db.columniterator.IColumnIteratorFactory;
import org.apache.cassandra.db.columniterator.LazyColumnIterator;
import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.compaction.ICompactionScanner;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.utils.ByteBufferUtil;
public class SSTableScanner implements ICompactionScanner
{
protected final RandomAccessReader dfile;
protected final RandomAccessReader ifile;
public final SSTableReader sstable;
private final DataRange dataRange;
private final long stopAt;
protected Iterator<OnDiskAtomIterator> iterator;
/**
* @param sstable SSTable to scan; must not be null
* @param filter range of data to fetch; must not be null
* @param limiter background i/o RateLimiter; may be null
*/
SSTableScanner(SSTableReader sstable, DataRange dataRange, RateLimiter limiter)
{
assert sstable != null;
this.dfile = limiter == null ? sstable.openDataReader() : sstable.openDataReader(limiter);
this.ifile = sstable.openIndexReader();
this.sstable = sstable;
this.dataRange = dataRange;
this.stopAt = computeStopAt();
seekToStart();
}
private void seekToStart()
{
if (dataRange.startKey().isMinimum(sstable.partitioner))
return;
long indexPosition = sstable.getIndexScanPosition(dataRange.startKey());
// -1 means the key is before everything in the sstable. So just start from the beginning.
if (indexPosition == -1)
return;
ifile.seek(indexPosition);
try
{
while (!ifile.isEOF())
{
indexPosition = ifile.getFilePointer();
DecoratedKey indexDecoratedKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
int comparison = indexDecoratedKey.compareTo(dataRange.startKey());
if (comparison >= 0)
{
// Found, just read the dataPosition and seek into index and data files
long dataPosition = ifile.readLong();
ifile.seek(indexPosition);
dfile.seek(dataPosition);
break;
}
else
{
RowIndexEntry.serializer.skip(ifile);
}
}
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
private long computeStopAt()
{
AbstractBounds<RowPosition> keyRange = dataRange.keyRange();
if (dataRange.stopKey().isMinimum(sstable.partitioner) || (keyRange instanceof Range && ((Range)keyRange).isWrapAround()))
return dfile.length();
RowIndexEntry position = sstable.getPosition(keyRange.toRowBounds().right, SSTableReader.Operator.GT);
return position == null ? dfile.length() : position.position;
}
public void close() throws IOException
{
FileUtils.close(dfile, ifile);
}
public long getLengthInBytes()
{
return dfile.length();
}
public long getCurrentPosition()
{
return dfile.getFilePointer();
}
public String getBackingFiles()
{
return sstable.toString();
}
public boolean hasNext()
{
if (iterator == null)
iterator = createIterator();
return iterator.hasNext();
}
public OnDiskAtomIterator next()
{
if (iterator == null)
iterator = createIterator();
return iterator.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
private Iterator<OnDiskAtomIterator> createIterator()
{
return new KeyScanningIterator();
}
protected class KeyScanningIterator extends AbstractIterator<OnDiskAtomIterator>
{
private DecoratedKey nextKey;
private RowIndexEntry nextEntry;
private DecoratedKey currentKey;
private RowIndexEntry currentEntry;
protected OnDiskAtomIterator computeNext()
{
try
{
if (ifile.isEOF() && nextKey == null)
return endOfData();
if (currentKey == null)
{
currentKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
currentEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
else
{
currentKey = nextKey;
currentEntry = nextEntry;
}
assert currentEntry.position <= stopAt;
if (currentEntry.position == stopAt)
return endOfData();
if (ifile.isEOF())
{
nextKey = null;
nextEntry = null;
}
else
{
nextKey = sstable.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(ifile));
nextEntry = RowIndexEntry.serializer.deserialize(ifile, sstable.descriptor.version);
}
assert !dfile.isEOF();
if (dataRange.selectsFullRowFor(currentKey.key))
{
dfile.seek(currentEntry.position);
ByteBufferUtil.readWithShortLength(dfile); // key
if (sstable.descriptor.version.hasRowSizeAndColumnCount)
dfile.readLong();
long dataSize = (nextEntry == null ? dfile.length() : nextEntry.position) - dfile.getFilePointer();
return new SSTableIdentityIterator(sstable, dfile, currentKey, dataSize);
}
return new LazyColumnIterator(currentKey, new IColumnIteratorFactory()
{
public OnDiskAtomIterator create()
{
return dataRange.columnFilter(currentKey.key).getSSTableColumnIterator(sstable, dfile, currentKey, currentEntry);
}
});
}
catch (IOException e)
{
sstable.markSuspect();
throw new CorruptSSTableException(e, sstable.getFilename());
}
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(" +
"dfile=" + dfile +
" ifile=" + ifile +
" sstable=" + sstable +
")";
}
}
| DavidHerzogTU-Berlin/cassandraToRun | src/java/org/apache/cassandra/io/sstable/SSTableScanner.java | Java | apache-2.0 | 8,241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.