repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
nethergrim/Training-Log | app/src/main/java/com/nethergrim/combogymdiary/model/ExerciseGroup.java | 825 | package com.nethergrim.combogymdiary.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExerciseGroup implements Serializable {
private String name;
private int positionInGlobalArray = 0;
private List<Exercise> list = new ArrayList<Exercise>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPositionInGlobalArray() {
return positionInGlobalArray;
}
public void setPositionInGlobalArray(int positionInGlobalArray) {
this.positionInGlobalArray = positionInGlobalArray;
}
public List<Exercise> getExercisesList() {
return list;
}
public void setList(List<Exercise> list) {
this.list = list;
}
}
| apache-2.0 |
mikessh/mageri | src/test/java/com/antigenomics/mageri/core/mapping/StatsByRef.java | 3464 | /*
* Copyright 2014-2016 Mikhail Shugay
*
* 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.antigenomics.mageri.core.mapping;
import com.antigenomics.mageri.core.genomic.Reference;
import com.antigenomics.mageri.core.genomic.ReferenceLibrary;
import com.antigenomics.mageri.generators.MigWithMutations;
import java.util.HashMap;
import java.util.Map;
import static com.milaboratory.core.sequence.mutations.Mutations.*;
public class StatsByRef {
private final Map<Reference, Map<Integer, Integer>> majorCountsByRef = new HashMap<>(),
minorCountsByRef = new HashMap<>();
private final ReferenceLibrary referenceLibrary;
public StatsByRef(ReferenceLibrary referenceLibrary) {
this.referenceLibrary = referenceLibrary;
for (Reference reference : referenceLibrary.getReferences()) {
majorCountsByRef.put(reference, new HashMap<Integer, Integer>());
minorCountsByRef.put(reference, new HashMap<Integer, Integer>());
}
}
public void update(MigWithMutations MigWithMutations,
Reference reference, int offset) {
final Map<Integer, Integer> majorCounts = majorCountsByRef.get(reference),
minorCounts = minorCountsByRef.get(reference);
Integer count;
for (int major : MigWithMutations.getMajorMutations()) {
major = move(major, offset);
majorCounts.put(major,
((count = majorCounts.get(major)) == null ? 0 : count) + 1);
}
for (int minor : MigWithMutations.getMinorMutationCounts().keySet()) {
minor = move(minor, offset);
minorCounts.put(minor,
((count = minorCounts.get(minor)) == null ? 0 : count) + 1);
}
}
public int[][] getMajorCounts(Reference reference) {
int[][] majorMatrix = new int[reference.getSequence().size()][4];
for (Map.Entry<Integer, Integer> majorEntry : majorCountsByRef.get(reference).entrySet()) {
int code = majorEntry.getKey(), count = majorEntry.getValue(), pos = getPosition(code);
if (isSubstitution(code) && pos >= 0 && pos < reference.getSequence().size()) {
majorMatrix[pos][getTo(code)] += count;
}
}
return majorMatrix;
}
public int[][] getMinorCounts(Reference reference) {
int[][] minorMatrix = new int[reference.getSequence().size()][4];
for (Map.Entry<Integer, Integer> minorEntry : minorCountsByRef.get(reference).entrySet()) {
int code = minorEntry.getKey(), count = minorEntry.getValue(), pos = getPosition(code);
if (isSubstitution(code) && pos >= 0 && pos < reference.getSequence().size()) {
minorMatrix[pos][getTo(code)] += count;
}
}
return minorMatrix;
}
public ReferenceLibrary getReferenceLibrary() {
return referenceLibrary;
}
} | apache-2.0 |
viewreka/viewreka | projects/viewreka-fxui/src/main/java/org/beryx/viewreka/fxui/settings/GuiSettings.java | 4670 | /**
* Copyright 2015-2016 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.beryx.viewreka.fxui.settings;
import static org.beryx.viewreka.core.Util.getValue;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.beryx.viewreka.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* General GUI settings (not related to a specific Viewreka project).
*/
public interface GuiSettings extends Settings {
static final Logger _log = LoggerFactory.getLogger(GuiSettings.class);
/**
* @return a map of property values indexed by their names
*/
Map<String, Serializable> getProperties();
/**
* Retrieves the value of a specified property or a default value.
* @param name the name of the desired property
* @param defaultValue the default value to be returned if the specified property is not available
* @param allowNull true, if null is a permitted value for the specified property
* @return the value of the property with the specified name or a default value if no such property exists.
* The default value is also returned if the value of the specified property is null and {@code allowNull} is false.
*/
default <T> T getProperty(String name, T defaultValue, boolean allowNull) {
return getValue(getProperties(), name, defaultValue, allowNull);
}
/**
* Sets the value of a specified property.
* @param name the name of the property to be set
* @param value the value to be set
* @return the previous value of the property with the specified name
*/
default <T extends Serializable> Object setProperty(String name, T value) {
_log.debug("Setting {} to {}", name, value);
return getProperties().put(name, value);
}
/**
* @return the X coordinate of the upper-left corner of the application window
*/
double getWindowX();
/**
* @param x the X coordinate of the upper-left corner of the application window
*/
void setWindowX(double x);
/**
* @return the Y coordinate of the upper-left corner of the application window
*/
double getWindowY();
/**
* @param y the Y coordinate of the upper-left corner of the application window
*/
void setWindowY(double y);
/**
* @return the width of the application window
*/
double getWindowWidth();
/**
* @param width the width of the application window
*/
void setWindowWidth(double width);
/**
* @return the height of the application window
*/
double getWindowHeight();
/**
* @param height the height of the application window
*/
void setWindowHeight(double height);
/**
* @return the list of the file paths of recently opened Viewreka project script files
*/
List<String> getRecentProjectPaths();
/**
* @return the directory of the script file of the most recently opened Viewreka project.
* If not available, the current user directory is returned.
*/
default File getMostRecentProjectDir() {
List<String> recentProjectPaths = getRecentProjectPaths();
File prjDir = null;
try {
if(!recentProjectPaths.isEmpty()) {
File prj = new File(recentProjectPaths.get(0));
prjDir = prj.getParentFile();
}
if((prjDir == null) || !prjDir.isDirectory()) {
String defaultDirPath = System.getProperty("user.dir");
prjDir = new File(defaultDirPath);
}
} catch(Exception e) {
_log.warn("Cannot retrieve most recent project dir", e);
prjDir = null;
}
return (prjDir != null && prjDir.isDirectory()) ? prjDir : new File(".");
}
/**
* @return the maximum number of entries in the list returned by {@link #getRecentProjectPaths()}
*/
int getMaxRecentProjects();
/**
* @param maxRecentProjects the maximum number of entries in the list returned by {@link #getRecentProjectPaths()}
*/
void setMaxRecentProjects(int maxRecentProjects);
/**
* @return true, if on start the application should try to open the last opened project
*/
boolean isLoadLastProject();
/**
* @param loadLastProject true, if on start the application should try to open the last opened project
*/
void setLoadLastProject(boolean loadLastProject);
}
| apache-2.0 |
aaronphilips/as1 | app/build/generated/source/buildConfig/androidTest/debug/ca/as1/test/BuildConfig.java | 427 | /**
* Automatically generated file. DO NOT MODIFY
*/
package ca.as1.test;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "ca.as1.test";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = -1;
public static final String VERSION_NAME = "";
}
| apache-2.0 |
ivarptr/clobaframe-web | source/page/src/test/java/org/archboy/clobaframe/web/controller/exception/resolver/FileNotFoundExceptionResolver.java | 1705 | package org.archboy.clobaframe.web.controller.exception.resolver;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import org.archboy.clobaframe.common.collection.DefaultObjectMap;
import org.archboy.clobaframe.common.collection.ObjectMap;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
/**
* see also
* {@link DefaultHandlerExceptionResolver},
* {@link SimpleMappingExceptionResolver} and
* {@link ExceptionHandlerExceptionResolver}.
*
* @author yang
*/
@Named
public class FileNotFoundExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex) {
if (ex instanceof FileNotFoundException) {
// disable the client cache
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
response.setDateHeader(HttpHeaders.EXPIRES, 1L);
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
ObjectMap viewModel = new DefaultObjectMap()
.addChild("error")
.add("code", "notFound")
.top();
return new ModelAndView("error", viewModel);
}
return null; // let other resolver to handle.
}
} | apache-2.0 |
asakusafw/asakusafw-mapreduce | compiler/core/src/test/java/com/asakusafw/compiler/flow/processor/flow/ExtractFlowOp3.java | 2691 | /**
* Copyright 2011-2021 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.compiler.flow.processor.flow;
import com.asakusafw.compiler.flow.processor.ExtractFlowProcessor;
import com.asakusafw.compiler.flow.processor.operator.ExtractFlowFactory;
import com.asakusafw.compiler.flow.processor.operator.ExtractFlowFactory.Op3;
import com.asakusafw.compiler.flow.testing.external.Ex1MockExporterDescription;
import com.asakusafw.compiler.flow.testing.external.Ex1MockImporterDescription;
import com.asakusafw.compiler.flow.testing.external.Ex2MockExporterDescription;
import com.asakusafw.compiler.flow.testing.model.Ex1;
import com.asakusafw.compiler.flow.testing.model.Ex2;
import com.asakusafw.vocabulary.flow.Export;
import com.asakusafw.vocabulary.flow.FlowDescription;
import com.asakusafw.vocabulary.flow.Import;
import com.asakusafw.vocabulary.flow.In;
import com.asakusafw.vocabulary.flow.JobFlow;
import com.asakusafw.vocabulary.flow.Out;
/**
* test for {@link ExtractFlowProcessor}.
*/
@JobFlow(name = "testing")
public class ExtractFlowOp3 extends FlowDescription {
private In<Ex1> in1;
private Out<Ex1> out1;
private Out<Ex2> out2;
private Out<Ex1> out3;
/**
* Creates a new instance.
* @param in1 input
* @param out1 output1
* @param out2 output2
* @param out3 output3
*/
public ExtractFlowOp3(
@Import(name = "in", description = Ex1MockImporterDescription.class)
In<Ex1> in1,
@Export(name = "out1", description = Ex1MockExporterDescription.class)
Out<Ex1> out1,
@Export(name = "out2", description = Ex2MockExporterDescription.class)
Out<Ex2> out2,
@Export(name = "out3", description = Ex1MockExporterDescription.class)
Out<Ex1> out3) {
this.in1 = in1;
this.out1 = out1;
this.out2 = out2;
this.out3 = out3;
}
@Override
protected void describe() {
ExtractFlowFactory f = new ExtractFlowFactory();
Op3 op = f.op3(in1);
out1.add(op.r1);
out2.add(op.r2);
out3.add(op.r3);
}
}
| apache-2.0 |
apereo/cas | support/cas-server-support-u2f-mongo/src/main/java/org/apereo/cas/config/U2FMongoDbConfiguration.java | 2380 | package org.apereo.cas.config;
import org.apereo.cas.adaptors.u2f.storage.U2FDeviceRepository;
import org.apereo.cas.adaptors.u2f.storage.U2FMongoDbDeviceRepository;
import org.apereo.cas.authentication.CasSSLContext;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.mongo.MongoDbConnectionFactory;
import org.apereo.cas.util.crypto.CipherExecutor;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
/**
* This is {@link U2FMongoDbConfiguration}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@Configuration(value = "U2fMongoDbConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class U2FMongoDbConfiguration {
@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
public U2FDeviceRepository u2fDeviceRepository(
final CasConfigurationProperties casProperties,
@Qualifier("u2fRegistrationRecordCipherExecutor")
final CipherExecutor u2fRegistrationRecordCipherExecutor,
@Qualifier(CasSSLContext.BEAN_NAME)
final CasSSLContext casSslContext) {
val u2f = casProperties.getAuthn().getMfa().getU2f();
val factory = new MongoDbConnectionFactory(casSslContext.getSslContext());
val mongoProps = u2f.getMongo();
val mongoTemplate = factory.buildMongoTemplate(mongoProps);
MongoDbConnectionFactory.createCollection(mongoTemplate, mongoProps.getCollection(), mongoProps.isDropCollection());
final LoadingCache<String, String> requestStorage =
Caffeine.newBuilder().expireAfterWrite(u2f.getCore().getExpireRegistrations(), u2f.getCore().getExpireRegistrationsTimeUnit()).build(key -> StringUtils.EMPTY);
return new U2FMongoDbDeviceRepository(requestStorage, mongoTemplate,
u2fRegistrationRecordCipherExecutor, casProperties);
}
}
| apache-2.0 |
jy01649210/ambrose | hive/src/main/java/com/twitter/ambrose/hive/HiveDriverRunHookContext.java | 309 | package com.twitter.ambrose.hive;
import org.apache.hadoop.conf.Configurable;
/**
* Context information provided by Hive to implementations of
* HiveDriverRunHook.
*/
public interface HiveDriverRunHookContext extends Configurable{
public String getCommand();
public void setCommand(String command);
} | apache-2.0 |
Pompeu/JavaThreads | src/Threads10ReentrantLocks/App.java | 600 | package Threads10ReentrantLocks;
public class App {
public static void main(String[] args) throws InterruptedException {
final Runner runner = new Runner();
Thread t1 = new Thread(()-> {
try {
runner.firstThreada();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
Thread t2 = new Thread(()-> {
try {
runner.secondThreads();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
runner.finished();
}
}
| apache-2.0 |
grignaak/jReform | src/org/jreform/HtmlForm.java | 1806 | package org.jreform;
import java.util.Date;
import org.jreform.internal.BaseHtmlForm;
import org.jreform.types.BooleanType;
import org.jreform.types.CharType;
import org.jreform.types.DateType;
import org.jreform.types.DoubleType;
import org.jreform.types.FloatType;
import org.jreform.types.IntType;
import org.jreform.types.LongType;
import org.jreform.types.ShortType;
import org.jreform.types.StringType;
/**
* This is a base class that should be extended to create a form.
*
* @author armandino (at) gmail.com
*/
public class HtmlForm extends BaseHtmlForm
{
// --------------------------------------------------------------------
// ---------------- Types supported out-of-the-box---------------------
// --------------------------------------------------------------------
public static InputDataType<Boolean> booleanType()
{
return BooleanType.booleanType();
}
public static InputDataType<Character> charType()
{
return CharType.charType();
}
public static InputDataType<Short> shortType()
{
return ShortType.shortType();
}
public static InputDataType<Integer> intType()
{
return IntType.intType();
}
public static InputDataType<Long> longType()
{
return LongType.longType();
}
public static InputDataType<Double> doubleType()
{
return DoubleType.doubleType();
}
public static InputDataType<Float> floatType()
{
return FloatType.floatType();
}
public static InputDataType<String> stringType()
{
return StringType.stringType();
}
public static InputDataType<Date> dateType(String dateFormatPattern)
{
return DateType.dateType(dateFormatPattern);
}
}
| apache-2.0 |
speedycontrol/googleapis | output/com/google/cloud/functions/v1beta2/GetFunctionRequest.java | 17911 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/functions/v1beta2/functions.proto
package com.google.cloud.functions.v1beta2;
/**
* <pre>
* Request for the GetFunction method.
* </pre>
*
* Protobuf type {@code google.cloud.functions.v1beta2.GetFunctionRequest}
*/
public final class GetFunctionRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.functions.v1beta2.GetFunctionRequest)
GetFunctionRequestOrBuilder {
// Use GetFunctionRequest.newBuilder() to construct.
private GetFunctionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetFunctionRequest() {
name_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private GetFunctionRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.functions.v1beta2.FunctionsProto.internal_static_google_cloud_functions_v1beta2_GetFunctionRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.functions.v1beta2.FunctionsProto.internal_static_google_cloud_functions_v1beta2_GetFunctionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.functions.v1beta2.GetFunctionRequest.class, com.google.cloud.functions.v1beta2.GetFunctionRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.functions.v1beta2.GetFunctionRequest)) {
return super.equals(obj);
}
com.google.cloud.functions.v1beta2.GetFunctionRequest other = (com.google.cloud.functions.v1beta2.GetFunctionRequest) obj;
boolean result = true;
result = result && getName()
.equals(other.getName());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.functions.v1beta2.GetFunctionRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Request for the GetFunction method.
* </pre>
*
* Protobuf type {@code google.cloud.functions.v1beta2.GetFunctionRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.functions.v1beta2.GetFunctionRequest)
com.google.cloud.functions.v1beta2.GetFunctionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.functions.v1beta2.FunctionsProto.internal_static_google_cloud_functions_v1beta2_GetFunctionRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.functions.v1beta2.FunctionsProto.internal_static_google_cloud_functions_v1beta2_GetFunctionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.functions.v1beta2.GetFunctionRequest.class, com.google.cloud.functions.v1beta2.GetFunctionRequest.Builder.class);
}
// Construct using com.google.cloud.functions.v1beta2.GetFunctionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
name_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.functions.v1beta2.FunctionsProto.internal_static_google_cloud_functions_v1beta2_GetFunctionRequest_descriptor;
}
public com.google.cloud.functions.v1beta2.GetFunctionRequest getDefaultInstanceForType() {
return com.google.cloud.functions.v1beta2.GetFunctionRequest.getDefaultInstance();
}
public com.google.cloud.functions.v1beta2.GetFunctionRequest build() {
com.google.cloud.functions.v1beta2.GetFunctionRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.cloud.functions.v1beta2.GetFunctionRequest buildPartial() {
com.google.cloud.functions.v1beta2.GetFunctionRequest result = new com.google.cloud.functions.v1beta2.GetFunctionRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.functions.v1beta2.GetFunctionRequest) {
return mergeFrom((com.google.cloud.functions.v1beta2.GetFunctionRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.functions.v1beta2.GetFunctionRequest other) {
if (other == com.google.cloud.functions.v1beta2.GetFunctionRequest.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.functions.v1beta2.GetFunctionRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.functions.v1beta2.GetFunctionRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* The name of the function which details should be obtained.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.cloud.functions.v1beta2.GetFunctionRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.functions.v1beta2.GetFunctionRequest)
private static final com.google.cloud.functions.v1beta2.GetFunctionRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.functions.v1beta2.GetFunctionRequest();
}
public static com.google.cloud.functions.v1beta2.GetFunctionRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetFunctionRequest>
PARSER = new com.google.protobuf.AbstractParser<GetFunctionRequest>() {
public GetFunctionRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetFunctionRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetFunctionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetFunctionRequest> getParserForType() {
return PARSER;
}
public com.google.cloud.functions.v1beta2.GetFunctionRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
vital-ai/sparql-spin | src/org/topbraid/spin/model/impl/FilterImpl.java | 1442 | /*******************************************************************************
* Copyright (c) 2009 TopQuadrant, Inc.
* All rights reserved.
*******************************************************************************/
package org.topbraid.spin.model.impl;
import org.topbraid.spin.model.Filter;
import org.topbraid.spin.model.SPINFactory;
import org.topbraid.spin.model.print.PrintContext;
import org.topbraid.spin.model.visitor.ElementVisitor;
import org.topbraid.spin.vocabulary.SP;
import com.hp.hpl.jena.enhanced.EnhGraph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
public class FilterImpl extends ElementImpl implements Filter {
public FilterImpl(Node node, EnhGraph graph) {
super(node, graph);
}
public RDFNode getExpression() {
Statement s = getProperty(SP.expression);
if(s != null) {
RDFNode object = s.getObject();
return SPINFactory.asExpression(object);
}
else {
return null;
}
}
public void print(PrintContext context) {
context.printKeyword("FILTER");
context.print(" ");
RDFNode expression = getExpression();
if(expression == null) {
context.print("<Error: Missing expression>");
}
else {
printNestedExpressionString(context, expression, true);
}
}
public void visit(ElementVisitor visitor) {
visitor.visit(this);
}
}
| apache-2.0 |
Distrotech/maven | maven-core/src/main/java/org/apache/maven/project/DefaultProjectBuilder.java | 26121 | package org.apache.maven.project;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.LegacyLocalRepositoryManager;
import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.Profile;
import org.apache.maven.model.building.DefaultModelBuildingRequest;
import org.apache.maven.model.building.DefaultModelProblem;
import org.apache.maven.model.building.FileModelSource;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelBuildingResult;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.building.ModelProcessor;
import org.apache.maven.model.building.ModelSource;
import org.apache.maven.model.building.StringModelSource;
import org.apache.maven.model.resolution.ModelResolver;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.repository.internal.ArtifactDescriptorUtils;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.RequestTrace;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.WorkspaceRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResult;
/**
*/
@Component( role = ProjectBuilder.class )
public class DefaultProjectBuilder
implements ProjectBuilder
{
@Requirement
private Logger logger;
@Requirement
private ModelBuilder modelBuilder;
@Requirement
private ModelProcessor modelProcessor;
@Requirement
private ProjectBuildingHelper projectBuildingHelper;
@Requirement
private RepositorySystem repositorySystem;
@Requirement
private org.eclipse.aether.RepositorySystem repoSystem;
@Requirement
private RemoteRepositoryManager repositoryManager;
@Requirement
private ProjectDependenciesResolver dependencyResolver;
// ----------------------------------------------------------------------
// MavenProjectBuilder Implementation
// ----------------------------------------------------------------------
public ProjectBuildingResult build( File pomFile, ProjectBuildingRequest request )
throws ProjectBuildingException
{
return build( pomFile, new FileModelSource( pomFile ), new InternalConfig( request, null ) );
}
public ProjectBuildingResult build( ModelSource modelSource, ProjectBuildingRequest request )
throws ProjectBuildingException
{
return build( null, modelSource, new InternalConfig( request, null ) );
}
private ProjectBuildingResult build( File pomFile, ModelSource modelSource, InternalConfig config )
throws ProjectBuildingException
{
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
ProjectBuildingRequest configuration = config.request;
MavenProject project = configuration.getProject();
List<ModelProblem> modelProblems = null;
Throwable error = null;
if ( project == null )
{
ModelBuildingRequest request = getModelBuildingRequest( config );
project = new MavenProject( repositorySystem, this, configuration, logger );
DefaultModelBuildingListener listener =
new DefaultModelBuildingListener( project, projectBuildingHelper, configuration );
request.setModelBuildingListener( listener );
request.setPomFile( pomFile );
request.setModelSource( modelSource );
request.setLocationTracking( true );
ModelBuildingResult result;
try
{
result = modelBuilder.build( request );
}
catch ( ModelBuildingException e )
{
result = e.getResult();
if ( result == null || result.getEffectiveModel() == null )
{
throw new ProjectBuildingException( e.getModelId(), e.getMessage(), pomFile, e );
}
// validation error, continue project building and delay failing to help IDEs
error = e;
}
modelProblems = result.getProblems();
initProject( project, Collections.<String, MavenProject> emptyMap(), result,
new HashMap<File, Boolean>() );
}
else if ( configuration.isResolveDependencies() )
{
projectBuildingHelper.selectProjectRealm( project );
}
DependencyResolutionResult resolutionResult = null;
if ( configuration.isResolveDependencies() )
{
resolutionResult = resolveDependencies( project, config.session );
}
ProjectBuildingResult result = new DefaultProjectBuildingResult( project, modelProblems, resolutionResult );
if ( error != null )
{
ProjectBuildingException e = new ProjectBuildingException( Arrays.asList( result ) );
e.initCause( error );
throw e;
}
return result;
}
finally
{
Thread.currentThread().setContextClassLoader( oldContextClassLoader );
}
}
private DependencyResolutionResult resolveDependencies( MavenProject project, RepositorySystemSession session )
{
DependencyResolutionResult resolutionResult = null;
try
{
DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest( project, session );
resolutionResult = dependencyResolver.resolve( resolution );
}
catch ( DependencyResolutionException e )
{
resolutionResult = e.getResult();
}
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
if ( resolutionResult.getDependencyGraph() != null )
{
RepositoryUtils.toArtifacts( artifacts, resolutionResult.getDependencyGraph().getChildren(),
Collections.singletonList( project.getArtifact().getId() ), null );
// Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
LocalRepositoryManager lrm = session.getLocalRepositoryManager();
for ( Artifact artifact : artifacts )
{
if ( !artifact.isResolved() )
{
String path = lrm.getPathForLocalArtifact( RepositoryUtils.toArtifact( artifact ) );
artifact.setFile( new File( lrm.getRepository().getBasedir(), path ) );
}
}
}
project.setResolvedArtifacts( artifacts );
project.setArtifacts( artifacts );
return resolutionResult;
}
private List<String> getProfileIds( List<Profile> profiles )
{
List<String> ids = new ArrayList<String>( profiles.size() );
for ( Profile profile : profiles )
{
ids.add( profile.getId() );
}
return ids;
}
private ModelBuildingRequest getModelBuildingRequest( InternalConfig config )
{
ProjectBuildingRequest configuration = config.request;
ModelBuildingRequest request = new DefaultModelBuildingRequest();
RequestTrace trace = RequestTrace.newChild( null, configuration ).newChild( request );
ModelResolver resolver =
new ProjectModelResolver( config.session, trace, repoSystem, repositoryManager, config.repositories,
configuration.getRepositoryMerging(), config.modelPool );
request.setValidationLevel( configuration.getValidationLevel() );
request.setProcessPlugins( configuration.isProcessPlugins() );
request.setProfiles( configuration.getProfiles() );
request.setActiveProfileIds( configuration.getActiveProfileIds() );
request.setInactiveProfileIds( configuration.getInactiveProfileIds() );
request.setSystemProperties( configuration.getSystemProperties() );
request.setUserProperties( configuration.getUserProperties() );
request.setBuildStartTime( configuration.getBuildStartTime() );
request.setModelResolver( resolver );
request.setModelCache( new ReactorModelCache() );
return request;
}
public ProjectBuildingResult build( Artifact artifact, ProjectBuildingRequest request )
throws ProjectBuildingException
{
return build( artifact, false, request );
}
public ProjectBuildingResult build( Artifact artifact, boolean allowStubModel, ProjectBuildingRequest request )
throws ProjectBuildingException
{
org.eclipse.aether.artifact.Artifact pomArtifact = RepositoryUtils.toArtifact( artifact );
pomArtifact = ArtifactDescriptorUtils.toPomArtifact( pomArtifact );
InternalConfig config = new InternalConfig( request, null );
boolean localProject;
try
{
ArtifactRequest pomRequest = new ArtifactRequest();
pomRequest.setArtifact( pomArtifact );
pomRequest.setRepositories( config.repositories );
ArtifactResult pomResult = repoSystem.resolveArtifact( config.session, pomRequest );
pomArtifact = pomResult.getArtifact();
localProject = pomResult.getRepository() instanceof WorkspaceRepository;
}
catch ( org.eclipse.aether.resolution.ArtifactResolutionException e )
{
if ( e.getResults().get( 0 ).isMissing() && allowStubModel )
{
return build( null, createStubModelSource( artifact ), config );
}
throw new ProjectBuildingException( artifact.getId(),
"Error resolving project artifact: " + e.getMessage(), e );
}
File pomFile = pomArtifact.getFile();
if ( "pom".equals( artifact.getType() ) )
{
artifact.selectVersion( pomArtifact.getVersion() );
artifact.setFile( pomFile );
artifact.setResolved( true );
}
return build( localProject ? pomFile : null, new FileModelSource( pomFile ), config );
}
private ModelSource createStubModelSource( Artifact artifact )
{
StringBuilder buffer = new StringBuilder( 1024 );
buffer.append( "<?xml version='1.0'?>" );
buffer.append( "<project>" );
buffer.append( "<modelVersion>4.0.0</modelVersion>" );
buffer.append( "<groupId>" ).append( artifact.getGroupId() ).append( "</groupId>" );
buffer.append( "<artifactId>" ).append( artifact.getArtifactId() ).append( "</artifactId>" );
buffer.append( "<version>" ).append( artifact.getBaseVersion() ).append( "</version>" );
buffer.append( "<packaging>" ).append( artifact.getType() ).append( "</packaging>" );
buffer.append( "</project>" );
return new StringModelSource( buffer, artifact.getId() );
}
public List<ProjectBuildingResult> build( List<File> pomFiles, boolean recursive, ProjectBuildingRequest request )
throws ProjectBuildingException
{
List<ProjectBuildingResult> results = new ArrayList<ProjectBuildingResult>();
List<InterimResult> interimResults = new ArrayList<InterimResult>();
ReactorModelPool modelPool = new ReactorModelPool();
InternalConfig config = new InternalConfig( request, modelPool );
Map<String, MavenProject> projectIndex = new HashMap<String, MavenProject>( 256 );
boolean noErrors =
build( results, interimResults, projectIndex, pomFiles, new LinkedHashSet<File>(), true, recursive, config );
populateReactorModelPool( modelPool, interimResults );
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
noErrors =
build( results, new ArrayList<MavenProject>(), projectIndex, interimResults, request,
new HashMap<File, Boolean>() ) && noErrors;
}
finally
{
Thread.currentThread().setContextClassLoader( oldContextClassLoader );
}
if ( !noErrors )
{
throw new ProjectBuildingException( results );
}
return results;
}
private boolean build( List<ProjectBuildingResult> results, List<InterimResult> interimResults,
Map<String, MavenProject> projectIndex, List<File> pomFiles, Set<File> aggregatorFiles,
boolean isRoot, boolean recursive, InternalConfig config )
{
boolean noErrors = true;
for ( File pomFile : pomFiles )
{
aggregatorFiles.add( pomFile );
if ( !build( results, interimResults, projectIndex, pomFile, aggregatorFiles, isRoot, recursive, config ) )
{
noErrors = false;
}
aggregatorFiles.remove( pomFile );
}
return noErrors;
}
private boolean build( List<ProjectBuildingResult> results, List<InterimResult> interimResults,
Map<String, MavenProject> projectIndex, File pomFile, Set<File> aggregatorFiles,
boolean isRoot, boolean recursive, InternalConfig config )
{
boolean noErrors = true;
ModelBuildingRequest request = getModelBuildingRequest( config );
MavenProject project = new MavenProject( repositorySystem, this, config.request, logger );
request.setPomFile( pomFile );
request.setTwoPhaseBuilding( true );
request.setLocationTracking( true );
DefaultModelBuildingListener listener =
new DefaultModelBuildingListener( project, projectBuildingHelper, config.request );
request.setModelBuildingListener( listener );
try
{
ModelBuildingResult result = modelBuilder.build( request );
Model model = result.getEffectiveModel();
projectIndex.put( result.getModelIds().get( 0 ), project );
InterimResult interimResult = new InterimResult( pomFile, request, result, listener, isRoot );
interimResults.add( interimResult );
if ( recursive && !model.getModules().isEmpty() )
{
File basedir = pomFile.getParentFile();
List<File> moduleFiles = new ArrayList<File>();
for ( String module : model.getModules() )
{
if ( StringUtils.isEmpty( module ) )
{
continue;
}
module = module.replace( '\\', File.separatorChar ).replace( '/', File.separatorChar );
File moduleFile = new File( basedir, module );
if ( moduleFile.isDirectory() )
{
moduleFile = modelProcessor.locatePom( moduleFile );
}
if ( !moduleFile.isFile() )
{
ModelProblem problem =
new DefaultModelProblem( "Child module " + moduleFile + " of " + pomFile
+ " does not exist", ModelProblem.Severity.ERROR, ModelProblem.Version.BASE, model, -1, -1, null );
result.getProblems().add( problem );
noErrors = false;
continue;
}
if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
{
// we don't canonicalize on unix to avoid interfering with symlinks
try
{
moduleFile = moduleFile.getCanonicalFile();
}
catch ( IOException e )
{
moduleFile = moduleFile.getAbsoluteFile();
}
}
else
{
moduleFile = new File( moduleFile.toURI().normalize() );
}
if ( aggregatorFiles.contains( moduleFile ) )
{
StringBuilder buffer = new StringBuilder( 256 );
for ( File aggregatorFile : aggregatorFiles )
{
buffer.append( aggregatorFile ).append( " -> " );
}
buffer.append( moduleFile );
ModelProblem problem =
new DefaultModelProblem( "Child module " + moduleFile + " of " + pomFile
+ " forms aggregation cycle " + buffer, ModelProblem.Severity.ERROR, ModelProblem.Version.BASE, model, -1, -1,
null );
result.getProblems().add( problem );
noErrors = false;
continue;
}
moduleFiles.add( moduleFile );
}
interimResult.modules = new ArrayList<InterimResult>();
if ( !build( results, interimResult.modules, projectIndex, moduleFiles, aggregatorFiles, false,
recursive, config ) )
{
noErrors = false;
}
}
}
catch ( ModelBuildingException e )
{
results.add( new DefaultProjectBuildingResult( e.getModelId(), pomFile, e.getProblems() ) );
noErrors = false;
}
return noErrors;
}
static class InterimResult
{
File pomFile;
ModelBuildingRequest request;
ModelBuildingResult result;
DefaultModelBuildingListener listener;
boolean root;
List<InterimResult> modules = Collections.emptyList();
InterimResult( File pomFile, ModelBuildingRequest request, ModelBuildingResult result,
DefaultModelBuildingListener listener, boolean root )
{
this.pomFile = pomFile;
this.request = request;
this.result = result;
this.listener = listener;
this.root = root;
}
}
private void populateReactorModelPool( ReactorModelPool reactorModelPool, List<InterimResult> interimResults )
{
for ( InterimResult interimResult : interimResults )
{
Model model = interimResult.result.getEffectiveModel();
reactorModelPool.put( model.getGroupId(), model.getArtifactId(), model.getVersion(), model.getPomFile() );
populateReactorModelPool( reactorModelPool, interimResult.modules );
}
}
private boolean build( List<ProjectBuildingResult> results, List<MavenProject> projects,
Map<String, MavenProject> projectIndex, List<InterimResult> interimResults,
ProjectBuildingRequest request, Map<File, Boolean> profilesXmls )
{
boolean noErrors = true;
for ( InterimResult interimResult : interimResults )
{
try
{
ModelBuildingResult result = modelBuilder.build( interimResult.request, interimResult.result );
MavenProject project = interimResult.listener.getProject();
initProject( project, projectIndex, result, profilesXmls );
List<MavenProject> modules = new ArrayList<MavenProject>();
noErrors =
build( results, modules, projectIndex, interimResult.modules, request, profilesXmls ) && noErrors;
projects.addAll( modules );
projects.add( project );
project.setExecutionRoot( interimResult.root );
project.setCollectedProjects( modules );
results.add( new DefaultProjectBuildingResult( project, result.getProblems(), null ) );
}
catch ( ModelBuildingException e )
{
results.add( new DefaultProjectBuildingResult( e.getModelId(), interimResult.pomFile, e.getProblems() ) );
noErrors = false;
}
}
return noErrors;
}
private void initProject( MavenProject project, Map<String, MavenProject> projects, ModelBuildingResult result,
Map<File, Boolean> profilesXmls )
{
Model model = result.getEffectiveModel();
project.setModel( model );
project.setOriginalModel( result.getRawModel() );
project.setFile( model.getPomFile() );
File parentPomFile = result.getRawModel( result.getModelIds().get( 1 ) ).getPomFile();
project.setParentFile( parentPomFile );
project.setParent( projects.get( result.getModelIds().get( 1 ) ) );
Artifact projectArtifact =
repositorySystem.createArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), null,
project.getPackaging() );
project.setArtifact( projectArtifact );
if ( project.getFile() != null )
{
Build build = project.getBuild();
project.addScriptSourceRoot( build.getScriptSourceDirectory() );
project.addCompileSourceRoot( build.getSourceDirectory() );
project.addTestCompileSourceRoot( build.getTestSourceDirectory() );
}
List<Profile> activeProfiles = new ArrayList<Profile>();
activeProfiles.addAll( result.getActivePomProfiles( result.getModelIds().get( 0 ) ) );
activeProfiles.addAll( result.getActiveExternalProfiles() );
project.setActiveProfiles( activeProfiles );
project.setInjectedProfileIds( "external", getProfileIds( result.getActiveExternalProfiles() ) );
for ( String modelId : result.getModelIds() )
{
project.setInjectedProfileIds( modelId, getProfileIds( result.getActivePomProfiles( modelId ) ) );
}
String modelId = findProfilesXml( result, profilesXmls );
if ( modelId != null )
{
ModelProblem problem =
new DefaultModelProblem( "Detected profiles.xml alongside " + modelId
+ ", this file is no longer supported and was ignored" + ", please use the settings.xml instead",
ModelProblem.Severity.WARNING, ModelProblem.Version.V30, model, -1, -1, null );
result.getProblems().add( problem );
}
}
private String findProfilesXml( ModelBuildingResult result, Map<File, Boolean> profilesXmls )
{
for ( String modelId : result.getModelIds() )
{
Model model = result.getRawModel( modelId );
File basedir = model.getProjectDirectory();
if ( basedir == null )
{
break;
}
Boolean profilesXml = profilesXmls.get( basedir );
if ( profilesXml == null )
{
profilesXml = new File( basedir, "profiles.xml" ).exists();
profilesXmls.put( basedir, profilesXml );
}
if ( profilesXml.booleanValue() )
{
return modelId;
}
}
return null;
}
class InternalConfig
{
public final ProjectBuildingRequest request;
public final RepositorySystemSession session;
public final List<RemoteRepository> repositories;
public final ReactorModelPool modelPool;
InternalConfig( ProjectBuildingRequest request, ReactorModelPool modelPool )
{
this.request = request;
this.modelPool = modelPool;
session =
LegacyLocalRepositoryManager.overlay( request.getLocalRepository(), request.getRepositorySession(),
repoSystem );
repositories = RepositoryUtils.toRepos( request.getRemoteRepositories() );
}
}
}
| apache-2.0 |
hongyan99/chart-faces | chartfaces/src/main/java/org/javaq/chartfaces/converter/AbstractIterableToIterable.java | 1608 | package org.javaq.chartfaces.converter;
import java.util.Iterator;
import org.javaq.chartfaces.iterable.IIterableConverter;
import org.javaq.chartfaces.iterable.ISizeAwareIterable;
import org.javaq.chartfaces.iterable.IterableUtility;
/**
* Converts Iterable of one data type to that of another.
*
* @author Hongyan Li
*
*/
public abstract class AbstractIterableToIterable<TIn, TData> implements
IIterableConverter<Iterable<TIn>, TData, ISizeAwareIterable<TData>> {
private final class DataTransformIterator implements Iterator<TData> {
private final Iterator<TIn> delegate;
private DataTransformIterator(final Iterator<TIn> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return this.delegate.hasNext();
}
@Override
public TData next() {
return transform(this.delegate.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public ISizeAwareIterable<TData> convert(final Iterable<TIn> target) {
return new ISizeAwareIterable<TData>() {
@Override
public Iterator<TData> iterator() {
return target == null ? null : new DataTransformIterator(
target.iterator());
}
@Override
public int size() {
return target == null ? 0 : IterableUtility.getSize(target);
}
};
}
/**
* Transforms the passed in data to the returned.
*
* @param target
* @return an Object if type TData that the passed in is transformed to.
*/
protected abstract TData transform(TIn target);
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-networkmanager/src/main/java/com/amazonaws/services/networkmanager/model/DeregisterTransitGatewayRequest.java | 5456 | /*
* 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.networkmanager.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeregisterTransitGateway"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeregisterTransitGatewayRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the global network.
* </p>
*/
private String globalNetworkId;
/**
* <p>
* The Amazon Resource Name (ARN) of the transit gateway.
* </p>
*/
private String transitGatewayArn;
/**
* <p>
* The ID of the global network.
* </p>
*
* @param globalNetworkId
* The ID of the global network.
*/
public void setGlobalNetworkId(String globalNetworkId) {
this.globalNetworkId = globalNetworkId;
}
/**
* <p>
* The ID of the global network.
* </p>
*
* @return The ID of the global network.
*/
public String getGlobalNetworkId() {
return this.globalNetworkId;
}
/**
* <p>
* The ID of the global network.
* </p>
*
* @param globalNetworkId
* The ID of the global network.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeregisterTransitGatewayRequest withGlobalNetworkId(String globalNetworkId) {
setGlobalNetworkId(globalNetworkId);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the transit gateway.
* </p>
*
* @param transitGatewayArn
* The Amazon Resource Name (ARN) of the transit gateway.
*/
public void setTransitGatewayArn(String transitGatewayArn) {
this.transitGatewayArn = transitGatewayArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the transit gateway.
* </p>
*
* @return The Amazon Resource Name (ARN) of the transit gateway.
*/
public String getTransitGatewayArn() {
return this.transitGatewayArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the transit gateway.
* </p>
*
* @param transitGatewayArn
* The Amazon Resource Name (ARN) of the transit gateway.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeregisterTransitGatewayRequest withTransitGatewayArn(String transitGatewayArn) {
setTransitGatewayArn(transitGatewayArn);
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 (getGlobalNetworkId() != null)
sb.append("GlobalNetworkId: ").append(getGlobalNetworkId()).append(",");
if (getTransitGatewayArn() != null)
sb.append("TransitGatewayArn: ").append(getTransitGatewayArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeregisterTransitGatewayRequest == false)
return false;
DeregisterTransitGatewayRequest other = (DeregisterTransitGatewayRequest) obj;
if (other.getGlobalNetworkId() == null ^ this.getGlobalNetworkId() == null)
return false;
if (other.getGlobalNetworkId() != null && other.getGlobalNetworkId().equals(this.getGlobalNetworkId()) == false)
return false;
if (other.getTransitGatewayArn() == null ^ this.getTransitGatewayArn() == null)
return false;
if (other.getTransitGatewayArn() != null && other.getTransitGatewayArn().equals(this.getTransitGatewayArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getGlobalNetworkId() == null) ? 0 : getGlobalNetworkId().hashCode());
hashCode = prime * hashCode + ((getTransitGatewayArn() == null) ? 0 : getTransitGatewayArn().hashCode());
return hashCode;
}
@Override
public DeregisterTransitGatewayRequest clone() {
return (DeregisterTransitGatewayRequest) super.clone();
}
}
| apache-2.0 |
javamelody/javamelody | javamelody-core/src/main/java/net/bull/javamelody/internal/model/JRobin.java | 27348 | /*
* Copyright 2008-2019 by Emeric Vernat
*
* This file is part of Java Melody.
*
* 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.bull.javamelody.internal.model;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import javax.imageio.ImageIO;
import org.jrobin.core.ConsolFuns;
import org.jrobin.core.FetchRequest;
import org.jrobin.core.RrdBackendFactory;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDbPool;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdException;
import org.jrobin.core.Sample;
import org.jrobin.core.Util;
import org.jrobin.data.DataProcessor;
import org.jrobin.data.Plottable;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;
import net.bull.javamelody.Parameter;
import net.bull.javamelody.internal.common.I18N;
import net.bull.javamelody.internal.common.LOG;
import net.bull.javamelody.internal.common.Parameters;
/**
* Stockage RRD et graphiques statistiques.
* Cette classe utilise <a href='http://www.jrobin.org/index.php/Main_Page'>JRobin</a>
* qui est une librairie Java opensource (LGPL) similaire à <a href='http://oss.oetiker.ch/rrdtool/'>RRDTool</a>.
* L'API et le tutorial JRobin sont à http://oldwww.jrobin.org/api/index.html
* @author Emeric Vernat
*/
public final class JRobin {
public static final int SMALL_HEIGHT = 50;
private static final Color PERCENTILE_COLOR = new Color(200, 50, 50);
private static final Color LIGHT_RED = Color.RED.brighter().brighter();
private static final Paint SMALL_GRADIENT = new GradientPaint(0, 0, LIGHT_RED, 0, SMALL_HEIGHT,
Color.GREEN, false);
private static final int HOUR = 60 * 60;
private static final int DAY = 24 * HOUR;
private static final int DEFAULT_OBSOLETE_GRAPHS_DAYS = 90;
private static final int DEFAULT_MAX_RRD_DISK_USAGE_MB = 20;
// pool of open RRD files
private final RrdDbPool rrdPool = getRrdDbPool();
private final String application;
private final String name;
private final String rrdFileName;
private final int step;
private final String requestName;
private static final class AppContextClassLoaderLeakPrevention {
private AppContextClassLoaderLeakPrevention() {
super();
}
static {
// issue 476: appContextProtection is disabled by default in JreMemoryLeakPreventionListener since Tomcat 7.0.42,
// so protect from sun.awt.AppContext ourselves
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
// Use the system classloader as the victim for this ClassLoader pinning we're about to do.
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
// Trigger a call to sun.awt.AppContext.getAppContext().
// This will pin the system class loader in memory but that shouldn't be an issue.
ImageIO.getCacheDirectory();
} catch (final Throwable t) { // NOPMD
LOG.info("prevention of AppContext ClassLoader leak failed, skipping");
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
}
static void dummy() {
// just to initialize the class
}
}
private JRobin(String application, String name, File rrdFile, int step, String requestName)
throws RrdException, IOException {
super();
assert application != null;
assert name != null;
assert rrdFile != null;
assert step > 0;
// requestName est null pour un compteur
this.application = application;
this.name = name;
this.rrdFileName = rrdFile.getPath();
this.step = step;
this.requestName = requestName;
init();
}
public static void stop() {
if (RrdNioBackend.getFileSyncTimer() != null) {
RrdNioBackend.getFileSyncTimer().cancel();
}
}
/**
* JavaMelody uses a custom RrdNioBackendFactory,
* in order to use its own and cancelable file sync timer.
* @param timer Timer
* @throws IOException e
*/
public static void initBackendFactory(Timer timer) throws IOException {
RrdNioBackend.setFileSyncTimer(timer);
try {
if (!RrdBackendFactory.getDefaultFactory().getFactoryName()
.equals(RrdNioBackendFactory.FACTORY_NAME)) {
RrdBackendFactory.registerAndSetAsDefaultFactory(new RrdNioBackendFactory());
}
} catch (final RrdException e) {
throw createIOException(e);
}
}
static JRobin createInstance(String application, String name, String requestName)
throws IOException {
final File rrdFile = getRrdFile(application, name);
final int step = Parameters.getResolutionSeconds();
try {
return new JRobin(application, name, rrdFile, step, requestName);
} catch (final RrdException e) {
throw createIOException(e);
}
}
static JRobin createInstanceIfFileExists(String application, String name, String requestName)
throws IOException {
final File rrdFile = getRrdFile(application, name);
if (rrdFile.exists()) {
final int step = Parameters.getResolutionSeconds();
try {
return new JRobin(application, name, rrdFile, step, requestName);
} catch (final RrdException e) {
throw createIOException(e);
}
}
return null;
}
private static File getRrdFile(String application, String name) {
final File dir = Parameters.getStorageDirectory(application);
return new File(dir, name + ".rrd");
}
private void init() throws IOException, RrdException {
final File rrdFile = new File(rrdFileName);
final File rrdDirectory = rrdFile.getParentFile();
if (!rrdDirectory.mkdirs() && !rrdDirectory.exists()) {
throw new IOException(
"JavaMelody directory can't be created: " + rrdDirectory.getPath());
}
// cf issue 41: rrdFile could have been created with length 0 if out of disk space
// (fix IOException: Read failed, file xxx.rrd not mapped for I/O)
if (!rrdFile.exists() || rrdFile.length() == 0) {
// create RRD file since it does not exist (or is empty)
final RrdDef rrdDef = new RrdDef(rrdFileName, step);
// "startTime" décalé de "step" pour éviter que addValue appelée juste
// après ne lance l'exception suivante la première fois
// "Bad sample timestamp x. Last update time was x, at least one second step is required"
rrdDef.setStartTime(Util.getTime() - step);
// single gauge datasource
final String dsType = "GAUGE";
// max time before "unknown value"
final int heartbeat = step * 2;
rrdDef.addDatasource(getDataSourceName(), dsType, heartbeat, 0, Double.NaN);
// several archives
final String average = ConsolFuns.CF_AVERAGE;
final String max = ConsolFuns.CF_MAX;
// 1 jour
rrdDef.addArchive(average, 0.25, 1, DAY / step);
rrdDef.addArchive(max, 0.25, 1, DAY / step);
// 1 semaine
rrdDef.addArchive(average, 0.25, HOUR / step, 7 * 24);
rrdDef.addArchive(max, 0.25, HOUR / step, 7 * 24);
// 1 mois
rrdDef.addArchive(average, 0.25, 6 * HOUR / step, 31 * 4);
rrdDef.addArchive(max, 0.25, 6 * HOUR / step, 31 * 4);
// 2 ans (1 an pour période "1 an" et 2 ans pour période "tout")
rrdDef.addArchive(average, 0.25, 8 * 6 * HOUR / step, 2 * 12 * 15);
rrdDef.addArchive(max, 0.25, 8 * 6 * HOUR / step, 2 * 12 * 15);
// create RRD file in the pool
final RrdDb rrdDb = rrdPool.requestRrdDb(rrdDef);
rrdPool.release(rrdDb);
}
}
private void resetFile() throws IOException {
deleteFile();
try {
init();
} catch (final RrdException e) {
throw createIOException(e);
}
}
public byte[] graph(Range range, int width, int height) throws IOException {
return graph(range, width, height, false);
}
public byte[] graph(Range range, int width, int height, boolean maxHidden) throws IOException {
// static init of the AppContext ClassLoader
AppContextClassLoaderLeakPrevention.dummy();
try {
// Rq : il pourrait être envisagé de récupérer les données dans les fichiers rrd ou autre stockage
// puis de faire des courbes en sparklines html (écrites dans la page html) ou jfreechart
// create common part of graph definition
final RrdGraphDef graphDef = new RrdGraphDef();
if (Locale.CHINESE.getLanguage()
.equals(I18N.getResourceBundle().getLocale().getLanguage())) {
graphDef.setSmallFont(new Font(Font.MONOSPACED, Font.PLAIN, 10));
graphDef.setLargeFont(new Font(Font.MONOSPACED, Font.BOLD, 12));
}
initGraphSource(graphDef, height, maxHidden, range);
initGraphPeriodAndSize(range, width, height, graphDef);
graphDef.setImageFormat("png");
graphDef.setFilename("-");
// il faut utiliser le pool pour les performances
// et pour éviter des erreurs d'accès concurrents sur les fichiers
// entre différentes générations de graphs et aussi avec l'écriture des données
graphDef.setPoolUsed(true);
return new RrdGraph(graphDef).getRrdGraphInfo().getBytes();
} catch (final RrdException e) {
throw createIOException(e);
}
}
private void initGraphPeriodAndSize(Range range, int width, int height, RrdGraphDef graphDef) {
// ending timestamp is the (current) timestamp in seconds
// starting timestamp will be adjusted for each graph
final long endTime = range.getJRobinEndTime();
final long startTime = range.getJRobinStartTime();
final String label = getLabel();
final String titleStart;
if (label.length() > 31 && width <= 200) {
// si le label est trop long, on raccourci le titre sinon il ne rentre pas
titleStart = label;
} else {
titleStart = label + " - " + range.getLabel();
}
final String titleEnd;
if (width > 400) {
if (range.getPeriod() == null) {
titleEnd = " - " + I18N.getFormattedString("sur", getApplication());
} else {
titleEnd = " - " + I18N.getCurrentDate() + ' '
+ I18N.getFormattedString("sur", getApplication());
}
} else {
titleEnd = "";
if (range.getPeriod() == null) {
// si période entre 2 dates et si pas de zoom,
// alors on réduit de 2 point la fonte du titre pour qu'il rentre dans le cadre
graphDef.setLargeFont(graphDef.getLargeFont()
.deriveFont(graphDef.getLargeFont().getSize2D() - 2f));
}
}
graphDef.setStartTime(startTime);
graphDef.setEndTime(endTime);
graphDef.setTitle(titleStart + titleEnd);
graphDef.setFirstDayOfWeek(
Calendar.getInstance(I18N.getCurrentLocale()).getFirstDayOfWeek());
// or if the user locale patch is merged we should do:
// (https://sourceforge.net/tracker/?func=detail&aid=3403733&group_id=82668&atid=566807)
//graphDef.setLocale(I18N.getCurrentLocale());
// rq : la largeur et la hauteur de l'image sont plus grandes que celles fournies
// car jrobin ajoute la largeur et la hauteur des textes et autres
graphDef.setWidth(width);
graphDef.setHeight(height);
if (width <= 100) {
graphDef.setNoLegend(true);
graphDef.setUnitsLength(0);
graphDef.setShowSignature(false);
graphDef.setTitle(null);
}
// graphDef.setColor(RrdGraphConstants.COLOR_BACK, new GradientPaint(0, 0,
// RrdGraphConstants.DEFAULT_BACK_COLOR.brighter(), 0, height,
// RrdGraphConstants.DEFAULT_BACK_COLOR));
}
private void initGraphSource(RrdGraphDef graphDef, int height, boolean maxHidden, Range range)
throws IOException {
final String dataSourceName = getDataSourceName();
final String average = "average";
graphDef.datasource(average, rrdFileName, dataSourceName, ConsolFuns.CF_AVERAGE);
graphDef.setMinValue(0);
final String moyenneLabel = I18N.getString("Moyenne");
graphDef.area(average, getPaint(height), moyenneLabel);
graphDef.gprint(average, ConsolFuns.CF_AVERAGE, moyenneLabel + ": %9.0f %S\\r");
//graphDef.gprint(average, ConsolFuns.CF_MIN, "Minimum: %9.0f %S\\r");
if (!maxHidden) {
final String max = "max";
graphDef.datasource(max, rrdFileName, dataSourceName, ConsolFuns.CF_MAX);
final String maximumLabel = I18N.getString("Maximum");
graphDef.line(max, Color.BLUE, maximumLabel);
graphDef.gprint(max, ConsolFuns.CF_MAX, maximumLabel + ": %9.0f %S\\r");
}
if (height > 200) {
final double percentileValue = get95PercentileValue(range);
final Plottable constantDataSource = new Plottable() {
@Override
public double getValue(long timestamp) {
return percentileValue;
}
};
final String percentile = "percentile";
graphDef.datasource(percentile, constantDataSource);
final String percentileLabel = I18N.getString("95percentile");
graphDef.line(percentile, PERCENTILE_COLOR, percentileLabel);
graphDef.gprint(percentile, ConsolFuns.CF_MAX, ":%9.0f %S\\r");
}
// graphDef.comment("JRobin :: RRDTool Choice for the Java World");
}
private static Paint getPaint(int height) {
// si on avait la moyenne globale/glissante des valeurs et l'écart type
// on pourrait mettre vert si < moyenne + 1 écart type puis orange puis rouge si > moyenne + 2 écarts types,
// en utilisant LinearGradientPaint par exemple, ou bien selon paramètres de plages de couleurs par graphe
if (height == SMALL_HEIGHT) {
// design pattern fly-weight (poids-mouche) pour le cas des 9 ou 12 graphs
// dans la page html de départ
return SMALL_GRADIENT;
}
return new GradientPaint(0, 0, LIGHT_RED, 0, height, Color.GREEN, false);
}
void addValue(double value) throws IOException {
try {
// request RRD database reference from the pool
final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName);
synchronized (rrdDb) {
try {
// create sample with the current timestamp
final Sample sample = rrdDb.createSample();
// test pour éviter l'erreur suivante au redéploiement par exemple:
// org.jrobin.core.RrdException:
// Bad sample timestamp x. Last update time was x, at least one second step is required
if (sample.getTime() > rrdDb.getLastUpdateTime()) {
// set value for load datasource
sample.setValue(getDataSourceName(), value);
// update database
sample.update();
}
} finally {
// release RRD database reference
rrdPool.release(rrdDb);
}
}
} catch (final FileNotFoundException e) {
if (e.getMessage() != null && e.getMessage().endsWith("[non existent]")) {
// cf issue 255
LOG.debug("A JRobin file was deleted and created again: "
+ new File(rrdFileName).getPath());
resetFile();
addValue(value);
}
} catch (final RrdException e) {
if (e.getMessage() != null && e.getMessage().startsWith("Invalid file header")) {
// le fichier RRD a été corrompu, par exemple en tuant le process java au milieu
// d'un write, donc on efface le fichier corrompu et on le recrée pour corriger
// le problème
LOG.debug("A JRobin file was found corrupted and was reset: "
+ new File(rrdFileName).getPath());
resetFile();
addValue(value);
}
throw createIOException(e);
} catch (final IllegalArgumentException | ArithmeticException e) {
// catch IllegalArgumentException for issue 533:
// java.lang.IllegalArgumentException
// at java.nio.Buffer.position(Buffer.java:244)
// at net.bull.javamelody.RrdNioBackend.read(RrdNioBackend.java:147)
// ...
// at org.jrobin.core.RrdDbPool.requestRrdDb(RrdDbPool.java:103)
// at net.bull.javamelody.JRobin.addValue(JRobin.java:334)
// ou catch ArithmeticException for issue 139 / JENKINS-51590:
// java.lang.ArithmeticException : / by zero
// at org.jrobin.core.Archive.archive(Archive.java:129)
// at org.jrobin.core.RrdDb.archive(RrdDb.java:720)
// at org.jrobin.core.Datasource.process(Datasource.java:201)
// at org.jrobin.core.RrdDb.store(RrdDb.java:593)
// at org.jrobin.core.Sample.update(Sample.java:228)
// at net.bull.javamelody.internal.model.JRobin.addValue(JRobin.java:374)
// le fichier RRD a été corrompu, par exemple en tuant le process java au milieu
// d'un write, donc on efface le fichier corrompu et on le recrée pour corriger
// le problème
LOG.debug("A JRobin file was found corrupted and was reset: "
+ new File(rrdFileName).getPath());
resetFile();
addValue(value);
throw createIOException(e);
}
}
public double getLastValue() throws IOException {
try {
// request RRD database reference from the pool
final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName);
try {
return rrdDb.getLastDatasourceValue(getDataSourceName());
} finally {
// release RRD database reference
rrdPool.release(rrdDb);
}
} catch (final RrdException e) {
throw createIOException(e);
}
}
public void dumpXml(OutputStream output, Range range) throws IOException {
try {
// request RRD database reference from the pool
final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName);
try {
if (range.getPeriod() == Period.TOUT) {
rrdDb.exportXml(output);
} else {
final FetchRequest fetchRequest = rrdDb.createFetchRequest(
ConsolFuns.CF_AVERAGE, range.getJRobinStartTime(),
range.getJRobinEndTime());
final String xml = fetchRequest.fetchData().exportXml()
.replaceFirst("<file>.*</file>", "");
output.write(xml.getBytes(StandardCharsets.UTF_8));
}
} finally {
// release RRD database reference
rrdPool.release(rrdDb);
}
} catch (final RrdException e) {
throw createIOException(e);
}
}
public String dumpTxt(Range range) throws IOException {
try {
// request RRD database reference from the pool
final RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName);
try {
if (range.getPeriod() == Period.TOUT) {
return rrdDb.dump();
}
final FetchRequest fetchRequest = rrdDb.createFetchRequest(ConsolFuns.CF_AVERAGE,
range.getJRobinStartTime(), range.getJRobinEndTime());
return fetchRequest.fetchData().dump();
} finally {
// release RRD database reference
rrdPool.release(rrdDb);
}
} catch (final RrdException e) {
throw createIOException(e);
}
}
double getMeanValue(Range range) throws IOException {
assert range.getPeriod() == null;
try {
final DataProcessor dproc = processData(range);
return dproc.getAggregate("average", ConsolFuns.CF_AVERAGE);
} catch (final RrdException e) {
throw createIOException(e);
}
}
private double get95PercentileValue(Range range) throws IOException {
try {
final DataProcessor dproc = processData(range);
// 95th percentile et non un autre percentile par choix
return dproc.get95Percentile("average");
} catch (final RrdException e) {
throw createIOException(e);
}
}
private DataProcessor processData(Range range) throws IOException, RrdException {
final String dataSourceName = getDataSourceName();
final long endTime = range.getJRobinEndTime();
final long startTime = range.getJRobinStartTime();
final DataProcessor dproc = new DataProcessor(startTime, endTime);
dproc.addDatasource("average", rrdFileName, dataSourceName, ConsolFuns.CF_AVERAGE);
dproc.setPoolUsed(true);
dproc.processData();
return dproc;
}
boolean deleteFile() {
return new File(rrdFileName).delete();
}
private String getApplication() {
return application;
}
public String getName() {
return name;
}
private String getDataSourceName() {
// RrdDef.addDatasource n'accepte pas un nom de datasource supérieur à 20 caractères
return name.substring(0, Math.min(20, name.length()));
}
public String getLabel() {
if (requestName == null) {
// c'est un jrobin global issu soit de JavaInformations soit d'un Counter dans le Collector
return I18N.getString(getName());
}
// c'est un jrobin issu d'un CounterRequest dans le Collector
final String shortRequestName = requestName.substring(0,
Math.min(30, requestName.length()));
// plus nécessaire: if (getName().startsWith("error")) {
// c'est un jrobin issu d'un CounterRequest du Counter "error"
// return I18N.getString("Erreurs_par_minute_pour") + ' ' + shortRequestName; }
return I18N.getFormattedString("Temps_moyens_de", shortRequestName);
}
private static IOException createIOException(Exception e) {
// Rq: le constructeur de IOException avec message et cause n'existe qu'en jdk 1.6
return new IOException(e.getMessage(), e);
}
static long deleteObsoleteJRobinFiles(String application) {
final Calendar nowMinusThreeMonthsAndADay = Calendar.getInstance();
nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -getObsoleteGraphsDays());
nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -1);
final long timestamp = Util.getTimestamp(nowMinusThreeMonthsAndADay);
final int counterRequestIdLength = new CounterRequest("", "").getId().length();
long diskUsage = 0;
final Map<String, Long> lastUpdateTimesByPath = new HashMap<>();
final List<File> rrdFiles = new ArrayList<>(listRrdFiles(application));
for (final File file : rrdFiles) {
// on ne supprime que les fichiers rrd de requêtes (les autres sont peu nombreux)
if (file.getName().length() > counterRequestIdLength
&& file.lastModified() < nowMinusThreeMonthsAndADay.getTimeInMillis()) {
final long lastUpdateTime = getLastUpdateTime(file);
lastUpdateTimesByPath.put(file.getPath(), lastUpdateTime);
final boolean obsolete = lastUpdateTime < timestamp;
boolean deleted = false;
if (obsolete) {
deleted = file.delete();
}
if (!deleted) {
diskUsage += file.length();
}
} else {
diskUsage += file.length();
}
}
final long maxRrdDiskUsage = getMaxRrdDiskUsageMb() * 1024L * 1024L;
if (diskUsage > maxRrdDiskUsage) {
// sort rrd files from least to most recently used
for (final File file : rrdFiles) {
if (lastUpdateTimesByPath.get(file.getPath()) == null) {
lastUpdateTimesByPath.put(file.getPath(), getLastUpdateTime(file));
}
}
final Comparator<File> comparatorByLastUpdateTime = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return lastUpdateTimesByPath.get(o1.getPath())
.compareTo(lastUpdateTimesByPath.get(o2.getPath()));
}
};
Collections.sort(rrdFiles, comparatorByLastUpdateTime);
// delete least recently used rrd files until rrd disk usage < 20 MB
for (final File file : rrdFiles) {
if (diskUsage < maxRrdDiskUsage) {
break;
}
if (file.getName().length() > counterRequestIdLength) {
final long length = file.length();
if (file.delete()) {
diskUsage -= length;
}
}
}
}
return diskUsage;
}
private static long getLastUpdateTime(File file) {
try {
final RrdDbPool rrdPool = getRrdDbPool();
final RrdDb rrdDb = rrdPool.requestRrdDb(file.getPath());
final long lastUpdateTime = rrdDb.getLastUpdateTime();
rrdPool.release(rrdDb);
return lastUpdateTime;
} catch (final IOException | RrdException e) {
return file.lastModified() / 1000L;
}
}
private static long getMaxRrdDiskUsageMb() {
final String param = Parameters.getParameterValue(Parameter.MAX_RRD_DISK_USAGE_MB);
if (param != null) {
// lance une NumberFormatException si ce n'est pas un nombre
final int result = Integer.parseInt(param);
if (result <= 0) {
throw new IllegalStateException(
"The parameter max-rrd-disk-usage-mb should be > 0 (20 recommended)");
}
return result;
}
return DEFAULT_MAX_RRD_DISK_USAGE_MB;
}
/**
* @return Nombre de jours avant qu'un fichier de graphique JRobin (extension .rrd) qui n'est plus utilisé,
* soit considéré comme obsolète et soit supprimé automatiquement, à minuit (90 par défaut, soit 3 mois).
*/
private static int getObsoleteGraphsDays() {
final String param = Parameter.OBSOLETE_GRAPHS_DAYS.getValue();
if (param != null) {
// lance une NumberFormatException si ce n'est pas un nombre
final int result = Integer.parseInt(param);
if (result <= 0) {
throw new IllegalStateException(
"The parameter obsolete-graphs-days should be > 0 (90 recommended)");
}
return result;
}
return DEFAULT_OBSOLETE_GRAPHS_DAYS;
}
private static List<File> listRrdFiles(String application) {
final File storageDir = Parameters.getStorageDirectory(application);
// filtre pour ne garder que les fichiers d'extension .rrd et pour éviter d'instancier des File inutiles
final FilenameFilter filenameFilter = new FilenameFilter() {
/** {@inheritDoc} */
@Override
public boolean accept(File dir, String fileName) {
return fileName.endsWith(".rrd");
}
};
final File[] files = storageDir.listFiles(filenameFilter);
if (files == null) {
return Collections.emptyList();
}
return Arrays.asList(files);
}
private static RrdDbPool getRrdDbPool() throws IOException {
try {
return RrdDbPool.getInstance();
} catch (final RrdException e) {
throw createIOException(e);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "[application=" + getApplication() + ", name="
+ getName() + ']';
}
// public void test() throws RrdException, IOException {
// for (int i = 1000; i > 0; i--) {
// // request RRD database reference from the pool
// RrdDb rrdDb = rrdPool.requestRrdDb(rrdFileName);
// // create sample with the current timestamp
// Sample sample = rrdDb.createSample(Util.getTime() - 120 * i);
// // set value for load datasource
// // println(i + " " + new byte[5000]);
// sample.setValue(name, Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
// // update database
// sample.update();
// // release RRD database reference
// rrdPool.release(rrdDb);
// }
//
// graph(Period.JOUR);
// graph(Period.SEMAINE);
// graph(Period.MOIS);
// graph(Period.ANNEE);
// }
//
// public static void main(String[] args) throws IOException, RrdException {
// new JRobin("Mémoire", "jrobin", 120).test();
// }
}
| apache-2.0 |
tasomaniac/DevFest | src/com/metrekare/devfest/ArticleDetailFragment.java | 7848 | /*
* Copyright 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.metrekare.devfest;
import java.util.Locale;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.MenuItem;
import com.netmera.mobile.NetmeraCallback;
import com.netmera.mobile.NetmeraContent;
import com.netmera.mobile.NetmeraException;
import com.netmera.mobile.NetmeraService;
import com.squareup.picasso.Picasso;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
/**
* A fragment representing a single Article detail screen. This fragment is
* either contained in a {@link ArticleListActivity} in two-pane mode (on
* tablets) or a {@link ArticleDetailActivity} on handsets.
*/
public class ArticleDetailFragment extends SherlockFragment {
public static String CONTENT = "Bacon ipsum dolor sit amet <a href='foo.html'>frankfurter tenderloin</a> beef ribs pig turducken,"
+ " tail jowl cow bresaola pork shoulder pastrami short ribs drumstick"
+ " strip steak.<br>"
+ "<br>"
+ "Beef ribs kielbasa sirloin pork loin chicken pork chop"
+ " rump andouille tail. Beef ribs corned beef sausage, doner shoulder"
+ " capicola pork pastrami jowl chuck shankle. T-bone ribeye chicken"
+ " turducken drumstick rump prosciutto tri-tip pork belly sausage"
+ " shankle venison shoulder pastrami ball tip.<br>"
+ "<br>"
+ "Frankfurter ball tip pork belly shoulder short loin. Boudin"
+ " andouille ham hock tri-tip tail, capicola t-bone fatback kielbasa"
+ " venison cow drumstick ribeye biltong. Shoulder ribeye hamburger,"
+ " pork belly strip steak chuck spare ribs ham hock salami. Turkey"
+ " filet mignon t-bone, ribeye tail boudin jowl short loin andouille"
+ " spare ribs. Cow tri-tip ball tip chuck, leberkas venison meatball"
+ " pastrami salami short loin bresaola. Turducken sirloin turkey"
+ " ribeye bresaola jowl bacon meatloaf sausage.<br>"
+ "<br>"
+ "Brisket doner tail capicola. Ham swine biltong jowl ribeye jerky"
+ " tenderloin pork belly hamburger venison brisket. Capicola ground"
+ " round pancetta jowl, turducken pork belly doner venison spare"
+ " ribs boudin frankfurter. Cow swine ball tip jowl, hamburger salami"
+ " prosciutto biltong ribeye venison tail short loin chuck turkey"
+ ". Leberkas fatback tongue, shoulder prosciutto strip steak ground"
+ " round short ribs kielbasa short loin flank. Meatball drumstick"
+ " turkey pork loin. Cow spare ribs chuck, beef ribs tongue ham salami"
+ " swine drumstick capicola jowl sirloin pork bresaola.";
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private NetmeraContent mItem;
private View rootView;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ArticleDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
// mItem = new NetmeraContent("article");
// mItem.setPath(getArguments().getString(
// ARG_ITEM_ID));
NetmeraService service = new NetmeraService("article");
service.setPath(getArguments().getString(
ARG_ITEM_ID));
service.getInBackground(new NetmeraCallback<NetmeraContent>() {
@Override
public void onFail(NetmeraException exception) {
Crouton.showText(getActivity(), exception.getMessage(), Style.ALERT);
}
@Override
public void onSuccess(NetmeraContent result) {
mItem = result;
fill();
}
});
// mItem.
//DummyContent.ITEM_MAP.get(getArguments().getString(
// ARG_ITEM_ID));
}
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(getActivity(), new Intent(getActivity(),
ArticleListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_article_detail,
container, false);
return rootView;
}
public void fill() {
// Show the dummy content as text in a TextView.
try {
if (mItem != null) {
((TextView) rootView.findViewById(R.id.article_title))
.setText(mItem.getString("title"));
((TextView) rootView.findViewById(R.id.article_byline))
.setText(Html.fromHtml(mItem.getString("article_date").toUpperCase(Locale.getDefault())
+ " BY <font color='"
+ getResources().getString(R.string.author_font_color) + "'>"
+ mItem.getString("author").toUpperCase(Locale.getDefault()) + "</a>"));
((TextView) rootView.findViewById(R.id.article_byline))
.setMovementMethod(new LinkMovementMethod());
// ((TextView) rootView.findViewById(R.id.article_date))
// .setText(mItem.time);
((TextView) rootView.findViewById(R.id.article_body))
.setText(Html.fromHtml(CONTENT));
Picasso.with(getActivity()).load(mItem.getString("imageUrl")).into((ImageView) rootView.findViewById(R.id.photo));
}
} catch(NetmeraException e ){}
}
}
| apache-2.0 |
imirp/imirp-app | app/dto/ProjectMutateConfigDto.java | 2650 | /**
* Copyright 2014 Torben Werner, Bridget Ryan
*
* 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 dto;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.bson.types.ObjectId;
import org.imirp.imirp.ImirpContext;
import org.imirp.imirp.MutationStrategy;
import org.imirp.imirp.data.Nucleotide;
import org.imirp.imirp.data.SiteType;
import org.imirp.imirp.data.TargetSiteType;
import org.imirp.imirp.mutation.region.MultiSiteMutation;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class ProjectMutateConfigDto implements Serializable {
private static final long serialVersionUID = 892398190189871L;
public static final Set<TargetSiteType> DEFAULT_INVALID_SITE_TYPES = new HashSet<>();
static {
DEFAULT_INVALID_SITE_TYPES.add(new TargetSiteType(SiteType.EIGHT_MER, false));
DEFAULT_INVALID_SITE_TYPES.add(new TargetSiteType(SiteType.SEVEN_MER_M8, false));
DEFAULT_INVALID_SITE_TYPES.add(new TargetSiteType(SiteType.SEVEN_MER_A1, false));
};
public static final Set<TargetSiteType> DEFAULT_VALID_SITE_TYPES = new HashSet<>();
static {
// Add all possibilities
Collections.addAll(DEFAULT_VALID_SITE_TYPES, TargetSiteType.values());
// Remove the ones we put in INVALID
DEFAULT_VALID_SITE_TYPES.removeAll(DEFAULT_INVALID_SITE_TYPES);
};
public ProjectDto project;
public Set<TargetSiteType> invalidSiteTypes;
public Set<TargetSiteType> validSiteTypes;
public MutationStrategy strategy;
public ProjectMutateConfigDto() {
this(null);
}
public ProjectMutateConfigDto(String projectId) {
super();
invalidSiteTypes = DEFAULT_INVALID_SITE_TYPES;
validSiteTypes = DEFAULT_VALID_SITE_TYPES;
strategy = new MutationStrategy(2, new Nucleotide[] { Nucleotide.GUANOSINE });
}
public MutationStrategy getStrategy() {
return strategy;
}
@JsonIgnore
public ImirpContext getImirpContext() {
MultiSiteMutation msm = new MultiSiteMutation(project.sequence, project.mutationSites, null);
return new ImirpContext(invalidSiteTypes, new ObjectId(project.id), project.species, msm, strategy, true);
}
} | apache-2.0 |
roguePanda/vetinari | vetinari-core/src/main/java/com/bennavetta/vetinari/render/internal/NoOpRenderer.java | 1039 | /**
* Copyright 2014 Ben Navetta
*
* 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.bennavetta.vetinari.render.internal;
import com.bennavetta.vetinari.render.Renderer;
import com.google.common.collect.ImmutableSet;
/**
* Does nothing.
*/
public class NoOpRenderer implements Renderer
{
@Override
public String render(String source)
{
return source;
}
@Override
public String getName()
{
return "noOp";
}
@Override
public Iterable<String> getFileExtensions()
{
return ImmutableSet.of();
}
}
| apache-2.0 |
romankagan/DDBWorkbench | plugins/hg4idea/src/org/zmlx/hg4idea/util/HgHistoryUtil.java | 10298 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zmlx.hg4idea.util;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.*;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.*;
import org.zmlx.hg4idea.action.HgCommandResultNotifier;
import org.zmlx.hg4idea.command.HgLogCommand;
import org.zmlx.hg4idea.execution.HgCommandException;
import org.zmlx.hg4idea.log.HgContentRevisionFactory;
import org.zmlx.hg4idea.provider.HgCommittedChangeList;
import java.io.File;
import java.util.*;
/**
* @author Nadya Zabrodina
*/
public class HgHistoryUtil {
private HgHistoryUtil() {
}
/**
* <p>Get & parse hg log detailed output with commits, their parents and their changes.</p>
* <p/>
* <p>Warning: this is method is efficient by speed, but don't query too much, because the whole log output is retrieved at once,
* and it can occupy too much memory. The estimate is ~600Kb for 1000 commits.</p>
*/
@NotNull
public static List<VcsFullCommitDetails> history(@NotNull final Project project,
@NotNull final VirtualFile root, int limit,
String... parameters)
throws VcsException {
List<HgCommittedChangeList> result = getCommittedChangeList(project, root, limit, true, parameters);
return ContainerUtil.mapNotNull(result, new Function<HgCommittedChangeList, VcsFullCommitDetails>() {
@Override
public VcsFullCommitDetails fun(HgCommittedChangeList record) {
return createCommit(project, root, record);
}
});
}
@NotNull
private static List<HgCommittedChangeList> getCommittedChangeList(@NotNull final Project project,
@NotNull final VirtualFile root, int limit, boolean withFiles,
String... parameters) {
HgFile hgFile = new HgFile(root, VcsUtil.getFilePath(root.getPath()));
List<String> args = ContainerUtil.newArrayList(parameters);
args.add("--debug");
List<HgCommittedChangeList> result = new LinkedList<HgCommittedChangeList>();
final List<HgFileRevision> localRevisions;
HgLogCommand hgLogCommand = new HgLogCommand(project);
hgLogCommand.setLogFile(false);
HgVcs hgvcs = HgVcs.getInstance(project);
assert hgvcs != null;
try {
localRevisions = hgLogCommand.execute(hgFile, limit, withFiles, args);
}
catch (HgCommandException e) {
new HgCommandResultNotifier(project).notifyError(null, HgVcsMessages.message("hg4idea.error.log.command.execution"), e.getMessage());
return Collections.emptyList();
}
Collections.reverse(localRevisions);
for (HgFileRevision revision : localRevisions) {
HgRevisionNumber vcsRevisionNumber = revision.getRevisionNumber();
List<HgRevisionNumber> parents = vcsRevisionNumber.getParents();
HgRevisionNumber firstParent = parents.isEmpty() ? null : parents.get(0); // can have no parents if it is a root
List<Change> changes = new ArrayList<Change>();
for (String file : revision.getModifiedFiles()) {
changes.add(createChange(project, root, file, firstParent, file, vcsRevisionNumber, FileStatus.MODIFIED));
}
for (String file : revision.getAddedFiles()) {
changes.add(createChange(project, root, null, null, file, vcsRevisionNumber, FileStatus.ADDED));
}
for (String file : revision.getDeletedFiles()) {
changes.add(createChange(project, root, file, firstParent, null, vcsRevisionNumber, FileStatus.DELETED));
}
for (Map.Entry<String, String> copiedFile : revision.getCopiedFiles().entrySet()) {
changes
.add(createChange(project, root, copiedFile.getKey(), firstParent, copiedFile.getValue(), vcsRevisionNumber, FileStatus.ADDED));
}
result.add(new HgCommittedChangeList(hgvcs, vcsRevisionNumber, revision.getBranchName(), revision.getCommitMessage(),
revision.getAuthor(), revision.getRevisionDate(), changes));
}
Collections.reverse(result);
return result;
}
@NotNull
public static List<? extends VcsShortCommitDetails> readMiniDetails(Project project, final VirtualFile root, List<String> hashes)
throws VcsException {
final VcsLogObjectsFactory factory = ServiceManager.getService(project, VcsLogObjectsFactory.class);
return ContainerUtil.map(getCommittedChangeList(project, root, -1, false, prepareHashes(hashes)),
new Function<HgCommittedChangeList, VcsShortCommitDetails>() {
@Override
public VcsShortCommitDetails fun(HgCommittedChangeList record) {
HgRevisionNumber revNumber = (HgRevisionNumber)record.getRevisionNumber();
List<Hash> parents = new SmartList<Hash>();
for (HgRevisionNumber parent : revNumber.getParents()) {
parents.add(factory.createHash(parent.getChangeset()));
}
return factory.createShortDetails(factory.createHash(revNumber.getChangeset()), parents,
record.getCommitDate().getTime(), root,
revNumber.getSubject(), revNumber.getAuthor(), revNumber.getEmail());
}
});
}
@NotNull
public static List<TimedVcsCommit> readAllHashes(@NotNull Project project, @NotNull VirtualFile root,
@NotNull final Consumer<VcsUser> userRegistry) throws VcsException {
final VcsLogObjectsFactory factory = ServiceManager.getService(project, VcsLogObjectsFactory.class);
return ContainerUtil.map(getCommittedChangeList(project, root, -1, false, ""), new Function<HgCommittedChangeList, TimedVcsCommit>() {
@Override
public TimedVcsCommit fun(HgCommittedChangeList record) {
HgRevisionNumber revNumber = (HgRevisionNumber)record.getRevisionNumber();
List<Hash> parents = new SmartList<Hash>();
for (HgRevisionNumber parent : revNumber.getParents()) {
parents.add(factory.createHash(parent.getChangeset()));
}
userRegistry.consume(factory.createUser(record.getRevision().getAuthor(), revNumber.getEmail()));
return factory.createTimedCommit(factory.createHash(revNumber.getChangeset()),
parents, record.getCommitDate().getTime());
}
});
}
@NotNull
public static Change createChange(Project project, VirtualFile root,
@Nullable String fileBefore,
@Nullable HgRevisionNumber revisionBefore,
@Nullable String fileAfter,
HgRevisionNumber revisionAfter,
FileStatus aStatus) {
HgContentRevision beforeRevision =
fileBefore == null ? null : new HgContentRevision(project, new HgFile(root, new File(root.getPath(), fileBefore)), revisionBefore);
HgContentRevision afterRevision =
fileAfter == null ? null : new HgContentRevision(project, new HgFile(root, new File(root.getPath(), fileAfter)), revisionAfter);
return new Change(beforeRevision, afterRevision, aStatus);
}
@NotNull
private static VcsFullCommitDetails createCommit(@NotNull Project project, @NotNull VirtualFile root,
@NotNull HgCommittedChangeList record) {
final VcsLogObjectsFactory factory = ServiceManager.getService(project, VcsLogObjectsFactory.class);
HgRevisionNumber revNumber = (HgRevisionNumber)record.getRevisionNumber();
List<Hash> parents = ContainerUtil.map(revNumber.getParents(), new Function<HgRevisionNumber, Hash>() {
@Override
public Hash fun(HgRevisionNumber parent) {
return factory.createHash(parent.getChangeset());
}
});
return factory.createFullDetails(factory.createHash(revNumber.getChangeset()), parents, record.getCommitDate().getTime(), root,
revNumber.getSubject(),
revNumber.getAuthor(), revNumber.getEmail(), revNumber.getCommitMessage(), record.getCommitterName(),
"", record.getCommitDate().getTime(),
ContainerUtil.newArrayList(record.getChanges()), HgContentRevisionFactory.getInstance(project));
}
@Nullable
public static String[] prepareHashes(@NotNull List<String> hashes) {
if (hashes.isEmpty()) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
StringBuilder builder = new StringBuilder();
for (String hash : hashes) {
builder.append(hash).append('+');
}
builder.deleteCharAt(builder.length() - 1);
//todo change ugly style
return new String[]{"--rev", builder.toString()};
}
}
| apache-2.0 |
raphaelning/resteasy-client-android | jaxrs/resteasy-jaxrs/src/test/java/org/jboss/resteasy/test/form/ComplexFormTest.java | 2139 | package org.jboss.resteasy.test.form;
import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.test.BaseResourceTest;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import static junit.framework.Assert.assertEquals;
public class ComplexFormTest extends BaseResourceTest
{
public static class Person
{
@FormParam("name")
private String name;
@Form(prefix = "invoice")
private Address invoice;
@Form(prefix = "shipping")
private Address shipping;
@Override
public String toString()
{
return new StringBuilder("name:'").append(name).append("', invoice:'").append(invoice.street).append("', shipping:'").append(shipping.street).append("'").toString();
}
}
public static class Address
{
@FormParam("street")
private String street;
}
@Path("person")
public static class MyResource
{
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(@Form Person p)
{
return p.toString();
}
}
@Before
public void register()
{
deployment.getRegistry().
addPerRequestResource(MyResource.class);
}
@Test
public void shouldSupportNestedForm() throws Exception
{
MockHttpResponse response = new MockHttpResponse();
MockHttpRequest request = MockHttpRequest.post("person").accept(MediaType.TEXT_PLAIN).contentType(MediaType.APPLICATION_FORM_URLENCODED);
request.addFormHeader("name", "John Doe");
request.addFormHeader("invoice.street", "Main Street");
request.addFormHeader("shipping.street", "Station Street");
dispatcher.invoke(request, response);
assertEquals("name:'John Doe', invoice:'Main Street', shipping:'Station Street'", response.getContentAsString());
}
}
| apache-2.0 |
scarabsoft/jrest | jrest-api/src/main/java/com/scarabsoft/jrest/Put.java | 357 | package com.scarabsoft.jrest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Put {
String value() default "";
boolean multipart() default true;
}
| apache-2.0 |
punit-naik/MLHadoop | Top_N_MapReduce/src/Top_N_Mapper.java | 2099 | import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class Top_N_Mapper extends Mapper<LongWritable, Text, Text, Text> {
public static Map<String, Integer> sortByComparator(Map<String, Integer> m){
List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(m.entrySet());
Collections.sort(list, new Comparator<Entry<String,Integer>>(){
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return -(o1.getValue().compareTo(o2.getValue()));
}
});
Map<String,Integer> sortedMap=new LinkedHashMap<String,Integer>();
for(Iterator<Entry<String,Integer>> it=list.iterator(); it.hasNext();){
Entry<String,Integer> e=it.next();
sortedMap.put(e.getKey(), e.getValue());
}
return sortedMap;
}
public static Map<String,Integer> sm=new HashMap<String,Integer>();
public static int N=0;
@Override
public void setup(Context context){
N=Integer.parseInt(context.getConfiguration().get("N"));
}
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] values=value.toString().split(",");
if(sm.containsKey(values[0]))
sm.put(values[0], sm.get(values[0])+Integer.parseInt(values[1]));
else
sm.put(values[0], Integer.parseInt(values[1]));
}
@Override
public void cleanup(Context context) throws IOException, InterruptedException{
int count=0;
// Sorting based on values descendingly
Map<String,Integer> p=sortByComparator(sm);
Map<String,Integer> x=new LinkedHashMap<String,Integer>();
for(Entry<String,Integer> e:p.entrySet()){
if(count<=N){
x.put(e.getKey(), e.getValue());
count++;
}
else
break;
}
context.write(new Text("1"), new Text(x.toString()));
sm.clear();
}
}
| apache-2.0 |
InformaticaCorp/Surf | transforms/grok/src/test/java/com/informatica/surf/transforms/grok/GrokTransformTest.java | 2540 | package com.informatica.surf.transforms.grok;
import com.informatica.vds.api.VDSConfiguration;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
/**
* Created by jerry on 02/04/14.
*/
public class GrokTransformTest {
@org.junit.Test
public void testApply() throws Exception {
GrokTransform g = new GrokTransform();
String input = "141.243.1.172 - - [13/Mar/2014:00:06:13 -0700] \"GET /Software.html HTTP/1.0\" 200 1497";
String expectedStr =" { " +
"\"COMMONAPACHELOG\": \"141.243.1.172 - - [13/Mar/2014:00:06:13 -0700] \"GET /Software.html HTTP/1.0\" 200 1497\", " +
"\"HOUR\": 0, " +
"\"INT\": -700, " +
"\"MINUTE\": 6, " +
"\"MONTH\": \"Mar\", " +
"\"MONTHDAY\": 13, " +
"\"SECOND\": 13, " +
"\"TIME\": \"00:06:13\", " +
"\"YEAR\": 2014, " +
"\"auth\": \"-\", " +
"\"bytes\": 1497, " +
"\"clientip\": \"141.243.1.172\", " +
"\"httpversion\": \"1.0\", " +
"\"ident\": \"-\", " +
"\"request\": \"/Software.html\", " +
"\"response\": 200, " +
"\"timestamp\": \"13/Mar/2014:00:06:13 -0700\", " +
"\"verb\": \"GET\" " +
"}";
final byte[]arr = input.getBytes();
VDSConfiguration ctx = mock(VDSConfiguration.class);
when(ctx.optString("pattern", "%{COMMONAPACHELOG}")).thenReturn("%{COMMONAPACHELOG}");
g.open(ctx);
String output = g.convertToJSON(input);
JSONObject json = (JSONObject)JSONValue.parse(output);
assertEquals(0, json.get("HOUR"));
assertEquals(-700, json.get("INT"));
assertEquals(6, json.get("MINUTE"));
assertEquals("Mar", json.get("MONTH"));
assertEquals(13, json.get("MONTHDAY"));
assertEquals(13, json.get("SECOND"));
assertEquals("00:06:13", json.get("TIME"));
assertEquals(2014, json.get("YEAR"));
assertEquals("-", json.get("auth"));
assertEquals(1497, json.get("bytes"));
assertEquals("141.243.1.172", json.get("clientip"));
assertEquals("1.0", json.get("httpversion"));
assertEquals("-", json.get("ident"));
assertEquals("/Software.html", json.get("request"));
assertEquals(200, json.get("response"));
assertEquals("13/Mar/2014:00:06:13 -0700", json.get("timestamp"));
assertEquals("GET", json.get("verb"));
}
}
| apache-2.0 |
mufaddalq/cloudstack-datera-driver | api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java | 3762 | // 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.cloudstack.api.command.admin.host;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.log4j.Logger;
import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.host.Host;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
@APICommand(name = "cancelHostMaintenance", description="Cancels host maintenance.", responseObject=HostResponse.class)
public class CancelMaintenanceCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(CancelMaintenanceCmd.class.getName());
private static final String s_name = "cancelhostmaintenanceresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HostResponse.class,
required=true, description="the host ID")
private Long id;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
public static String getResultObjectName() {
return "host";
}
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}
return Account.ACCOUNT_ID_SYSTEM;
}
@Override
public String getEventType() {
return EventTypes.EVENT_MAINTENANCE_CANCEL;
}
@Override
public String getEventDescription() {
return "canceling maintenance for host: " + getId();
}
@Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.Host;
}
@Override
public Long getInstanceId() {
return getId();
}
@Override
public void execute(){
Host result = _resourceService.cancelMaintenance(this);
if (result != null) {
HostResponse response = _responseGenerator.createHostResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to cancel host maintenance");
}
}
}
| apache-2.0 |
MegatronKing/SVG-Android | svg-iconlibs/av/src/main/java/com/github/megatronking/svg/iconlibs/ic_fast_forward.java | 1806 | package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_fast_forward extends SVGRenderer {
public ic_fast_forward(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(4.0f, 18.0f);
mPath.rLineTo(8.5f, -6.0f);
mPath.lineTo(4.0f, 6.0f);
mPath.rLineTo(0f, 12.0f);
mPath.close();
mPath.moveTo(4.0f, 18.0f);
mPath.rMoveTo(9.0f, -12.0f);
mPath.rLineTo(0f, 12.0f);
mPath.rLineTo(8.5f, -6.0f);
mPath.lineTo(13.0f, 6.0f);
mPath.close();
mPath.moveTo(13.0f, 6.0f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | apache-2.0 |
forvvard09/job4j_CoursesJunior | 1_Trainee/03_CollectionsLite/04_TestTaskCollectionsLite/task_1_03_04_01/src/test/java/model/UserTest.java | 2450 | package model;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Test class - testing class User.
*
* @author Sergei Poddubnyak (forvvard09@gmail.com)
* @version 1.0
* @since 19.04.2017
*/
public class UserTest {
/**
* property test NAME_TEST.
*/
private static final String NAME_TEST = "nameTest";
/**
* property test PASSPORT_TEST.
*/
private static final int PASSPORT_TEST = 123456790;
/**
* Test create new object User through a constructor with empty values.
*/
@Test
public void whenConstructorNewUserObjectThenGetExpectedFields() {
User user = new User(NAME_TEST, PASSPORT_TEST);
assertThat(user.getName(), is(NAME_TEST));
assertThat(user.getPassport(), is(PASSPORT_TEST));
}
/**
* Test seters and getters objects User.
*/
@Test
public void whenSettersObjectThenExpectedGetters() {
User user = new User(NAME_TEST, PASSPORT_TEST);
String expectedName = "expectedName";
final int expectedPassport = 1111222222;
user.setName(expectedName);
user.setPassport(expectedPassport);
assertThat(user.getName(), is(expectedName));
assertThat(user.getPassport(), is(expectedPassport));
}
/**
* Test equals for User.
*/
@Test
public void whenNotEqualsThenExpectedFalse() {
User user = new User(NAME_TEST, PASSPORT_TEST);
assertThat(user.equals(null), is(false));
}
/**
* Test equals for User.
*/
@Test
public void whenEqualsThenExpectedTrue() {
User userOne = new User(NAME_TEST, PASSPORT_TEST);
User userTwo = new User(NAME_TEST, PASSPORT_TEST);
assertThat(userOne.equals(userTwo), is(true));
}
/**
* Test equals for User.
*/
@Test
public void whenFieldPassportEqualsThenExpectedFalse() {
User userOne = new User(NAME_TEST, PASSPORT_TEST);
final int passportTest = 0;
User userTwo = new User(NAME_TEST, passportTest);
assertThat(userOne.equals(userTwo), is(false));
}
/**
* Test hashCode for User.
*/
@Test
public void whenHashCodeThenExpectedresult() {
User user = new User(null, 0);
assertThat(user.hashCode(), is(0));
}
} | apache-2.0 |
asual/summer | modules/core/src/main/java/com/asual/summer/core/spring/ExtendedServletRequestDataBinder.java | 1343 | /*
* 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.asual.summer.core.spring;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.ServletRequestDataBinder;
import com.asual.summer.core.util.RequestUtils;
/**
*
* @author Rostislav Hristov
*
*/
public class ExtendedServletRequestDataBinder extends ServletRequestDataBinder {
public ExtendedServletRequestDataBinder(Object target, String objectName) {
super(target, objectName);
}
public BindingResult getBindingResult() {
BindingResult result = super.getInternalBindingResult();
if ((RequestUtils.getRequest() != null && RequestUtils.isValidation()) && !result.hasErrors()) {
result.addError(new ObjectError("validation", "success"));
}
return result;
}
}
| apache-2.0 |
presidentio/teamcity-matrix-build-plugin | matrix-build-common/src/main/java/com/presidentio/teamcity/matrix/build/common/dto/Build.java | 772 | package com.presidentio.teamcity.matrix.build.common.dto;
import java.util.Map;
/**
* Created by presidentio on 1/3/16.
*/
public class Build {
private Long buildId;
private Map<String, String> parameters;
public Build() {
}
public Build(Long buildId, Map<String, String> parameters) {
this.buildId = buildId;
this.parameters = parameters;
}
public Map<String, String> getParameters() {
return parameters;
}
public Build setParameters(Map<String, String> parameters) {
this.parameters = parameters;
return this;
}
public Long getBuildId() {
return buildId;
}
public Build setBuildId(Long buildId) {
this.buildId = buildId;
return this;
}
}
| apache-2.0 |
gchq/stroom | stroom-core-shared/src/main/java/stroom/meta/shared/MetaFields.java | 5061 | package stroom.meta.shared;
import stroom.datasource.api.v2.AbstractField;
import stroom.datasource.api.v2.DateField;
import stroom.datasource.api.v2.DocRefField;
import stroom.datasource.api.v2.IdField;
import stroom.datasource.api.v2.LongField;
import stroom.datasource.api.v2.TextField;
import stroom.docref.DocRef;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MetaFields {
public static final String STREAM_STORE_TYPE = "StreamStore";
public static final DocRef STREAM_STORE_DOC_REF = DocRef.builder()
.type(STREAM_STORE_TYPE)
.uuid("0")
.name(STREAM_STORE_TYPE)
.build();
public static final String FIELD_ID = "Id";
public static final String FIELD_FEED = "Feed";
public static final String FIELD_TYPE = "Type";
public static final String FIELD_PARENT_FEED = "Parent Feed";
private static final List<AbstractField> FIELDS = new ArrayList<>();
private static final Map<String, AbstractField> FIELD_MAP;
private static final List<AbstractField> EXTENDED_FIELDS = new ArrayList<>();
private static final List<AbstractField> ALL_FIELDS = new ArrayList<>();
private static final Map<String, AbstractField> ALL_FIELD_MAP;
// Non grouped fields
public static final DocRefField FEED = new DocRefField("Feed", "Feed");
public static final DocRefField PIPELINE = new DocRefField("Pipeline", "Pipeline");
public static final TextField STATUS = new TextField("Status");
public static final TextField TYPE = new TextField("Type");
// Id's
public static final IdField ID = new IdField("Id");
public static final IdField META_INTERNAL_PROCESSOR_ID = new IdField("Processor Id");
public static final IdField META_PROCESSOR_FILTER_ID = new IdField("Processor Filter Id");
public static final IdField META_PROCESSOR_TASK_ID = new IdField("Processor Task Id");
// Times
public static final DateField CREATE_TIME = new DateField("Create Time");
public static final DateField EFFECTIVE_TIME = new DateField("Effective Time");
public static final DateField STATUS_TIME = new DateField("Status Time");
// Extended fields.
// public static final String NODE = "Node";
public static final LongField REC_READ = new LongField("Read Count");
public static final LongField REC_WRITE = new LongField("Write Count");
public static final LongField REC_INFO = new LongField("Info Count");
public static final LongField REC_WARN = new LongField("Warning Count");
public static final LongField REC_ERROR = new LongField("Error Count");
public static final LongField REC_FATAL = new LongField("Fatal Error Count");
public static final LongField DURATION = new LongField("Duration");
public static final LongField FILE_SIZE = new LongField("File Size");
public static final LongField RAW_SIZE = new LongField("Raw Size");
// Parent fields.
public static final IdField PARENT_ID = new IdField("Parent Id");
public static final TextField PARENT_STATUS = new TextField("Parent Status");
public static final DateField PARENT_CREATE_TIME = new DateField("Parent Create Time");
public static final DocRefField PARENT_FEED = new DocRefField("Feed", FIELD_PARENT_FEED);
static {
// Non grouped fields
FIELDS.add(FEED);
FIELDS.add(PIPELINE);
FIELDS.add(STATUS);
FIELDS.add(TYPE);
// Id's
FIELDS.add(ID);
FIELDS.add(PARENT_ID);
FIELDS.add(META_INTERNAL_PROCESSOR_ID);
FIELDS.add(META_PROCESSOR_FILTER_ID);
FIELDS.add(META_PROCESSOR_TASK_ID);
// Times
FIELDS.add(CREATE_TIME);
FIELDS.add(EFFECTIVE_TIME);
FIELDS.add(STATUS_TIME);
FIELD_MAP = FIELDS.stream().collect(Collectors.toMap(AbstractField::getName, Function.identity()));
// Single Items
EXTENDED_FIELDS.add(DURATION);
// Counts
EXTENDED_FIELDS.add(REC_READ);
EXTENDED_FIELDS.add(REC_WRITE);
EXTENDED_FIELDS.add(REC_INFO);
EXTENDED_FIELDS.add(REC_WARN);
EXTENDED_FIELDS.add(REC_ERROR);
EXTENDED_FIELDS.add(REC_FATAL);
// Sizes
EXTENDED_FIELDS.add(FILE_SIZE);
EXTENDED_FIELDS.add(RAW_SIZE);
ALL_FIELDS.addAll(FIELDS);
ALL_FIELDS.addAll(EXTENDED_FIELDS);
ALL_FIELD_MAP = ALL_FIELDS.stream().collect(Collectors.toMap(AbstractField::getName, Function.identity()));
}
public static List<AbstractField> getFields() {
return new ArrayList<>(FIELDS);
}
public static Map<String, AbstractField> getFieldMap() {
return FIELD_MAP;
}
public static List<AbstractField> getAllFields() {
return ALL_FIELDS;
}
public static Map<String, AbstractField> getAllFieldMap() {
return ALL_FIELD_MAP;
}
public static List<AbstractField> getExtendedFields() {
return EXTENDED_FIELDS;
}
}
| apache-2.0 |
frett/cas | support/cas-server-support-actions/src/test/java/org/apereo/cas/web/flow/GenerateServiceTicketActionTests.java | 5747 | package org.apereo.cas.web.flow;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.web.support.WebUtils;
import lombok.val;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.Action;
import org.springframework.webflow.test.MockRequestContext;
import javax.servlet.http.Cookie;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* @author Scott Battaglia
* @since 3.0.0
*/
public class GenerateServiceTicketActionTests extends AbstractWebflowActionsTests {
private static final String SERVICE_PARAM = "service";
@Autowired
@Qualifier("generateServiceTicketAction")
private Action action;
private TicketGrantingTicket ticketGrantingTicket;
@Before
public void onSetUp() {
val authnResult = getAuthenticationSystemSupport()
.handleAndFinalizeSingleAuthenticationTransaction(CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword());
this.ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(authnResult);
getTicketRegistry().addTicket(this.ticketGrantingTicket);
}
@Test
public void verifyServiceTicketFromCookie() throws Exception {
val context = new MockRequestContext();
context.getFlowScope().put(SERVICE_PARAM, RegisteredServiceTestUtils.getService());
context.getFlowScope().put(WebUtils.PARAMETER_TICKET_GRANTING_TICKET_ID, this.ticketGrantingTicket.getId());
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(
new MockServletContext(), request, new MockHttpServletResponse()));
request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, SERVICE_PARAM);
request.setCookies(new Cookie("TGT", this.ticketGrantingTicket.getId()));
this.action.execute(context);
assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
@Test
public void verifyTicketGrantingTicketFromRequest() throws Exception {
val context = new MockRequestContext();
context.getFlowScope().put(SERVICE_PARAM, RegisteredServiceTestUtils.getService());
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, SERVICE_PARAM);
WebUtils.putTicketGrantingTicketInScopes(context, this.ticketGrantingTicket);
this.action.execute(context);
assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
@Test
public void verifyTicketGrantingTicketNoTgt() throws Exception {
val context = new MockRequestContext();
context.getFlowScope().put(SERVICE_PARAM, RegisteredServiceTestUtils.getService());
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, SERVICE_PARAM);
val tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("bleh");
WebUtils.putTicketGrantingTicketInScopes(context, tgt);
assertEquals(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, this.action.execute(context).getId());
}
@Test
public void verifyTicketGrantingTicketExpiredTgt() throws Exception {
val context = new MockRequestContext();
context.getFlowScope().put(SERVICE_PARAM, RegisteredServiceTestUtils.getService());
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, SERVICE_PARAM);
WebUtils.putTicketGrantingTicketInScopes(context, this.ticketGrantingTicket);
this.ticketGrantingTicket.markTicketExpired();
getTicketRegistry().updateTicket(this.ticketGrantingTicket);
assertEquals(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, this.action.execute(context).getId());
}
@Test
public void verifyTicketGrantingTicketNotTgtButGateway() throws Exception {
val context = new MockRequestContext();
context.getFlowScope().put(SERVICE_PARAM, RegisteredServiceTestUtils.getService());
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, SERVICE_PARAM);
request.addParameter(CasProtocolConstants.PARAMETER_GATEWAY, "true");
val tgt = mock(TicketGrantingTicket.class);
when(tgt.getId()).thenReturn("bleh");
WebUtils.putTicketGrantingTicketInScopes(context, tgt);
assertEquals(CasWebflowConstants.STATE_ID_GATEWAY, this.action.execute(context).getId());
}
}
| apache-2.0 |
intrigus/VisEditor | UI/src/com/kotcrab/vis/ui/util/form/FormValidator.java | 7229 | /*
* Copyright 2014-2015 See AUTHORS file.
*
* 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.kotcrab.vis.ui.util.form;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.kotcrab.vis.ui.widget.VisTextField;
import com.kotcrab.vis.ui.widget.VisValidatableTextField;
import java.io.File;
/**
* Makes validating forms easier <br>
* FromValidator is not gwt compatible, if you need that see {@link SimpleFormValidator}
* @author Kotcrab
*/
public class FormValidator extends SimpleFormValidator {
public FormValidator (Button buttonToDisable, Label errorMsgLabel) {
super(buttonToDisable, errorMsgLabel);
}
public FormInputValidator fileExists (VisValidatableTextField field, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(errorMsg);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileExists (VisValidatableTextField field, VisTextField relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo, errorMsg);
field.addValidator(validator);
add(field);
return validator;
}
/**
* @param errorIfRelativeEmpty if true field input will be valid if 'relativeTo' field is empty, usually used with notEmpty validator on 'relativeTo' to
* avoid form errors. Settings this to true improves UX, error are not displayed until user types something in 'relativeTo'
* field
*/
public FormInputValidator fileExists (VisValidatableTextField field, VisTextField relativeTo, String errorMsg, boolean errorIfRelativeEmpty) {
FileExistsValidator validator = new FileExistsValidator(relativeTo, errorMsg, false, errorIfRelativeEmpty);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileExists (VisValidatableTextField field, File relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo, errorMsg);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileExists (VisValidatableTextField field, FileHandle relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo.file(), errorMsg);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileNotExists (VisValidatableTextField field, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(errorMsg, true);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileNotExists (VisValidatableTextField field, VisTextField relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo, errorMsg, true);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileNotExists (VisValidatableTextField field, File relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo, errorMsg, true);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator fileNotExists (VisValidatableTextField field, FileHandle relativeTo, String errorMsg) {
FileExistsValidator validator = new FileExistsValidator(relativeTo.file(), errorMsg, true);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator directory (VisValidatableTextField field, String errorMsg) {
DirectoryValidator validator = new DirectoryValidator(errorMsg);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator directoryEmpty (VisValidatableTextField field, String errorMsg) {
DirectoryContentValidator validator = new DirectoryContentValidator(errorMsg, true);
field.addValidator(validator);
add(field);
return validator;
}
public FormInputValidator directoryNotEmpty (VisValidatableTextField field, String errorMsg) {
DirectoryContentValidator validator = new DirectoryContentValidator(errorMsg, false);
field.addValidator(validator);
add(field);
return validator;
}
public static class DirectoryValidator extends FormInputValidator {
public DirectoryValidator (String errorMsg) {
super(errorMsg);
}
@Override
protected boolean validate (String input) {
FileHandle file = Gdx.files.absolute(input);
return file.exists() || file.isDirectory();
}
}
public static class DirectoryContentValidator extends FormInputValidator {
private final boolean mustBeEmpty;
public DirectoryContentValidator (String errorMsg, boolean mustBeEmpty) {
super(errorMsg);
this.mustBeEmpty = mustBeEmpty;
}
@Override
protected boolean validate (String input) {
FileHandle file = Gdx.files.absolute(input);
if (file.exists() == false || file.isDirectory() == false) return false;
if (mustBeEmpty)
return file.list().length == 0;
else
return file.list().length != 0;
}
}
public static class FileExistsValidator extends FormInputValidator {
VisTextField relativeTo;
File relativeToFile;
boolean existNot;
boolean errorIfRelativeEmpty;
public FileExistsValidator (String errorMsg) {
this(errorMsg, false);
}
public FileExistsValidator (VisTextField relativeTo, String errorMsg) {
this(relativeTo, errorMsg, false);
}
public FileExistsValidator (File relativeTo, String errorMsg) {
this(relativeTo, errorMsg, false);
}
public FileExistsValidator (String errorMsg, boolean existNot) {
super(errorMsg);
this.existNot = existNot;
}
public FileExistsValidator (VisTextField relativeTo, String errorMsg, boolean existNot) {
super(errorMsg);
this.relativeTo = relativeTo;
this.existNot = existNot;
}
public FileExistsValidator (File relativeTo, String errorMsg, boolean existNot) {
super(errorMsg);
this.relativeToFile = relativeTo;
this.existNot = existNot;
}
public FileExistsValidator (VisTextField relativeTo, String errorMsg, boolean existNot, boolean errorIfRelativeEmpty) {
super(errorMsg);
this.relativeTo = relativeTo;
this.existNot = existNot;
this.errorIfRelativeEmpty = errorIfRelativeEmpty;
}
@Override
public boolean validate (String input) {
File file;
if (relativeTo != null) {
if (relativeTo.getText().length() == 0 && errorIfRelativeEmpty == false) {
return true;
}
file = new File(relativeTo.getText(), input);
} else if (relativeToFile != null)
file = new File(relativeToFile, input);
else
file = new File(input);
if (existNot)
return !file.exists();
else
return file.exists();
}
}
}
| apache-2.0 |
masaki-yamakawa/geode | geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/ParameterRequirements/SlowlogParameterRequirements.java | 2745 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.redis.internal.ParameterRequirements;
import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_INTEGER;
import static org.apache.geode.redis.internal.RedisConstants.ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND;
import org.apache.geode.redis.internal.netty.Command;
import org.apache.geode.redis.internal.netty.ExecutionHandlerContext;
public class SlowlogParameterRequirements implements ParameterRequirements {
@Override
public void checkParameters(Command command, ExecutionHandlerContext context) {
int numberOfArguments = command.getProcessedCommand().size();
if (numberOfArguments < 2) {
throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage());
} else if (numberOfArguments == 2) {
confirmKnownSubcommands(command);
} else if (numberOfArguments == 3) {
confirmArgumentsToGetSubcommand(command);
} else { // numberOfArguments > 3
throw new RedisParametersMismatchException(
String.format(ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND, command.getStringKey()));
}
}
private void confirmKnownSubcommands(Command command) {
if (!command.getStringKey().toLowerCase().equals("reset") &&
!command.getStringKey().toLowerCase().equals("len") &&
!command.getStringKey().toLowerCase().equals("get")) {
throw new RedisParametersMismatchException(
String.format(ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND, command.getStringKey()));
}
}
private void confirmArgumentsToGetSubcommand(Command command) {
if (!command.getStringKey().toLowerCase().equals("get")) {
throw new RedisParametersMismatchException(
String.format(ERROR_UNKNOWN_SLOWLOG_SUBCOMMAND, command.getStringKey()));
}
try {
Long.parseLong(new String(command.getProcessedCommand().get(2)));
} catch (NumberFormatException nex) {
throw new RedisParametersMismatchException(ERROR_NOT_INTEGER);
}
}
}
| apache-2.0 |
zhcet-amu/zhcet-web | src/main/java/amu/zhcet/common/error/InvalidEmailException.java | 209 | package amu.zhcet.common.error;
public class InvalidEmailException extends RuntimeException {
public InvalidEmailException(String email) {
super(email + " is an invalid email address");
}
}
| apache-2.0 |
MightyElemental/JavaProjects | Tree Generator/src/net/mightyelemental/tree/Blur.java | 6562 | package net.mightyelemental.tree;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.imageout.ImageIOWriter;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.util.BufferedImageUtil;
public class Blur {
public static Image processImage(Image img) {
return null;
}
@SuppressWarnings("unused")
private static Image convertToImage(BufferedImage img) throws IOException, SlickException {
Texture texture = BufferedImageUtil.getTexture("", img);
Image slickImage = new Image(texture.getImageWidth(), texture.getImageHeight());
slickImage.setTexture(texture);
return slickImage;
}
@SuppressWarnings("unused")
private static BufferedImage convertToBufferedImage(Image img) throws IOException, SlickException {
Texture texture = img.getTexture();
BufferedImage buffimg = new BufferedImage(texture.getImageWidth(), texture.getImageHeight(), BufferedImage.TYPE_INT_ARGB);
img.getTexture();
ImageIOWriter imgio = new ImageIOWriter();
ByteArrayOutputStream os = null;
imgio.saveImage(img, "", os, true);
byte[] b = null;
os.write(b);
os.flush();
return buffimg;
}
@SuppressWarnings("unused")
private static BufferedImage ProcessImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
int[] changedPixels = new int[pixels.length];
FastGaussianBlur(pixels, changedPixels, width, height, 12);
BufferedImage newImage = new BufferedImage(width, height, image.getType());
newImage.setRGB(0, 0, width, height, changedPixels, 0, width);
return newImage;
}
private static void FastGaussianBlur(int[] source, int[] output, int width, int height, int radius) {
ArrayList<Integer> gaussianBoxes = CreateGausianBoxes(radius, 3);
BoxBlur(source, output, width, height, (gaussianBoxes.get(0) - 1) / 2);
BoxBlur(output, source, width, height, (gaussianBoxes.get(1) - 1) / 2);
BoxBlur(source, output, width, height, (gaussianBoxes.get(2) - 1) / 2);
}
private static ArrayList<Integer> CreateGausianBoxes(double sigma, int n) {
double idealFilterWidth = Math.sqrt((12 * sigma * sigma / n) + 1);
int filterWidth = (int) Math.floor(idealFilterWidth);
if (filterWidth % 2 == 0) {
filterWidth--;
}
int filterWidthU = filterWidth + 2;
double mIdeal = (12 * sigma * sigma - n * filterWidth * filterWidth - 4 * n * filterWidth - 3 * n) / (-4 * filterWidth - 4);
double m = Math.round(mIdeal);
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
result.add(i < m ? filterWidth : filterWidthU);
}
return result;
}
private static void BoxBlur(int[] source, int[] output, int width, int height, int radius) {
System.arraycopy(source, 0, output, 0, source.length);
BoxBlurHorizontal(output, source, width, height, radius);
BoxBlurVertical(source, output, width, height, radius);
}
private static void BoxBlurHorizontal(int[] sourcePixels, int[] outputPixels, int width, int height, int radius) {
int resultingColorPixel;
float iarr = 1f / (radius + radius);
for (int i = 0; i < height; i++) {
int outputIndex = i * width;
int li = outputIndex;
int sourceIndex = outputIndex + radius;
int fv = ((byte) sourcePixels[outputIndex]);
int lv = ((byte) sourcePixels[outputIndex + width - 1]);
float val = (radius) * fv;
for (int j = 0; j < radius; j++) {
val += ((byte) (sourcePixels[outputIndex + j]));
}
for (int j = 0; j < radius; j++) {
val += ((byte) sourcePixels[sourceIndex++]) - fv;
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex++] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8)
| (resultingColorPixel);
}
for (int j = (radius + 1); j < (width - radius); j++) {
val += ((byte) sourcePixels[sourceIndex++]) - ((byte) sourcePixels[li++]);
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex++] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8)
| (resultingColorPixel);
}
for (int j = (width - radius); j < width; j++) {
val += lv - ((byte) sourcePixels[li++]);
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex++] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8)
| (resultingColorPixel);
}
}
}
private static void BoxBlurVertical(int[] sourcePixels, int[] outputPixels, int width, int height, int radius) {
int resultingColorPixel;
float iarr = 1f / (radius + radius + 1);
for (int i = 0; i < width; i++) {
int outputIndex = i;
int li = outputIndex;
int sourceIndex = outputIndex + radius * width;
int fv = ((byte) sourcePixels[outputIndex]);
int lv = ((byte) sourcePixels[outputIndex + width * (height - 1)]);
float val = (radius + 1) * fv;
for (int j = 0; j < radius; j++) {
val += ((byte) sourcePixels[outputIndex + j * width]);
}
for (int j = 0; j <= radius; j++) {
val += ((byte) sourcePixels[sourceIndex]) - fv;
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8) | (resultingColorPixel);
sourceIndex += width;
outputIndex += width;
}
for (int j = radius + 1; j < (height - radius); j++) {
val += ((byte) sourcePixels[sourceIndex]) - ((byte) sourcePixels[li]);
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8) | (resultingColorPixel);
li += width;
sourceIndex += width;
outputIndex += width;
}
for (int j = (height - radius); j < height; j++) {
val += lv - ((byte) sourcePixels[li]);
resultingColorPixel = (((Integer) Math.round(val * iarr)).byteValue());
outputPixels[outputIndex] = (0xFF << 24) | (resultingColorPixel << 16) | (resultingColorPixel << 8) | (resultingColorPixel);
li += width;
outputIndex += width;
}
}
}
}
| apache-2.0 |
Qiang-Feng/Workout | app/src/main/java/com/qiang/workout/ProfileActivity.java | 6395 | package com.qiang.workout;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.qiang.workout.Interfaces.TimeSelectFragmentListener;
import com.qiang.workout.Models.Profile;
import com.qiang.workout.Utilities.DBHandler;
import com.qiang.workout.Utilities.TextTimeClickListener;
public class ProfileActivity extends AppCompatActivity implements TimeSelectFragmentListener
{
// Values for the actions add and edit
public static final int PROFILE_ADDED = 1;
public static final int PROFILE_EDITED = 2;
// Input area components
private EditText name;
private EditText repeatNumber;
private TextView textTimeMinutes;
private TextView textTimeSeconds;
private TextView timeError;
private CheckBox repeat;
// Database
private DBHandler dbHandler;
// Profile management
private Profile profile;
private boolean isEditingProfile = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Sets the activity_profile as this activity's display
setContentView(R.layout.activity_profile);
// Initialising components
// Input area components
name = (EditText) findViewById(R.id.profile_text_name);
repeatNumber = (EditText) findViewById(R.id.profile_text_repeat);
textTimeMinutes = (TextView) findViewById(R.id.profile_text_time_minutes);
textTimeSeconds = (TextView) findViewById(R.id.profile_text_time_seconds);
timeError = (TextView) findViewById(R.id.profile_text_time_error);
repeat = (CheckBox) findViewById(R.id.profile_checkbox_repeat);
// Database
dbHandler = new DBHandler(this, null, null, 1);
// Handles click events for textTimeMinutes and textTimeSeconds
textTimeMinutes.setOnClickListener(new TextTimeClickListener(true, this));
textTimeSeconds.setOnClickListener(new TextTimeClickListener(false, this));
if (getIntent().hasExtra("profileID"))
{
isEditingProfile = true;
// Changes activity's title to @string/title_edit_profile
setTitle(R.string.title_edit_profile);
// Creates new chosen profile object
profile = dbHandler.getProfile(getIntent().getIntExtra("profileID", 1));
// Sets input box values for profile loaded from database
name.setText(profile.getName());
setTextTime(textTimeMinutes, profile.getMinutes());
setTextTime(textTimeSeconds, profile.getSeconds());
repeat.setChecked(profile.isRepeat());
repeatNumber.setText(Integer.toString(profile.getRepeatNumber()));
}
else
{
// Changes activity's title to @string/title_new_profile
setTitle(R.string.title_new_profile);
}
}
private void setTextTime(TextView textTime, int timeChosen)
{
// Appends 0 in front of timeChosen if less than 10 before setting textTime
if (timeChosen < 10)
{
textTime.setText("0" + Integer.toString(timeChosen));
}
else
{
textTime.setText(Integer.toString(timeChosen));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handles item selection in action bar
if (item.getItemId() == R.id.action_save_profile)
{
/*
Performs validation of input data
*/
boolean isError = false;
if (name.getText().length() == 0)
{
isError = true;
name.setError("Name is required");
}
if (name.getText().toString().trim().length() > 50)
{
isError = true;
name.setError("Name can't be longer than 50 characters");
}
if (textTimeMinutes.getText().equals("00") && textTimeSeconds.getText().equals("00"))
{
isError = true;
timeError.setError("Time is required");
}
if (repeat.isChecked() && repeatNumber.getText().length() == 0)
{
isError = true;
repeatNumber.setError("Number of laps is required");
}
/*
Produces an error if:
- name of profile is taken and adding a new profile
- changed profile name is taken
*/
if (dbHandler.profileExists(name.getText().toString().trim()))
{
if (!isEditingProfile || !name.getText().toString().trim().equals(profile.getName()))
{
isError = true;
name.setError("Name already exists");
}
}
if (!isError)
{
// Either adds or edits the profile depending on what's needed
if (isEditingProfile)
{
setResult(PROFILE_EDITED);
updateProfile();
}
else
{
setResult(PROFILE_ADDED);
addProfile();
}
finish();
}
}
return super.onOptionsItemSelected(item);
}
private void addProfile()
{
// Creates a profile object with user's settings (to be inserted to the database)
Profile newProfile = new Profile(name.getText().toString().trim());
newProfile.setMinutes(Integer.parseInt(textTimeMinutes.getText().toString()));
newProfile.setSeconds(Integer.parseInt(textTimeSeconds.getText().toString()));
newProfile.setRepeat(repeat.isChecked());
// Only set user's repeatNumber if repeat is checked
newProfile.setRepeatNumber((repeat.isChecked()) ? Integer.parseInt(repeatNumber.getText().toString()) : 0);
dbHandler.addProfile(newProfile);
}
private void updateProfile()
{
// Updates profile object with user's settings
profile.setName(name.getText().toString().trim());
profile.setMinutes(Integer.parseInt(textTimeMinutes.getText().toString()));
profile.setSeconds(Integer.parseInt(textTimeSeconds.getText().toString()));
profile.setRepeat(repeat.isChecked());
// Only set user's repeatNumber if repeat is checked
profile.setRepeatNumber((repeat.isChecked()) ? Integer.parseInt(repeatNumber.getText().toString()) : 0);
dbHandler.saveEditedProfile(profile);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_profile, menu);
return true;
}
@Override
public void onFinishTimeSelectFragment(boolean isMinutes, int timeChosen)
{
// Removes time error if user has selected a non-zero value
if (timeChosen != 0)
{
timeError.setError(null);
}
// Determines whether minutes or seconds should be updated
if (isMinutes)
{
setTextTime(textTimeMinutes, timeChosen);
}
else
{
setTextTime(textTimeSeconds, timeChosen);
}
}
} | apache-2.0 |
alel890/Kerbrum | app/src/main/java/ar/com/kerbrum/kerbrum/fragment_paso2.java | 10363 | package ar.com.kerbrum.kerbrum;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Parcel;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
import ivb.com.materialstepper.stepperFragment;
import static android.widget.Toast.LENGTH_SHORT;
public class fragment_paso2 extends stepperFragment implements View.OnClickListener {
View v;
private EditText et_Remaining, et_PastillasConsumidas, et_Cajas, et_valorPeriodo;
Button btn_fechainicio;
Activity activity;
Spinner spin_duracionIngesta;
<<<<<<< HEAD
Medicamento med;
=======
String unidadPeriodoIngesta;
private Menu menu;
EditText et_nombreMed;
>>>>>>> origin/master
ToggleButton lunes, martes, miercoles, jueves, viernes, sabado, domingo;
TextView hora, dosis, tv_unidadPeriodo;
int count;
public fragment_paso2() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ===== action bar ======= */
android.support.v7.app.ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.mipmap.ic_launcherdrawer2);
setHasOptionsMenu(true);
LayoutInflater inflator = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflator.inflate(R.layout.actionbar_et, null);
actionBar.setCustomView(vi);
actionBar.show();
et_nombreMed = (EditText) vi.findViewById(R.id.et_actionbar);
/* ===== action bar ======= */
med = new Medicamento(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
med = bundle.getParcelable("Medicamento");
}
v = inflater.inflate(R.layout.fragment_paso2, container, false);
et_valorPeriodo = (EditText)v.findViewById(R.id.et_valor_periodo);
//et_valorPeriodo.setVisibility(View.INVISIBLE);
tv_unidadPeriodo = (TextView)v.findViewById(R.id.tv_unidad_periodo);
activity = getActivity();
//TODO poder seleccionar todos los días tipo con un checkbox
lunes = (ToggleButton) v.findViewById(R.id.lunes);
martes = (ToggleButton) v.findViewById(R.id.martes);
miercoles = (ToggleButton) v.findViewById(R.id.miercoles);
jueves = (ToggleButton) v.findViewById(R.id.jueves);
viernes = (ToggleButton) v.findViewById(R.id.viernes);
sabado = (ToggleButton) v.findViewById(R.id.sabado);
domingo = (ToggleButton) v.findViewById(R.id.domingo);
spin_duracionIngesta = (Spinner) v.findViewById(R.id.spin_duracion);
et_Remaining = (EditText) v.findViewById(R.id.etRemaining);
et_Remaining.setText("1");
et_PastillasConsumidas = (EditText) v.findViewById(R.id.etPastillasConsumidas);
et_Cajas = (EditText) v.findViewById(R.id.etCajas);
btn_fechainicio = (Button) v.findViewById(R.id.btn_setFechaInicio);
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Indefinido");
SpinnerArray.add("Días");
SpinnerArray.add("Meses");
SpinnerArray.add("Años");
//ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(), R.array.duracionIngesta, android.R.layout.simple_spinner_item);
//adapter2.setDropDownViewResource(android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, SpinnerArray);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin_duracionIngesta.setAdapter(adapter2);
et_Cajas.setText("2");
et_PastillasConsumidas.setText(med.getNombre());
CompoundButton.OnCheckedChangeListener touchListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String estado;
switch (buttonView.getId()) {
case R.id.lunes:
break;
case R.id.martes:
break;
case R.id.miercoles:
break;
case R.id.jueves:
break;
case R.id.viernes:
break;
case R.id.sabado:
break;
case R.id.domingo:
break;
}
}
};
lunes.setOnCheckedChangeListener(touchListener);
martes.setOnCheckedChangeListener(touchListener);
miercoles.setOnCheckedChangeListener(touchListener);
jueves.setOnCheckedChangeListener(touchListener);
miercoles.setOnCheckedChangeListener(touchListener);
jueves.setOnCheckedChangeListener(touchListener);
viernes.setOnCheckedChangeListener(touchListener);
sabado.setOnCheckedChangeListener(touchListener);
domingo.setOnCheckedChangeListener(touchListener);
spin_duracionIngesta.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String item = parent.getItemAtPosition(position).toString();
if(item != null) {
Toast t = Toast.makeText(getActivity(), "posicion: " + item, Toast.LENGTH_SHORT);
t.show();
}
if(position != 0){
et_valorPeriodo.setVisibility(View.VISIBLE);
}else{
et_valorPeriodo.setVisibility(View.GONE);
}
/*switch (position){
case 0:
et_valorPeriodo.setVisibility(View.INVISIBLE);
break;
case 1:
//et_valorPeriodo.setVisibility(View.VISIBLE);
break;
case 2:
//et_valorPeriodo.setVisibility(View.VISIBLE);
break;
case 3:
//et_valorPeriodo.setVisibility(View.VISIBLE);
break;
}*/
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
<<<<<<< HEAD
et_Remaining.setText( med.getNombre());
=======
}
});
>>>>>>> origin/master
return v;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu = menu;
getActivity().getMenuInflater().inflate(R.menu.ab_primeruso, menu);
super.getActivity().onCreateOptionsMenu(menu);
MenuItem itemEditNombreMed = menu.findItem(R.id.editNombreMed);
itemEditNombreMed.setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MenuItem itemcheck = menu.findItem(R.id.check);
MenuItem itemEditNombreMed = menu.findItem(R.id.editNombreMed);
View view = getActivity().getCurrentFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
switch (item.getItemId()) {
case R.id.check:
et_nombreMed.setImeOptions(EditorInfo.IME_ACTION_DONE);
if (view != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
itemcheck.setVisible(false);
itemEditNombreMed.setVisible(true);
et_nombreMed.setEnabled(false);
et_nombreMed.setFocusable(false);
//et_nombreMed.getText(); get nombre medicina
return true;
case R.id.editNombreMed:
et_nombreMed.setEnabled(true);
et_nombreMed.setFocusable(true);
et_nombreMed.setFocusableInTouchMode(true);
et_nombreMed.requestFocus();
imm.showSoftInput(et_nombreMed, InputMethodManager.SHOW_FORCED);
itemcheck.setVisible(true);
itemEditNombreMed.setVisible(false);
//et_nombreMed.getText(); get nombre medicina
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
@Override
public boolean onNextButtonHandler() {
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_setFechaInicio:
break;
}
}
}
| apache-2.0 |
aidanPB/aspect-logging | aspect-logging/src/main/java/com/github/aidanPB/aspects/logging/LoggedMember.java | 526 | package com.github.aidanPB.aspects.logging;
import java.lang.annotation.*;
/**
* A flag annotation indicating to this library's aspects that
* the annotated field, method, or constructor should be logged.
* @{@linkplain Logged} and @LoggedMember turn on
* basic, everyday logging that should be present even in production
* code.
* @author aidanPB
*/
@Target(value={ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggedMember {
}
| apache-2.0 |
yahoo/pulsar | pulsar-client/src/main/java/org/apache/pulsar/client/impl/UnAckedMessageTracker.java | 9193 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl;
import com.google.common.base.Preconditions;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class UnAckedMessageTracker implements Closeable {
private static final Logger log = LoggerFactory.getLogger(UnAckedMessageTracker.class);
protected final ConcurrentHashMap<MessageId, ConcurrentOpenHashSet<MessageId>> messageIdPartitionMap;
protected final ArrayDeque<ConcurrentOpenHashSet<MessageId>> timePartitions;
protected final Lock readLock;
protected final Lock writeLock;
public static final UnAckedMessageTrackerDisabled UNACKED_MESSAGE_TRACKER_DISABLED = new UnAckedMessageTrackerDisabled();
private final long ackTimeoutMillis;
private final long tickDurationInMs;
private static class UnAckedMessageTrackerDisabled extends UnAckedMessageTracker {
@Override
public void clear() {
}
@Override
long size() {
return 0;
}
@Override
public boolean add(MessageId m) {
return true;
}
@Override
public boolean remove(MessageId m) {
return true;
}
@Override
public int removeMessagesTill(MessageId msgId) {
return 0;
}
@Override
public void close() {
}
}
private Timeout timeout;
public UnAckedMessageTracker() {
readLock = null;
writeLock = null;
timePartitions = null;
messageIdPartitionMap = null;
this.ackTimeoutMillis = 0;
this.tickDurationInMs = 0;
}
public UnAckedMessageTracker(PulsarClientImpl client, ConsumerBase<?> consumerBase, long ackTimeoutMillis) {
this(client, consumerBase, ackTimeoutMillis, ackTimeoutMillis);
}
private static final FastThreadLocal<HashSet<MessageId>> TL_MESSAGE_IDS_SET = new FastThreadLocal<HashSet<MessageId>>() {
@Override
protected HashSet<MessageId> initialValue() throws Exception {
return new HashSet<>();
}
};
public UnAckedMessageTracker(PulsarClientImpl client, ConsumerBase<?> consumerBase, long ackTimeoutMillis, long tickDurationInMs) {
Preconditions.checkArgument(tickDurationInMs > 0 && ackTimeoutMillis >= tickDurationInMs);
this.ackTimeoutMillis = ackTimeoutMillis;
this.tickDurationInMs = tickDurationInMs;
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
this.readLock = readWriteLock.readLock();
this.writeLock = readWriteLock.writeLock();
this.messageIdPartitionMap = new ConcurrentHashMap<>();
this.timePartitions = new ArrayDeque<>();
int blankPartitions = (int)Math.ceil((double)this.ackTimeoutMillis / this.tickDurationInMs);
for (int i = 0; i < blankPartitions + 1; i++) {
timePartitions.add(new ConcurrentOpenHashSet<>(16, 1));
}
timeout = client.timer().newTimeout(new TimerTask() {
@Override
public void run(Timeout t) throws Exception {
Set<MessageId> messageIds = TL_MESSAGE_IDS_SET.get();
messageIds.clear();
writeLock.lock();
try {
ConcurrentOpenHashSet<MessageId> headPartition = timePartitions.removeFirst();
if (!headPartition.isEmpty()) {
log.warn("[{}] {} messages have timed-out", consumerBase, headPartition.size());
headPartition.forEach(messageId -> {
addChunkedMessageIdsAndRemoveFromSequnceMap(messageId, messageIds, consumerBase);
messageIds.add(messageId);
messageIdPartitionMap.remove(messageId);
});
}
headPartition.clear();
timePartitions.addLast(headPartition);
} finally {
try {
if (messageIds.size() > 0) {
consumerBase.onAckTimeoutSend(messageIds);
consumerBase.redeliverUnacknowledgedMessages(messageIds);
}
timeout = client.timer().newTimeout(this, tickDurationInMs, TimeUnit.MILLISECONDS);
} finally {
writeLock.unlock();
}
}
}
}, this.tickDurationInMs, TimeUnit.MILLISECONDS);
}
public static void addChunkedMessageIdsAndRemoveFromSequnceMap(MessageId messageId, Set<MessageId> messageIds,
ConsumerBase<?> consumerBase) {
if (messageId instanceof MessageIdImpl) {
MessageIdImpl[] chunkedMsgIds = consumerBase.unAckedChunkedMessageIdSequenceMap.get((MessageIdImpl) messageId);
if (chunkedMsgIds != null && chunkedMsgIds.length > 0) {
for (MessageIdImpl msgId : chunkedMsgIds) {
messageIds.add(msgId);
}
}
consumerBase.unAckedChunkedMessageIdSequenceMap.remove((MessageIdImpl) messageId);
}
}
public void clear() {
writeLock.lock();
try {
messageIdPartitionMap.clear();
timePartitions.forEach(tp -> tp.clear());
} finally {
writeLock.unlock();
}
}
public boolean add(MessageId messageId) {
writeLock.lock();
try {
ConcurrentOpenHashSet<MessageId> partition = timePartitions.peekLast();
ConcurrentOpenHashSet<MessageId> previousPartition = messageIdPartitionMap.putIfAbsent(messageId,
partition);
if (previousPartition == null) {
return partition.add(messageId);
} else {
return false;
}
} finally {
writeLock.unlock();
}
}
boolean isEmpty() {
readLock.lock();
try {
return messageIdPartitionMap.isEmpty();
} finally {
readLock.unlock();
}
}
public boolean remove(MessageId messageId) {
writeLock.lock();
try {
boolean removed = false;
ConcurrentOpenHashSet<MessageId> exist = messageIdPartitionMap.remove(messageId);
if (exist != null) {
removed = exist.remove(messageId);
}
return removed;
} finally {
writeLock.unlock();
}
}
long size() {
readLock.lock();
try {
return messageIdPartitionMap.size();
} finally {
readLock.unlock();
}
}
public int removeMessagesTill(MessageId msgId) {
writeLock.lock();
try {
int removed = 0;
Iterator<MessageId> iterator = messageIdPartitionMap.keySet().iterator();
while (iterator.hasNext()) {
MessageId messageId = iterator.next();
if (messageId.compareTo(msgId) <= 0) {
ConcurrentOpenHashSet<MessageId> exist = messageIdPartitionMap.get(messageId);
if (exist != null) {
exist.remove(messageId);
}
iterator.remove();
removed ++;
}
}
return removed;
} finally {
writeLock.unlock();
}
}
private void stop() {
writeLock.lock();
try {
if (timeout != null && !timeout.isCancelled()) {
timeout.cancel();
}
this.clear();
} finally {
writeLock.unlock();
}
}
@Override
public void close() {
stop();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/CreateAccessKeyResultStaxUnmarshaller.java | 2494 | /*
* 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.identitymanagement.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.identitymanagement.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* CreateAccessKeyResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateAccessKeyResultStaxUnmarshaller implements Unmarshaller<CreateAccessKeyResult, StaxUnmarshallerContext> {
public CreateAccessKeyResult unmarshall(StaxUnmarshallerContext context) throws Exception {
CreateAccessKeyResult createAccessKeyResult = new CreateAccessKeyResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return createAccessKeyResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("AccessKey", targetDepth)) {
createAccessKeyResult.setAccessKey(AccessKeyStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return createAccessKeyResult;
}
}
}
}
private static CreateAccessKeyResultStaxUnmarshaller instance;
public static CreateAccessKeyResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new CreateAccessKeyResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-compute/alpha/1.31.0/com/google/api/services/compute/model/InterconnectsGetMacsecConfigResponse.java | 2696 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Response for the InterconnectsGetMacsecConfigRequest.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class InterconnectsGetMacsecConfigResponse extends com.google.api.client.json.GenericJson {
/**
* end_interface: MixerGetResponseWithEtagBuilder
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String etag;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private InterconnectMacsecConfig result;
/**
* end_interface: MixerGetResponseWithEtagBuilder
* @return value or {@code null} for none
*/
public java.lang.String getEtag() {
return etag;
}
/**
* end_interface: MixerGetResponseWithEtagBuilder
* @param etag etag or {@code null} for none
*/
public InterconnectsGetMacsecConfigResponse setEtag(java.lang.String etag) {
this.etag = etag;
return this;
}
/**
* @return value or {@code null} for none
*/
public InterconnectMacsecConfig getResult() {
return result;
}
/**
* @param result result or {@code null} for none
*/
public InterconnectsGetMacsecConfigResponse setResult(InterconnectMacsecConfig result) {
this.result = result;
return this;
}
@Override
public InterconnectsGetMacsecConfigResponse set(String fieldName, Object value) {
return (InterconnectsGetMacsecConfigResponse) super.set(fieldName, value);
}
@Override
public InterconnectsGetMacsecConfigResponse clone() {
return (InterconnectsGetMacsecConfigResponse) super.clone();
}
}
| apache-2.0 |
VasAndr/trainings_pft | sandbox/src/main/java/ru/stqa/pft/sandbox/MyFirstProga.java | 474 | package ru.stqa.pft.sandbox;
public class MyFirstProga {
public static void main(String[] args) {
System.out.println("Hello World!");
Square s = new Square(5);
System.out.println("Площадь квадрата со стороной " + s.l + " = " +s.area());
Rectangle r = new Rectangle(4, 6);
System.out.println("Площадь прямоугольника со сторонами " + r.a + " и " + r.b + " = " +r.area());
}
} | apache-2.0 |
rhusar/radargun | core/src/main/java/org/radargun/stages/test/PerformanceCondition.java | 12397 | package org.radargun.stages.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.radargun.config.DefinitionElement;
import org.radargun.config.Init;
import org.radargun.config.Property;
import org.radargun.config.PropertyHelper;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.stats.OperationStats;
import org.radargun.stats.Statistics;
import org.radargun.stats.representation.DefaultOutcome;
import org.radargun.utils.NanoTimeConverter;
import org.radargun.utils.Projections;
import org.radargun.utils.ReflexiveConverters;
import org.radargun.utils.Utils;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class PerformanceCondition {
private static Log log = LogFactory.getLog(PerformanceCondition.class);
public abstract boolean evaluate(int threads, Statistics statistics);
private static class Predicate implements Projections.Condition<PerformanceCondition> {
private final int threads;
private final Statistics statistics;
public Predicate(int threads, Statistics statistics) {
this.threads = threads;
this.statistics = statistics;
}
@Override
public boolean accept(PerformanceCondition cond) {
return cond.evaluate(threads, statistics);
}
}
@DefinitionElement(name = "any", doc = "Any of inner conditions is true", resolveType = DefinitionElement.ResolveType.PASS_BY_DEFINITION)
protected static class Any extends PerformanceCondition {
@Property(name = "", doc = "Inner conditions", complexConverter = ListConverter.class)
public final List<PerformanceCondition> subs = new ArrayList<>();
@Override
public boolean evaluate(int threads, final Statistics statistics) {
return Projections.any(subs, new Predicate(threads, statistics));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("any [");
if (!subs.isEmpty()) sb.append(subs.get(0));
for (int i = 1; i < subs.size(); ++i) sb.append(", ").append(subs.get(i));
return sb.append("]").toString();
}
}
@DefinitionElement(name = "all", doc = "All inner conditions are true", resolveType = DefinitionElement.ResolveType.PASS_BY_DEFINITION)
protected static class All extends PerformanceCondition {
@Property(name = "", doc = "Inner conditions", complexConverter = ListConverter.class)
public final List<PerformanceCondition> subs = new ArrayList<>();
@Override
public boolean evaluate(int threads, final Statistics statistics) {
return Projections.all(subs, new Predicate(threads, statistics));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("all [");
if (!subs.isEmpty()) sb.append(subs.get(0));
for (int i = 1; i < subs.size(); ++i) sb.append(", ").append(subs.get(i));
return sb.append("]").toString();
}
}
protected static abstract class AbstractCondition extends PerformanceCondition {
@Property(doc = "Identifier of the operation (or its derivate) that should be tested.", optional = false)
protected String on;
@Override
public String toString() {
return this.getClass().getSimpleName() + PropertyHelper.toString(this);
}
}
@DefinitionElement(name = "mean", doc = "Checks value of the mean response time of given operation.")
protected static class Mean extends AbstractCondition {
@Property(doc = "Test if the mean response time is below specified value (use time unit!)", converter = NanoTimeConverter.class)
protected Long below;
@Property(doc = "Test if the mean response time is above specified value (use time unit!)", converter = NanoTimeConverter.class)
protected Long over;
@Init
public void init() {
if (below != null && over != null) throw new IllegalStateException("Cannot define both 'below' and 'over'!");
if (below == null && over == null) throw new IllegalStateException("Must define either 'below' or 'over'!");
}
@Override
public boolean evaluate(int threads, Statistics statistics) {
OperationStats stats = statistics.getOperationsStats().get(on);
if (stats == null) throw new IllegalStateException("No statistics for operation " + on);
DefaultOutcome outcome = stats.getRepresentation(DefaultOutcome.class);
if (outcome == null) throw new IllegalStateException("Cannot determine mean from " + stats);
log.info("Mean is " + Utils.prettyPrintTime((long) outcome.responseTimeMean, TimeUnit.NANOSECONDS) + PropertyHelper.toString(this));
if (below != null) return outcome.responseTimeMean < below;
if (over != null) return outcome.responseTimeMean > over;
throw new IllegalStateException();
}
}
@DefinitionElement(name = "throughput", doc = "Checks value of throughput of given operation.")
protected static class Throughput extends AbstractCondition {
@Property(doc = "Test if the actual throughput is below specified value (operations per second)")
protected Long below;
@Property(doc = "Test if the actual throughput is above specified value (operations per second)")
protected Long over;
@Init
public void init() {
if (below != null && over != null) throw new IllegalStateException("Cannot define both 'below' and 'over'!");
if (below == null && over == null) throw new IllegalStateException("Must define either 'below' or 'over'!");
}
@Override
public boolean evaluate(int threads, Statistics statistics) {
OperationStats stats = statistics.getOperationsStats().get(on);
if (stats == null) throw new IllegalStateException("No statistics for operation " + on);
org.radargun.stats.representation.OperationThroughput throughput = stats.getRepresentation(
org.radargun.stats.representation.OperationThroughput.class, threads,
TimeUnit.MILLISECONDS.toNanos(statistics.getEnd() - statistics.getBegin()));
if (throughput == null) throw new IllegalStateException("Cannot determine throughput from " + stats);
log.info("Throughput is " + throughput.actual + " ops/s " + PropertyHelper.toString(this));
if (below != null) return throughput.actual < below;
if (over != null) return throughput.actual > over;
throw new IllegalStateException();
}
}
@DefinitionElement(name = "requests", doc = "Checks number of executed operations.")
protected static class Requests extends AbstractCondition {
@Property(doc = "Test if the number of executed operations is below this value.")
protected Long below;
@Property(doc = "Test if the number of executed operations is above this value.")
protected Long over;
@Init
public void init() {
if (below != null && over != null) throw new IllegalStateException("Cannot define both 'below' and 'over'!");
if (below == null && over == null) throw new IllegalStateException("Must define either 'below' or 'over'!");
}
@Override
public boolean evaluate(int threads, Statistics statistics) {
OperationStats stats = statistics.getOperationsStats().get(on);
if (stats == null) throw new IllegalStateException("No statistics for operation " + on);
DefaultOutcome outcome = stats.getRepresentation(DefaultOutcome.class);
if (outcome == null) throw new IllegalStateException("Cannot determine request count from " + stats);
log.info("Executed " + outcome.requests + " reqs " + PropertyHelper.toString(this));
if (below != null) return outcome.requests < below;
if (over != null) return outcome.requests > over;
throw new IllegalStateException();
}
}
@DefinitionElement(name = "errors", doc = "Checks number of executed operations.")
protected static class Errors extends AbstractCondition {
@Property(doc = "Test if the percentage of errors (out of total number of requests) is below this value.")
protected Integer percentBelow;
@Property(doc = "Test if the percentage of errors (out of total number of requests) is above this value.")
protected Integer percentOver;
@Property(doc = "Test if the total number of errors is below this value.")
protected Long totalBelow;
@Property(doc = "Test if the total number of errors is above this value.")
protected Long totalOver;
@Init
public void init() {
int defs = 0;
if (totalBelow != null) defs++;
if (totalOver != null) defs++;
if (percentBelow != null) defs++;
if (percentOver != null) defs++;
if (defs != 1) throw new IllegalStateException("Must define exactly one of 'total-below', 'total-over', 'percent-below', 'percent-over'");
}
@Override
public boolean evaluate(int threads, Statistics statistics) {
OperationStats stats = statistics.getOperationsStats().get(on);
if (stats == null) throw new IllegalStateException("No statistics for operation " + on);
DefaultOutcome outcome = stats.getRepresentation(DefaultOutcome.class);
if (outcome == null) throw new IllegalStateException("Cannot determine error count from " + stats);
log.info("Encountered " + outcome.errors + " errors " + PropertyHelper.toString(this));
if (totalBelow != null) return outcome.errors < totalBelow;
if (totalOver != null) return outcome.errors > totalOver;
if (percentBelow != null) return outcome.errors * 100 < outcome.requests * percentBelow;
if (percentBelow != null) return outcome.errors * 100 > outcome.requests * percentOver;
throw new IllegalStateException();
}
}
@DefinitionElement(name = "percentile", doc = "Checks value of the response time of given operation " +
"at some percentile (0 = fastest operation, 100 = slowest operation).")
protected static class Percentile extends AbstractCondition {
@Property(doc = "Test if the response time is below specified value (use time unit!)", converter = NanoTimeConverter.class)
protected Long below;
@Property(doc = "Test if the response time is above specified value (use time unit!)", converter = NanoTimeConverter.class)
protected Long over;
@Property(doc = "Percentile used for the comparison: (0 = fastest operation, 100 = slowest operation)", optional = false)
protected double value;
@Init
public void init() {
if (below != null && over != null) throw new IllegalStateException("Cannot define both 'below' and 'over'!");
if (below == null && over == null) throw new IllegalStateException("Must define either 'below' or 'over'!");
}
@Override
public boolean evaluate(int threads, Statistics statistics) {
OperationStats stats = statistics.getOperationsStats().get(on);
if (stats == null) throw new IllegalStateException("No statistics for operation " + on);
org.radargun.stats.representation.Percentile percentile
= stats.getRepresentation(org.radargun.stats.representation.Percentile.class, value);
if (percentile == null) throw new IllegalStateException("Cannot determine percentile from " + stats);
log.info("Response time is " + Utils.prettyPrintTime((long) percentile.responseTimeMax, TimeUnit.NANOSECONDS) + PropertyHelper.toString(this));
if (below != null) return percentile.responseTimeMax < below;
if (over != null) return percentile.responseTimeMax > over;
throw new IllegalStateException();
}
}
public static class Converter extends ReflexiveConverters.ObjectConverter {
public Converter() {
super(new Class<?>[] { Any.class, All.class, Mean.class, Throughput.class, Requests.class, Errors.class, Percentile.class});
}
}
protected static class ListConverter extends ReflexiveConverters.ListConverter {
public ListConverter() {
super(new Class<?>[] { Any.class, All.class, Mean.class, Throughput.class, Requests.class, Errors.class, Percentile.class});
}
}
}
| apache-2.0 |
aaronbinns/jbs | src/java/org/archive/jbs/misc/PageRank.java | 12488 | /*
* Copyright 2011 Internet Archive
*
* 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.archive.jbs.misc;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
import org.apache.hadoop.mapred.lib.MultipleInputs;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.nutch.parse.ParseData;
import org.apache.nutch.parse.ParseText;
import org.apache.nutch.parse.Outlink;
import org.apache.nutch.metadata.Metadata;
import org.archive.jbs.util.*;
import org.archive.jbs.Document;
/**
* <p>
* Map/Reduce job to produce "page rank" information. In this case,
* we are merely counting the number of links <em>to</em> a URL that
* is in the collection.
* </p>
* <p>
* Since the URLs in an archival collection are keyed by a
* combination of URL and digest, yet the outlinks on a page only
* have a URL (no digest of the linked-to page), we apply links to a
* URL to all versions of that URL.
* </p>
* <p>
* This map/reduce job performs both tasks: counting the number of
* inlinks, and matching the URLs to the URL+hash keys of the pages
* in the collection. This means that an <em>entire</em> collection
* must be page-ranked as one job.
* </p>
* <p>
* The output is a Hadoop SequenceFile with a Text key and a
* JSON-encoded Document as the value. The Document has a
* property of "numInlinks" with corresponding value.
* </p>
*/
public class PageRank extends Configured implements Tool
{
public static final Log LOG = LogFactory.getLog(PageRank.class);
public static class Map extends MapReduceBase implements Mapper<Text, Writable, Text, GenericObject>
{
// For efficiency, create one instance of the output object '1'.
private static final GenericObject ONE = new GenericObject( new LongWritable( 1 ) );
private boolean ignoreInternalLinks = true;
private IDNHelper idnHelper;
/**
* Configure the job by obtaining local copy of relevant
* properties as well as building the IDNHelper which is used for
* getting the host/domain of a URL.
*/
public void configure( JobConf job )
{
this.ignoreInternalLinks = job.getBoolean( "pageranker.ignoreInternalLinks", true );
try
{
this.idnHelper = buildIDNHelper( job );
}
catch ( IOException ioe )
{
throw new RuntimeException( ioe );
}
}
/**
* Map the document's outlinks to inlinks for the URL being
* linked-to. Skip intra-domain links, or any that are malformed.
* Also emit the source URL with it's digest as the payload to the
* linked-to URLs can be joined with the list of captured URLs.
*/
public void map( Text key, Writable value, OutputCollector<Text, GenericObject> output, Reporter reporter)
throws IOException
{
String[] keyParts = key.toString().split("\\s+");
// Maformed key, should be "url digest". Skip it.
if ( keyParts.length != 2 ) return;
String fromUrl = keyParts[0];
String fromDigest = keyParts[1];
String fromHost = getHost( fromUrl );
// If there is no fromHost, skip it.
if ( fromHost == null || fromHost.length() == 0 ) return;
// Emit the source URL with it's digest as the payload.
output.collect( new Text( fromUrl ), new GenericObject( new Text( fromDigest ) ) );
// Now, get the outlinks and emit records for them.
Set<String> uniqueOutlinks = null;
if ( value instanceof ParseData )
{
uniqueOutlinks = getOutlinks( (ParseData) value );
}
else if ( value instanceof Text )
{
uniqueOutlinks = getOutlinks( new Document( ((Text) value).toString() ) );
}
else
{
// Hrmm...what type could it be...
return ;
}
// If no outlinks, skip the rest.
if ( uniqueOutlinks.size() == 0 ) return ;
Text inlink = new Text( );
for ( String outlink : uniqueOutlinks )
{
// FIXME: Use a Heritrix UURI to do minimal canonicalization
// of the toUrl. This way, it will match the URL if
// we actually crawled it.
String toUrl = outlink;
String toHost = getHost( toUrl );
// If the toHost is null, then there was a serious problem
// with the URL, so we just skip it.
if ( toHost == null ) continue;
// But if the toHost is empty, then assume the URL is a
// relative URL within the fromHost's site.
if ( toHost.length() == 0 ) toHost = fromHost;
// If we are ignoring intra-site links, then skip it.
if ( ignoreInternalLinks && fromHost.equals( toHost ) ) continue ;
inlink.set( toUrl );
output.collect( inlink, ONE );
}
}
/**
* Utility to return the host/domain of a URL, null if URL is
* malformed.
*/
public String getHost( String url )
{
try
{
return idnHelper.getDomain( new URL(url) );
}
catch ( Exception e )
{
return null;
}
}
/**
* Utility to return a set of the unique outlinks in a Nutch(WAX) ParseData object.
*/
public Set<String> getOutlinks( ParseData parsedata )
{
Outlink[] outlinks = parsedata.getOutlinks();
if ( outlinks.length == 0 ) return Collections.emptySet();
Set<String> uniqueOutlinks = new HashSet<String>( outlinks.length );
for ( Outlink outlink : outlinks )
{
uniqueOutlinks.add( outlink.getToUrl().trim() );
}
return uniqueOutlinks;
}
/**
* Utility to return a set of the unique outlinks in a JBs Document
*/
public Set<String> getOutlinks( Document document )
{
Set<String> uniqueOutlinks = new HashSet<String>( 16 );
for ( Document.Link link : document.getLinks( ) )
{
uniqueOutlinks.add( link.getUrl( ) );
}
return uniqueOutlinks;
}
}
public static class Reduce extends MapReduceBase implements Reducer<Text, GenericObject, Text, Text>
{
// For efficiency, only create one instance of the outputKey and outputValue
private Text outputKey = new Text();
private Text outputValue = new Text();
/**
*
*/
public void reduce( Text key, Iterator<GenericObject> values, OutputCollector<Text, Text> output, Reporter reporter)
throws IOException
{
long sum = 0;
Set<String> digests = new HashSet<String>( );
while ( values.hasNext( ) )
{
Writable value = values.next( ).get( );
if ( value instanceof Text )
{
String newDigest = ((Text) value).toString();
digests.add( newDigest );
}
else if ( value instanceof LongWritable )
{
LongWritable count = (LongWritable) value;
sum += count.get( );
}
else
{
// Hrmm...should only be one of the previous two.
LOG.warn( "reduce: unknown value type: " + value );
continue ;
}
}
// Ok, now we have:
// key : the url
// digests : all the digests for that url
// sum : num of inlinks to that url
//
// Emit all "url digest" combos, with the sum total of the
// inlinks. If there is no digest, then we don't emit a record.
// This is good because if there is no digest, then we do not
// have any captures for that URL -- i.e. we never crawled it.
// If no inlinks, do not bother emitting an output value.
if ( sum == 0 ) return ;
// Hand code a trivial JSON string to hold the property.
outputValue.set( "{\"numInlinks\":\"" + Long.toString(sum) + "\"}" );
for ( String digest : digests )
{
outputKey.set( key + " " + digest );
output.collect( outputKey, outputValue );
}
}
}
public static class GenericObject extends GenericWritable
{
private static Class[] CLASSES = {
Text .class,
LongWritable.class,
};
public GenericObject( )
{
super();
}
public GenericObject( Writable w )
{
super();
super.set( w );
}
protected Class[] getTypes()
{
return CLASSES;
}
}
public static IDNHelper buildIDNHelper( JobConf job )
throws IOException
{
IDNHelper helper = new IDNHelper( );
if ( job.getBoolean( "jbs.idnHelper.useDefaults", true ) )
{
InputStream is = PageRank.class.getClassLoader( ).getResourceAsStream( "effective_tld_names.dat" );
if ( is == null )
{
throw new RuntimeException( "Cannot load default tld rules: effective_tld_names.dat" );
}
Reader reader = new InputStreamReader( is, "utf-8" );
helper.addRules( reader );
}
String moreRules = job.get( "jbs.idnHelper.moreRules", "" );
if ( moreRules.length() > 0 )
{
helper.addRules( new StringReader( moreRules ) );
}
return helper;
}
public static void main(String[] args) throws Exception
{
int result = ToolRunner.run( new JobConf(PageRank.class), new PageRank(), args );
System.exit( result );
}
public int run( String[] args ) throws Exception
{
if (args.length < 2)
{
System.err.println( "PageRank <output> <input>..." );
return 1;
}
JobConf conf = new JobConf( getConf(), PageRank.class);
conf.setJobName("jbs.PageRank");
// No need to set this since we use the MultipleInputs class
// below, which allows us to specify a mapper for each input.
// conf.setMapperClass(Map.class);
conf.setReducerClass(Reduce.class);
conf.setMapOutputKeyClass(Text.class);
conf.setMapOutputValueClass(GenericObject.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setOutputFormat(SequenceFileOutputFormat.class);
// The input paths should be either NutchWAX segment directories
// or Hadoop SequenceFiles containing JSON-encoded Documents
for ( int i = 1; i < args.length ; i++ )
{
Path p = new Path( args[i] );
// Expand any file globs and then check each matching path
FileStatus[] files = FileSystem.get( conf ).globStatus( p );
for ( FileStatus file : files )
{
if ( file.isDir( ) )
{
// If it's a directory, then check if it is a Nutch segment, otherwise treat as a SequenceFile.
Path nwp = new Path( file.getPath( ), "parse_data" );
if ( p.getFileSystem( conf ).exists( nwp ) )
{
LOG.info( "Adding input path: " + nwp );
MultipleInputs.addInputPath( conf, nwp, SequenceFileInputFormat.class, Map.class );
}
else
{
LOG.info( "Adding input path: " + file.getPath() );
MultipleInputs.addInputPath( conf, file.getPath(), SequenceFileInputFormat.class, Map.class );
}
}
else
{
// Not a directory, skip it.
LOG.warn( "Not a directory, skip input: " + file.getPath( ) );
}
}
}
FileOutputFormat.setOutputPath(conf, new Path(args[0]));
RunningJob rj = JobClient.runJob( conf );
return rj.isSuccessful( ) ? 0 : 1;
}
}
| apache-2.0 |
simplelifetian/GomeOnline | jrj-TouGu/src/com/gome/haoyuangong/net/result/tougu/PraiseResultBean.java | 457 | package com.gome.haoyuangong.net.result.tougu;
import com.gome.haoyuangong.net.result.BaseResultWeb;
public class PraiseResultBean extends BaseResultWeb {
private Data data = new Data();
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data{
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
}
| apache-2.0 |
lodgvideon/HP-ALM-Connector | src/main/java/org/lodgvideon/hpalm/infrastructure/Response.java | 2959 | /*
* Copyright (C) 2015 Hamburg Sud and the contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lodgvideon.hpalm.infrastructure;
import java.util.Map;
/**
* This is a naive implementation of an HTTP response. We use it to simplify matters in the examples. It is nothing more than a
* container of the response headers and the response body.
*/
public class Response {
private Map<String, ? extends Iterable<String>> responseHeaders = null;
private byte[] responseData = null;
private Exception failure = null;
private int statusCode = 0;
public Response(Map<String, Iterable<String>> responseHeaders, byte[] responseData, Exception failure, int statusCode) {
super();
this.responseHeaders = responseHeaders;
this.responseData = responseData;
this.failure = failure;
this.statusCode = statusCode;
}
public Response() {
}
/**
* @return the responseHeaders
*/
public Map<String, ? extends Iterable<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* @param responseHeaders the responseHeaders to set
*/
public void setResponseHeaders(Map<String, ? extends Iterable<String>> responseHeaders) {
this.responseHeaders = responseHeaders;
}
/**
* @return the responseData
*/
public byte[] getResponseData() {
return responseData;
}
/**
* @param responseData the responseData to set
*/
public void setResponseData(byte[] responseData) {
this.responseData = responseData;
}
/**
* @return the failure if the access to the requested URL failed, such as a 404 or 500. If no such failure occured this method
* returns null.
*/
public Exception getFailure() {
return failure;
}
/**
* @param failure the failure to set
*/
public void setFailure(Exception failure) {
this.failure = failure;
}
/**
* @return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* @param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* @see Object#toString() return the contents of the byte[] data as a string.
*/
@Override
public String toString() {
return new String(this.responseData);
}
} | apache-2.0 |
rome753/ActivityTaskView | activitytaskview/src/main/java/cc/rome753/activitytask/view/ATextView.java | 2470 | package cc.rome753.activitytask.view;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
import java.util.Observable;
import java.util.Observer;
import cc.rome753.activitytask.model.LifecycleInfo;
/**
* change text color when update
* Created by rome753@163.com on 2017/4/3.
*/
public class ATextView extends AppCompatTextView implements Observer {
private static AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(8, true);
public ATextView(Context context) {
this(context, null);
}
public ATextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ATextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setMaxLines(1);
setTextSize(10);
}
public void setInfoText(String s, String lifecycle) {
String hash = s.substring(s.indexOf("@"));
setTag(hash);
s = s.replace("Activity", "A…");
s = s.replace("Fragment", "F…");
s = s.replace(hash, " ");
addLifecycle(s, lifecycle);
}
private void addLifecycle(String s, String lifecycle) {
lifecycle = lifecycle.replace("onFragment", "");
lifecycle = lifecycle.replace("onActivity", "");
lifecycle = lifecycle.replace("SaveInstanceState", "SIS");
setTextColor(lifecycle.contains("Resume") ? Color.YELLOW : Color.WHITE);
SpannableString span = new SpannableString(s + lifecycle);
span.setSpan(absoluteSizeSpan, s.length(), span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(span);
}
@Override
public void update(Observable o, Object arg) {
if(getTag() == null) {
return;
}
if(arg instanceof LifecycleInfo) {
LifecycleInfo info = (LifecycleInfo) arg;
String s = info.fragments != null ? info.fragments.get(0) : info.activity;
String hash = s.substring(s.indexOf("@"));
if(TextUtils.equals((CharSequence) getTag(), hash)) {
s = getText().toString();
s = s.substring(0, s.lastIndexOf(" ") + 1);
addLifecycle(s, info.lifecycle);
}
}
}
}
| apache-2.0 |
afs/quack | src/test/java/org/apache/jena/engine/AbstractTestOpExecutor.java | 4457 | /**
* 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.jena.engine;
import java.io.PrintStream ;
import org.apache.jena.atlas.junit.BaseTest ;
import org.apache.jena.riot.RDFDataMgr ;
import org.junit.Test ;
import com.hp.hpl.jena.query.* ;
import com.hp.hpl.jena.sparql.engine.main.OpExecutorFactory ;
import com.hp.hpl.jena.sparql.engine.main.QC ;
import com.hp.hpl.jena.sparql.resultset.ResultSetCompare ;
/** Tests of OpExecutor */
public abstract class AbstractTestOpExecutor extends BaseTest
{
private static final String DIR = "testing/Engines" ;
protected final OpExecutorFactory factory ;
private String name ;
public AbstractTestOpExecutor(String name, OpExecutorFactory factory) {
this.name = name ;
this.factory = factory ;
}
protected abstract Dataset createDataset() ;
// XXX Need more tests
// This first group of tests do not lead multiple matches per
// same predicate in results nor match same-variable.
//
@Test public void engine_triples_01() { test("query-triples-1.rq", "data-2.ttl", factory) ; }
@Test public void engine_triples_02() { test("query-triples-2.rq", "data-2.ttl", factory) ; }
@Test public void engine_triples_03() { test("query-triples-3.rq", "data-2.ttl", factory) ; }
@Test public void engine_quads_01() { test("query-quads-1.rq", "data-1.trig", factory) ; }
@Test public void engine_quads_02() { test("query-quads-2.rq", "data-1.trig", factory) ; }
@Test public void engine_quads_03() { test("query-quads-3.rq", "data-1.trig", factory) ; }
@Test public void engine_quads_04() { test("query-quads-4.rq", "data-1.trig", factory) ; }
@Test public void engine_quads_filter_01() { test("query-quads-filter-1.rq", "data-1.trig", factory) ; }
@Test public void engine_quads_filter_02() { test("query-quads-filter-2.rq", "data-1.trig", factory) ; }
// Tests of more complicate BGP and variable patterns
@Test public void engine_bgp_01() { test("query-bgp-4.rq", "data-2.ttl", factory) ; }
@Test public void engine_bgp_02() { test("query-bgp-5.rq", "data-2.ttl", factory) ; }
@Test public void engine_bgp_03() { test("query-bgp-6.rq", "data-2.ttl", factory) ; }
// Use of ?s in the object position!
private void test(String queryFile, String datafile, OpExecutorFactory factory) {
queryFile = DIR+"/"+queryFile ;
datafile = DIR+"/"+datafile ;
Query query = QueryFactory.read(queryFile) ;
Dataset ds = RDFDataMgr.loadDataset(datafile) ;
// Default. Generated expected results.
QueryExecution qExec1 = QueryExecutionFactory.create(query, ds) ;
ResultSetRewindable rs1 = ResultSetFactory.makeRewindable(qExec1.execSelect()) ;
// Test
ds = createDataset() ;
RDFDataMgr.read(ds, datafile) ;
// Test
if ( factory != null )
QC.setFactory(ds.getContext(), factory) ;
QueryExecution qExec = QueryExecutionFactory.create(query, ds) ;
ResultSetRewindable rs = ResultSetFactory.makeRewindable(qExec.execSelect()) ;
boolean b = ResultSetCompare.equalsByTerm(rs1, rs) ;
if ( ! b ) {
PrintStream out = System.out ;
out.println("---- Test : "+name) ;
out.println("-- Expected") ;
rs1.reset();
ResultSetFormatter.out(out, rs1, query) ;
out.println("-- Actual") ;
rs.reset();
ResultSetFormatter.out(out, rs, query) ;
fail(name+" : Results not equal") ;
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-comprehendmedical/src/main/java/com/amazonaws/services/comprehendmedical/model/transform/StartRxNormInferenceJobRequestProtocolMarshaller.java | 2846 | /*
* 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.comprehendmedical.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.comprehendmedical.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* StartRxNormInferenceJobRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StartRxNormInferenceJobRequestProtocolMarshaller implements Marshaller<Request<StartRxNormInferenceJobRequest>, StartRxNormInferenceJobRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("ComprehendMedical_20181030.StartRxNormInferenceJob").serviceName("AWSComprehendMedical").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public StartRxNormInferenceJobRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<StartRxNormInferenceJobRequest> marshall(StartRxNormInferenceJobRequest startRxNormInferenceJobRequest) {
if (startRxNormInferenceJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<StartRxNormInferenceJobRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, startRxNormInferenceJobRequest);
protocolMarshaller.startMarshalling();
StartRxNormInferenceJobRequestMarshaller.getInstance().marshall(startRxNormInferenceJobRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
spoon-bot/RxJava | src/test/java/io/reactivex/internal/operators/nbp/NbpOperatorAsObservableTest.java | 2095 | /**
* Copyright 2015 Netflix, 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 io.reactivex.internal.operators.nbp;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import org.junit.Test;
import io.reactivex.*;
import io.reactivex.NbpObservable.NbpSubscriber;
import io.reactivex.exceptions.TestException;
import io.reactivex.subjects.nbp.NbpPublishSubject;
public class NbpOperatorAsObservableTest {
@Test
public void testHiding() {
NbpPublishSubject<Integer> src = NbpPublishSubject.create();
NbpObservable<Integer> dst = src.asObservable();
assertFalse(dst instanceof NbpPublishSubject);
NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();
dst.subscribe(o);
src.onNext(1);
src.onComplete();
verify(o).onNext(1);
verify(o).onComplete();
verify(o, never()).onError(any(Throwable.class));
}
@Test
public void testHidingError() {
NbpPublishSubject<Integer> src = NbpPublishSubject.create();
NbpObservable<Integer> dst = src.asObservable();
assertFalse(dst instanceof NbpPublishSubject);
NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();
dst.subscribe(o);
src.onError(new TestException());
verify(o, never()).onNext(any());
verify(o, never()).onComplete();
verify(o).onError(any(TestException.class));
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/UpdateSamplingRuleRequest.java | 3778 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.xray.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/xray-2016-04-12/UpdateSamplingRule" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateSamplingRuleRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The rule and fields to change.
* </p>
*/
private SamplingRuleUpdate samplingRuleUpdate;
/**
* <p>
* The rule and fields to change.
* </p>
*
* @param samplingRuleUpdate
* The rule and fields to change.
*/
public void setSamplingRuleUpdate(SamplingRuleUpdate samplingRuleUpdate) {
this.samplingRuleUpdate = samplingRuleUpdate;
}
/**
* <p>
* The rule and fields to change.
* </p>
*
* @return The rule and fields to change.
*/
public SamplingRuleUpdate getSamplingRuleUpdate() {
return this.samplingRuleUpdate;
}
/**
* <p>
* The rule and fields to change.
* </p>
*
* @param samplingRuleUpdate
* The rule and fields to change.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateSamplingRuleRequest withSamplingRuleUpdate(SamplingRuleUpdate samplingRuleUpdate) {
setSamplingRuleUpdate(samplingRuleUpdate);
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 (getSamplingRuleUpdate() != null)
sb.append("SamplingRuleUpdate: ").append(getSamplingRuleUpdate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateSamplingRuleRequest == false)
return false;
UpdateSamplingRuleRequest other = (UpdateSamplingRuleRequest) obj;
if (other.getSamplingRuleUpdate() == null ^ this.getSamplingRuleUpdate() == null)
return false;
if (other.getSamplingRuleUpdate() != null && other.getSamplingRuleUpdate().equals(this.getSamplingRuleUpdate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSamplingRuleUpdate() == null) ? 0 : getSamplingRuleUpdate().hashCode());
return hashCode;
}
@Override
public UpdateSamplingRuleRequest clone() {
return (UpdateSamplingRuleRequest) super.clone();
}
}
| apache-2.0 |
wgou/EasyJ | EasyJ/src/org/easyj/framework/util/SQL.java | 1222 | package org.easyj.framework.util;
import java.io.Serializable;
import java.util.List;
public class SQL {
private String sql;//Æ´½ÓÖ®ºó´ø£¿µÄsql
private List<String> cloumnName; //ÁÐÃû¼¯ºÏ
private List<Object> paramsValue;//²ÎÊý¼¯ºÏ
private String tableName;//±íÃû
private Serializable primaryKeyValue;//Ö÷¼üÁÐÖµ
private String primaryKey;//Ö÷¼ü
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public List<String> getCloumnName() {
return cloumnName;
}
public void setCloumnName(List<String> cloumnName) {
this.cloumnName = cloumnName;
}
public List<Object> getParamsValue() {
return paramsValue;
}
public void setParamsValue(List<Object> paramsValue) {
this.paramsValue = paramsValue;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public Serializable getPrimaryKeyValue() {
return primaryKeyValue;
}
public void setPrimaryKeyValue(Serializable primaryKeyValue) {
this.primaryKeyValue = primaryKeyValue;
}
public String getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(String primaryKey) {
this.primaryKey = primaryKey;
}
}
| apache-2.0 |
googleapis/java-websecurityscanner | proto-google-cloud-websecurityscanner-v1beta/src/main/java/com/google/cloud/websecurityscanner/v1beta/CrawledUrlOrBuilder.java | 2310 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1beta/crawled_url.proto
package com.google.cloud.websecurityscanner.v1beta;
public interface CrawledUrlOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.websecurityscanner.v1beta.CrawledUrl)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The http method of the request that was used to visit the URL, in
* uppercase.
* </pre>
*
* <code>string http_method = 1;</code>
*
* @return The httpMethod.
*/
java.lang.String getHttpMethod();
/**
*
*
* <pre>
* The http method of the request that was used to visit the URL, in
* uppercase.
* </pre>
*
* <code>string http_method = 1;</code>
*
* @return The bytes for httpMethod.
*/
com.google.protobuf.ByteString getHttpMethodBytes();
/**
*
*
* <pre>
* The URL that was crawled.
* </pre>
*
* <code>string url = 2;</code>
*
* @return The url.
*/
java.lang.String getUrl();
/**
*
*
* <pre>
* The URL that was crawled.
* </pre>
*
* <code>string url = 2;</code>
*
* @return The bytes for url.
*/
com.google.protobuf.ByteString getUrlBytes();
/**
*
*
* <pre>
* The body of the request that was used to visit the URL.
* </pre>
*
* <code>string body = 3;</code>
*
* @return The body.
*/
java.lang.String getBody();
/**
*
*
* <pre>
* The body of the request that was used to visit the URL.
* </pre>
*
* <code>string body = 3;</code>
*
* @return The bytes for body.
*/
com.google.protobuf.ByteString getBodyBytes();
}
| apache-2.0 |
vaclav/CalculatorJS | languages/CalculatorJS/source_gen/CalculatorJS/editor/InputFieldReference_SubstituteMenu.java | 4666 | package CalculatorJS.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.menus.substitute.SubstituteMenuBase;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import jetbrains.mps.lang.editor.menus.MenuPart;
import jetbrains.mps.openapi.editor.menus.substitute.SubstituteMenuItem;
import jetbrains.mps.openapi.editor.menus.substitute.SubstituteMenuContext;
import java.util.ArrayList;
import jetbrains.mps.lang.editor.menus.substitute.ConstraintsFilteringSubstituteMenuPartDecorator;
import jetbrains.mps.lang.editor.menus.EditorMenuDescriptorBase;
import jetbrains.mps.smodel.SNodePointer;
import jetbrains.mps.lang.editor.menus.substitute.ReferenceScopeSubstituteMenuPart;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import jetbrains.mps.lang.editor.menus.ConceptMenusPart;
import java.util.Collection;
import jetbrains.mps.smodel.ConceptDescendantsCache;
import jetbrains.mps.lang.editor.menus.substitute.DefaultSubstituteMenuLookup;
import jetbrains.mps.smodel.language.LanguageRegistry;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SReferenceLink;
public class InputFieldReference_SubstituteMenu extends SubstituteMenuBase {
@NotNull
@Override
protected List<MenuPart<SubstituteMenuItem, SubstituteMenuContext>> getParts(final SubstituteMenuContext _context) {
List<MenuPart<SubstituteMenuItem, SubstituteMenuContext>> result = new ArrayList<MenuPart<SubstituteMenuItem, SubstituteMenuContext>>();
result.add(new ConstraintsFilteringSubstituteMenuPartDecorator(new SMP_ReferenceScope_i4w2se_a(), CONCEPTS.InputFieldReference$6Z));
result.add(new SMP_Subconcepts_i4w2se_b());
return result;
}
@NotNull
@Override
public List<SubstituteMenuItem> createMenuItems(@NotNull SubstituteMenuContext context) {
context.getEditorMenuTrace().pushTraceInfo();
context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase("default substitute menu for InputFieldReference. Generated from implicit smart reference attribute.", new SNodePointer("r:777db787-7bec-48b0-b73b-6edaca65b33b(CalculatorJS.structure)", "5843916997827694720")));
try {
return super.createMenuItems(context);
} finally {
context.getEditorMenuTrace().popTraceInfo();
}
}
public class SMP_ReferenceScope_i4w2se_a extends ReferenceScopeSubstituteMenuPart {
public SMP_ReferenceScope_i4w2se_a() {
// that cast is needed for prevent the users from https://youtrack.jetbrains.com/issue/MPS-29051
super((SAbstractConcept) CONCEPTS.InputFieldReference$6Z, LINKS.target$Lmf$);
}
@NotNull
@Override
public List<SubstituteMenuItem> createItems(SubstituteMenuContext context) {
context.getEditorMenuTrace().pushTraceInfo();
context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase("reference scope substitute menu part", null));
try {
return super.createItems(context);
} finally {
context.getEditorMenuTrace().popTraceInfo();
}
}
}
public class SMP_Subconcepts_i4w2se_b extends ConceptMenusPart<SubstituteMenuItem, SubstituteMenuContext> {
protected Collection getConcepts(final SubstituteMenuContext _context) {
return ConceptDescendantsCache.getInstance().getDirectDescendants(CONCEPTS.InputFieldReference$6Z);
}
@NotNull
@Override
public List<SubstituteMenuItem> createItems(SubstituteMenuContext context) {
context.getEditorMenuTrace().pushTraceInfo();
context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase("include menus for all the direct subconcepts of " + "InputFieldReference", null));
try {
return super.createItems(context);
} finally {
context.getEditorMenuTrace().popTraceInfo();
}
}
@Override
protected Collection<SubstituteMenuItem> createItemsForConcept(SubstituteMenuContext context, SAbstractConcept concept) {
return context.createItems(new DefaultSubstituteMenuLookup(LanguageRegistry.getInstance(context.getEditorContext().getRepository()), concept));
}
}
private static final class CONCEPTS {
/*package*/ static final SConcept InputFieldReference$6Z = MetaAdapterFactory.getConcept(0x73f4da510e3e448cL, 0xa68b428ef5388ac7L, 0x5119c38c10631080L, "CalculatorJS.structure.InputFieldReference");
}
private static final class LINKS {
/*package*/ static final SReferenceLink target$Lmf$ = MetaAdapterFactory.getReferenceLink(0x73f4da510e3e448cL, 0xa68b428ef5388ac7L, 0x5119c38c10631080L, 0x5119c38c10631081L, "target");
}
}
| apache-2.0 |
LAB-SI/RooWifi-Controller | src/test/java/labsi/roowificontroller/ExampleUnitTest.java | 417 | package labsi.roowificontroller;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
ONLYOFFICE/document-server-integration | web/documentserver-example/java-spring/src/main/java/com/onlyoffice/integration/documentserver/models/configurations/Embedded.java | 1576 | /**
*
* (c) Copyright Ascensio System SIA 2021
*
* 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.onlyoffice.integration.documentserver.models.configurations;
import com.onlyoffice.integration.documentserver.models.enums.ToolbarDocked;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
@Getter
@Setter
public class Embedded { // the parameters which allow to change the settings which define the behavior of the buttons in the embedded mode
private String embedUrl; // the absolute URL to the document serving as a source file for the document embedded into the web page
private String saveUrl; // the absolute URL that will allow the document to be saved onto the user personal computer
private String shareUrl; // the absolute URL that will allow other users to share this document
private ToolbarDocked toolbarDocked; // the place for the embedded viewer toolbar, can be either top or bottom
}
| apache-2.0 |
candrews/spring-boot | spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMapping.java | 3805 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.cloudfoundry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.mvc.AbstractEndpointHandlerMapping;
import org.springframework.boot.actuate.endpoint.mvc.HalJsonMvcEndpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
import org.springframework.boot.actuate.endpoint.mvc.NamedMvcEndpoint;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* {@link HandlerMapping} to map {@link Endpoint}s to Cloud Foundry specific URLs.
*
* @author Madhura Bhave
*/
class CloudFoundryEndpointHandlerMapping
extends AbstractEndpointHandlerMapping<NamedMvcEndpoint> {
CloudFoundryEndpointHandlerMapping(Collection<? extends NamedMvcEndpoint> endpoints) {
super(endpoints);
}
CloudFoundryEndpointHandlerMapping(Set<NamedMvcEndpoint> endpoints,
CorsConfiguration corsConfiguration) {
super(endpoints, corsConfiguration);
}
@Override
protected void postProcessEndpoints(Set<NamedMvcEndpoint> endpoints) {
super.postProcessEndpoints(endpoints);
Iterator<NamedMvcEndpoint> iterator = endpoints.iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof HalJsonMvcEndpoint) {
iterator.remove();
}
}
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
detectHandlerMethods(new CloudFoundryDiscoveryMvcEndpoint(getEndpoints()));
}
@Override
protected String getPath(MvcEndpoint endpoint) {
if (endpoint instanceof NamedMvcEndpoint) {
return "/" + ((NamedMvcEndpoint) endpoint).getName();
}
return super.getPath(endpoint);
}
@Override
protected HandlerExecutionChain getHandlerExecutionChain(Object handler,
HttpServletRequest request) {
HandlerExecutionChain chain = super.getHandlerExecutionChain(handler, request);
HandlerInterceptor[] interceptors = addSecurityInterceptor(
chain.getInterceptors());
return new HandlerExecutionChain(chain.getHandler(), interceptors);
}
private HandlerInterceptor[] addSecurityInterceptor(HandlerInterceptor[] existing) {
List<HandlerInterceptor> interceptors = new ArrayList<HandlerInterceptor>();
interceptors.add(new SecurityInterceptor());
if (existing != null) {
interceptors.addAll(Arrays.asList(existing));
}
return interceptors.toArray(new HandlerInterceptor[interceptors.size()]);
}
/**
* Security interceptor to check cloud foundry token.
*/
static class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// Currently open
return true;
}
}
}
| apache-2.0 |
REBOOTERS/My-MVP | RxJava2-Retorfit2/src/test/java/home/smart/fly/http/ExampleUnitTest.java | 380 | package home.smart.fly.http;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
SH4DY/tripitude | backend/src/main/java/ac/tuwien/ase08/tripitude/service/interfaces/IDiaryService.java | 427 | package ac.tuwien.ase08.tripitude.service.interfaces;
import java.util.List;
import ac.tuwien.ase08.tripitude.entity.Diary;
import ac.tuwien.ase08.tripitude.entity.User;
public interface IDiaryService extends IGenericService<Diary, Long> {
public List<Diary> findByUser(User user);
public Diary findFull(Long key);
public String getAccessHash(Long key);
public Boolean verifyAccessHash(Long key, String hashToVerify);
}
| apache-2.0 |
iQuick/2048 | app/src/main/java/tk/woppo/mgame/MainView.java | 23281 | package tk.woppo.mgame;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.util.ArrayList;
public class MainView extends View {
//Internal variables
Paint paint = new Paint();
public MainGame game;
public boolean hasSaveState = false;
public final int numCellTypes = 18;
public boolean continueButtonEnabled = false;
//Layout variables
private int cellSize = 0;
private float textSize = 0;
private float cellTextSize = 0;
private int gridWidth = 0;
private int TEXT_BLACK;
private int TEXT_WHITE;
private int TEXT_BROWN;
public int startingX;
public int startingY;
public int endingX;
public int endingY;
private int textPaddingSize;
private int iconPaddingSize;
//Assets
private Drawable backgroundRectangle;
private BitmapDrawable[] bitmapCell = new BitmapDrawable[numCellTypes];
private Drawable lightUpRectangle;
private Drawable fadeRectangle;
private Bitmap background = null;
private BitmapDrawable loseGameOverlay;
private BitmapDrawable winGameContinueOverlay;
private BitmapDrawable winGameFinalOverlay;
//Text variables
private int sYAll;
private int titleStartYAll;
private int bodyStartYAll;
private int eYAll;
private int titleWidthHighScore;
private int titleWidthScore;
//Icon variables
public int sYIcons;
public int sXNewGame;
public int sXUndo;
public int iconSize;
//Timing
long lastFPSTime = System.nanoTime();
long currentTime = System.nanoTime();
//Text
float titleTextSize;
float bodyTextSize;
float headerTextSize;
float instructionsTextSize;
float gameOverTextSize;
//Misc
boolean refreshLastTime = true;
//Intenal Constants
static final int BASE_ANIMATION_TIME = 100000000;
static final float MERGING_ACCELERATION = (float) -0.5;
static final float INITIAL_VELOCITY = (1 - MERGING_ACCELERATION) / 4;
@Override
public void onDraw(Canvas canvas) {
//Reset the transparency of the screen
canvas.drawBitmap(background, 0, 0, paint);
drawScoreText(canvas);
if (!game.isActive() && !game.aGrid.isAnimationActive()) {
drawNewGameButton(canvas, true);
}
drawCells(canvas);
if (!game.isActive()) {
drawEndGameState(canvas);
}
if (!game.canContinue()) {
drawEndlessText(canvas);
}
//Refresh the screen if there is still an animation running
if (game.aGrid.isAnimationActive()) {
invalidate(startingX, startingY, endingX, endingY);
tick();
//Refresh one last time on game end.
} else if (!game.isActive() && refreshLastTime) {
invalidate();
refreshLastTime = false;
}
}
@Override
protected void onSizeChanged(int width, int height, int oldw, int oldh) {
super.onSizeChanged(width, height, oldw, oldh);
getLayout(width, height);
createBitmapCells();
createBackgroundBitmap(width, height);
createOverlays();
}
private void drawDrawable(Canvas canvas, Drawable draw, int startingX, int startingY, int endingX, int endingY) {
draw.setBounds(startingX, startingY, endingX, endingY);
draw.draw(canvas);
}
private void drawCellText(Canvas canvas, int value, int sX, int sY) {
int textShiftY = centerText();
if (value >= 8) {
paint.setColor(TEXT_WHITE);
} else {
paint.setColor(TEXT_BLACK);
}
canvas.drawText("" + value, sX + cellSize / 2, sY + cellSize / 2 - textShiftY, paint);
}
private void drawScoreText(Canvas canvas) {
//Drawing the score text: Ver 2
paint.setTextSize(bodyTextSize);
paint.setTextAlign(Paint.Align.CENTER);
int bodyWidthHighScore = (int) (paint.measureText("" + game.highScore));
int bodyWidthScore = (int) (paint.measureText("" + game.score));
int textWidthHighScore = Math.max(titleWidthHighScore, bodyWidthHighScore) + textPaddingSize * 2;
int textWidthScore = Math.max(titleWidthScore, bodyWidthScore) + textPaddingSize * 2;
int textMiddleHighScore = textWidthHighScore / 2;
int textMiddleScore = textWidthScore / 2;
int eXHighScore = endingX;
int sXHighScore = eXHighScore - textWidthHighScore;
int eXScore = sXHighScore - textPaddingSize;
int sXScore = eXScore - textWidthScore;
//Outputting high-scores box
backgroundRectangle.setBounds(sXHighScore, sYAll, eXHighScore, eYAll);
backgroundRectangle.draw(canvas);
paint.setTextSize(titleTextSize);
paint.setColor(TEXT_BROWN);
canvas.drawText(getResources().getString(R.string.high_score), sXHighScore + textMiddleHighScore, titleStartYAll, paint);
paint.setTextSize(bodyTextSize);
paint.setColor(TEXT_WHITE);
canvas.drawText(String.valueOf(game.highScore), sXHighScore + textMiddleHighScore, bodyStartYAll, paint);
//Outputting scores box
backgroundRectangle.setBounds(sXScore, sYAll, eXScore, eYAll);
backgroundRectangle.draw(canvas);
paint.setTextSize(titleTextSize);
paint.setColor(TEXT_BROWN);
canvas.drawText(getResources().getString(R.string.score), sXScore + textMiddleScore, titleStartYAll, paint);
paint.setTextSize(bodyTextSize);
paint.setColor(TEXT_WHITE);
canvas.drawText(String.valueOf(game.score), sXScore + textMiddleScore, bodyStartYAll, paint);
}
private void drawNewGameButton(Canvas canvas, boolean lightUp) {
if (lightUp) {
drawDrawable(canvas,
lightUpRectangle,
sXNewGame,
sYIcons,
sXNewGame + iconSize,
sYIcons + iconSize
);
} else {
drawDrawable(canvas,
backgroundRectangle,
sXNewGame,
sYIcons, sXNewGame + iconSize,
sYIcons + iconSize
);
}
drawDrawable(canvas,
getResources().getDrawable(R.drawable.ic_action_refresh),
sXNewGame + iconPaddingSize,
sYIcons + iconPaddingSize,
sXNewGame + iconSize - iconPaddingSize,
sYIcons + iconSize - iconPaddingSize
);
}
private void drawUndoButton(Canvas canvas) {
drawDrawable(canvas,
backgroundRectangle,
sXUndo,
sYIcons, sXUndo + iconSize,
sYIcons + iconSize
);
drawDrawable(canvas,
getResources().getDrawable(R.drawable.ic_action_undo),
sXUndo + iconPaddingSize,
sYIcons + iconPaddingSize,
sXUndo + iconSize - iconPaddingSize,
sYIcons + iconSize - iconPaddingSize
);
}
private void drawHeader(Canvas canvas) {
//Drawing the header
paint.setTextSize(headerTextSize);
paint.setColor(TEXT_BLACK);
paint.setTextAlign(Paint.Align.LEFT);
int textShiftY = centerText() * 2;
int headerStartY = sYAll - textShiftY;
canvas.drawText(getResources().getString(R.string.header), startingX, headerStartY, paint);
}
private void drawInstructions(Canvas canvas) {
//Drawing the instructions
paint.setTextSize(instructionsTextSize);
paint.setTextAlign(Paint.Align.LEFT);
int textShiftY = centerText() * 2;
canvas.drawText(getResources().getString(R.string.instructions),
startingX, endingY - textShiftY + textPaddingSize, paint);
}
private void drawBackground(Canvas canvas) {
drawDrawable(canvas, backgroundRectangle, startingX, startingY, endingX, endingY);
}
//Renders the set of 16 background squares.
private void drawBackgroundGrid(Canvas canvas) {
Resources resources = getResources();
Drawable backgroundCell = resources.getDrawable(R.drawable.cell_rectangle);
// Outputting the game grid
for (int xx = 0; xx < game.numSquaresX; xx++) {
for (int yy = 0; yy < game.numSquaresY; yy++) {
int sX = startingX + gridWidth + (cellSize + gridWidth) * xx;
int eX = sX + cellSize;
int sY = startingY + gridWidth + (cellSize + gridWidth) * yy;
int eY = sY + cellSize;
drawDrawable(canvas, backgroundCell, sX, sY, eX, eY);
}
}
}
private void drawCells(Canvas canvas) {
paint.setTextSize(textSize);
paint.setTextAlign(Paint.Align.CENTER);
// Outputting the individual cells
for (int xx = 0; xx < game.numSquaresX; xx++) {
for (int yy = 0; yy < game.numSquaresY; yy++) {
int sX = startingX + gridWidth + (cellSize + gridWidth) * xx;
int eX = sX + cellSize;
int sY = startingY + gridWidth + (cellSize + gridWidth) * yy;
int eY = sY + cellSize;
Tile currentTile = game.grid.getCellContent(xx, yy);
if (currentTile != null) {
//Get and represent the value of the tile
int value = currentTile.getValue();
int index = log2(value);
//Check for any active animations
ArrayList<AnimationCell> aArray = game.aGrid.getAnimationCell(xx, yy);
boolean animated = false;
for (int i = aArray.size() - 1; i >= 0; i--) {
AnimationCell aCell = aArray.get(i);
//If this animation is not active, skip it
if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) {
animated = true;
}
if (!aCell.isActive()) {
continue;
}
if (aCell.getAnimationType() == MainGame.SPAWN_ANIMATION) { // Spawning animation
double percentDone = aCell.getPercentageDone();
float textScaleSize = (float) (percentDone);
paint.setTextSize(textSize * textScaleSize);
float cellScaleSize = cellSize / 2 * (1 - textScaleSize);
bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize));
bitmapCell[index].draw(canvas);
} else if (aCell.getAnimationType() == MainGame.MERGE_ANIMATION) { // Merging Animation
double percentDone = aCell.getPercentageDone();
float textScaleSize = (float) (1 + INITIAL_VELOCITY * percentDone
+ MERGING_ACCELERATION * percentDone * percentDone / 2);
paint.setTextSize(textSize * textScaleSize);
float cellScaleSize = cellSize / 2 * (1 - textScaleSize);
bitmapCell[index].setBounds((int) (sX + cellScaleSize), (int) (sY + cellScaleSize), (int) (eX - cellScaleSize), (int) (eY - cellScaleSize));
bitmapCell[index].draw(canvas);
} else if (aCell.getAnimationType() == MainGame.MOVE_ANIMATION) { // Moving animation
double percentDone = aCell.getPercentageDone();
int tempIndex = index;
if (aArray.size() >= 2) {
tempIndex = tempIndex - 1;
}
int previousX = aCell.extras[0];
int previousY = aCell.extras[1];
int currentX = currentTile.getX();
int currentY = currentTile.getY();
int dX = (int) ((currentX - previousX) * (cellSize + gridWidth) * (percentDone - 1) * 1.0);
int dY = (int) ((currentY - previousY) * (cellSize + gridWidth) * (percentDone - 1) * 1.0);
bitmapCell[tempIndex].setBounds(sX + dX, sY + dY, eX + dX, eY + dY);
bitmapCell[tempIndex].draw(canvas);
}
animated = true;
}
//No active animations? Just draw the cell
if (!animated) {
bitmapCell[index].setBounds(sX, sY, eX, eY);
bitmapCell[index].draw(canvas);
}
}
}
}
}
private void drawEndGameState(Canvas canvas) {
double alphaChange = 1;
continueButtonEnabled = false;
for (AnimationCell animation : game.aGrid.globalAnimation) {
if (animation.getAnimationType() == MainGame.FADE_GLOBAL_ANIMATION) {
alphaChange = animation.getPercentageDone();
}
}
BitmapDrawable displayOverlay = null;
if (game.gameWon()) {
if (game.canContinue()) {
continueButtonEnabled = true;
displayOverlay = winGameContinueOverlay;
} else {
displayOverlay = winGameFinalOverlay;
}
} else if (game.gameLost()) {
displayOverlay = loseGameOverlay;
}
if (displayOverlay != null) {
displayOverlay.setBounds(startingX, startingY, endingX, endingY);
displayOverlay.setAlpha((int) (255 * alphaChange));
displayOverlay.draw(canvas);
}
}
private void drawEndlessText(Canvas canvas) {
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(bodyTextSize);
paint.setColor(TEXT_BLACK);
canvas.drawText(getResources().getString(R.string.endless), startingX, sYIcons - centerText() * 2, paint);
}
private void createEndGameStates(Canvas canvas, boolean win, boolean showButton) {
int width = endingX - startingX;
int length = endingY - startingY;
int middleX = width / 2;
int middleY = length / 2;
if (win) {
lightUpRectangle.setAlpha(127);
drawDrawable(canvas, lightUpRectangle, 0, 0, width, length);
lightUpRectangle.setAlpha(255);
paint.setColor(TEXT_WHITE);
paint.setAlpha(255);
paint.setTextSize(gameOverTextSize);
paint.setTextAlign(Paint.Align.CENTER);
int textBottom = middleY - centerText();
canvas.drawText(getResources().getString(R.string.you_win), middleX, textBottom, paint);
paint.setTextSize(bodyTextSize);
String text = showButton ? getResources().getString(R.string.go_on) :
getResources().getString(R.string.for_now);
canvas.drawText(text, middleX, textBottom + textPaddingSize * 2 - centerText() * 2, paint);
} else {
fadeRectangle.setAlpha(127);
drawDrawable(canvas, fadeRectangle, 0, 0, width, length);
fadeRectangle.setAlpha(255);
paint.setColor(TEXT_BLACK);
paint.setAlpha(255);
paint.setTextSize(gameOverTextSize);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(getResources().getString(R.string.game_over), middleX, middleY - centerText(), paint);
}
}
private void createBackgroundBitmap(int width, int height) {
background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(background);
drawHeader(canvas);
drawNewGameButton(canvas, false);
drawUndoButton(canvas);
drawBackground(canvas);
drawBackgroundGrid(canvas);
drawInstructions(canvas);
}
private void createBitmapCells() {
Resources resources = getResources();
int[] cellRectangleIds = getCellRectangleIds();
paint.setTextAlign(Paint.Align.CENTER);
for (int xx = 1; xx < bitmapCell.length; xx++) {
int value = (int) Math.pow(2, xx);
paint.setTextSize(cellTextSize);
float tempTextSize = cellTextSize * cellSize * 0.9f / Math.max(cellSize * 0.9f, paint.measureText(String.valueOf(value)));
paint.setTextSize(tempTextSize);
Bitmap bitmap = Bitmap.createBitmap(cellSize, cellSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawDrawable(canvas, resources.getDrawable(cellRectangleIds[xx]), 0, 0, cellSize, cellSize);
drawCellText(canvas, value, 0, 0);
bitmapCell[xx] = new BitmapDrawable(resources, bitmap);
}
}
private int[] getCellRectangleIds() {
int[] cellRectangleIds = new int[numCellTypes];
cellRectangleIds[0] = R.drawable.cell_rectangle;
cellRectangleIds[1] = R.drawable.cell_rectangle_2;
cellRectangleIds[2] = R.drawable.cell_rectangle_4;
cellRectangleIds[3] = R.drawable.cell_rectangle_8;
cellRectangleIds[4] = R.drawable.cell_rectangle_16;
cellRectangleIds[5] = R.drawable.cell_rectangle_32;
cellRectangleIds[6] = R.drawable.cell_rectangle_64;
cellRectangleIds[7] = R.drawable.cell_rectangle_128;
cellRectangleIds[8] = R.drawable.cell_rectangle_256;
cellRectangleIds[9] = R.drawable.cell_rectangle_512;
cellRectangleIds[10] = R.drawable.cell_rectangle_1024;
cellRectangleIds[11] = R.drawable.cell_rectangle_2048;
for (int xx = 12; xx < cellRectangleIds.length; xx++) {
cellRectangleIds[xx] = R.drawable.cell_rectangle_4096;
}
return cellRectangleIds;
}
private void createOverlays() {
Resources resources = getResources();
//Initalize overlays
Bitmap bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
createEndGameStates(canvas, true, true);
winGameContinueOverlay = new BitmapDrawable(resources, bitmap);
bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
createEndGameStates(canvas, true, false);
winGameFinalOverlay = new BitmapDrawable(resources, bitmap);
bitmap = Bitmap.createBitmap(endingX - startingX, endingY - startingY, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
createEndGameStates(canvas, false, false);
loseGameOverlay = new BitmapDrawable(resources, bitmap);
}
private void tick() {
currentTime = System.nanoTime();
game.aGrid.tickAll(currentTime - lastFPSTime);
lastFPSTime = currentTime;
}
public void resyncTime() {
lastFPSTime = System.nanoTime();
}
private static int log2(int n) {
if (n <= 0) throw new IllegalArgumentException();
return 31 - Integer.numberOfLeadingZeros(n);
}
private void getLayout(int width, int height) {
cellSize = Math.min(width / (game.numSquaresX + 1), height / (game.numSquaresY + 3));
gridWidth = cellSize / 7;
int screenMiddleX = width / 2;
int screenMiddleY = height / 2;
int boardMiddleX = screenMiddleX;
int boardMiddleY = screenMiddleY + cellSize / 2;
iconSize = cellSize / 2;
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(cellSize);
textSize = cellSize * cellSize / Math.max(cellSize, paint.measureText("0000"));
cellTextSize = textSize;
titleTextSize = textSize / 3;
bodyTextSize = (int) (textSize / 1.5);
instructionsTextSize = (int) (textSize / 1.5);
headerTextSize = textSize * 2;
gameOverTextSize = textSize * 2;
textPaddingSize = (int) (textSize / 3);
iconPaddingSize = (int) (textSize / 5);
//Grid Dimensions
double halfNumSquaresX = game.numSquaresX / 2d;
double halfNumSquaresY = game.numSquaresY / 2d;
startingX = (int) (boardMiddleX - (cellSize + gridWidth) * halfNumSquaresX - gridWidth / 2);
endingX = (int) (boardMiddleX + (cellSize + gridWidth) * halfNumSquaresX + gridWidth / 2);
startingY = (int) (boardMiddleY - (cellSize + gridWidth) * halfNumSquaresY - gridWidth / 2);
endingY = (int) (boardMiddleY + (cellSize + gridWidth) * halfNumSquaresY + gridWidth / 2);
paint.setTextSize(titleTextSize);
int textShiftYAll = centerText();
//static variables
sYAll = (int) (startingY - cellSize * 1.5);
titleStartYAll = (int) (sYAll + textPaddingSize + titleTextSize / 2 - textShiftYAll);
bodyStartYAll = (int) (titleStartYAll + textPaddingSize + titleTextSize / 2 + bodyTextSize / 2);
titleWidthHighScore = (int) (paint.measureText(getResources().getString(R.string.high_score)));
titleWidthScore = (int) (paint.measureText(getResources().getString(R.string.score)));
paint.setTextSize(bodyTextSize);
textShiftYAll = centerText();
eYAll = (int) (bodyStartYAll + textShiftYAll + bodyTextSize / 2 + textPaddingSize);
sYIcons = (startingY + eYAll) / 2 - iconSize / 2;
sXNewGame = (endingX - iconSize);
sXUndo = sXNewGame - iconSize * 3 / 2 - iconPaddingSize;
resyncTime();
}
private int centerText() {
return (int) ((paint.descent() + paint.ascent()) / 2);
}
public MainView(Context context) {
super(context);
Resources resources = context.getResources();
//Loading resources
game = new MainGame(context, this);
try {
//Getting assets
backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle);
lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle);
fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle);
TEXT_WHITE = resources.getColor(R.color.text_white);
TEXT_BLACK = resources.getColor(R.color.text_black);
TEXT_BROWN = resources.getColor(R.color.text_brown);
this.setBackgroundColor(resources.getColor(R.color.background));
Typeface font = Typeface.createFromAsset(resources.getAssets(), "ClearSans-Bold.ttf");
paint.setTypeface(font);
paint.setAntiAlias(true);
} catch (Exception e) {
System.out.println("Error getting assets?");
}
setOnTouchListener(new InputListener(this));
game.newGame();
}
} | apache-2.0 |
xangqun/distribute-task-schedule | schedule-job-core/src/main/java/com/xxl/job/core/rpc/netcom/jetty/client/ScheduleClient.java | 19698 | /**
* Copyright 2017-2025 schedule Group.
*/
package com.xxl.job.core.rpc.netcom.jetty.client;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.rpc.codec.RpcRequest;
import com.xxl.job.core.rpc.codec.RpcResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.logging.LogLevel;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
/**
* @author laixiangqun
* @since 2018-6-29
*/
@Component("scheduleClient")
public class ScheduleClient {
protected final Logger logger = LoggerFactory.getLogger(ScheduleClient.class);
// @Autowired
private RestTemplate restTemplate;
@Value("${spring.application.name}")
private String appName;
@Value("${egsc.schedule.ssl.enabled:false}")
private String sslEnabled;
@Value("${egsc.schedule.ssl.pfxpath:UNKOWN}")
private String pfxpath;
@Value("${egsc.schedule.ssl.pfxpwd:UNKOWN}")
private String pfxpwd;
@Value("${egsc.comfig.api.client.maxTotal:200}")
private int clientMaxTotal;
@Value("${egsc.comfig.api.client.defaultMaxPerRoute:100}")
private int clientDefaultMaxPerRoute;
@Value("${egsc.config.api.client.clientRequestTimeout:2000}")
private int clientConnectRequestTimeout;
@Value("${egsc.config.api.client.clientRequestSocketTimeout:10000}")
private int clientRequestSocketTimeout;
@Value("${egsc.config.api.client.readTimeout:10000}")
private int clientReadTimeout;
@Value("${egsc.config.api.client.connectTimeout:5000}")
private int clientConnectTimeout;
@Value("${egsc.config.api.client.retryCount:2}")
private int retryCount;
@Value("${logging.logtoELK:false}")
private boolean logtoELK;
@Value("${schedule.context-path:/}")
private String contextPath;
@PostConstruct
public void init(){
//初始化客户端
initRestTemplate();
}
/**
*
* 初始化restTemplate相关配置
*
*/
private void initRestTemplate(){
boolean flag = false;
try {
if ("true".equals(this.sslEnabled)) {
CloseableHttpClient httpClient = this.acceptsUntrustedCertsHttpClient();
if (null != httpClient) {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
clientHttpRequestFactory.setReadTimeout(this.clientReadTimeout);
clientHttpRequestFactory.setConnectTimeout(this.clientConnectTimeout);
this.restTemplate = new RestTemplate(clientHttpRequestFactory);
flag = true;
}
}
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | IOException | KeyManagementException e) {
this.logger.error("实例化RestTemplate异常", e);
}
if (!flag) {
this.restTemplate = this.createHttpClientRestTemplate();
}
}
private RestTemplate createHttpClientRestTemplate(){
PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager();
// 总连接数
pollingConnectionManager.setMaxTotal(this.clientMaxTotal);
// 同路由的并发数
pollingConnectionManager.setDefaultMaxPerRoute(this.clientDefaultMaxPerRoute);
HttpClientBuilder httpClientBuilder = HttpClients.custom().disableRedirectHandling();
httpClientBuilder.setConnectionManager(pollingConnectionManager);
// 重试次数,默认是3次,没有开启
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(this.retryCount, true));
// 保持长连接配置,需要在头添加Keep-Alive
// httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
// 发送请求相关配置
/*RequestConfig.Builder builder = RequestConfig.custom();
builder.setConnectionRequestTimeout(this.clientConnectRequestTimeout);
builder.setConnectTimeout(this.clientConnectTimeout);
builder.setSocketTimeout(this.clientRequestSocketTimeout);
RequestConfig requestConfig = builder.build();
httpClientBuilder.setDefaultRequestConfig(requestConfig);*/
CloseableHttpClient httpClient = httpClientBuilder.build();
// httpClient连接配置,底层是配置RequestConfig
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
/* 连接超时
* 这定义了通过网络与服务器建立连接的超时时间。
* Httpclient包中通过一个异步线程去创建与服务器的socket连接,这就是该socket连接的超时时间,
* 假设:访问一个IP,192.168.10.100,这个IP不存在或者响应太慢,那么将会返回
* java.net.SocketTimeoutException: connect timed out
*/
clientHttpRequestFactory.setConnectTimeout(this.clientConnectTimeout);
/* 数据读取超时时间,即SocketTimeout
* 指的是连接上一个url,获取response的返回等待时间,假设:url程序中存在阻塞、或者response
* 返回的文件内容太大,在指定的时间内没有读完,则出现
* java.net.SocketTimeoutException: Read timed out
*/
clientHttpRequestFactory.setReadTimeout(this.clientReadTimeout);
/* 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
* 从连接池中获取连接的超时时间,假设:连接池中已经使用的连接数等于setMaxTotal,新来的线程在等待1*1000
* 后超时,错误内容:org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
*/
clientHttpRequestFactory.setConnectionRequestTimeout(this.clientConnectRequestTimeout);
// 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
// clientHttpRequestFactory.setBufferRequestBody(false);
return new RestTemplate(clientHttpRequestFactory);
}
/**
* 用于访问服务的客户端
* 该方式会导致重复实例化restTemplate对象,在高并发下会导致CPU暴涨慎重使用
* @return RestTemplate
*/
@Deprecated
protected RestTemplate getRestTemplate() {
boolean flag = false;
try {
if ("true".equals(sslEnabled)) {
CloseableHttpClient httpClient = acceptsUntrustedCertsHttpClient();
if (null != httpClient) {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);
clientHttpRequestFactory.setReadTimeout(clientReadTimeout);// ms
clientHttpRequestFactory.setConnectTimeout(clientConnectTimeout);// ms
restTemplate = new RestTemplate(clientHttpRequestFactory);
flag = true;
}
}
} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException
| UnrecoverableKeyException | CertificateException | IOException e) {
logger.error("实例化RestTemplate异常", e);
}
if (!flag) {
SimpleClientHttpRequestFactory clientHttpRequestFactory =
new SimpleClientHttpRequestFactory();
clientHttpRequestFactory.setReadTimeout(clientReadTimeout);// ms
clientHttpRequestFactory.setConnectTimeout(clientConnectTimeout);// ms
restTemplate = new RestTemplate(clientHttpRequestFactory);
}
return restTemplate;
}
/**
* 获取可复用的访问服务的客户端
* @return
*/
protected RestTemplate getReuseRestTemplate() {
return this.restTemplate;
}
/**
* 调用接口,并封装公共框架
*
* @param url
* @param rpcRequest
* @return ResponseDto
*/
public RpcResponse post(String serverAddress,String url, RpcRequest rpcRequest){
String path = StringUtils.isBlank(url)?"":url;
if (!StringUtils.isEmpty(getContextPath()) && !"/".equals(getContextPath())) {
path = getContextPath() + path;
}
if ("true".equals(this.sslEnabled)) {
return postWithContextPath("https://"+serverAddress,rpcRequest, path);
}else {
return postWithContextPath("http://"+serverAddress,rpcRequest, path);
}
}
/**
* @param rpcRequest
* @param path
* @return ResponseDto
*/
protected RpcResponse postWithContextPath(String serverAddress,RpcRequest rpcRequest, String path) {
RpcResponse response = null;
try {
response = call(serverAddress,path, rpcRequest);
}
// connect
catch (ResourceAccessException e) {
logError(path, rpcRequest, e);
response = processConnectError(e);
}
// 400
catch (HttpClientErrorException e) {
logError(path, rpcRequest, e);
logger.error(e.getMessage(), e);
response = process4xxError(e);
}
// 500
catch (HttpServerErrorException e) {
logError(path, rpcRequest, e);
response = process5xxError(e);
}
// others
catch (Exception e) {
logError(path, rpcRequest, e);
response = processDefaultError(e);
}
return response;
}
/**
* @param e void
* @return
*/
private RpcResponse processDefaultError(Exception e) {
RpcResponse resDto = new RpcResponse( null, "网络连接失败");;
String errMsg = e.getMessage();
if (errMsg != null) {
resDto = new RpcResponse( HttpStatus.REQUEST_TIMEOUT.name(), errMsg);
}
return resDto;
}
/**
* @param e
* @return
*/
private RpcResponse processConnectError(ResourceAccessException e) {
logger.error(e.getMessage(), e);
return new RpcResponse( HttpStatus.REQUEST_TIMEOUT.name(), "网络连接失败");
}
/**
* @param url
* @param rpcRequest
* @param e void
*/
private void logError(String url, RpcRequest rpcRequest, Exception e) {
logger.error(String.format("Access Error - url(%s) request (%s)", url, rpcRequest));
logger.error(e.getMessage(), e);
}
/**
* void
*
* @return
*/
private RpcResponse process5xxError(HttpServerErrorException e) {
RpcResponse resDto = null;
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(e.getStatusCode())) {
resDto = getResponseDto(e.getResponseBodyAsString());
}
if (resDto == null) {
resDto = new RpcResponse(HttpStatus.INTERNAL_SERVER_ERROR.name(), "系统内部错误");
}
return resDto;
}
private RpcResponse process4xxError(HttpClientErrorException e) {
RpcResponse resDto = null;
HttpStatus statusCode = e.getStatusCode();
if (HttpStatus.UNAUTHORIZED.equals(statusCode) || HttpStatus.FORBIDDEN.equals(statusCode)
|| HttpStatus.NOT_FOUND.equals(statusCode) || HttpStatus.BAD_REQUEST.equals(statusCode)
|| HttpStatus.REQUEST_TIMEOUT.equals(statusCode)) {
String code = String.format("framework.network.http.status.%d", statusCode.value());
resDto = new RpcResponse( statusCode.name(), "00400:请求错误"+code);
} else if (statusCode != null) {
resDto = new RpcResponse( statusCode.name(), statusCode.getReasonPhrase());
} else {
resDto = new RpcResponse( "系统内部错误", "系统内部错误");
}
return resDto;
}
/**
* @param strRes
* @return ResponseDto
*/
private RpcResponse getResponseDto(String strRes) {
RpcResponse resDto = null;
try {
resDto = JSON.parseObject(strRes, RpcResponse.class);
} catch (Throwable e) {
logger.debug(e.getMessage());
}
return resDto;
}
/**
* 封装公共框架的BusinessId、TargetSysId、SourceSysId
*
* @param url
* @param requestDto
* @return ResponseDto
*/
private RpcResponse call(String serverAddress,String url, RpcRequest requestDto) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("Accept", MediaType.ALL_VALUE);
HttpEntity<RpcRequest> formEntity = new HttpEntity<>(requestDto, headers);
URI uri = URI.create(serverAddress + url);
logger.info(String.format("post -> %s", uri.toString()));
RpcResponse response = null;
try {
response = this.getReuseRestTemplate().postForObject(uri, formEntity, RpcResponse.class);
if (response != null) {
logger.info("response:{}", JSON.toJSONString(response));
} else {
logger.info("response is null!!");
}
} catch (Exception e) {
logger.error(e.getMessage());
response = callGatewayAgain(serverAddress,url, formEntity);
}
if (logger.isDebugEnabled()) {
logger.debug("Response: " + JSON.toJSONString(response));
}
return response;
}
/**
* @param url
* @param formEntity
* @return ResponseDto
*/
private RpcResponse callGatewayAgain(String serverAddress,String url, HttpEntity<RpcRequest> formEntity){
URI uri = URI.create(serverAddress + url);
RpcResponse response= this.getReuseRestTemplate().postForObject(uri, formEntity,RpcResponse.class);
return response;
}
/**
* 获得系统上下文
*
* @return String
*/
private String getContextPath() {
return contextPath;
}
/**
* Get pfxpath from resource(include:http,classpath,file)
*
* @param pfxpath Cert file path
* @return InputStream
* @throws IOException InputStream
*/
private InputStream getPfxpathInputStream(String pfxpath) throws IOException {
InputStream instream = null;
if (StringUtils.startsWith(pfxpath, ResourceUtils.FILE_URL_PREFIX)) {
instream = new FileInputStream(ResourceUtils.getFile(pfxpath));
}
else if (StringUtils.startsWith(pfxpath, "http:")) {
URL url = new URL(pfxpath);
instream = url.openStream();
}
else {
instream = this.getClass().getResourceAsStream(pfxpath);
}
return instream;
}
/**
*
* @return CloseableHttpClient
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws CertificateException
* @throws IOException
* @throws UnrecoverableKeyException
*/
private CloseableHttpClient acceptsUntrustedCertsHttpClient()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException,
CertificateException, IOException, UnrecoverableKeyException {
logger.debug("Start acceptsUntrustedCertsHttpClient");
HttpClientBuilder b = HttpClientBuilder.create();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream instream = this.getPfxpathInputStream(pfxpath);
logger.debug(String.format("client cer path : %s", pfxpath));
if (null == instream) {
logger.error("Can't load " + pfxpath);
return null;
}
try {
keyStore.load(instream, pfxpwd.toCharArray());
logger.debug(String.format("Load %s sucessfully", pfxpath));
} finally {
instream.close();
}
logger.debug("Load keystore into sslcontext");
SSLContext sslcontext =
SSLContexts.custom().loadKeyMaterial(keyStore, pfxpwd.toCharArray()).build();
logger.debug("initialize one new sslContext and set it to http client builder");
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
logger.debug("initialize a ssl socket factory");
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
logger.debug("initialize a socket factory registry");
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory).build();
logger.debug("initialize a http client connection manager with the socket factory registry");
PoolingHttpClientConnectionManager connMgr =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connMgr.setMaxTotal(200);
connMgr.setDefaultMaxPerRoute(100);
b.setConnectionManager(connMgr);
logger.debug("build a ssl http client");
CloseableHttpClient httpClient = b.build();
logger.debug("End acceptsUntrustedCertsHttpClient");
return httpClient;
}
}
| apache-2.0 |
cocoatomo/asakusafw | core-project/asakusa-runtime/src/main/java/com/asakusafw/runtime/io/util/WritableRawComparable.java | 1700 | /**
* Copyright 2011-2017 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.runtime.io.util;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
/**
* {@link WritableComparable} which is comparable in is bytes.
* Clients must override {@link Object#hashCode()} and {@link Object#equals(Object)}.
* @since 0.2.5
*/
public interface WritableRawComparable extends WritableComparable<WritableRawComparable> {
/**
* Computes and returns size in bytes.
* @param buf bytes array
* @param offset bytes offset
* @return size in bytes
* @throws IOException if failed to compute size
*/
int getSizeInBytes(byte[] buf, int offset) throws IOException;
/**
* Compares two objects in bytes.
* @param b1 bytes representation of the first object
* @param o1 offset of the first object
* @param b2 bytes representation of the second object
* @param o2 offset of the second object
* @return the comparison result
* @throws IOException if failed to comparison
*/
int compareInBytes(byte[] b1, int o1, byte[] b2, int o2) throws IOException;
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p60/Production1214.java | 1890 | package org.gradle.test.performance.mediummonolithicjavaproject.p60;
public class Production1214 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
newbiet/zstack | compute/src/main/java/org/zstack/compute/vm/VmDestroyOnHypervisorFlow.java | 5470 | package org.zstack.compute.vm;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.gc.EventBasedGCPersistentContext;
import org.zstack.core.gc.GCEventTrigger;
import org.zstack.core.gc.GCFacade;
import org.zstack.header.core.workflow.FlowTrigger;
import org.zstack.header.core.workflow.NoRollbackFlow;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.host.HostCanonicalEvents;
import org.zstack.header.host.HostConstant;
import org.zstack.header.host.HostErrors;
import org.zstack.header.host.HostStatus;
import org.zstack.header.message.MessageReply;
import org.zstack.header.vm.DestroyVmOnHypervisorMsg;
import org.zstack.header.vm.VmInstanceConstant;
import org.zstack.header.vm.VmInstanceSpec;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import java.util.Map;
import static org.zstack.utils.StringDSL.ln;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VmDestroyOnHypervisorFlow extends NoRollbackFlow {
private static final CLogger logger = Utils.getLogger(VmDestroyOnHypervisorFlow.class);
@Autowired
protected DatabaseFacade dbf;
@Autowired
protected CloudBus bus;
@Autowired
protected GCFacade gcf;
@Override
public void run(final FlowTrigger chain, Map data) {
final VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
final String hostUuid = spec.getVmInventory().getHostUuid() == null ? spec.getVmInventory().getLastHostUuid() : spec.getVmInventory().getHostUuid();
if (spec.getVmInventory().getClusterUuid() == null || hostUuid == null) {
// the vm failed to start because no host available at that time
// no need to send DestroyVmOnHypervisorMsg
chain.next();
return;
}
if (VmInstanceState.Stopped.toString().equals(spec.getVmInventory().getState())) {
chain.next();
return;
}
DestroyVmOnHypervisorMsg msg = new DestroyVmOnHypervisorMsg();
msg.setVmInventory(spec.getVmInventory());
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
bus.send(msg, new CloudBusCallBack(chain) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
chain.next();
return;
}
if (!SysErrors.HTTP_ERROR.toString().equals(reply.getError().getCode()) &&
!HostErrors.HOST_IS_DISCONNECTED.toString().equals(reply.getError().getCode())) {
chain.fail(reply.getError());
return;
}
GCDeleteVmContext c = new GCDeleteVmContext();
c.setHostUuid(hostUuid);
c.setVmUuid(spec.getVmInventory().getUuid());
c.setInventory(spec.getVmInventory());
c.setTriggerHostStatus(HostStatus.Connected.toString());
EventBasedGCPersistentContext<GCDeleteVmContext> ctx = new EventBasedGCPersistentContext<GCDeleteVmContext>();
ctx.setRunnerClass(GCDeleteVmRunner.class);
ctx.setContextClass(GCDeleteVmContext.class);
ctx.setName(String.format("delete-vm-%s", spec.getVmInventory().getUuid()));
ctx.setContext(c);
GCEventTrigger trigger = new GCEventTrigger();
trigger.setCodeName("gc-delete-vm-on-host-connected");
trigger.setEventPath(HostCanonicalEvents.HOST_STATUS_CHANGED_PATH);
String code = ln(
"import org.zstack.header.host.HostCanonicalEvents.HostStatusChangedData",
"import org.zstack.compute.vm.GCDeleteVmContext",
"HostStatusChangedData d = (HostStatusChangedData) data",
"GCDeleteVmContext c = (GCDeleteVmContext) context",
"return c.hostUuid == d.hostUuid && d.newStatus == c.triggerHostStatus"
).toString();
trigger.setCode(code);
ctx.addTrigger(trigger);
trigger = new GCEventTrigger();
trigger.setCodeName("gc-delete-vm-on-host-deleted");
trigger.setEventPath(HostCanonicalEvents.HOST_DELETED_PATH);
code = ln(
"import org.zstack.header.host.HostCanonicalEvents.HostDeletedData",
"import org.zstack.compute.vm.GCDeleteVmContext",
"HostDeletedData d = (HostDeletedData) data",
"GCDeleteVmContext c = (GCDeleteVmContext) context",
"return c.hostUuid == d.hostUuid"
).toString();
trigger.setCode(code);
ctx.addTrigger(trigger);
gcf.schedule(ctx);
chain.next();
}
});
}
}
| apache-2.0 |
Navaneethsen/hipster | hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ScalarOperation.java | 2430 | /**
* Copyright (C) 2013-2018 Centro de Investigación en Tecnoloxías da Información (CITIUS) (http://citius.usc.es)
*
* 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 es.usc.citius.hipster.model.function.impl;
import es.usc.citius.hipster.model.function.ScalarFunction;
/**
* A scalar operation is an implementation of {@link ScalarFunction} that
* also defines:
* <ul>
* <li>identity element (A*i = A)</li>
* </ul>
*
* @param <E> element type
*
* @author Pablo Rodríguez Mier <<a href="mailto:pablo.rodriguez.mier@usc.es">pablo.rodriguez.mier@usc.es</a>>
* @author Adrián González Sieira <<a href="adrian.gonzalez@usc.es">adrian.gonzalez@usc.es</a>>
*/
public class ScalarOperation<E extends Comparable<E>> implements ScalarFunction<E> {
private double identityElem;
private ScalarFunction<E> op;
/**
* Unique constructor for {@link ScalarOperation}, that takes the {@link ScalarFunction}
* applied and the identity element.
*
* @param operation operation definition
* @param identityElem identity
*/
public ScalarOperation(ScalarFunction<E> operation, double identityElem) {
this.identityElem = identityElem;
this.op = operation;
}
@Override
public E scale(E a, double b) {
return this.op.scale(a, b);
}
/**
* @return identity element
*/
public double getIdentityElem() {
return identityElem;
}
/**
* Builds the scaling operation for Doubles, that is the multiplying
* operation for the factor.
*
* @return {@link ScalarOperation} for Double
*/
public static ScalarOperation<Double> doubleMultiplicationOp() {
return new ScalarOperation<Double>(new ScalarFunction<Double>() {
@Override
public Double scale(Double a, double b) {
return a * b;
}
@Override
public double div(Double a, Double b) {
return a / b;
}
}, 1d);
}
@Override
public double div(E a, E b) {
return this.op.div(a, b);
}
}
| apache-2.0 |
alancnet/artifactory | web/rest-ui/src/main/java/org/artifactory/ui/rest/service/artifacts/search/DeleteArtifactsService.java | 2804 | package org.artifactory.ui.rest.service.artifacts.search;
import org.apache.commons.lang.StringUtils;
import org.artifactory.api.repo.RepositoryService;
import org.artifactory.common.StatusHolder;
import org.artifactory.repo.InternalRepoPathFactory;
import org.artifactory.repo.RepoPath;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.artifactory.rest.common.service.RestResponse;
import org.artifactory.rest.common.service.RestService;
import org.artifactory.ui.rest.model.artifacts.browse.treebrowser.action.DeleteArtifact;
import org.artifactory.ui.rest.model.artifacts.search.DeleteArtifactsModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @author Gidi Shabat
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class DeleteArtifactsService<T extends DeleteArtifactsModel> implements RestService<T> {
private static final Logger log = LoggerFactory.getLogger(DeleteArtifactsService.class);
@Autowired
private RepositoryService repositoryService;
@Override
public void execute(ArtifactoryRestRequest<T> request, RestResponse response) {
DeleteArtifactsModel model = request.getImodel();
for (DeleteArtifact deleteArtifactModel : model.getArtifacts()) {
String repoKey = deleteArtifactModel.getRepoKey();
String path = deleteArtifactModel.getPath();
if(StringUtils.isNotBlank(repoKey) && StringUtils.isNotBlank(path)) {
RepoPath repoPath = InternalRepoPathFactory.create(repoKey, path);
// delete artifact from repo path
StatusHolder statusHolder = deleteArtifact(repoPath);
// update response data
updateResponseData(response, statusHolder, repoPath);
}else {
log.warn("Failed to delete item : {} ", repoKey+"/"+path);
}
}
}
/**
* update response feedback
*/
private void updateResponseData(RestResponse artifactoryResponse, StatusHolder statusHolder, RepoPath repoPath) {
if (statusHolder.isError()) {
artifactoryResponse.error("Fail to delete the artifact : "+repoPath);
} else {
artifactoryResponse.info("Successfully deleted artifacts");
}
}
/**
* un deploy artifact from repo path
*
* @param repoPath - artifact repo path
* @return - status of the un deploy
*/
protected StatusHolder deleteArtifact(RepoPath repoPath) {
return repositoryService.undeploy(repoPath, true, true);
}
} | apache-2.0 |
mapr/elasticsearch | core/src/main/java/org/elasticsearch/index/mapper/ip/IpFieldMapper.java | 15117 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper.ip;
import org.apache.lucene.analysis.LegacyNumericTokenStream;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.Terms;
import org.apache.lucene.search.LegacyNumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LegacyNumericUtils;
import org.elasticsearch.Version;
import org.elasticsearch.action.fieldstats.FieldStats;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.network.Cidrs;
import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.analysis.NumericAnalyzer;
import org.elasticsearch.index.analysis.NumericTokenizer;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexNumericFieldData.NumericType;
import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.core.LongFieldMapper;
import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField;
import org.elasticsearch.index.mapper.core.NumberFieldMapper;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.aggregations.bucket.range.ipv4.InternalIPv4Range;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;
/**
*
*/
public class IpFieldMapper extends NumberFieldMapper {
public static final String CONTENT_TYPE = "ip";
public static final long MAX_IP = 4294967296L;
public static String longToIp(long longIp) {
int octet3 = (int) ((longIp >> 24) % 256);
int octet2 = (int) ((longIp >> 16) % 256);
int octet1 = (int) ((longIp >> 8) % 256);
int octet0 = (int) ((longIp) % 256);
return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
}
private static final Pattern pattern = Pattern.compile("\\.");
public static long ipToLong(String ip) {
try {
if (!InetAddresses.isInetAddress(ip)) {
throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ip address");
}
String[] octets = pattern.split(ip);
if (octets.length != 4) {
throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ipv4 address (4 dots)");
}
return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
(Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
throw (IllegalArgumentException) e;
}
throw new IllegalArgumentException("failed to parse ip [" + ip + "]", e);
}
}
public static class Defaults extends NumberFieldMapper.Defaults {
public static final String NULL_VALUE = null;
public static final MappedFieldType FIELD_TYPE = new IpFieldType();
static {
FIELD_TYPE.freeze();
}
}
public static class Builder extends NumberFieldMapper.Builder<Builder, IpFieldMapper> {
protected String nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, Defaults.FIELD_TYPE, Defaults.PRECISION_STEP_64_BIT);
builder = this;
}
@Override
public IpFieldMapper build(BuilderContext context) {
setupFieldType(context);
IpFieldMapper fieldMapper = new IpFieldMapper(name, fieldType, defaultFieldType, ignoreMalformed(context), coerce(context),
context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
return (IpFieldMapper) fieldMapper.includeInAll(includeInAll);
}
@Override
protected NamedAnalyzer makeNumberAnalyzer(int precisionStep) {
String name = precisionStep == Integer.MAX_VALUE ? "_ip/max" : ("_ip/" + precisionStep);
return new NamedAnalyzer(name, new NumericIpAnalyzer(precisionStep));
}
@Override
protected int maxPrecisionStep() {
return 64;
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
IpFieldMapper.Builder builder = new Builder(name);
parseNumberField(builder, name, node, parserContext);
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
if (propNode == null) {
throw new MapperParsingException("Property [null_value] cannot be null.");
}
builder.nullValue(propNode.toString());
iterator.remove();
}
}
return builder;
}
}
public static final class IpFieldType extends LongFieldMapper.LongFieldType {
public IpFieldType() {
}
protected IpFieldType(IpFieldType ref) {
super(ref);
}
@Override
public NumberFieldType clone() {
return new IpFieldType(this);
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public Long value(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof BytesRef) {
return Numbers.bytesToLong((BytesRef) value);
}
return ipToLong(value.toString());
}
/**
* IPs should return as a string.
*/
@Override
public Object valueForSearch(Object value) {
Long val = value(value);
if (val == null) {
return null;
}
return longToIp(val);
}
@Override
public BytesRef indexedValueForSearch(Object value) {
BytesRefBuilder bytesRef = new BytesRefBuilder();
LegacyNumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match
return bytesRef.get();
}
@Override
public Query termQuery(Object value, @Nullable QueryShardContext context) {
if (value != null) {
String term;
if (value instanceof BytesRef) {
term = ((BytesRef) value).utf8ToString();
} else {
term = value.toString();
}
long[] fromTo;
// assume that the term is either a CIDR range or the
// term is a single IPv4 address; if either of these
// assumptions is wrong, the CIDR parsing will fail
// anyway, and that is okay
if (term.contains("/")) {
// treat the term as if it is in CIDR notation
fromTo = Cidrs.cidrMaskToMinMax(term);
} else {
// treat the term as if it is a single IPv4, and
// apply a CIDR mask equivalent to the host route
fromTo = Cidrs.cidrMaskToMinMax(term + "/32");
}
if (fromTo != null) {
return rangeQuery(fromTo[0] == 0 ? null : fromTo[0],
fromTo[1] == InternalIPv4Range.MAX_IP ? null : fromTo[1], true, false);
}
}
return super.termQuery(value, context);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper) {
return LegacyNumericRangeQuery.newLongRange(name(), numericPrecisionStep(),
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Query fuzzyQuery(Object value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) {
long iValue = parseValue(value);
long iSim;
try {
iSim = ipToLong(fuzziness.asString());
} catch (IllegalArgumentException e) {
iSim = fuzziness.asLong();
}
return LegacyNumericRangeQuery.newLongRange(name(), numericPrecisionStep(),
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public FieldStats stats(Terms terms, int maxDoc) throws IOException {
long minValue = LegacyNumericUtils.getMinLong(terms);
long maxValue = LegacyNumericUtils.getMaxLong(terms);
return new FieldStats.Ip(maxDoc, terms.getDocCount(), terms.getSumDocFreq(), terms.getSumTotalTermFreq(), minValue, maxValue);
}
@Override
public IndexFieldData.Builder fielddataBuilder() {
failIfNoDocValues();
return new DocValuesIndexFieldData.Builder().numericType(NumericType.LONG);
}
}
protected IpFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType,
Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce,
Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(simpleName, fieldType, defaultFieldType, ignoreMalformed, coerce, indexSettings, multiFields, copyTo);
}
private static long parseValue(Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof BytesRef) {
return ipToLong(((BytesRef) value).utf8ToString());
}
return ipToLong(value.toString());
}
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
String ipAsString;
if (context.externalValueSet()) {
ipAsString = (String) context.externalValue();
if (ipAsString == null) {
ipAsString = fieldType().nullValueAsString();
}
} else {
if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) {
ipAsString = fieldType().nullValueAsString();
} else {
ipAsString = context.parser().text();
}
}
if (ipAsString == null) {
return;
}
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(fieldType().name(), ipAsString, fieldType().boost());
}
final long value = ipToLong(ipAsString);
if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) {
CustomLongNumericField field = new CustomLongNumericField(value, fieldType());
if (fieldType.boost() != 1f && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) {
field.setBoost(fieldType().boost());
}
fields.add(field);
}
if (fieldType().hasDocValues()) {
addDocValue(context, fields, value);
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || fieldType().numericPrecisionStep() != Defaults.PRECISION_STEP_64_BIT) {
builder.field("precision_step", fieldType().numericPrecisionStep());
}
if (includeDefaults || fieldType().nullValueAsString() != null) {
builder.field("null_value", fieldType().nullValueAsString());
}
if (includeInAll != null) {
builder.field("include_in_all", includeInAll);
} else if (includeDefaults) {
builder.field("include_in_all", false);
}
}
public static class NumericIpAnalyzer extends NumericAnalyzer<NumericIpTokenizer> {
private final int precisionStep;
public NumericIpAnalyzer(int precisionStep) {
this.precisionStep = precisionStep;
}
@Override
protected NumericIpTokenizer createNumericTokenizer(char[] buffer) throws IOException {
return new NumericIpTokenizer(precisionStep, buffer);
}
}
public static class NumericIpTokenizer extends NumericTokenizer {
public NumericIpTokenizer(int precisionStep, char[] buffer) throws IOException {
super(new LegacyNumericTokenStream(precisionStep), buffer, null);
}
@Override
protected void setValue(LegacyNumericTokenStream tokenStream, String value) {
tokenStream.setLongValue(ipToLong(value));
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cloudtrail/src/test/java/com/amazonaws/services/cloudtrail/smoketests/RunCucumberTest.java | 950 | /*
* 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.cloudtrail.smoketests;
import javax.annotation.Generated;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@CucumberOptions(glue = { "com.amazonaws.smoketest" })
@RunWith(Cucumber.class)
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RunCucumberTest {
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/SnapshotScheduleQuotaExceededExceptionUnmarshaller.java | 1673 | /*
* 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.redshift.model.transform;
import org.w3c.dom.Node;
import javax.annotation.Generated;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.redshift.model.SnapshotScheduleQuotaExceededException;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SnapshotScheduleQuotaExceededExceptionUnmarshaller extends StandardErrorUnmarshaller {
public SnapshotScheduleQuotaExceededExceptionUnmarshaller() {
super(SnapshotScheduleQuotaExceededException.class);
}
@Override
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("SnapshotScheduleQuotaExceeded"))
return null;
SnapshotScheduleQuotaExceededException e = (SnapshotScheduleQuotaExceededException) super.unmarshall(node);
return e;
}
}
| apache-2.0 |
fumandito/recruiting | recruiting-pagination/src/main/java/it/f2informatica/pagination/repository/mongodb/SimpleMongoPaginationRepository.java | 2060 | /*
* =============================================================================
*
* Copyright (c) 2014, Fernando Aspiazu
*
* 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 it.f2informatica.pagination.repository.mongodb;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.SimpleMongoRepository;
import java.io.Serializable;
import java.util.List;
public class SimpleMongoPaginationRepository<T, ID extends Serializable>
extends SimpleMongoRepository<T, ID> implements MongoDBQueryExecutor<T> {
public SimpleMongoPaginationRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
super(metadata, mongoOperations);
}
@Override
public List<T> findAll(MongoQueryPredicate<T> predicate) {
return getMongoOperations().findAll(predicate.getEntityClass());
}
@Override
public Page<T> findAll(MongoQueryPredicate<T> predicate, Pageable pageable) {
List<T> content = getMongoOperations().find(predicate.queryPredicate().with(pageable), predicate.getEntityClass());
return new PageImpl<>(content, pageable, getMongoOperations().count(predicate.queryPredicate(), predicate.getEntityClass()));
}
}
| apache-2.0 |
eugene-smola/drools-examples | InsuranceBruteForce/src/main/java/com/smolnij/calculator/drools/InsuranceCalculatorDroolsTables.java | 396 | package com.smolnij.calculator.drools;
import org.drools.runtime.StatelessKnowledgeSession;
import com.smolnij.drools.DecisionTableKnowledgeSessionBuilder;
public class InsuranceCalculatorDroolsTables extends AbstractDroolsCalculator {
public StatelessKnowledgeSession createKnowledgeSession() {
return new DecisionTableKnowledgeSessionBuilder().populateStatelessKnowledgeSession();
}
} | apache-2.0 |
justomiguel/CustomMessenger | TMessagesProj/src/main/java/com/jmv/frre/moduloestudiante/ui/LoginActivityPhoneView.java | 17789 | /*
* This is the source code of Telegram for Android v. 1.3.2.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013.
*/
package com.jmv.frre.moduloestudiante.ui;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import com.jmv.frre.moduloestudiante.R;
import com.jmv.frre.moduloestudiante.android.AndroidUtilities;
import com.jmv.frre.moduloestudiante.PhoneFormat.PhoneFormat;
import com.jmv.frre.moduloestudiante.messenger.BuildVars;
import com.jmv.frre.moduloestudiante.android.LocaleController;
import com.jmv.frre.moduloestudiante.messenger.TLObject;
import com.jmv.frre.moduloestudiante.messenger.TLRPC;
import com.jmv.frre.moduloestudiante.messenger.ConnectionsManager;
import com.jmv.frre.moduloestudiante.messenger.FileLog;
import com.jmv.frre.moduloestudiante.messenger.RPCRequest;
import com.jmv.frre.moduloestudiante.ui.Views.ActionBar.BaseFragment;
import com.jmv.frre.moduloestudiante.ui.Views.SlideView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
public class LoginActivityPhoneView extends SlideView implements AdapterView.OnItemSelectedListener {
private EditText codeField;
private EditText phoneField;
private TextView countryButton;
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private HashMap<String, String> codesMap = new HashMap<String, String>();
private HashMap<String, String> languageMap = new HashMap<String, String>();
private boolean ignoreSelection = false;
private boolean ignoreOnTextChange = false;
private boolean ignoreOnPhoneChange = false;
private boolean nextPressed = false;
public LoginActivityPhoneView(Context context) {
super(context);
}
public LoginActivityPhoneView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LoginActivityPhoneView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
TextView textView = (TextView)findViewById(R.id.login_confirm_text);
textView.setText(LocaleController.getString("StartText", R.string.StartText));
countryButton = (TextView)findViewById(R.id.login_coutry_textview);
countryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (delegate == null) {
return;
}
BaseFragment activity = (BaseFragment)delegate;
CountrySelectActivity fragment = new CountrySelectActivity();
fragment.setCountrySelectActivityDelegate(new CountrySelectActivity.CountrySelectActivityDelegate() {
@Override
public void didSelectCountry(String name) {
selectCountry(name);
phoneField.requestFocus();
}
});
activity.presentFragment(fragment);
}
});
codeField = (EditText)findViewById(R.id.login_county_code_field);
codeField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
if (ignoreOnTextChange) {
ignoreOnTextChange = false;
return;
}
ignoreOnTextChange = true;
String text = PhoneFormat.stripExceptNumbers(codeField.getText().toString());
codeField.setText(text);
if (text.length() == 0) {
countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
countryState = 1;
} else {
String country = codesMap.get(text);
if (country != null) {
int index = countriesArray.indexOf(country);
if (index != -1) {
ignoreSelection = true;
countryButton.setText(countriesArray.get(index));
updatePhoneField();
countryState = 0;
} else {
countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
countryState = 2;
}
} else {
countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry));
countryState = 2;
}
codeField.setSelection(codeField.getText().length());
}
}
});
codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_NEXT) {
phoneField.requestFocus();
return true;
}
return false;
}
});
phoneField = (EditText)findViewById(R.id.login_phone_field);
phoneField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (ignoreOnPhoneChange) {
return;
}
if (count == 1 && after == 0 && s.length() > 1) {
String phoneChars = "0123456789";
String str = s.toString();
String substr = str.substring(start, start + 1);
if (!phoneChars.contains(substr)) {
ignoreOnPhoneChange = true;
StringBuilder builder = new StringBuilder(str);
int toDelete = 0;
for (int a = start; a >= 0; a--) {
substr = str.substring(a, a + 1);
if(phoneChars.contains(substr)) {
break;
}
toDelete++;
}
builder.delete(Math.max(0, start - toDelete), start + 1);
str = builder.toString();
if (PhoneFormat.strip(str).length() == 0) {
phoneField.setText("");
} else {
phoneField.setText(str);
updatePhoneField();
}
ignoreOnPhoneChange = false;
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (ignoreOnPhoneChange) {
return;
}
updatePhoneField();
}
});
if(!isInEditMode()) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt")));
String line;
while ((line = reader.readLine()) != null) {
String[] args = line.split(";");
countriesArray.add(0, args[2]);
countriesMap.put(args[2], args[0]);
codesMap.put(args[0], args[2]);
languageMap.put(args[1], args[2]);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
Collections.sort(countriesArray, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
String country = null;
try {
TelephonyManager telephonyManager = (TelephonyManager)ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
country = telephonyManager.getSimCountryIso().toUpperCase();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (country != null) {
String countryName = languageMap.get(country);
if (countryName != null) {
int index = countriesArray.indexOf(countryName);
if (index != -1) {
codeField.setText(countriesMap.get(countryName));
countryState = 0;
}
}
}
if (codeField.length() == 0) {
countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
countryState = 1;
}
}
if (codeField.length() != 0) {
AndroidUtilities.showKeyboard(phoneField);
phoneField.requestFocus();
} else {
AndroidUtilities.showKeyboard(codeField);
codeField.requestFocus();
}
phoneField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_NEXT) {
delegate.onNextAction();
return true;
}
return false;
}
});
}
public void selectCountry(String name) {
int index = countriesArray.indexOf(name);
if (index != -1) {
ignoreOnTextChange = true;
codeField.setText(countriesMap.get(name));
countryButton.setText(name);
countryState = 0;
}
}
private void updatePhoneField() {
ignoreOnPhoneChange = true;
String codeText = codeField.getText().toString();
String phone = PhoneFormat.getInstance().format("+" + codeText + phoneField.getText().toString());
int idx = phone.indexOf(" ");
if (idx != -1) {
String resultCode = PhoneFormat.stripExceptNumbers(phone.substring(0, idx));
if (!codeText.equals(resultCode)) {
phone = PhoneFormat.getInstance().format(phoneField.getText().toString()).trim();
phoneField.setText(phone);
int len = phoneField.length();
phoneField.setSelection(phoneField.length());
} else {
phoneField.setText(phone.substring(idx).trim());
int len = phoneField.length();
phoneField.setSelection(phoneField.length());
}
} else {
phoneField.setSelection(phoneField.length());
}
ignoreOnPhoneChange = false;
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (ignoreSelection) {
ignoreSelection = false;
return;
}
ignoreOnTextChange = true;
String str = countriesArray.get(i);
codeField.setText(countriesMap.get(str));
updatePhoneField();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
@Override
public void onNextPressed() {
if (nextPressed) {
return;
}
if (countryState == 1) {
delegate.needShowAlert(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
return;
} else if (countryState == 2) {
delegate.needShowAlert(LocaleController.getString("WrongCountry", R.string.WrongCountry));
return;
}
if (codeField.length() == 0) {
delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
return;
}
TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode();
String phone = PhoneFormat.stripExceptNumbers("" + codeField.getText() + phoneField.getText());
ConnectionsManager.getInstance().applyCountryPortNumber(phone);
req.api_hash = BuildVars.APP_HASH;
req.api_id = BuildVars.APP_ID;
req.sms_type = 0;
req.phone_number = phone;
req.lang_code = LocaleController.getLocaleString(Locale.getDefault());
if (req.lang_code == null || req.lang_code.length() == 0) {
req.lang_code = "en";
}
final Bundle params = new Bundle();
params.putString("phone", "+" + codeField.getText() + phoneField.getText());
params.putString("phoneFormated", phone);
nextPressed = true;
if (delegate != null) {
delegate.needShowProgress();
}
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
nextPressed = false;
if (error == null) {
final TLRPC.TL_auth_sentCode res = (TLRPC.TL_auth_sentCode)response;
params.putString("phoneHash", res.phone_code_hash);
params.putInt("calltime", res.send_call_timeout * 1000);
if (res.phone_registered) {
params.putString("registered", "true");
}
if (delegate != null) {
delegate.setPage(1, true, params, false);
}
} else {
if (delegate != null && error.text != null) {
if (error.text.contains("PHONE_NUMBER_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode));
} else if (error.text.contains("PHONE_CODE_EXPIRED")) {
delegate.needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired));
} else if (error.text.startsWith("FLOOD_WAIT")) {
delegate.needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else {
delegate.needShowAlert(error.text);
}
}
}
if (delegate != null) {
delegate.needHideProgress();
}
}
});
}
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin | RPCRequest.RPCRequestClassTryDifferentDc | RPCRequest.RPCRequestClassEnableUnauthorized);
}
@Override
public void onShow() {
super.onShow();
if (phoneField != null) {
phoneField.requestFocus();
phoneField.setSelection(phoneField.length());
}
}
@Override
public String getHeaderName() {
return LocaleController.getString("YourPhone", R.string.YourPhone);
}
@Override
public void saveStateParams(Bundle bundle) {
String code = codeField.getText().toString();
if (code != null && code.length() != 0) {
bundle.putString("phoneview_code", code);
}
String phone = phoneField.getText().toString();
if (phone != null && phone.length() != 0) {
bundle.putString("phoneview_phone", phone);
}
}
@Override
public void restoreStateParams(Bundle bundle) {
String code = bundle.getString("phoneview_code");
if (code != null) {
codeField.setText(code);
}
String phone = bundle.getString("phoneview_phone");
if (phone != null) {
phoneField.setText(phone);
}
}
}
| apache-2.0 |
rkapsi/gibson | gibson-appender/src/test/java/org/ardverk/gibson/appender/ExampleIT.java | 3888 | /*
* Copyright 2012 Will Benedict, Felix Berger and Roger Kapsi
*
* 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.ardverk.gibson.appender;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.ardverk.gibson.transport.MongoTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a simple test class that produces a lot of fake logging messages.
*/
public class ExampleIT {
private static final Logger[] LOGGERS = {
LoggerFactory.getLogger(Class.class),
LoggerFactory.getLogger(System.class),
LoggerFactory.getLogger(MongoTransport.class),
LoggerFactory.getLogger(ClassLoader.class),
};
private static final Random GENERATOR = new Random();
private static final Class<?>[] TYPES = {
IOException.class,
NullPointerException.class,
IllegalArgumentException.class,
IllegalStateException.class,
UnsupportedOperationException.class,
NoSuchMethodException.class,
ClassNotFoundException.class,
ArithmeticException.class,
ArrayIndexOutOfBoundsException.class,
IndexOutOfBoundsException.class,
};
private static final String[] MESSAGES = {
"Abstract",
"Provider",
"State",
"Bad",
"User",
"Factory",
"Facy",
"Builder",
"Hello",
"World",
"test"
};
private static Logger logger() {
return LOGGERS[GENERATOR.nextInt(LOGGERS.length)];
}
private static String log() {
int count = 1 + GENERATOR.nextInt(4);
return message(count);
}
private static String msg() {
int count = 1 + GENERATOR.nextInt(2);
return message(count);
}
private static String message(int count) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(MESSAGES[GENERATOR.nextInt(MESSAGES.length)]).append(' ');
}
return sb.toString().trim();
}
public static void main(String[] args) throws InterruptedException {
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
logger().error(log(), createThrowable(msg(), 5 + GENERATOR.nextInt(10)));
} catch (Exception err) {
logger().error("Excpetion", err);
}
try { Thread.sleep(25); } catch (InterruptedException ignore) {}
}
}
};
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 4; i++) {
executor.execute(task);
}
Thread.sleep(Long.MAX_VALUE);
}
private static Throwable createThrowable(String message, int stack) {
if (0 < stack) {
return createThrowable(message, --stack);
}
Throwable throwable = newThrowable(message);
if (Math.random() < 0.25) {
throwable.initCause(createThrowable(msg(), 5 + GENERATOR.nextInt(10)));
}
return throwable;
}
private static Throwable newThrowable(String message) {
int index = GENERATOR.nextInt(TYPES.length);
Class<?> clazz = TYPES[index];
try {
Constructor<?> constructor = clazz.getConstructor(String.class);
return (Throwable)constructor.newInstance(message);
} catch (Exception err) {
return err;
}
}
}
| apache-2.0 |
typetools/commons-bcel | src/main/java/org/apache/bcel/generic/FieldGen.java | 11764 | /*
* 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.bcel.generic;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Annotations;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantObject;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantValue;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.Utility;
import org.apache.bcel.util.BCELComparator;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Template class for building up a field. The only extraordinary thing
* one can do is to add a constant value attribute to a field (which must of
* course be compatible with to the declared type).
*
* @see Field
*/
public class FieldGen extends FieldGenOrMethodGen {
private Object value = null;
private static BCELComparator bcelComparator = new BCELComparator() {
@Override
public boolean equals( final Object o1, final Object o2 ) {
final FieldGen THIS = (FieldGen) o1;
final FieldGen THAT = (FieldGen) o2;
return Objects.equals(THIS.getName(), THAT.getName())
&& Objects.equals(THIS.getSignature(), THAT.getSignature());
}
@Override
public int hashCode( final Object o ) {
final FieldGen THIS = (FieldGen) o;
return THIS.getSignature().hashCode() ^ THIS.getName().hashCode();
}
};
/**
* Declare a field. If it is static (isStatic() == true) and has a
* basic type like int or String it may have an initial value
* associated with it as defined by setInitValue().
*
* @param access_flags access qualifiers
* @param type field type
* @param name field name
* @param cp constant pool
*/
public FieldGen(final int access_flags, final Type type, final String name, final ConstantPoolGen cp) {
super(access_flags);
setType(type);
setName(name);
setConstantPool(cp);
}
/**
* Instantiate from existing field.
*
* @param field Field object
* @param cp constant pool (must contain the same entries as the field's constant pool)
*/
public FieldGen(final Field field, final ConstantPoolGen cp) {
this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
final Attribute[] attrs = field.getAttributes();
for (final Attribute attr : attrs) {
if (attr instanceof ConstantValue) {
setValue(((ConstantValue) attr).getConstantValueIndex());
} else if (attr instanceof Annotations) {
final Annotations runtimeAnnotations = (Annotations)attr;
final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();
for (final AnnotationEntry element : annotationEntries) {
addAnnotationEntry(new AnnotationEntryGen(element,cp,false));
}
} else {
addAttribute(attr);
}
}
}
private void setValue( final int index ) {
final ConstantPool cp = super.getConstantPool().getConstantPool();
final Constant c = cp.getConstant(index);
value = ((ConstantObject) c).getConstantValue(cp);
}
/**
* Set (optional) initial value of field, otherwise it will be set to null/0/false
* by the JVM automatically.
*/
public void setInitValue( final String str ) {
checkType( ObjectType.getInstance("java.lang.String"));
if (str != null) {
value = str;
}
}
public void setInitValue( final long l ) {
checkType(Type.LONG);
if (l != 0L) {
value = Long.valueOf(l);
}
}
public void setInitValue( final int i ) {
checkType(Type.INT);
if (i != 0) {
value = Integer.valueOf(i);
}
}
public void setInitValue( final short s ) {
checkType(Type.SHORT);
if (s != 0) {
value = Integer.valueOf(s);
}
}
public void setInitValue( final char c ) {
checkType(Type.CHAR);
if (c != 0) {
value = Integer.valueOf(c);
}
}
public void setInitValue( final byte b ) {
checkType(Type.BYTE);
if (b != 0) {
value = Integer.valueOf(b);
}
}
public void setInitValue( final boolean b ) {
checkType(Type.BOOLEAN);
if (b) {
value = Integer.valueOf(1);
}
}
public void setInitValue( final float f ) {
checkType(Type.FLOAT);
if (f != 0.0) {
value = new Float(f);
}
}
public void setInitValue( final double d ) {
checkType(Type.DOUBLE);
if (d != 0.0) {
value = new Double(d);
}
}
/** Remove any initial value.
*/
public void cancelInitValue() {
value = null;
}
private void checkType( final Type atype ) {
final Type superType = super.getType();
if (superType == null) {
throw new ClassGenException("You haven't defined the type of the field yet");
}
if (!isFinal()) {
throw new ClassGenException("Only final fields may have an initial value!");
}
if (!superType.equals(atype)) {
throw new ClassGenException("Types are not compatible: " + superType + " vs. " + atype);
}
}
/**
* Get field object after having set up all necessary values.
*/
public Field getField() {
final String signature = getSignature();
final int name_index = super.getConstantPool().addUtf8(super.getName());
final int signature_index = super.getConstantPool().addUtf8(signature);
if (value != null) {
checkType(super.getType());
final int index = addConstant();
addAttribute(new ConstantValue(super.getConstantPool().addUtf8("ConstantValue"), 2, index,
super.getConstantPool().getConstantPool())); // sic
}
addAnnotationsAsAttribute(super.getConstantPool());
return new Field(super.getAccessFlags(), name_index, signature_index, getAttributes(),
super.getConstantPool().getConstantPool()); // sic
}
private void addAnnotationsAsAttribute(final ConstantPoolGen cp) {
final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries());
for (final Attribute attr : attrs) {
addAttribute(attr);
}
}
private int addConstant() {
switch (super.getType().getType()) { // sic
case Const.T_INT:
case Const.T_CHAR:
case Const.T_BYTE:
case Const.T_BOOLEAN:
case Const.T_SHORT:
return super.getConstantPool().addInteger(((Integer) value).intValue());
case Const.T_FLOAT:
return super.getConstantPool().addFloat(((Float) value).floatValue());
case Const.T_DOUBLE:
return super.getConstantPool().addDouble(((Double) value).doubleValue());
case Const.T_LONG:
return super.getConstantPool().addLong(((Long) value).longValue());
case Const.T_REFERENCE:
return super.getConstantPool().addString((String) value);
default:
throw new IllegalStateException("Unhandled : " + super.getType().getType()); // sic
}
}
@Override
public String getSignature() {
return super.getType().getSignature();
}
private List<FieldObserver> observers;
/** Add observer for this object.
*/
public void addObserver( final FieldObserver o ) {
if (observers == null) {
observers = new ArrayList<>();
}
observers.add(o);
}
/** Remove observer for this object.
*/
public void removeObserver( final FieldObserver o ) {
if (observers != null) {
observers.remove(o);
}
}
/** Call notify() method on all observers. This method is not called
* automatically whenever the state has changed, but has to be
* called by the user after he has finished editing the object.
*/
public void update() {
if (observers != null) {
for (final FieldObserver observer : observers ) {
observer.notify(this);
}
}
}
public @Nullable String getInitValue() {
if (value != null) {
return value.toString();
}
return null;
}
/**
* Return string representation close to declaration format,
* `public static final short MAX = 100', e.g..
*
* @return String representation of field
*/
@Override
public final String toString() {
String name;
String signature;
String access; // Short cuts to constant pool
access = Utility.accessToString(super.getAccessFlags());
access = access.isEmpty() ? "" : (access + " ");
signature = super.getType().toString();
name = getName();
final StringBuilder buf = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber
buf.append(access).append(signature).append(" ").append(name);
final String value = getInitValue();
if (value != null) {
buf.append(" = ").append(value);
}
return buf.toString();
}
/** @return deep copy of this field
*/
public FieldGen copy( final ConstantPoolGen cp ) {
final FieldGen fg = (FieldGen) clone();
fg.setConstantPool(cp);
return fg;
}
/**
* @return Comparison strategy object
*/
public static BCELComparator getComparator() {
return bcelComparator;
}
/**
* @param comparator Comparison strategy object
*/
public static void setComparator( final BCELComparator comparator ) {
bcelComparator = comparator;
}
/**
* Return value as defined by given BCELComparator strategy.
* By default two FieldGen objects are said to be equal when
* their names and signatures are equal.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals( final @Nullable Object obj ) {
return bcelComparator.equals(this, obj);
}
/**
* Return value as defined by given BCELComparator strategy.
* By default return the hashcode of the field's name XOR signature.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return bcelComparator.hashCode(this);
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/errors/AssetGroupListingGroupFilterErrorEnumOrBuilder.java | 433 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/errors/asset_group_listing_group_filter_error.proto
package com.google.ads.googleads.v10.errors;
public interface AssetGroupListingGroupFilterErrorEnumOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.errors.AssetGroupListingGroupFilterErrorEnum)
com.google.protobuf.MessageOrBuilder {
}
| apache-2.0 |
visallo/visallo | core/core/src/main/java/org/visallo/core/ingest/video/VideoPropertyHelper.java | 1683 | package org.visallo.core.ingest.video;
import org.visallo.core.model.properties.VisalloProperties;
import org.visallo.core.model.properties.MediaVisalloProperties;
import org.visallo.core.util.RowKeyHelper;
import org.vertexium.Property;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VideoPropertyHelper {
private static final Pattern START_TIME_AND_END_TIME_PATTERN = Pattern.compile("^(.*)" + RowKeyHelper.FIELD_SEPARATOR + MediaVisalloProperties.VIDEO_FRAME.getPropertyName() + RowKeyHelper.FIELD_SEPARATOR + "([0-9]+)" + RowKeyHelper.FIELD_SEPARATOR + "([0-9]+)");
private static final Pattern START_TIME_ONLY_PATTERN = Pattern.compile("^(.*)" + RowKeyHelper.FIELD_SEPARATOR + MediaVisalloProperties.VIDEO_FRAME.getPropertyName() + RowKeyHelper.FIELD_SEPARATOR + "([0-9]+)");
public static VideoFrameInfo getVideoFrameInfoFromProperty(Property property) {
String mimeType = VisalloProperties.MIME_TYPE_METADATA.getMetadataValueOrDefault(property.getMetadata(), null);
if (mimeType == null || !mimeType.equals("text/plain")) {
return null;
}
return getVideoFrameInfo(property.getKey());
}
public static VideoFrameInfo getVideoFrameInfo(String propertyKey) {
Matcher m = START_TIME_AND_END_TIME_PATTERN.matcher(propertyKey);
if (m.find()) {
return new VideoFrameInfo(Long.parseLong(m.group(2)), Long.parseLong(m.group(3)), m.group(1));
}
m = START_TIME_ONLY_PATTERN.matcher(propertyKey);
if (m.find()) {
return new VideoFrameInfo(Long.parseLong(m.group(2)), null, m.group(1));
}
return null;
}
}
| apache-2.0 |
consp1racy/android-support-preference | support-preference/src/main/java/net/xpece/android/support/preference/Preference.java | 11552 | package net.xpece.android.support.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcelable;
import android.preference.PreferenceActivity;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;
/**
* Represents the basic Preference UI building
* block displayed by a {@link PreferenceActivity} in the form of a
* {@link ListView}. This class provides the {@link View} to be displayed in
* the activity and associates with a {@link SharedPreferences} to
* store/retrieve the preference data.
* <p>
* When specifying a preference hierarchy in XML, each element can point to a
* subclass of {@link Preference}, similar to the view hierarchy and layouts.
* <p>
* This class contains a {@code key} that will be used as the key into the
* {@link SharedPreferences}. It is up to the subclass to decide how to store
* the value.
* <p></p>
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about building a settings UI with Preferences,
* read the <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>
* guide.</p>
* </div>
*/
public class Preference extends android.support.v7.preference.Preference
implements TintablePreference, CustomIconPreference, ColorableTextPreference, LongClickablePreference {
private PreferenceTextHelper mPreferenceTextHelper;
private PreferenceIconHelper mPreferenceIconHelper;
@SuppressWarnings("WeakerAccess")
OnPreferenceLongClickListener mOnPreferenceLongClickListener;
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of Preference allows subclasses to use their own base style
* when they are inflating. For example, a {@link android.preference.CheckBoxPreference}
* constructor calls this version of the super class constructor and
* supplies {@code android.R.attr.checkBoxPreferenceStyle} for
* <var>defStyleAttr</var>. This allows the theme's checkbox preference
* style to modify all of the base preference attributes as well as the
* {@link android.preference.CheckBoxPreference} class's attributes.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources,
* {@link SharedPreferences}, etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme. Can be 0
* to not look for defaults.
* @see #Preference(Context, AttributeSet)
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public Preference(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of Preference allows subclasses to use their own base style
* when they are inflating. For example, a {@link android.preference.CheckBoxPreference}
* constructor calls this version of the super class constructor and
* supplies {@code android.R.attr.checkBoxPreferenceStyle} for
* <var>defStyleAttr</var>. This allows the theme's checkbox preference
* style to modify all of the base preference attributes as well as the
* {@link android.preference.CheckBoxPreference} class's attributes.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources,
* {@link SharedPreferences}, etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @see #Preference(Context, AttributeSet)
*/
public Preference(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
this(context, attrs, defStyleAttr, R.style.Preference_Asp_Material);
}
/**
* Constructor that is called when inflating a Preference from XML. This is
* called when a Preference is being constructed from an XML file, supplying
* attributes that were specified in the XML file. This version uses a
* default style of 0, so the only attribute values applied are those in the
* Context's Theme and the given AttributeSet.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources, {@link SharedPreferences},
* etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @see #Preference(Context, AttributeSet, int)
*/
public Preference(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.preferenceStyle);
}
/**
* Constructor to create a Preference.
*
* @param context The Context in which to store Preference values.
*/
public Preference(@NonNull Context context) {
this(context, null);
}
private void init(final @NonNull Context context, @Nullable final AttributeSet attrs, @AttrRes final int defStyleAttr, @StyleRes final int defStyleRes) {
mPreferenceIconHelper = new PreferenceIconHelper(this);
mPreferenceIconHelper.loadFromAttributes(attrs, defStyleAttr, defStyleRes);
mPreferenceTextHelper = new PreferenceTextHelper();
mPreferenceTextHelper.init(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isSupportIconPaddingEnabled() {
return mPreferenceIconHelper.isIconPaddingEnabled();
}
@Override
public void setSupportIconPaddingEnabled(boolean enabled) {
mPreferenceIconHelper.setIconPaddingEnabled(enabled);
}
@Override
public boolean isSupportIconTintEnabled() {
return mPreferenceIconHelper.isIconTintEnabled();
}
@Override
public void setSupportIconTintEnabled(boolean enabled) {
mPreferenceIconHelper.setIconTintEnabled(enabled);
}
@Override
public void setSupportIconTintList(@Nullable final ColorStateList tint) {
mPreferenceIconHelper.setTintList(tint);
}
@Nullable
@Override
public ColorStateList getSupportIconTintList() {
return mPreferenceIconHelper.getTintList();
}
@Override
public void setSupportIconTintMode(@Nullable final PorterDuff.Mode tintMode) {
mPreferenceIconHelper.setTintMode(tintMode);
}
@Nullable
@Override
public PorterDuff.Mode getSupportIconTintMode() {
return mPreferenceIconHelper.getTintMode();
}
@Override
public void setSupportIcon(@Nullable final Drawable icon) {
mPreferenceIconHelper.setIcon(icon);
}
@Override
public void setSupportIcon(@DrawableRes final int icon) {
mPreferenceIconHelper.setIcon(icon);
}
@Nullable
@Override
public Drawable getSupportIcon() {
return mPreferenceIconHelper.getIcon();
}
@Override
public void onBindViewHolder(@NonNull PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
mPreferenceTextHelper.onBindViewHolder(holder);
final boolean hasLongClickListener = hasOnPreferenceLongClickListener();
if (hasLongClickListener) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(@NonNull View v) {
return mOnPreferenceLongClickListener.onLongClick(Preference.this, v);
}
});
} else {
holder.itemView.setOnLongClickListener(null);
}
holder.itemView.setLongClickable(hasLongClickListener && isSelectable());
}
@Override
public void setTitleTextColor(@NonNull ColorStateList titleTextColor) {
mPreferenceTextHelper.setTitleTextColor(titleTextColor);
notifyChanged();
}
@Override
public void setTitleTextColor(@ColorInt int titleTextColor) {
mPreferenceTextHelper.setTitleTextColor(titleTextColor);
notifyChanged();
}
@Override
public void setTitleTextAppearance(@StyleRes int titleTextAppearance) {
mPreferenceTextHelper.setTitleTextAppearance(titleTextAppearance);
notifyChanged();
}
@Override
public void setSummaryTextColor(@NonNull ColorStateList summaryTextColor) {
mPreferenceTextHelper.setSummaryTextColor(summaryTextColor);
notifyChanged();
}
@Override
public void setSummaryTextColor(@ColorInt int summaryTextColor) {
mPreferenceTextHelper.setSummaryTextColor(summaryTextColor);
notifyChanged();
}
@Override
public void setSummaryTextAppearance(@StyleRes int summaryTextAppearance) {
mPreferenceTextHelper.setSummaryTextAppearance(summaryTextAppearance);
notifyChanged();
}
@Override
public boolean hasTitleTextColor() {
return mPreferenceTextHelper.hasTitleTextColor();
}
@Override
public boolean hasSummaryTextColor() {
return mPreferenceTextHelper.hasSummaryTextColor();
}
@Override
public boolean hasTitleTextAppearance() {
return mPreferenceTextHelper.hasTitleTextAppearance();
}
@Override
public boolean hasSummaryTextAppearance() {
return mPreferenceTextHelper.hasSummaryTextAppearance();
}
@Override
public void setOnPreferenceLongClickListener(@Nullable OnPreferenceLongClickListener listener) {
if (listener != mOnPreferenceLongClickListener) {
mOnPreferenceLongClickListener = listener;
notifyChanged();
}
}
@Override
public boolean hasOnPreferenceLongClickListener() {
return mOnPreferenceLongClickListener != null;
}
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
return super.onSaveInstanceState();
}
@Override
protected void onRestoreInstanceState(final @NonNull Parcelable state) {
super.onRestoreInstanceState(state);
}
}
| apache-2.0 |
irunninglog/api | irunninglog-spring/src/main/java/com/irunninglog/spring/security/User.java | 1197 | package com.irunninglog.spring.security;
import com.google.common.base.MoreObjects;
import com.irunninglog.api.security.IUser;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
final class User implements IUser {
private long id;
private String username;
private String token;
@Override
public IUser setId(long id) {
this.id = id;
return this;
}
@Override
public IUser setUsername(String username) {
this.username = username;
return this;
}
@Override
public IUser setToken(String token) {
this.token = token;
return this;
}
@Override
public String getUsername() {
return username;
}
@Override
public long getId() {
return id;
}
@Override
public String getToken() {
return token;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("username", username)
.add("token", token == null ? null : "*****")
.toString();
}
}
| apache-2.0 |
cping/LGame | Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/action/sprite/SpriteControls.java | 22669 | /**
* Copyright 2008 - 2015 The Loon Game Engine Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.5
*/
package loon.action.sprite;
import loon.LObject;
import loon.LSysException;
import loon.PlayerUtils;
import loon.action.ActionBind;
import loon.action.ActionTween;
import loon.action.map.Field2D;
import loon.canvas.LColor;
import loon.component.layout.Margin;
import loon.event.EventDispatcher;
import loon.font.FontSet;
import loon.font.IFont;
import loon.utils.CollectionUtils;
import loon.utils.MathUtils;
import loon.utils.ObjectMap;
import loon.utils.TArray;
import loon.utils.Easing.EasingMode;
public class SpriteControls {
public static float getChildrenHeight(Sprites s) {
float totalHeight = 0;
ISprite[] list = s._sprites;
for (int i = 0; i < list.length; i++) {
totalHeight += list[i].getHeight();
}
return totalHeight;
}
public static float getChildrenWidth(Sprites s) {
float totalWidth = 0;
ISprite[] list = s._sprites;
for (int i = 0; i < list.length; i++) {
totalWidth += list[i].getWidth();
}
return totalWidth;
}
public static float getMaxChildHeight(Sprites s) {
int maxHeight = 0;
ISprite[] list = s._sprites;
for (int i = 0; i < list.length; i++) {
maxHeight = MathUtils.max(maxHeight, (int) list[i].getHeight());
}
return maxHeight;
}
public static int getMaxChildWidth(Sprites s) {
int maxWidth = 0;
ISprite[] list = s._sprites;
for (int i = 0; i < list.length; i++) {
maxWidth = MathUtils.max(maxWidth, (int) list[i].getWidth());
}
return maxWidth;
}
private ObjectMap<ISprite, ActionTween> tweens = new ObjectMap<ISprite, ActionTween>(
CollectionUtils.INITIAL_CAPACITY);
private Margin _margin;
private final TArray<ISprite> _sprs;
public SpriteControls(ISprite... comps) {
this();
add(comps);
}
public SpriteControls(TArray<ISprite> comps) {
this();
add(comps);
}
public SpriteControls() {
this._sprs = new TArray<ISprite>();
}
public SpriteControls add(ISprite spr) {
if (spr == null) {
throw new LSysException("ISprite cannot be null.");
}
_sprs.add(spr);
return this;
}
public SpriteControls add(TArray<ISprite> comps) {
if (comps == null) {
throw new LSysException("Sprites cannot be null.");
}
_sprs.addAll(comps);
return this;
}
public SpriteControls remove(ISprite spr) {
if (spr == null) {
throw new LSysException("ISprite cannot be null.");
}
_sprs.remove(spr);
return this;
}
public SpriteControls add(ISprite... comps) {
if (comps == null) {
throw new LSysException("Sprites cannot be null.");
}
for (int i = 0, n = comps.length; i < n; i++) {
add(comps[i]);
}
return this;
}
public SpriteControls remove(ISprite... comps) {
if (comps == null) {
throw new LSysException("Sprites cannot be null.");
}
for (int i = 0, n = comps.length; i < n; i++) {
remove(comps[i]);
}
return this;
}
public SpriteControls removeAll() {
_sprs.clear();
return this;
}
public SpriteControls setSize(int w, int h) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setSize(w, h);
} else if (spr instanceof Entity) {
((Entity) spr).setSize(w, h);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setSize(w, h);
}
}
}
return this;
}
public SpriteControls setColor(LColor c) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
spr.setColor(c);
}
}
return this;
}
public SpriteControls setRunning(boolean running) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setRunning(running);
}
}
}
return this;
}
public SpriteControls alpha(float a) {
return setAlpha(a);
}
public SpriteControls setAlpha(float a) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setAlpha(a);
} else if (spr instanceof Entity) {
((Entity) spr).setAlpha(a);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setAlpha(a);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setAlpha(a);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setAlpha(a);
} else {
spr.setAlpha(a);
}
}
}
return this;
}
public SpriteControls setScale(float s) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setScale(s);
} else if (spr instanceof Entity) {
((Entity) spr).setScale(s);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setScale(s);
} else if (spr instanceof MovieClip) {
((MovieClip) spr).setScale(s, s);
} else {
spr.setScale(s, s);
}
}
}
return this;
}
public SpriteControls setScale(float sx, float sy) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setScale(sx, sy);
} else if (spr instanceof Entity) {
((Entity) spr).setScale(sx, sy);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setScale(sx, sy);
} else if (spr instanceof MovieClip) {
((MovieClip) spr).setScale(sx, sy);
} else {
spr.setScale(sx, sy);
}
}
}
return this;
}
public SpriteControls setX(float x) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setX(x);
} else if (spr instanceof Entity) {
((Entity) spr).setX(x);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setX(x);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setX(x);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setX(x);
} else {
spr.setX(x);
}
}
}
return this;
}
public SpriteControls setY(float y) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setY(y);
} else if (spr instanceof Entity) {
((Entity) spr).setY(y);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setY(y);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setY(y);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setY(y);
} else {
spr.setY(y);
}
}
}
return this;
}
public SpriteControls location(float x, float y) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setLocation(x, y);
} else if (spr instanceof Entity) {
((Entity) spr).setLocation(x, y);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setLocation(x, y);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setLocation(x, y);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setLocation(x, y);
} else {
spr.setLocation(x, y);
}
}
}
return this;
}
public SpriteControls offset(float x, float y) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
float oldX = spr.getX();
float oldY = spr.getY();
if (spr instanceof Sprite) {
((Sprite) spr).setLocation(oldX + x, oldY + y);
} else if (spr instanceof Entity) {
((Entity) spr).setLocation(oldX + x, oldY + y);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setLocation(oldX + x, oldY + y);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setLocation(oldX + x, oldY + y);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setLocation(oldX + x, oldY + y);
} else {
spr.setLocation(oldX + x, oldY + y);
}
}
}
return this;
}
public SpriteControls setWidth(int w) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setWidth(w);
} else if (spr instanceof Entity) {
((Entity) spr).setWidth(w);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setWidth(w);
} else if (spr instanceof MovieClip) {
((MovieClip) spr).setWidth(w);
}
}
}
return this;
}
public SpriteControls setHeight(int h) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setHeight(h);
} else if (spr instanceof Entity) {
((Entity) spr).setHeight(h);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setHeight(h);
} else if (spr instanceof MovieClip) {
((MovieClip) spr).setHeight(h);
}
}
}
return this;
}
public SpriteControls setFont(IFont font) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof FontSet<?>) {
((FontSet<?>) spr).setFont(font);
}
}
}
return this;
}
public SpriteControls setRotation(float r) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setRotation(r);
} else if (spr instanceof Entity) {
((Entity) spr).setRotation(r);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setRotation(r);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setRotation(r);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setRotation(r);
}
}
}
return this;
}
public SpriteControls setLocation(float dx, float dy) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setLocation(dx, dy);
} else if (spr instanceof Entity) {
((Entity) spr).setLocation(dx, dy);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setLocation(dx, dy);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setLocation(dx, dy);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setLocation(dx, dy);
}
}
}
return this;
}
public SpriteControls setLayer(int z) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setLayer(z);
} else if (spr instanceof Entity) {
((Entity) spr).setLayer(z);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setLayer(z);
} else if (spr instanceof EventDispatcher) {
((EventDispatcher) spr).setLayer(z);
} else if (spr instanceof LObject<?>) {
((LObject<?>) spr).setLayer(z);
}
}
}
return this;
}
public SpriteControls setVisible(boolean v) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
if (spr instanceof Sprite) {
((Sprite) spr).setVisible(v);
} else if (spr instanceof Entity) {
((Entity) spr).setVisible(v);
} else if (spr instanceof ActionObject) {
((ActionObject) spr).setVisible(v);
}
}
}
return this;
}
public SpriteControls clearTweens() {
for (ActionTween tween : tweens.values()) {
tween.free();
}
tweens.clear();
return this;
}
public SpriteControls startTweens() {
for (ActionTween tween : tweens.values()) {
tween.start();
}
return this;
}
public SpriteControls killTweens() {
for (ActionTween tween : tweens.values()) {
tween.kill();
}
return this;
}
public SpriteControls pauseTweens() {
for (ActionTween tween : tweens.values()) {
tween.pause();
}
return this;
}
public SpriteControls resumeTweens() {
for (ActionTween tween : tweens.values()) {
tween.resume();
}
return this;
}
public SpriteControls fadeOut(float speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (spr.getAlpha() >= 255) {
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).fadeIn(speed);
} else {
tween.fadeIn(speed);
}
} else {
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).fadeOut(speed);
} else {
tween.fadeOut(speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
}
return this;
}
public SpriteControls fadeIn(float speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (spr.getAlpha() <= 0) {
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).fadeOut(speed);
} else {
tween.fadeOut(speed);
}
} else {
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).fadeIn(speed);
} else {
tween.fadeIn(speed);
}
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls moveBy(float endX, float endY, int speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).moveBy(endX, endY, speed);
} else {
tween.moveBy(endX, endY, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls moveBy(float endX, float endY) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).moveBy(endX, endY);
} else {
tween.moveBy(endX, endY);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls moveTo(float endX, float endY, int speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).moveTo(endX, endY, speed);
} else {
tween.moveTo(endX, endY, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls moveTo(float endX, float endY, boolean flag, int speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).moveTo(endX, endY, flag, speed);
} else {
tween.moveTo(endX, endY, flag, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls moveTo(Field2D map, float endX, float endY, boolean flag, int speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).moveTo(map, endX, endY, flag, speed);
} else {
tween.moveTo(map, endX, endY, flag, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls delay(float d) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).delay(d);
} else {
tween.delay(d);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls rotateTo(float angle) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).rotateTo(angle);
} else {
tween.rotateTo(angle);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls rotateTo(float angle, float speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).rotateTo(angle, speed);
} else {
tween.rotateTo(angle, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls scaleTo(float sx, float sy) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).scaleTo(sx, sy);
} else {
tween.scaleTo(sx, sy);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls scaleTo(float sx, float sy, float speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).scaleTo(sx, sy, speed);
} else {
tween.scaleTo(sx, sy, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls showTo(boolean v) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).showTo(v);
} else {
tween.showTo(v);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls colorTo(LColor end) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).colorTo(end);
} else {
tween.colorTo(end);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls shakeTo(float shakeX, float shakeY) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).shakeTo(shakeX, shakeY);
} else {
tween.shakeTo(shakeX, shakeY);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls followTo(ActionBind bind, float follow, float speed) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).followTo(bind, follow, speed);
} else {
tween.followTo(bind, follow, speed);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls flashTo(float duration) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).flashTo(duration);
} else {
tween.flashTo(duration);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public SpriteControls transferTo(float startPos, float endPos, float duration, EasingMode mode, boolean controlX,
boolean controlY) {
for (int i = 0, n = _sprs.size; i < n; i++) {
ISprite spr = _sprs.get(i);
if (spr != null && (spr instanceof ActionBind)) {
ActionTween tween = tweens.get(spr);
if (tween == null) {
tween = PlayerUtils.set((ActionBind) spr).transferTo(startPos, endPos, duration, mode, controlX,
controlY);
} else {
tween.transferTo(startPos, endPos, duration, mode, controlX, controlY);
}
if (!tweens.containsKey(spr)) {
tweens.put(spr, tween);
}
}
}
return this;
}
public boolean isTweenFinished() {
int size = 0;
for (ActionTween tween : tweens.values()) {
if (tween.isFinished()) {
size++;
}
}
return size == tweens.size;
}
public Margin margin(float size, boolean vertical, float left, float top, float right, float bottom) {
if (_margin == null) {
_margin = new Margin(size, vertical);
} else {
_margin.setSize(size);
_margin.setVertical(vertical);
}
_margin.setMargin(left, top, right, bottom);
_margin.clear();
for (int i = 0; i < _sprs.size; i++) {
ISprite spr = _sprs.get(i);
if (spr != null) {
_margin.addChild(spr);
}
}
return _margin;
}
}
| apache-2.0 |
lastaflute/lasta-taglib | src/main/java/org/lastaflute/taglib/base/BaseTouchableInputTag.java | 7240 | /*
* Copyright 2015-2021 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.lastaflute.taglib.base;
import java.util.function.Supplier;
import javax.servlet.jsp.JspException;
/**
* @author modified by jflute (originated in Struts)
*/
public abstract class BaseTouchableInputTag extends BaseTouchableBodyTag {
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
protected String name = TaglibAttributeKey.BEAN_KEY;
protected String property; // required
protected String maxlength;
protected String rows;
protected String value;
protected String placeholder;
protected String autocomplete;
// ===================================================================================
// Start Tag
// =========
@Override
public int doStartTag() throws JspException {
write(renderInputElement());
return EVAL_BODY_BUFFERED;
}
protected String renderInputElement() throws JspException {
final StringBuilder sb = new StringBuilder();
sb.append("<").append(getTagName());
prepareBasicInputAttribute(sb);
sb.append(prepareEventHandlers());
sb.append(prepareStyles());
prepareHtml5Attribute(sb);
prepareOtherAttributes(sb);
prepareDynamicAttributes(sb);
prepareClosingInputAttribute(sb);
return sb.toString();
}
protected abstract String getTagName() throws JspException;
protected abstract void prepareBasicInputAttribute(StringBuilder sb) throws JspException;
protected void prepareHtml5Attribute(StringBuilder results) {
prepareAttribute(results, "placeholder", resolvePlaceholderResource(getPlaceholder()));
prepareAttribute(results, "autocomplete", resolveAutocompleteResource(getAutocomplete()));
}
protected abstract void prepareClosingInputAttribute(StringBuilder sb) throws JspException;
// ===================================================================================
// End Tag
// =======
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
// ===================================================================================
// Prepare Name
// ============
@Override
protected String prepareName() throws JspException {
if (property == null) {
return null;
}
if (indexed) {
final StringBuilder results = new StringBuilder();
prepareIndex(results, name);
results.append(property);
return results.toString();
}
return property;
}
// ===================================================================================
// Release
// =======
@Override
public void release() {
super.release();
name = TaglibAttributeKey.BEAN_KEY;
property = null;
maxlength = null;
rows = null;
value = null;
placeholder = null;
autocomplete = null;
}
// ===================================================================================
// Enhance
// =======
protected String resolvePlaceholderResource(String placeholder) {
return getEnhanceLogic().resolveLabelResource(pageContext, placeholder, new Supplier<Object>() {
public Object get() {
return buildErrorIdentity();
}
});
}
protected String resolveAutocompleteResource(String label) {
return getEnhanceLogic().resolveAutocompleteResource(pageContext, label, new Supplier<Object>() {
public Object get() {
return buildErrorIdentity();
}
});
}
// ===================================================================================
// Enhance
// =======
@Override
public void setTitle(String title) { // for label use
final TaglibEnhanceLogic tablibLogic = getEnhanceLogic();
super.setTitle(tablibLogic.resolveLabelResource(pageContext, title, new Supplier<Object>() {
public Object get() {
return buildErrorIdentity();
}
}));
}
// ===================================================================================
// Accessor
// ========
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMaxlength() {
return maxlength;
}
public void setMaxlength(String maxlength) {
this.maxlength = maxlength;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getRows() {
return rows;
}
public void setRows(String rows) {
this.rows = rows;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public String getAutocomplete() {
return autocomplete;
}
public void setAutocomplete(String autocomplete) {
this.autocomplete = autocomplete;
}
}
| apache-2.0 |
ok2c/httpclient | httpclient5-testing/src/test/java/org/apache/hc/client5/testing/external/HttpAsyncClientCompatibilityTest.java | 16231 | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.testing.external;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.Credentials;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
import org.apache.hc.core5.http.HeaderElements;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.TextUtils;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
public class HttpAsyncClientCompatibilityTest {
public static void main(final String... args) throws Exception {
final HttpAsyncClientCompatibilityTest[] tests = new HttpAsyncClientCompatibilityTest[] {
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("localhost", 8080, "http"), null, null),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("test-httpd", 8080, "http"), new HttpHost("localhost", 8888), null),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("test-httpd", 8080, "http"), new HttpHost("localhost", 8889),
new UsernamePasswordCredentials("squid", "nopassword".toCharArray())),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("localhost", 8443, "https"), null, null),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("test-httpd", 8443, "https"), new HttpHost("localhost", 8888), null),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_1_1,
new HttpHost("test-httpd", 8443, "https"), new HttpHost("localhost", 8889),
new UsernamePasswordCredentials("squid", "nopassword".toCharArray())),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_2_0,
new HttpHost("localhost", 8080, "http"), null, null),
new HttpAsyncClientCompatibilityTest(
HttpVersion.HTTP_2_0,
new HttpHost("localhost", 8443, "https"), null, null)
};
for (final HttpAsyncClientCompatibilityTest test: tests) {
try {
test.execute();
} finally {
test.shutdown();
}
}
}
private static final Timeout TIMEOUT = Timeout.ofSeconds(5);
private final HttpVersion protocolVersion;
private final HttpHost target;
private final HttpHost proxy;
private final BasicCredentialsProvider credentialsProvider;
private final PoolingAsyncClientConnectionManager connManager;
private final CloseableHttpAsyncClient client;
HttpAsyncClientCompatibilityTest(
final HttpVersion protocolVersion,
final HttpHost target,
final HttpHost proxy,
final Credentials proxyCreds) throws Exception {
this.protocolVersion = protocolVersion;
this.target = target;
this.proxy = proxy;
this.credentialsProvider = new BasicCredentialsProvider();
final RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy)
.build();
if (proxy != null && proxyCreds != null) {
this.credentialsProvider.setCredentials(new AuthScope(proxy), proxyCreds);
}
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(getClass().getResource("/test-ca.keystore"), "nopassword".toCharArray()).build();
this.connManager = PoolingAsyncClientConnectionManagerBuilder.create()
.setTlsStrategy(new DefaultClientTlsStrategy(sslContext))
.build();
this.client = HttpAsyncClients.custom()
.setVersionPolicy(this.protocolVersion == HttpVersion.HTTP_2 ? HttpVersionPolicy.FORCE_HTTP_2 : HttpVersionPolicy.FORCE_HTTP_1)
.setConnectionManager(this.connManager)
.setProxy(this.proxy)
.setDefaultRequestConfig(requestConfig)
.build();
}
void shutdown() throws Exception {
client.close();
}
enum TestResult {OK, NOK}
private void logResult(final TestResult result, final HttpRequest request, final String message) {
final StringBuilder buf = new StringBuilder();
buf.append(result);
if (buf.length() == 2) {
buf.append(" ");
}
buf.append(": ").append(protocolVersion).append(" ").append(target);
if (proxy != null) {
buf.append(" via ").append(proxy);
}
buf.append(": ");
buf.append(request.getMethod()).append(" ").append(request.getRequestUri());
if (message != null && !TextUtils.isBlank(message)) {
buf.append(" -> ").append(message);
}
System.out.println(buf.toString());
}
void execute() throws Exception {
client.start();
// Initial ping
{
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final SimpleHttpRequest options = SimpleHttpRequests.OPTIONS.create(target, "*");
final Future<SimpleHttpResponse> future = client.execute(options, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, options, Objects.toString(response.getFirstHeader("server")));
} else {
logResult(TestResult.NOK, options, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, options, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, options, "(time out)");
}
}
// Basic GET requests
{
connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS);
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final String[] requestUris = new String[] {"/", "/news.html", "/status.html"};
for (final String requestUri: requestUris) {
final SimpleHttpRequest httpGet = SimpleHttpRequests.GET.create(target, requestUri);
final Future<SimpleHttpResponse> future = client.execute(httpGet, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, httpGet, "200");
} else {
logResult(TestResult.NOK, httpGet, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGet, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGet, "(time out)");
}
}
}
// Wrong target auth scope
{
connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS);
credentialsProvider.setCredentials(
new AuthScope("http", "otherhost", -1, "Restricted Files", null),
new UsernamePasswordCredentials("testuser", "nopassword".toCharArray()));
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final SimpleHttpRequest httpGetSecret = SimpleHttpRequests.GET.create(target, "/private/big-secret.txt");
final Future<SimpleHttpResponse> future = client.execute(httpGetSecret, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_UNAUTHORIZED) {
logResult(TestResult.OK, httpGetSecret, "401 (wrong target auth scope)");
} else {
logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGetSecret, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGetSecret, "(time out)");
}
}
// Wrong target credentials
{
connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS);
credentialsProvider.setCredentials(
new AuthScope(target),
new UsernamePasswordCredentials("testuser", "wrong password".toCharArray()));
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final SimpleHttpRequest httpGetSecret = SimpleHttpRequests.GET.create(target, "/private/big-secret.txt");
final Future<SimpleHttpResponse> future = client.execute(httpGetSecret, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_UNAUTHORIZED) {
logResult(TestResult.OK, httpGetSecret, "401 (wrong target creds)");
} else {
logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGetSecret, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGetSecret, "(time out)");
}
}
// Correct target credentials
{
connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS);
credentialsProvider.setCredentials(
new AuthScope(target),
new UsernamePasswordCredentials("testuser", "nopassword".toCharArray()));
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final SimpleHttpRequest httpGetSecret = SimpleHttpRequests.GET.create(target, "/private/big-secret.txt");
final Future<SimpleHttpResponse> future = client.execute(httpGetSecret, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, httpGetSecret, "200 (correct target creds)");
} else {
logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGetSecret, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGetSecret, "(time out)");
}
}
// Correct target credentials (no keep-alive)
if (protocolVersion.lessEquals(HttpVersion.HTTP_1_1))
{
connManager.closeIdle(TimeValue.NEG_ONE_MILLISECONDS);
credentialsProvider.setCredentials(
new AuthScope(target),
new UsernamePasswordCredentials("testuser", "nopassword".toCharArray()));
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
final SimpleHttpRequest httpGetSecret = SimpleHttpRequests.GET.create(target, "/private/big-secret.txt");
httpGetSecret.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
final Future<SimpleHttpResponse> future = client.execute(httpGetSecret, context, null);
try {
final SimpleHttpResponse response = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, httpGetSecret, "200 (correct target creds / no keep-alive)");
} else {
logResult(TestResult.NOK, httpGetSecret, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGetSecret, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGetSecret, "(time out)");
}
}
}
}
| apache-2.0 |
UweTrottmann/QuickDic-Dictionary | jars/icu4j-4_8_1_1/main/tests/core/src/com/ibm/icu/dev/test/serializable/CoverageTest.java | 6987 | //##header
/*
*******************************************************************************
* Copyright (C) 2005-2011, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
*/
package com.ibm.icu.dev.test.serializable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Enumeration;
import com.ibm.icu.impl.URLHandler;
/**
* @author emader
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class CoverageTest extends CompatibilityTest implements URLHandler.URLVisitor
{
private static Class serializable;
public void init() {
try {
serializable = Class.forName("java.io.Serializable");
} catch (Exception e) {
// we're in deep trouble...
warnln("Woops! Can't get class info for Serializable.");
}
}
private Target head = new Target(null);
private Target tail = head;
private String path;
public CoverageTest()
{
this(null);
}
public CoverageTest(String path)
{
this.path = path;
if (path != null) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
private void writeFile(String className, byte bytes[])
{
File file = new File(path + File.separator + className + ".dat");
FileOutputStream stream;
try {
stream = new FileOutputStream(file);
stream.write(bytes);
stream.close();
} catch (Exception e) {
System.out.print(" - can't write file!");
}
}
private void add(String className, int classModifiers, byte bytes[])
{
CoverageTarget newTarget = new CoverageTarget(className, classModifiers, bytes);
tail.setNext(newTarget);
tail = newTarget;
}
public class CoverageTarget extends HandlerTarget
{
private byte bytes[];
private int modifiers;
public CoverageTarget(String className, int classModifiers, byte bytes[])
{
super(className, bytes == null? null : new ByteArrayInputStream(bytes));
this.bytes = bytes;
modifiers = classModifiers;
}
public boolean validate()
{
return super.validate() || Modifier.isAbstract(modifiers);
}
public void execute() throws Exception
{
Class c = Class.forName(name);
try {
/*Field uid = */c.getDeclaredField("serialVersionUID");
} catch (Exception e) {
errln("No serialVersionUID");
}
if (inputStream == null) {
params.testCount += 1;
} else {
if (path != null) {
writeFile(name, bytes);
}
super.execute();
}
}
}
public void visit(String str)
{
if(serializable==null){
return;
}
int ix = str.lastIndexOf(".class");
if (ix >= 0) {
String className = "com.ibm.icu" + str.substring(0, ix).replace('/', '.');
// Skip things in com.ibm.icu.dev; they're not relevant.
if (className.startsWith("com.ibm.icu.dev.")) {
return;
}
try {
Class c = Class.forName(className);
int m = c.getModifiers();
if (!c.isEnum() && serializable.isAssignableFrom(c)) {
if (Modifier.isPublic(m) && !Modifier.isInterface(m)) {
SerializableTest.Handler handler = SerializableTest.getHandler(className);
if (handler != null) {
Object objectsOut[] = handler.getTestObjects();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
try {
out.writeObject(objectsOut);
out.close();
byteOut.close();
} catch (IOException e) {
warnln("Error writing test objects: " + e.toString());
return;
}
add(className, m, byteOut.toByteArray());
} else {
add(className, m, null);
}
}
}
} catch (Exception e) {
e.printStackTrace();
warnln("coverage of " + className + ": " + e.toString());
} catch (Throwable e) {
e.printStackTrace();
warnln("coverage of " + className + ": " + e.toString());
}
}
}
protected Target getTargets(String targetName)
{
if (System.getSecurityManager() != null) {
// This test won't run under a security manager
// TODO: Is the above statement really true?
// We probably need to set up the security policy properly
// for writing/reading serialized data.
return null;
}
if(serializable==null){
init();
}
try {
Enumeration<URL> urlEnum = getClass().getClassLoader().getResources("com/ibm/icu");
while (urlEnum.hasMoreElements()) {
URL url = urlEnum.nextElement();
URLHandler handler = URLHandler.get(url);
if (handler == null) {
//#if defined(ECLIPSE)
//## logln("Unsupported URL: " + url);
//#else
errln("Unsupported URL: " + url);
//#endif
continue;
}
handler.guide(this, true, false);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return head.getNext();
}
public static void main(String[] args)
{
CoverageTest test = new CoverageTest();
test.run(args);
}
}
| apache-2.0 |
jeichler/junit-drools | src/main/java/com/github/jeichler/junit/drools/session/DroolsSession.java | 322 | package com.github.jeichler.junit.drools.session;
public interface DroolsSession<T> {
static final String IDENTIFIER_NUMBER_OF_FIRED_RULES = "numberOfFiredRules";
void fireAllRules();
void startProcess(String processId);
void insert(Object... objects);
int getNumberOfFiredRules();
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-events/src/main/java/com/amazonaws/services/cloudwatchevents/model/transform/UntagResourceResultJsonUnmarshaller.java | 1619 | /*
* 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.cloudwatchevents.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.cloudwatchevents.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UntagResourceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UntagResourceResultJsonUnmarshaller implements Unmarshaller<UntagResourceResult, JsonUnmarshallerContext> {
public UntagResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
UntagResourceResult untagResourceResult = new UntagResourceResult();
return untagResourceResult;
}
private static UntagResourceResultJsonUnmarshaller instance;
public static UntagResourceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UntagResourceResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
lincmin/FirstReactApp | android/app/src/main/java/com/firstreactapp/MainActivity.java | 371 | package com.firstreactapp;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "FirstReactApp";
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-s3control/src/main/java/com/amazonaws/services/s3control/model/UpdateJobStatusResult.java | 7368 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.s3control.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/UpdateJobStatus" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateJobStatusResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.services.s3control.S3ControlResponseMetadata> implements
Serializable, Cloneable {
/**
* <p>
* The ID for the job whose status was updated.
* </p>
*/
private String jobId;
/**
* <p>
* The current status for the specified job.
* </p>
*/
private String status;
/**
* <p>
* The reason that the specified job's status was updated.
* </p>
*/
private String statusUpdateReason;
/**
* <p>
* The ID for the job whose status was updated.
* </p>
*
* @param jobId
* The ID for the job whose status was updated.
*/
public void setJobId(String jobId) {
this.jobId = jobId;
}
/**
* <p>
* The ID for the job whose status was updated.
* </p>
*
* @return The ID for the job whose status was updated.
*/
public String getJobId() {
return this.jobId;
}
/**
* <p>
* The ID for the job whose status was updated.
* </p>
*
* @param jobId
* The ID for the job whose status was updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateJobStatusResult withJobId(String jobId) {
setJobId(jobId);
return this;
}
/**
* <p>
* The current status for the specified job.
* </p>
*
* @param status
* The current status for the specified job.
* @see JobStatus
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The current status for the specified job.
* </p>
*
* @return The current status for the specified job.
* @see JobStatus
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The current status for the specified job.
* </p>
*
* @param status
* The current status for the specified job.
* @return Returns a reference to this object so that method calls can be chained together.
* @see JobStatus
*/
public UpdateJobStatusResult withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* The current status for the specified job.
* </p>
*
* @param status
* The current status for the specified job.
* @return Returns a reference to this object so that method calls can be chained together.
* @see JobStatus
*/
public UpdateJobStatusResult withStatus(JobStatus status) {
this.status = status.toString();
return this;
}
/**
* <p>
* The reason that the specified job's status was updated.
* </p>
*
* @param statusUpdateReason
* The reason that the specified job's status was updated.
*/
public void setStatusUpdateReason(String statusUpdateReason) {
this.statusUpdateReason = statusUpdateReason;
}
/**
* <p>
* The reason that the specified job's status was updated.
* </p>
*
* @return The reason that the specified job's status was updated.
*/
public String getStatusUpdateReason() {
return this.statusUpdateReason;
}
/**
* <p>
* The reason that the specified job's status was updated.
* </p>
*
* @param statusUpdateReason
* The reason that the specified job's status was updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateJobStatusResult withStatusUpdateReason(String statusUpdateReason) {
setStatusUpdateReason(statusUpdateReason);
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 (getJobId() != null)
sb.append("JobId: ").append(getJobId()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getStatusUpdateReason() != null)
sb.append("StatusUpdateReason: ").append(getStatusUpdateReason());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateJobStatusResult == false)
return false;
UpdateJobStatusResult other = (UpdateJobStatusResult) obj;
if (other.getJobId() == null ^ this.getJobId() == null)
return false;
if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getStatusUpdateReason() == null ^ this.getStatusUpdateReason() == null)
return false;
if (other.getStatusUpdateReason() != null && other.getStatusUpdateReason().equals(this.getStatusUpdateReason()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getStatusUpdateReason() == null) ? 0 : getStatusUpdateReason().hashCode());
return hashCode;
}
@Override
public UpdateJobStatusResult clone() {
try {
return (UpdateJobStatusResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
yangfuhai/jboot | src/main/java/io/jboot/wechat/WechatSupport.java | 926 | /**
* Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.wechat;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import io.jboot.components.cache.support.JbootAccessTokenCache;
public class WechatSupport {
public void autoSupport() {
ApiConfigKit.setAccessTokenCache(new JbootAccessTokenCache());
}
}
| apache-2.0 |
yongkun/flume-0.9.3-cdh3u0-rakuten | src/java/com/cloudera/flume/agent/durability/NaiveFileWALDeco.java | 11828 | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.flume.agent.durability;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudera.flume.agent.FlumeNode;
import com.cloudera.flume.conf.Context;
import com.cloudera.flume.conf.FlumeConfiguration;
import com.cloudera.flume.conf.LogicalNodeContext;
import com.cloudera.flume.conf.SinkFactory.SinkDecoBuilder;
import com.cloudera.flume.core.Driver;
import com.cloudera.flume.core.DriverListener;
import com.cloudera.flume.core.Event;
import com.cloudera.flume.core.EventSink;
import com.cloudera.flume.core.EventSinkDecorator;
import com.cloudera.flume.core.EventSource;
import com.cloudera.flume.core.connector.DirectDriver;
import com.cloudera.flume.handlers.debug.LazyOpenDecorator;
import com.cloudera.flume.handlers.endtoend.AckChecksumInjector;
import com.cloudera.flume.handlers.endtoend.AckListener;
import com.cloudera.flume.handlers.rolling.RollSink;
import com.cloudera.flume.handlers.rolling.RollTrigger;
import com.cloudera.flume.handlers.rolling.TimeTrigger;
import com.cloudera.flume.reporter.ReportEvent;
import com.cloudera.flume.reporter.Reportable;
import com.google.common.base.Preconditions;
/**
* This decorator does write ahead logging using the NaiveFileWAL mechanism. It
* has a subordinate thread that drains the events that have been written to
* disk. Latches are used to maintain open and close semantics.
*/
public class NaiveFileWALDeco extends EventSinkDecorator<EventSink> {
static final Logger LOG = LoggerFactory.getLogger(NaiveFileWALDeco.class);
final WALManager walman;
final RollTrigger trigger;
final AckListener queuer;
final EventSinkDecorator<EventSink> drainSink;
final long checkMs;
RollSink input;
EventSource drainSource = null;
Driver conn;
Context ctx;
final AckListener al;
CountDownLatch completed = null; // block close until subthread is completes
CountDownLatch started = null; // blocks open until subthread is started
volatile IOException lastExn = null;
public NaiveFileWALDeco(Context ctx, EventSink s, final WALManager walman,
RollTrigger t, AckListener al, long checkMs) {
super(s);
this.ctx = ctx;
this.walman = walman;
this.trigger = t;
this.queuer = new AckListener.Empty();
this.al = al;
this.drainSink = new LazyOpenDecorator<EventSink>(
new AckChecksumRegisterer<EventSink>(s, al));
this.checkMs = checkMs;
}
public static class AckChecksumRegisterer<S extends EventSink> extends
EventSinkDecorator<S> {
AckListener q;
public AckChecksumRegisterer(S s, AckListener q) {
super(s);
this.q = q;
}
@Override
public void append(Event e) throws IOException, InterruptedException {
super.append(e);
// (TODO) this could actually verify check sum correctness, but it is
// generated locally
// check for and attempt to register interest in tag's checksum
byte[] btyp = e.get(AckChecksumInjector.ATTR_ACK_TYPE);
if (btyp == null) {
// nothing more to do
return;
}
byte[] btag = e.get(AckChecksumInjector.ATTR_ACK_TAG);
if (Arrays.equals(btyp, AckChecksumInjector.CHECKSUM_STOP)) {
String k = new String(btag);
LOG.info("Registering interest in checksum group called '" + k + "'");
// Checksum stop marker: register interest
q.end(k);
return;
}
}
}
/**
* TODO(jon): double check that the synchronization is appropriate here
*/
@Override
public synchronized void append(Event e) throws IOException,
InterruptedException {
Preconditions.checkNotNull(sink, "NaiveFileWALDeco was invalid!");
Preconditions.checkState(isOpen.get(),
"NaiveFileWALDeco not open for append");
if (lastExn != null) {
throw lastExn;
}
input.append(e);
}
@Override
public synchronized void close() throws IOException, InterruptedException {
Preconditions.checkNotNull(sink,
"Attmpted to close a null NaiveFileWALDeco");
LOG.debug("Closing NaiveFileWALDeco");
input.close(); // prevent new data from entering.
walman.stopDrains();
try {
LOG.debug("Waiting for subthread to complete .. ");
int maxNoProgressTime = 10;
ReportEvent rpt = sink.getMetrics();
Long levts = rpt.getLongMetric(EventSink.Base.R_NUM_EVENTS);
long evts = (levts == null) ? 0 : levts;
int count = 0;
while (true) {
if (conn.join(500)) {
// driver successfully completed
LOG.debug(".. subthread to completed");
break;
}
// driver still running, did we make progress?
ReportEvent rpt2 = sink.getMetrics();
Long levts2 = rpt2.getLongMetric(EventSink.Base.R_NUM_EVENTS);
long evts2 = (levts2 == null) ? 0 : levts;
if (evts2 > evts) {
// progress is being made, reset counts
count = 0;
evts = evts2;
LOG.info("Closing disk failover log, subsink still making progress");
continue;
}
// no progress.
count++;
LOG.info("Attempt " + count
+ " with no progress being made on disk failover subsink");
if (count >= maxNoProgressTime) {
LOG.warn("DFO drain thread was not making progress, forcing close");
conn.cancel();
break;
}
}
} catch (InterruptedException e) {
LOG.error("WAL drain thread interrupted", e);
}
if (drainSource != null) {
drainSource.close();
}
// This sets isOpen == false
super.close();
try {
completed.await();
} catch (InterruptedException e) {
LOG.error("WAL drain thread flush interrupted", e);
}
// This is throws an exception thrown by the subthread.
if (lastExn != null) {
IOException tmp = lastExn;
lastExn = null;
LOG.warn("Throwing exception from subthread");
throw tmp;
}
LOG.debug("Closed DiskFailoverDeco");
}
@Override
synchronized public void open() throws IOException, InterruptedException {
Preconditions.checkNotNull(sink,
"Attempted to open a null NaiveFileWALDeco subsink");
LOG.debug("Opening NaiveFileWALDeco");
input = walman.getAckingSink(ctx, trigger, queuer, checkMs);
drainSource = walman.getEventSource();
// TODO (jon) catch exceptions here and close them before rethrowing
// When this is open the sink is open from the callers point of view and we
// can return.
drainSource.open();
drainSink.open();
input.open();
started = new CountDownLatch(1);
completed = new CountDownLatch(1);
conn = new DirectDriver("naive file wal transmit", drainSource, drainSink);
/**
* Do not take the lock on NaiveFileWALDeco.this in the connector listener,
* as it's possible to deadlock within e.g. close()
*/
conn.registerListener(new DriverListener.Base() {
@Override
public void fireStarted(Driver c) {
started.countDown();
}
@Override
public void fireStopped(Driver c) {
completed.countDown();
}
@Override
public void fireError(Driver c, Exception ex) {
LOG.error("unexpected error with NaiveFileWALDeco", ex);
lastExn = (ex instanceof IOException) ? (IOException) ex
: new IOException(ex);
try {
conn.getSource().close();
conn.getSink().close();
} catch (IOException e) {
LOG.error("Error closing", e);
} catch (InterruptedException e) {
// TODO reconsider this
LOG.error("fireError interrupted", e);
}
completed.countDown();
LOG.info("Error'ed Connector closed " + conn);
}
});
conn.start();
try {
started.await();
} catch (InterruptedException e) {
LOG.error("Unexpected error waiting", e);
throw new IOException(e);
}
LOG.debug("Opened NaiveFileWALDeco");
Preconditions.checkNotNull(sink);
Preconditions.checkState(!isOpen.get());
isOpen.set(true);
}
public void setSink(EventSink sink) {
this.sink = sink;
// TODO get rid of this cast.
this.drainSink.setSink(new LazyOpenDecorator<EventSink>(
new AckChecksumRegisterer<EventSink>(sink, al)));
}
public synchronized boolean rotate() throws InterruptedException {
return input.rotate();
}
public boolean isEmpty() {
return walman.isEmpty();
}
/**
* End to end ack version, with logical node context (to isolate wals.)
* **/
public static SinkDecoBuilder builderEndToEndDir() {
return new SinkDecoBuilder() {
@Override
public EventSinkDecorator<EventSink> build(Context context,
String... argv) {
Preconditions.checkArgument(argv.length <= 3,
"usage: ackedWriteAhead[(maxMillis,walnode,checkMs)]");
FlumeConfiguration conf = FlumeConfiguration.get();
long delayMillis = conf.getAgentLogMaxAge();
if (argv.length >= 1) {
delayMillis = Long.parseLong(argv[0]);
}
// TODO (jon) this will cause problems with multiple nodes in same JVM
FlumeNode node = FlumeNode.getInstance();
String walnode = context.getValue(LogicalNodeContext.C_LOGICAL);
if (argv.length >= 2) {
walnode = argv[1];
}
Preconditions.checkArgument(walnode != null,
"Context does not have a logical node name");
long checkMs = 250; // TODO replace with config var;
if (argv.length >= 3) {
checkMs = Long.parseLong(argv[2]);
}
// TODO (jon) this is going to be unsafe because it creates before open.
// This needs to be pushed into the logic of the decorator
WALManager walman = node.getAddWALManager(walnode);
return new NaiveFileWALDeco(context, null, walman, new TimeTrigger(
delayMillis), node.getAckChecker().getAgentAckQueuer(), checkMs);
}
};
}
@Override
public String getName() {
return "NaiveFileWAL";
}
@Deprecated
@Override
public ReportEvent getReport() {
ReportEvent rpt = super.getReport();
ReportEvent walRpt = walman.getMetrics();
rpt.merge(walRpt);
ReportEvent sinkReport = sink.getReport();
rpt.hierarchicalMerge(getName(), sinkReport);
return rpt;
}
@Override
public ReportEvent getMetrics() {
ReportEvent rpt = super.getMetrics();
return rpt;
}
public Map<String, Reportable> getSubMetrics() {
Map<String, Reportable> map = new HashMap<String, Reportable>();
map.put(walman.getName(), walman);
map.put("drainSink." + sink.getName(), sink);
if (drainSource != null) {
// careful, drainSource can be null if deco not opened yet
map.put("drainSource." + drainSource.getName(), drainSource);
}
return map;
}
}
| apache-2.0 |
besom/bbossgroups-mvn | bboss_security/src/main/java/de/flexiprovider/pqc/hbc/gmss/GMSSPublicKey.java | 3247 | package de.flexiprovider.pqc.hbc.gmss;
import codec.asn1.ASN1Null;
import codec.asn1.ASN1ObjectIdentifier;
import codec.asn1.ASN1Type;
import de.flexiprovider.api.keys.PublicKey;
import de.flexiprovider.common.util.ASN1Tools;
import de.flexiprovider.common.util.ByteUtils;
/**
* This class implements the GMSS public key and is usually initiated by the <a
* href="GMSSKeyPairGenerator">GMSSKeyPairGenerator</a>.
*
* @author Sebastian Blume
*
* @see de.flexiprovider.pqc.hbc.gmss.GMSSKeyPairGenerator
* @see de.flexiprovider.pqc.hbc.gmss.GMSSPublicKeySpec
*/
public class GMSSPublicKey extends PublicKey {
/**
* The GMSS public key
*/
private byte[] publicKeyBytes;
/**
* The GMSSParameterset
*/
private GMSSParameterset gmssParameterset;
/**
* The constructor
*
* @param pub
* a raw GMSS public key
*
* @param gmssParameterset
* an instance of GMSS Parameterset
*
* @see de.flexiprovider.pqc.hbc.gmss.GMSSKeyPairGenerator
*/
protected GMSSPublicKey(byte[] pub, GMSSParameterset gmssParameterset) {
this.gmssParameterset = gmssParameterset;
this.publicKeyBytes = pub;
}
/**
* The constructor
*
* @param keySpec
* a GMSS key specification
*/
protected GMSSPublicKey(GMSSPublicKeySpec keySpec) {
this(keySpec.getPublicKey(), keySpec.getGMSSParameterset());
}
/**
* Returns the name of the algorithm
*
* @return "GMSS"
*/
public String getAlgorithm() {
return "GMSS";
}
/**
* @return the OID to encode in the SubjectPublicKeyInfo structure
*/
protected ASN1ObjectIdentifier getOID() {
return new ASN1ObjectIdentifier(GMSSKeyFactory.OID);
}
/**
* @return the algorithm parameters to encode in the SubjectPublicKeyInfo
* structure
*/
protected ASN1Type getAlgParams() {
return new ASN1Null();
}
/**
* @return the keyData to encode in the SubjectPublicKeyInfo structure
*/
protected byte[] getKeyData() {
GMSSPublicKeyASN1 key = new GMSSPublicKeyASN1(publicKeyBytes,
gmssParameterset);
return ASN1Tools.derEncode(key);
}
/**
* @return The GMSS public key byte array
*/
protected byte[] getPublicKeyBytes() {
return publicKeyBytes;
}
/**
* @return The GMSS Parameterset
*/
protected GMSSParameterset getParameterset() {
return gmssParameterset;
}
/**
* Returns a human readable form of the GMSS public key
*
* @return A human readable form of the GMSS public key
*/
public String toString() {
String out = "GMSS public key : "
+ ByteUtils.toHexString(publicKeyBytes) + "\n"
+ "Height of Trees: \n";
for (int i = 0; i < gmssParameterset.getHeightOfTrees().length; i++) {
out = out + "Layer " + i + " : "
+ gmssParameterset.getHeightOfTrees()[i]
+ " WinternitzParameter: "
+ gmssParameterset.getWinternitzParameter()[i] + " K: "
+ gmssParameterset.getK()[i] + "\n";
}
return out;
}
}
| apache-2.0 |
hymanme/MaterialHome | app/src/main/java/com/hymane/materialhome/bean/http/ebook/HotReview.java | 7765 | package com.hymane.materialhome.bean.http.ebook;
import java.util.ArrayList;
import java.util.List;
/**
* Author :hymanme
* Email :hymanme@163.com
* Create at 2016/9/28
* Description:
*/
public class HotReview extends Base {
/**
* _id : 5652c048a003ea7f55f74b78
* rating : 3
* content : 本人试毒500,前面还好可是后面真是索然无味,猪脚最开始魂魄寄存在造化玉碟碎片之中,后来结识盘古,但是连比较弱的混沌神魔都打不过的货色竟然帮助盘古开天?盘古就给他精血融合,那么为什么精血化形的12祖巫一点感应都没有?在盘古身陨是将50道鸿蒙紫气其中那遁去的一道.也就是那大道50中的1给了猪脚。可是之后的章节中直到猪脚成圣都再也未有看到,造化玉碟碎片作为猪脚混沌中的寄身之处也是莫名其妙不见鸟?猪脚作为圣人竟然不知道妻子玲玲前世自己死了之后发生了什么?他们可是夫妻有因果气运相连的啊,最最看不懂的是。为什么东皇太一是哥哥啊为什么他是妖皇,帝俊怎么就成弟弟了?为什么帝俊用的是混沌钟,为什么巫妖结仇仅仅是东皇太一帝俊出生散发的太阳真火本源被祝融吸收一些就在以后成为死敌?猪脚创下造化一脉自称造化天尊可是你造化一脉到底是什么教义?巫妖两族都杀戮不少人族可是为什么妖族能发现人族元神精魄可破巫族肉身,巫族就没有任何发现?要知道当时女娲以成圣,也就是说妖族当时在力量还是气运上都要强于巫族,那么天道会不帮巫族?不帮巫族等到巫妖大战如何同妖族两败俱伤?
* 其实前面龙凤三族的时代我竟然没有看到皇天,阴阳,颠倒,五行,等等这些大神成名?直到猪脚讲道,杀罗睺才冒泡2次,这些人不牛逼?当时的时代不是三族主宰,应该是他们称霸,直到大战罗睺陨落了才轮到三族!
* 总得来说此书不该有的漏洞实在有点多,想那原始天尊又不是没看到猪脚力抗鸿钧不落下风,那么为何他数次敢对猪脚冷眼热潮?他就这么傻?
* 此书人物刻画实在模糊。故事情节和其他洪荒小说没什么不同。虽然在其中加了一些东西,但说实话那实在有些碍眼!作者好像对两性相处写的并不是那么好,那请你不要在加上两人的甜蜜生活了,我看着真心胃呕,蛋疼
* title : 越到后面越是索然无味
* author : {"_id":"534a355422f7a7c71f0034d7","avatar":"/avatar/77/52/7752998834f5e632a404622f485343eb","nickname":"我就是静静","type":"normal","lv":8,"gender":"female"}
* helpful : {"yes":304,"total":241,"no":63}
* likeCount : 16
* state : normal
* updated : 2016-08-02T09:49:36.719Z
* created : 2015-11-23T07:29:12.396Z
* commentCount : 141
*/
private List<Reviews> reviews;
public HotReview() {
this.reviews = new ArrayList<>();
}
public List<Reviews> getReviews() {
return reviews;
}
public void setReviews(List<Reviews> reviews) {
this.reviews = reviews;
}
public static class Reviews {
private String _id;
private int rating;
private String content;
private String title;
/**
* _id : 534a355422f7a7c71f0034d7
* avatar : /avatar/77/52/7752998834f5e632a404622f485343eb
* nickname : 我就是静静
* type : normal
* lv : 8
* gender : female
*/
private Author author;
/**
* yes : 304
* total : 241
* no : 63
*/
private Helpful helpful;
private int likeCount;
private String state;
private String updated;
private String created;
private int commentCount;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Helpful getHelpful() {
return helpful;
}
public void setHelpful(Helpful helpful) {
this.helpful = helpful;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public int getCommentCount() {
return commentCount;
}
public void setCommentCount(int commentCount) {
this.commentCount = commentCount;
}
public static class Author {
private String _id;
private String avatar;
private String nickname;
private String type;
private int lv;
private String gender;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getLv() {
return lv;
}
public void setLv(int lv) {
this.lv = lv;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
public static class Helpful {
private int yes;
private int total;
private int no;
public int getYes() {
return yes;
}
public void setYes(int yes) {
this.yes = yes;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
}
}
| apache-2.0 |
LightSun/android-common-util-light | QuickAdapter/adapter/src/main/java/com/heaven7/adapter/drag/ItemTouchAdapterDelegate.java | 329 | package com.heaven7.adapter.drag;
/**
* start on 2019/5/6.
* @author heaven7
* @since 2.0.0
*/
public interface ItemTouchAdapterDelegate {
/**
* called on move target position item to another position
* @param from the from position
* @param to the to position
*/
void move(int from, int to);
}
| apache-2.0 |
sdgdsffdsfff/rsf | rsf-core/src/main/java/net/hasor/rsf/rpc/warp/RsfRequestLocal.java | 1400 | /*
* Copyright 2008-2009 the original 赵永春(zyc@hasor.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.hasor.rsf.rpc.warp;
import net.hasor.rsf.RsfRequest;
/**
* {@link RsfRequest}接口包装器(当前线程绑定)。
* @version : 2014年10月25日
* @author 赵永春(zyc@hasor.net)
*/
public class RsfRequestLocal extends AbstractRsfRequestWarp {
private static final ThreadLocal<RsfRequest> LOCAL_REQUEST = new ThreadLocal<RsfRequest>();
@Override
protected final RsfRequest getRsfRequest() {
return LOCAL_REQUEST.get();
}
//
static void removeLocal() {
if (LOCAL_REQUEST.get() != null) {
LOCAL_REQUEST.remove();
}
}
static void updateLocal(RsfRequest rsfRequest) {
removeLocal();
if (rsfRequest != null) {
LOCAL_REQUEST.set(rsfRequest);
}
}
} | apache-2.0 |
ludorival/dao | dao-test/src/main/java/com/github/ludorival/dao/testutilities/test/sample/Comment.java | 1267 | package com.github.ludorival.dao.testutilities.test.sample;
/*
* #%L
* DAO
* %%
* Copyright (C) 2015 ludorival
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.github.ludorival.dao.entity.annotation.IsBean;
import com.github.ludorival.dao.entity.annotation.IsMemo;
@IsBean
public interface Comment {
Integer COUNT_PROPERTIES = 3;
/**
* @return the user
*/
public String getUser();
/**
* @param user the user to set
*/
public void setUser(String user);
/**
* @return the date
*/
public long getDate();
/**
* @return the content
*/
@IsMemo
public String getContent();
/**
* @param content the content to set
*/
public void setContent(String content);
}
| apache-2.0 |
brosander/nifi-android-s2s | s2s/src/main/java/com/hortonworks/hdf/android/sitetosite/factory/PropertiesQueuedSiteToSiteClientConfigFactory.java | 3049 | /*
* Copyright 2017 Hortonworks, Inc.
* All rights reserved.
*
* Hortonworks, Inc. licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* See the associated NOTICE file for additional information regarding copyright ownership.
*/
package com.hortonworks.hdf.android.sitetosite.factory;
import com.hortonworks.hdf.android.sitetosite.client.QueuedSiteToSiteClientConfig;
import com.hortonworks.hdf.android.sitetosite.client.queued.DataPacketPrioritizer;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class PropertiesQueuedSiteToSiteClientConfigFactory extends PropertiesSiteToSiteClientConfigFactory implements QueuedSiteToSiteClientConfigFactory<Properties> {
@Override
public QueuedSiteToSiteClientConfig create(Properties input) throws SiteToSiteClientConfigCreationException {
QueuedSiteToSiteClientConfig queuedSiteToSiteClientConfig = new QueuedSiteToSiteClientConfig(super.create(input));
String maxRows = getPropEmptyToNull(input, S2S_CONFIG + "maxRows");
if (maxRows != null) {
queuedSiteToSiteClientConfig.setMaxRows(Long.parseLong(maxRows));
}
String maxSize = getPropEmptyToNull(input, S2S_CONFIG + "maxSize");
if (maxSize != null) {
queuedSiteToSiteClientConfig.setMaxSize(Long.parseLong(maxSize));
}
Long maxTransactionTime = getDurationNanos(input, S2S_CONFIG + "maxTransactionTime");
if (maxTransactionTime != null) {
queuedSiteToSiteClientConfig.setMaxTransactionTime(maxTransactionTime, TimeUnit.NANOSECONDS);
}
String dataPacketPrioritizerClass = getPropEmptyToNull(input, S2S_CONFIG + "dataPacketPrioritizerClass");
if (dataPacketPrioritizerClass != null) {
Object instance;
try {
instance = Class.forName(dataPacketPrioritizerClass).newInstance();
} catch (Exception e) {
throw new SiteToSiteClientConfigCreationException("Unable to create instance of dataPacketPrioritizerClass " + dataPacketPrioritizerClass, e);
}
if (!(instance instanceof DataPacketPrioritizer)) {
throw new SiteToSiteClientConfigCreationException("dataPacketPrioritizerClass " + dataPacketPrioritizerClass + " cannot be cast to " + DataPacketPrioritizer.class);
}
queuedSiteToSiteClientConfig.setDataPacketPrioritizer((DataPacketPrioritizer) instance);
}
return queuedSiteToSiteClientConfig;
}
}
| apache-2.0 |
piddubnyi/mongo4idea | src/main/java/org/codinjutsu/tools/mongo/view/MongoPanel.java | 7952 | /*
* Copyright (c) 2013 David Boissier
*
* 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.codinjutsu.tools.mongo.view;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.TreeExpander;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Disposer;
import com.mongodb.DBObject;
import org.codinjutsu.tools.mongo.ServerConfiguration;
import org.codinjutsu.tools.mongo.logic.MongoManager;
import org.codinjutsu.tools.mongo.model.MongoCollection;
import org.codinjutsu.tools.mongo.model.MongoCollectionResult;
import org.codinjutsu.tools.mongo.utils.GuiUtils;
import org.codinjutsu.tools.mongo.view.action.*;
import javax.swing.*;
import java.awt.*;
public class MongoPanel extends JPanel implements Disposable {
private JPanel rootPanel;
private Splitter splitter;
private JPanel toolBar;
private JPanel errorPanel;
private final MongoResultPanel resultPanel;
private final QueryPanel queryPanel;
private final MongoManager mongoManager;
private final ServerConfiguration configuration;
private final MongoCollection mongoCollection;
public MongoPanel(Project project, final MongoManager mongoManager, final ServerConfiguration configuration, final MongoCollection mongoCollection) {
this.mongoManager = mongoManager;
this.mongoCollection = mongoCollection;
this.configuration = configuration;
errorPanel.setLayout(new BorderLayout());
queryPanel = new QueryPanel(project);
splitter.setOrientation(true);
splitter.setProportion(0.1f);
toolBar.setLayout(new BorderLayout());
resultPanel = createResultPanel(project, new MongoDocumentOperations() {
public DBObject getMongoDocument(Object _id) {
return mongoManager.findMongoDocument(configuration, mongoCollection, _id);
}
public void updateMongoDocument(DBObject mongoDocument) {
mongoManager.update(configuration, mongoCollection, mongoDocument);
}
public void deleteMongoDocument(Object objectId) {
mongoManager.delete(configuration, mongoCollection, objectId);
}
});
splitter.setSecondComponent(resultPanel);
setLayout(new BorderLayout());
add(rootPanel);
installResultPanelActions();
installQueryPanelActions();
}
private MongoResultPanel createResultPanel(Project project, MongoDocumentOperations mongoDocumentOperations) {
return new MongoResultPanel(project, mongoDocumentOperations);
}
public void installResultPanelActions() {
DefaultActionGroup actionResultGroup = new DefaultActionGroup("MongoResultGroup", true);
if (ApplicationManager.getApplication() != null) {
actionResultGroup.add(new ExecuteQuery(this));
actionResultGroup.add(new OpenFindAction(this));
actionResultGroup.add(new CopyResultAction(resultPanel));
}
final TreeExpander treeExpander = new TreeExpander() {
@Override
public void expandAll() {
resultPanel.expandAll();
}
@Override
public boolean canExpand() {
return true;
}
@Override
public void collapseAll() {
resultPanel.collapseAll();
}
@Override
public boolean canCollapse() {
return true;
}
};
CommonActionsManager actionsManager = CommonActionsManager.getInstance();
final AnAction expandAllAction = actionsManager.createExpandAllAction(treeExpander, resultPanel);
final AnAction collapseAllAction = actionsManager.createCollapseAllAction(treeExpander, resultPanel);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
collapseAllAction.unregisterCustomShortcutSet(resultPanel);
expandAllAction.unregisterCustomShortcutSet(resultPanel);
}
});
actionResultGroup.add(expandAllAction);
actionResultGroup.add(collapseAllAction);
GuiUtils.installActionGroupInToolBar(actionResultGroup, resultPanel.getToolbar(), ActionManager.getInstance(), "MongoGroupActions", false);
}
public void installQueryPanelActions() {
JPanel queryPanelToolbar = queryPanel.getToolbar();
DefaultActionGroup actionQueryGroup = new DefaultActionGroup("MongoResultGroup", true);
if (ApplicationManager.getApplication() != null) {
actionQueryGroup.add(new EnableAggregateAction(this));
actionQueryGroup.add(new CloseFindEditorAction(this));
}
ActionToolbar actionToolBar = ActionManager.getInstance().createActionToolbar("MongoQueryGroupActions", actionQueryGroup, true);
actionToolBar.setLayoutPolicy(ActionToolbar.AUTO_LAYOUT_POLICY);
JComponent actionToolBarComponent = actionToolBar.getComponent();
actionToolBarComponent.setBorder(null);
actionToolBarComponent.setOpaque(false);
queryPanelToolbar.add(actionToolBarComponent, BorderLayout.CENTER);
}
public MongoCollection getMongoCollection() {
return mongoCollection;
}
public void showResults() {
executeQuery();
}
public void executeQuery() {
try {
errorPanel.setVisible(false);
validateQuery();
MongoCollectionResult mongoCollectionResult = mongoManager.loadCollectionValues(configuration, mongoCollection, queryPanel.getQueryOptions());
resultPanel.updateResultTableTree(mongoCollectionResult);
} catch (Exception ex) {
errorPanel.invalidate();
errorPanel.removeAll();
errorPanel.add(new ErrorPanel(ex), BorderLayout.CENTER);
errorPanel.validate();
errorPanel.setVisible(true);
}
}
private void validateQuery() {
queryPanel.validateQuery();
}
@Override
public void dispose() {
resultPanel.dispose();
}
public MongoResultPanel getResultPanel() {
return resultPanel;
}
public void openFindEditor() {
splitter.setFirstComponent(queryPanel);
GuiUtils.runInSwingThread(new Runnable() {
@Override
public void run() {
focusOnEditor();
}
});
}
public void closeFindEditor() {
splitter.setFirstComponent(null);
}
public void focusOnEditor() {
queryPanel.requestFocusOnEditor();
}
public boolean isFindEditorOpened() {
return splitter.getFirstComponent() == queryPanel;
}
public QueryPanel getQueryPanel() {
return queryPanel;
}
interface MongoDocumentOperations {
DBObject getMongoDocument(Object _id);
void deleteMongoDocument(Object mongoDocument);
void updateMongoDocument(DBObject mongoDocument);
}
}
| apache-2.0 |
mifodiy4j/smikhailov | chapter_002/src/main/java/ru/job4j/Bishop.java | 1830 | package ru.job4j;
public class Bishop extends Figure {
Cell[] cellArray;
private int changeString, changeColumn, lengthCellArray;
public Bishop (Cell position) {
super(position);
}
/*Метод должен работать так. dist - задают ячейку куда следует пойти. Если фигура может туда пойти. то Вернуть массив ячеек. которые должна пройти фигура.
Если фигура туда пойти не может. выбросить исключение ImposibleMoveException */
public Cell[] way(Cell dist) throws ImpossibleMoveException {
boolean newPositionInBoard = false;
boolean newPositionValid = false;
if ((dist.getString() < 8) && (dist.getString() >= 0) && (dist.getColumn() < 8) && (dist.getColumn() >= 0)) {
newPositionInBoard = true;
}
if (newPositionInBoard) {
changeString = dist.getString() - position.getString();
changeColumn = dist.getColumn() - position.getColumn();
if (Math.abs(changeString) == Math.abs(changeColumn))
newPositionValid = true;
} else {
throw new ImpossibleMoveException("Out of board rage.");
}
if (newPositionValid) {
lengthCellArray = Math.abs(changeString) - 1;
cellArray = new Cell[lengthCellArray];
int nextString = position.getString();
int nextColumn = position.getColumn();
for (int i = 0; i < lengthCellArray; i++) {
nextString = nextString + changeString/Math.abs(changeString);
nextColumn = nextColumn + changeColumn/Math.abs(changeColumn);
cellArray[i] = new Cell(nextString, nextColumn);
}
} else {
throw new ImpossibleMoveException("Invalid position on board, this figure has another move.");
}
return cellArray;
}
void clone(Cell position) {
new Bishop(position);
}
} | apache-2.0 |
ExtaSoft/extacrm | src/main/java/ru/extas/web/contacts/legalentity/LegalEntitiesField.java | 2354 | package ru.extas.web.contacts.legalentity;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import ru.extas.model.contacts.Company;
import ru.extas.model.contacts.LegalEntity;
import ru.extas.utils.SupplierSer;
import ru.extas.web.commons.ExtaEditForm;
import ru.extas.web.commons.container.ExtaBeanContainer;
import ru.extas.web.commons.container.ExtaDbContainer;
import java.util.Set;
/**
* Реализует ввод/редактирование списка юридических лиц (из владельца)
*
* @author Valery Orlov
* Date: 17.02.14
* Time: 20:03
* @version $Id: $Id
* @since 0.3
*/
public class LegalEntitiesField extends CustomField<Set> {
private SupplierSer<Company> companySupplier;
private ExtaBeanContainer<LegalEntity> itemContainer;
/**
* <p>Constructor for LegalEntitiesField.</p>
*
* @param company a {@link ru.extas.model.contacts.Company} object.
*/
public LegalEntitiesField() {
setBuffered(true);
setRequiredError("Необходимо выбрать хотябы одно юридическое лицо!");
}
/** {@inheritDoc} */
@Override
protected Component initContent() {
final LegalEntitiesGrid grid = new LegalEntitiesGrid() {
@Override
public ExtaEditForm<LegalEntity> createEditForm(final LegalEntity legalEntity, final boolean isInsert) {
final ExtaEditForm<LegalEntity> form = super.createEditForm(legalEntity, isInsert);
form.addCloseFormListener(e -> {
if (form.isSaved() && isInsert)
setValue(((ExtaDbContainer) container).getEntitiesSet());
});
form.setReadOnly(isReadOnly());
return form;
}
};
grid.setCompanySupplier(companySupplier);
grid.setSizeFull();
grid.setReadOnly(isReadOnly());
addReadOnlyStatusChangeListener(e -> grid.setReadOnly(isReadOnly()));
return grid;
}
/** {@inheritDoc} */
@Override
public Class<? extends Set> getType() {
return Set.class;
}
public SupplierSer<Company> getCompanySupplier() {
return companySupplier;
}
public void setCompanySupplier(final SupplierSer<Company> companySupplier) {
this.companySupplier = companySupplier;
}
}
| apache-2.0 |
sameera-jayasoma/product-mss | core/src/test/java/org/wso2/msf4j/internal/router/InterceptorTest.java | 2806 | /*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.msf4j.internal.router;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.wso2.msf4j.MicroservicesRunner;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.Response;
import static org.testng.AssertJUnit.assertEquals;
/**
* Tests handler interceptors.
*/
public class InterceptorTest extends InterceptorTestBase {
private static final TestInterceptor interceptor1 = new TestInterceptor();
private static final TestInterceptor interceptor2 = new TestInterceptor();
private static final TestMicroservice TEST_MICROSERVICE = new TestMicroservice();
private static final int port = Constants.PORT + 2;
private static final MicroservicesRunner microservicesRunner = new MicroservicesRunner(port);
@BeforeClass
public static void setup() throws Exception {
microservicesRunner.
deploy(TEST_MICROSERVICE).
addInterceptor(interceptor1).
addInterceptor(interceptor2)
.start();
baseURI = URI.create(String.format("http://%s:%d", Constants.HOSTNAME, port));
}
@AfterClass
public static void teardown() throws Exception {
microservicesRunner.stop();
}
@BeforeTest
public void reset() {
interceptor1.reset();
interceptor2.reset();
}
@Test
public void testPreInterceptorReject() throws Exception {
int status = doGet("/test/v1/resource", "X-Request-Type", "Reject");
assertEquals(status, Response.Status.NOT_ACCEPTABLE.getStatusCode());
// Wait for any post handlers to be called
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(1, interceptor1.getNumPreCalls());
// The second pre-call should not have happened due to rejection by the first pre-call
// None of the post calls should have happened.
assertEquals(0, interceptor1.getNumPostCalls());
assertEquals(0, interceptor2.getNumPreCalls());
assertEquals(0, interceptor2.getNumPostCalls());
}
}
| apache-2.0 |
liudeyu/MeLife | PMS/GzmeLife/src/com/gzmelife/app/device/SocketTool.java | 55311 | package com.gzmelife.app.device;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.text.TextUtils;
import com.gzmelife.app.KappAppliction;
import com.gzmelife.app.activity.CheckUpdateActivity;
import com.gzmelife.app.activity.CookBookDetailActivity;
import com.gzmelife.app.fragment.DeviceFragment;
import com.gzmelife.app.tools.DataUtil;
import com.gzmelife.app.tools.FileUtils;
import com.gzmelife.app.tools.KappUtils;
import com.gzmelife.app.tools.MyLogger;
import static com.gzmelife.app.device.Config.bufDownFileCancel;
import static com.gzmelife.app.device.Config.bufFileCancel;
/**
* Created by HHD on 2016/10/16.
* Socket类:发送指令;上传菜谱、固件;下载菜谱;解析、拼接帧数据;持续心跳
*
* 服务启动心跳
*/
public class SocketTool {
MyLogger HHDLog=MyLogger.HHDLog();
private String TAG = "SocketTool";
private Socket socket;
private OutputStream output;
private InputStream input;
private Context context;
private Activity activity;
public static HeartTimeCount heartTimer;
private OnReceiver receiver;
/** 当前是否正在发送命令:true=发送状态 */
private boolean isSendCMD = false;
/** 若指令发送不成功,3S后重发指令*/
private int timeCnt = 0;
/** 用于存储重发一帧数据 */
private byte[] bufLastTemp;
/** 记录重发次数,若超过3次则进行重连的操作*/
private int MaxReCnt = 0;
/** 是否超时(大于9秒):false=没超时 */
private boolean RecTimeOut = false;
/** 标记接收数据的总长度 */
private int num = 0;
/** 校验数据时缓存一帧数据 */
private byte[] bufTemp = new byte[256 * 256];
/** 指令发送是否成功、空闲状态、进行指令重发或心跳:false=非空闲状态 */
private boolean ConFalg = false;
/** PMS中录波文件列表总数 */
private int fileNum = 0;
/** 标记PMS中录波文件列表第几页 */
private int frmIndex = 0;
/** 标记PMS中录波文件列表最大一页 */
private int maxIndex = 0;
/** 发送的文件的总大小 */
private int numDownZie = 0;
/** 已经发到PMS的大小 */
private int numDownNow = 0;
// private int numUpZie = 0; // 上传到手机来的文件的大小
/** 手机已经接收的大小 */
private int numUpNow = 0;
/** 请求文件的长度 */
private byte[] bufRecFile;
/** 缓存传到PMS的文件 */
private byte[] bufSendFile = new byte[10 * 1024 * 1024];
/** 一次最大发送到PMS的大小 */
private int MaxPacket = 2 * 1024;
/** PMS中菜谱文件列表 */
private List<String> downFileList = new ArrayList<String>();
/** PMS中录波文件列表 */
private List<String> selfFileList = new ArrayList<String>();
/** 缓存(进行到)帧数的byte数组 */
private byte[] bufACK = {0x00, 0x00};
/** 连接状态:true=连接成功(不必重连)、false=断开状态 */
private boolean isConnected = false;
/** 三次重连与指令的机会 若三次后还失败(isConnected=false且不再自动连接)*/
int connectTimes = 3;
/** 是否在心跳 */
private boolean startHeart = false;
/**
* 生产者消费者设计模式(MSG=消费的对象)
*/
class Message {
private byte[] msg;
private boolean flag = true;//用于标记发送和接收
public Message() {
super();
}
public Message(byte[] msg) {
this.msg = msg;
}
public byte[] getMsg() {
return msg;
}
public void setMsg(byte[] msg) {
this.msg = msg;
}
/**
* 接收数据(生产者)
*/
public synchronized void receiveMessage() {
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
{/** 具体接收业务 */
byte[] resultTemp = new byte[512 * 3];
int len = -1;
try {
if (input != null || !socket.isClosed() || socket.isConnected()) {
len = input.read(resultTemp);
} else {
//
}
if (len == -1) {
//
} else {
/** 缓存Socket一次接过来的数据 */
byte[] result = new byte[len];
for (int i = 0; i < len; i++) {
result[i] = resultTemp[i];
}
HHDLog.i("读进---------------------------数据长度="+result.length);
System.out.println("\r\n接收---------------------------------------------------------------------------");
for (int i = 0; i < result.length; i++) {
if (i == 3) {
System.out.print("【 ");
}
if (i == 5) {
System.out.print("】 | ");
}
if (i == 6) {
System.out.print("| ");
}
System.out.print(byte2HexString(result[i]) + " ");
}
System.out.println("\r\n接收---------------------------------------------------------------------------");
System.out.println(" ");
android.os.Message msg = new android.os.Message();
msg.obj = result;//20161027把接收的数据封装为消息对象
checkDataHandler.sendMessage(msg);
// {
// /** 接收的总长度(有可能是两帧) */
// int receiveLen = 0;
// receiveLen = result.length;
// HHDLog.d("接收的总长度(有可能是两帧)=" + receiveLen);
// /** 当前解析帧的长度数据的长度L=功能码+子功能码+数据域长度 */
// int l = 0;
// /** 正确完整的一帧数据的长度(多帧数据重叠时) */
// int frameLen = 0;
//
// int checkSUM = 0;
// boolean isCheck=true;
// while (isCheck) {
// if (result[0] == (byte) 0xA5) {//是A5开头
// HHDLog.d("是A5开头=" + byte2HexString(result[0]));
// l = DataUtil.hexToTen(result[1]) + DataUtil.hexToTen(result[2]) * 256;
// frameLen = l + 4;
// /** 缓存正确的一帧数据(根据数据的长度L+4) */
// byte[] frameTemp = new byte[frameLen];
// for (int i = 0; i < frameLen; i++) {//根据len取帧
// frameTemp[i] = result[i];
// }
// for (int i = 1; i < frameLen-1; i++) {
// int temp = frameTemp[i];
// if (temp < 0) {
// temp += 256;
// }
// checkSUM += temp;
// }
// if (DataUtil.hexToTen(frameTemp[frameLen-1]) == (checkSUM % 256)) {
// num=frameLen;
// matching(frameTemp, frameLen);
// isCheck=false;
// HHDLog.d("校验码相等=" + DataUtil.hexToTen(frameTemp[frameLen-1]));
// } else {
// HHDLog.d("校验码不相等,是=" + DataUtil.hexToTen(frameTemp[frameLen - 1]));
// }
// } else {
// HHDLog.d("不是A5开头,是=" + byte2HexString(result[0]));
// }
// }
// }
}
} catch (Exception e) {
e.printStackTrace();
}
}
flag=true;
this.notify();
}
/**
* 发送数据(消费者)
* @param msg 待发送的数据
*/
public synchronized void sendMessage(byte[] msg) {
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setMsg(msg);
{/** 具体发送业务 */
// if (){
//
// }
if (socket == null || output == null || socket.isClosed()) {
if (socket == null) {
//
} else {
//
}
if (receiver != null) {
receiver.onFailure(0);
}
return;
}
try {
for (int i = 0; i < msg.length; i++) {
//
}
} catch (Exception e1) {
e1.printStackTrace();
}
try {
if (msg != null) {
output.write(msg);
output.flush();
System.out.println("\r\n发送---------------------------------------------------------------------------");
for (int i = 0; i < msg.length; i++) {
if (i == 3) {
System.out.print("【 ");
}
if (i == 5) {
System.out.print("】 | ");
}
if (i == 6) {
System.out.print("| ");
}
System.out.print(byte2HexString(msg[i]) + " ");
}
System.out.println("\r\n发送---------------------------------------------------------------------------");
System.out.println(" ");
HHDLog.i("写出数据长度="+msg.length);
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
flag=false;
this.notify();
}
}
/**
* Socket接收数据线程
*/
class ReceiveRunnable implements Runnable {
private Message message;
public ReceiveRunnable(Message msg) {
this.message = msg;
}
@Override
public void run() {
// if (地址不是我的) {
// }
/** 地址是我的 */
{
message.receiveMessage();
}
}
}
/**
* Socket发送数据线程
*/
class SendRunnable implements Runnable {
private Message message;
public SendRunnable(Message msg) {
this.message = msg;
}
@Override
public void run() {
// if (地址不是我的) {
// }
/** 地址是我的 */
{
message.sendMessage(message.msg);
}
}
}
/**
* 封装发送帧数据功能(发送后启动接收线程)
* 用到地方:发指令、数据指令、重发指令和数据指令
*
* @param frameData 帧数据(拼接好的数据)
*/
private void sendFrame(byte[] frameData){
Message msg=new Message(frameData);
ReceiveRunnable receiveRunnable=new ReceiveRunnable(msg);
Thread receiveThread = new Thread(receiveRunnable);
receiveThread.start();
SendRunnable sendRunnable =new SendRunnable(msg);
Thread sendThread=new Thread(sendRunnable);
sendThread.start();
}
public SocketTool(Context context, OnReceiver onReceiver) {
this.context = context;
this.receiver = onReceiver;
}
/**
* 只有DeviceFragment用到
*
* @param context
* @param activity
* @param onReceiver
*/
public SocketTool(Context context, Activity activity, OnReceiver onReceiver) {
this.context = context;
this.activity = activity;
this.receiver = onReceiver;
}
/**
* 初始化客户端Socket
*/
public void initClientSocket() {
try {
socket = new Socket(Config.SERVER_HOST_IP, Config.SERVER_HOST_PORT);
output = socket.getOutputStream();
input = socket.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 首次进入“设备”界面时调用(三次连接机会)
*/
public void firstConnect() {
isConnected = false;
connectTimes = 3;
connectHandler.sendEmptyMessage(0);
}
/**
* 关闭Socket连接
*/
public void closeSocket() {
try {
if (output != null) {
output.close();
output = null;
}
if (socket != null) {
socket.close();
socket = null;
}
if (heartTimer != null) {
heartTimer.cancel();
heartTimer = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 分析(PMS-》手机)数据,匹配相应的指令
*
* @param buf 接到的帧数据
* @param num 帧数据的下标
*/
private void matching(byte[] buf, int num) {
int len = DataUtil.hexToTen(bufTemp[1]) + DataUtil.hexToTen(bufTemp[2]) * 256;
ConFalg = true;
isSendCMD = false;
/** 截获其他客户端动作 */
// if (buf[5] != Config.clientPort) {
// switch (buf[3]) {
// case (byte) 0xF3:
// if (buf[4] == 0x00) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】获取录波文件数量");
// break;
// } else if (buf[4] == 0x01) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】查询录波文件列表");
// break;
// } else if (buf[4] == 0x02) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】遍历完毕");
// break;
// }
// break;
//
// case (byte) 0xF4:
// if (buf[4] == 0x00) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】获取录波文件大小");
// break;
// } else if (buf[4] == 0x01) {
// Config.isOtherInstruction = true;
// break;
// } else if (buf[4] == 0x02) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】录波发送结束");
// Config.isOtherInstruction = false;
// break;
// } else if (buf[4] == 0x03) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】中断文件传输");
// Config.isOtherInstruction = false;
// break;
// }
// break;
//
// case (byte) 0xF5:
// if (buf[4] == 0x00) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】获取录波文件大小");
// break;
// } else if (buf[4] == 0x01) {
//
// Config.isOtherInstruction = true;//20160927
// break;
//
// } else if (buf[4] == 0x02) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】数据发送结束");
// Config.isOtherInstruction = false;//20160927
// break;
// }
// break;
//
// case (byte) 0xF6:
// if (buf[4] == 0x00) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】生成录波文件操作");
// break;
// } else if (buf[4] == 0x01) {
// KappUtils.showToast(context, "【" + byte2HexString(buf[5]) + "】删除APP下载菜谱文件操作");
// break;
// }
// break;
// }
// return;
// }
/** 客户端地址匹配 */
switch (buf[3]) {
case (byte) 0xF3: // 文件列表
if (buf[4] == 0x00) { // 得到文件数目
fileNum = DataUtil.hexToTen(bufTemp[6]) + DataUtil.hexToTen(bufTemp[7]) * 256;
if (DeviceFragment.fileFlag) {
selfFileList.clear();
} else {
downFileList.clear();
}
if (fileNum > 0) {
frmIndex = 1;
maxIndex = fileNum / 25;
if ((fileNum % 25) > 0) {
maxIndex++;
}
ACK(frmIndex);
splitInstruction(Config.bufListFile, bufACK);
} else {
if (receiver != null) {
receiver.onSuccess(null, 0, 0, 0);
}
}
} else if (buf[4] == 0x01) { // 得到文件名称
String filename = "";
for (int index = 8; index < num - 40; index += 40) { // 9->8
String aa = "";
try {
aa = new String(buf, index, 40, "gbk");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
filename = aa.replace("\0", "");
} catch (Exception e) {
filename = aa;
}
if (DeviceFragment.fileFlag) {
selfFileList.add(filename);
} else {
downFileList.add(filename);
}
}
if (DeviceFragment.fileFlag) {
if (selfFileList.size() < fileNum) { // 加帧判断
frmIndex++;
ACK(frmIndex);
splitInstruction(Config.bufListFile, bufACK);
} else {
splitInstruction(Config.bufListFileOver, null);
}
} else {
if (downFileList.size() < fileNum) { // 加帧判断
frmIndex++;
ACK(frmIndex);
splitInstruction(Config.bufListFile, bufACK);
} else {
splitInstruction(Config.bufListFileOver, null);
}
}
} else if (buf[4] == 0x02) { // 遍历完成
if (DeviceFragment.fileFlag) {
if (receiver != null) {
receiver.onSuccess(selfFileList, 0, 0, 0);
}
} else {
if (receiver != null) {
receiver.onSuccess(downFileList, 0, 0, 0);
}
}
}
break;
case (byte) 0xF4: // 上召文件
if (buf[4] == 0x01) { // 得到文件数据
if (Config.cancelTransfer) {/** 21061009取消传输 */
splitInstruction(bufFileCancel, null);
return;
}
downloadCookbook(buf);
} else if (buf[4] == 0x00) { // 得到文件长度
int fileLen = DataUtil.hexToTen(buf[6]) + DataUtil.hexToTen(buf[7]) * 256
+ DataUtil.hexToTen(buf[8]) * 256 * 256 + DataUtil.hexToTen(buf[9]) * 256 * 256 * 256;
if (fileLen == 0) {
if (receiver != null) {
receiver.onFailure(-1);
}
return;
}
numUpNow = 0;
bufRecFile = new byte[fileLen];
frmIndex = 1;
maxIndex = fileLen / MaxPacket;
if ((fileLen % MaxPacket) > 0) {
maxIndex++;
}
ACK(frmIndex);
splitInstruction(Config.bufFileAck, bufACK);
} else if (buf[4] == 0x02) {
DeviceFragment.saveFileName = FileUtils.PMS_FILE_PATH + FileUtils.getFileName(DeviceFragment.saveFileName);
FileUtils.writeTextToFile(DeviceFragment.saveFileName, bufRecFile);
if (receiver != null) {
receiver.onSuccess(null, 1, 0, 0);
} else {
receiver.onFailure(0);
}
} else if (buf[4] == 0x03) {/** 20161009收到中断确认 */
Config.cancelTransfer = false;
}
break;
case (byte) 0xF5: // 下传文件
if (buf[4] == 0x00) { // 发送文件大小和文件名,得到确认
if (buf[6] == 0x01) {
Config.numDownNow = 0;
Config.frmIndex = 1;
uploadFile( Config.frmIndex);
} else if (buf[6] == 0x00) {
if (receiver != null) {
receiver.onFailure(50000);
}
}
} else if (buf[4] == 0x01) { // 发送文件一帧,得到确认
if (buf[6] == 0x01) {
if (Config.cancelTransfer) {/** 21061009取消传输 */
splitInstruction(bufDownFileCancel, null);
return;
}
Config.frmIndex++;
if (receiver != null) {
receiver.onSuccess(null, 8, Config.numDownNow, Config.numDownZie);
} else {
//
}
if (Config.numDownZie > Config.numDownNow) {
uploadFile( Config.frmIndex);
} else {
splitInstruction(Config.bufDownFileStop, null);
}
} else if (buf[6] == 0x00) {
uploadFile( Config.frmIndex);
}
} else if (buf[4] == 0x02) {
if (receiver != null) {
receiver.onSuccess(null, 7, 0, 0);
} else {
//
}
}
else if (buf[4] == 0x03) {/** 20161009收到中断确认 */
Config.cancelTransfer = false;
}
break;
case (byte) 0xF6:
if (buf[4] == (byte) 0x00) {
if (buf[6] == 0x01) {
if (receiver != null) {
receiver.onSuccess(null, 5, 0, 0);
}
} else {
if (receiver != null) {
receiver.onFailure(0);
}
}
} else if (buf[4] == (byte) 0x01) {
if (buf[6] == 0x01) {
if (receiver != null) {
receiver.onSuccess(null, 5, 0, 0);
}
} else {
if (receiver != null) {
receiver.onFailure(0);
}
}
}
break;
case (byte) 0xF7:
if (buf[4] == (byte) 0x00) {
Config.SYSTEM_A = ((DataUtil.hexToTen(buf[6]) + 256 * DataUtil.hexToTen(buf[7])) * 1650.0 / 48803.38944) + "A";
Config.SYSTEM_V = ((DataUtil.hexToTen(buf[8]) + 256 * DataUtil.hexToTen(buf[9])) / 10.0) + "V";
Config.SYSTEM_W = DataUtil.hexToTen(buf[15]) * 10 + "W";
Config.PMS_TEMP = ((DataUtil.hexToTen(buf[10]) + 256 * DataUtil.hexToTen(buf[11])) / 100.0) + "度";
Config.ROOM_TEMP = ((DataUtil.hexToTen(buf[12]) + 256 * DataUtil.hexToTen(buf[13])) / 100.0) + "度";
switch (DataUtil.hexToTen(buf[14])) {
case 0:
Config.PMS_STATUS = "POWEROFF";
break;
case 1:
Config.PMS_STATUS = "POWERON";
break;
case 2:
Config.PMS_STATUS = "POWERSTANDBY";
break;
case 3:
Config.PMS_STATUS = "POWERHALT";
break;
}
Config.PMS_ERRORS.clear();
StringBuffer sb = new StringBuffer();
for (int i = 17; i > 15; i--) {
String hex = Integer.toHexString(buf[i]);
int ihex = Integer.parseInt(hex);
String r = "";
if (ihex < 10) {
r = String.format("%02d", ihex);
} else {
r = ihex + "";
}
sb.append(r);
}
String result = hexString2binaryString(sb.toString());
StringBuffer sBuf = new StringBuffer();
for (int i = result.length(); i > 0; i--) {
sBuf.append(result.substring(i - 1, i));
}
for (int i = 0; i < result.length(); i++) {
if (sBuf.substring(i, i + 1).equals("1")) {
Config.PMS_ERRORS.add((i) + "");
}
}
if (receiver != null) {
receiver.onSuccess(null, 6, 0, 0);
}
} else {
if (receiver != null) {
receiver.onFailure(0);
}
}
break;
case (byte) 0xF8:/** 连接成功 */
if (buf[4] == (byte) 0x00) { // 连接确认报文,回复PMS的MAC
isConnected = true;
if (receiver != null) {
receiver.onSuccess(null, 4, 0, 0);
}
} else if (buf[4] == (byte) 0x02) {
// 心跳报文
}
break;
case (byte) 0xF2: {/** 对时 */
if (buf[4] == (byte) 0x00) {
if (receiver != null) {
receiver.onSuccess(null, 9, 0, 0);
}
}
}
break;
}
}
/**
* 拼接指令帧数据
*
* @param instruction 指令(除SocketTool有5处用到)
*/
public void splitInstruction(byte[] instruction) {//splitInstruction
int addNum = 0;
byte[] bufTemp = new byte[instruction.length + 5];
bufTemp[0] = (byte) 0xA5;
bufTemp[1] = (byte) (instruction.length % 256 + 1);
bufTemp[2] = (byte) (instruction.length / 256);
for (int i = 0; i < instruction.length; i++) {
bufTemp[i + 3] = instruction[i];
}
bufTemp[instruction.length + 3] = Config.clientPort;
for (int i = 1; i < instruction.length + 4; i++) {
addNum += bufTemp[i];
}
bufTemp[instruction.length + 4] = (byte) (addNum % 256);
try {
bufLastTemp = new byte[bufTemp.length];
for (int i = 0; i < bufTemp.length; i++) {
bufLastTemp[i] = bufTemp[i];
}
// 记录所发的指令,用于后续若指令失败时重发
bufLastTemp = new byte[bufTemp.length];
//sendMessage(bufTemp);
sendFrame(bufTemp);
timeCnt = 0;
Config.timeCntHeart = 0;
isSendCMD = true;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 拼接指令帧数据(带数据)
*
* @param functionCode 功能码
* @param data 数据
*/
public void splitInstruction(byte[] functionCode, byte[] data) {
if (data!=null){
int addNum = 0;
int i = 0;
int len = functionCode.length + data.length + 1;// PMS格式长度+数据长度+校验码
byte[] bufTemp = new byte[len + 4];/*Lotus 2016-07-27 修改长度*/
bufTemp[0] = (byte) 0xA5;
bufTemp[1] = (byte) (len % 256);
bufTemp[2] = (byte) ((len / 256) % 256);
bufTemp[3] = functionCode[0];
bufTemp[4] = functionCode[1];
if (Config.clientPort == -1) {
return;
}
bufTemp[5] = Config.clientPort;
for (i = 6; i < len + 3; i++) {
bufTemp[i] = data[i - 6];
}
for (i = 1; i < len + 3; i++) {
addNum += bufTemp[i];
}
bufTemp[len + 3] = (byte) (addNum % 256);
try {
// sendMessage(bufTemp);
sendFrame(bufTemp);
timeCnt = 0;
Config.timeCntHeart = 0;
isSendCMD = true;
// HHDLog.v("心跳时间为0表示上传清空="+Config.timeCntHeart);
} catch (Exception e) {
e.printStackTrace();
}
bufLastTemp = new byte[bufTemp.length];
for (i = 0; i < bufTemp.length; i++) {
bufLastTemp[i] = bufTemp[i];
}
} else {
int addNum = 0;
byte[] bufTemp = new byte[functionCode.length + 5];
bufTemp[0] = (byte) 0xA5;
bufTemp[1] = (byte) (functionCode.length % 256 + 1);
bufTemp[2] = (byte) (functionCode.length / 256);
for (int i = 0; i < functionCode.length; i++) {
bufTemp[i + 3] = functionCode[i];
}
bufTemp[functionCode.length + 3] = Config.clientPort;
for (int i = 1; i < functionCode.length + 4; i++) {
addNum += bufTemp[i];
}
bufTemp[functionCode.length + 4] = (byte) (addNum % 256);
try {
bufLastTemp = new byte[bufTemp.length];
for (int i = 0; i < bufTemp.length; i++) {
bufLastTemp[i] = bufTemp[i];
}
bufLastTemp = new byte[bufTemp.length];
//sendMessage(bufTemp);
sendFrame(bufTemp);
timeCnt = 0;
Config.timeCntHeart = 0;
isSendCMD = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** F4 01
* PMS(菜谱)-》手机(菜谱)
*
* @param buf 每帧数据
*/
private void downloadCookbook(byte[] buf) {
int fileLen = DataUtil.hexToTen(buf[1]) + DataUtil.hexToTen(buf[2]) * 256 - 9;//200160928//fileLen:长度L:功能码、子功能码以及数据域的长度之和
int allFileLen = DataUtil.hexToTen(buf[6]) + DataUtil.hexToTen(buf[7]) * 256 + DataUtil.hexToTen(buf[8]) * 256 * 256 + DataUtil.hexToTen(buf[9]) * 256 * 256 * 256;/** 20160920新增加的 */
for (int i = 0; i < 1037; i++) {
}
for (int i = 0; i < fileLen; i++) {
bufRecFile[numUpNow + i] = buf[i + 12];//20160928//bufRecFile:当前菜谱文件总长度
}
for (int j = 0; j < bufRecFile.length; j++) {
}
numUpNow += fileLen;// 40380 40124//20160928//fileLen:进度总长度(int)
if (receiver != null) {
receiver.onSuccess(null, 3, numUpNow, bufRecFile.length);
}
if (numUpNow == bufRecFile.length) {//20160928需要修改:帧序号=文件的长度/每帧大小
splitInstruction(Config.bufFileStop, null);
} else {
frmIndex++;
ACK(frmIndex);
splitInstruction(Config.bufFileAck, bufACK);//frmIndex(int)=帧序号=bufACK(byte)
}
}
/** F5 01
* 手机-》PMS
*
* @param index 第几帧
*/
private void uploadFile(int index) {
int lenth = Config.numDownZie - Config.numDownNow;// 所需下载长度为剩下的长度 但不大于最大请求长度
if (lenth > (MaxPacket)) {
lenth = (MaxPacket);
}
byte[] bufR = new byte[lenth + 2];
bufR[0] = (byte) (index % 256);
bufR[1] = (byte) (index / 256);
for (int i = 0; i < lenth; i++) {
bufR[i + 2] = Config.bufSendFile[(index - 1) * MaxPacket + i];// bufR[i + 2] = bufSendFile[(index - 1) * MaxPacket + i];
}
splitInstruction(Config.bufDownFileData, bufR);
Config.numDownNow = Config.numDownNow + lenth;
}
/** F5 00
* 手机(菜谱)-》PMS(菜谱);获取文件名称、大小
*/
public void uploadCookbookInfo() {
String fileName;
File file;
if (CookBookDetailActivity.stat == false) {
file = new File(CookBookDetailActivity.filePath);
fileName = CookBookDetailActivity.filePath.substring(CookBookDetailActivity.filePath.lastIndexOf('/'));// 文件名长度的限制
} else {
file = new File(CookBookDetailActivity.newFilePath);
fileName = CookBookDetailActivity.newFilePath.substring(CookBookDetailActivity.newFilePath.lastIndexOf('/'));// 文件名长度的限制
}
if (fileName.startsWith("\\")) {
fileName = fileName.replace("\\", "");
}
if (fileName.startsWith("/")) {
fileName = fileName.replace("/", "");
}
if (fileName.length() > 39) {
Looper.prepare();
KappUtils.showToast(context, "文件名称超长,请重新选择");
Looper.loop();
if (receiver != null) {
receiver.onFailure(0);
}
return;
}
byte[] bufFile = FileUtils.getBytesFromFile(file);// 要发送的文件数据
int check = 0;
bufSendFile = new byte[bufFile.length];
Config.bufSendFile = new byte[bufFile.length];//
for (int i = 0; i < bufFile.length; i++) {
bufSendFile[i] = bufFile[i];
Config.bufSendFile[i] = bufFile[i];//
check += bufFile[i];
}
byte[] arr = null;// 文件名的字节长度
try {
arr = fileName.getBytes("gbk");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] bufFileInfo = new byte[arr.length + 8];/* Lotus 2016-07-27 因为文件名称长度问题,需要给8位,跟文档上面4位不符*/// 所传参数,文件名长度+文件长度(均为字节长度)
bufFileInfo[0] = (byte) (bufFile.length % 256);
bufFileInfo[1] = (byte) ((bufFile.length / 256) % 256);
bufFileInfo[2] = (byte) ((bufFile.length / 256 / 256) % 256);
bufFileInfo[3] = (byte) ((bufFile.length / 256 / 256 / 256) % 256);
bufFileInfo[4] = (byte) (check % 256);
bufFileInfo[5] = (byte) ((check / 256) % 256);
bufFileInfo[6] = (byte) ((check / 256 / 256) % 256);
bufFileInfo[7] = (byte) ((check / 256 / 256 / 256) % 256);
numDownNow = 0;
numDownZie = (int) bufFile.length;
Config.numDownZie = (int) bufFile.length;//
for (int i = 0; i < arr.length; i++) {
bufFileInfo[i + 8] = arr[i];
}
ConFalg = false;
splitInstruction(Config.bufDownFileInfo, bufFileInfo);
}
/** F5 00
* 手机(固件)-》PMS(固件)
*/
public void uploadFirmwareInfo() {
String fileName;
File file;
file = new File(CheckUpdateActivity.result1.getPath());
// 文件名长度的限制
int index = CheckUpdateActivity.result1.getPath().lastIndexOf('/');
if (index > 0) {
index = index + 1;
}
fileName = CheckUpdateActivity.result1.getPath().substring(index);
if (fileName.length() > 39) {
Looper.prepare();
KappUtils.showToast(context, "文件名称超长,请重新选择");
Looper.loop();
if (receiver != null) {
receiver.onFailure(0);
}
return;
}
byte[] bufFile = FileUtils.getBytesFromFile(file);// 要发送的文件数据
int check = 0;
bufSendFile = new byte[bufFile.length];
//Config.bufSendFile = new byte[bufFile.length];//
for (int i = 0; i < bufFile.length; i++) {
bufSendFile[i] = bufFile[i];
//Config.bufSendFile[i] = bufFile[i];//
check += bufFile[i];
}
// 文件名的字节长度
byte[] arr = null;
try {
arr = fileName.getBytes("gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 所传参数,文件名长度+文件长度(均为字节长度)
byte[] bufFileInfo = new byte[arr.length + 8];
bufFileInfo[0] = (byte) (bufFile.length % 256);
bufFileInfo[1] = (byte) ((bufFile.length / 256) % 256);
bufFileInfo[2] = (byte) ((bufFile.length / 256 / 256) % 256);
bufFileInfo[3] = (byte) ((bufFile.length / 256 / 256 / 256) % 256);
bufFileInfo[4] = (byte) (check % 256);
bufFileInfo[5] = (byte) ((check / 256) % 256);
bufFileInfo[6] = (byte) ((check / 256 / 256) % 256);
bufFileInfo[7] = (byte) ((check / 256 / 256 / 256) % 256);
numDownNow = 0;
numDownZie = (int) bufFile.length;
//Config.numDownZie = (int) bufFile.length;//
for (int i = 0; i < arr.length; i++) {
bufFileInfo[i + 8] = arr[i];
}
ConFalg = false;
splitInstruction(Config.bufDownFileInfo, bufFileInfo);
}
/**
* 校验数据
*/
Handler checkDataHandler = new Handler(new Callback() {
/**
* 校验数据的正确性
*
* @param msg 需要校验的数据
* @return 是否正确
*/
@Override
public boolean handleMessage(android.os.Message msg) {
byte[] result = (byte[]) msg.obj;
try {
/** 拼接A5再次校验:false=不开始再次校验 */
boolean isAgain = false;
/** 当前解析帧的长度数据的长度L=功能码+子功能码+数据域长度 */
/** 正确完整的一帧数据的长度(多帧数据重叠时) */
int frameLen = (DataUtil.hexToTen(result[1]) + DataUtil.hexToTen(result[2]) * 256)+4;
HHDLog.d("Len+4=" + frameLen);
/** 校验算术和 */
int checkSUM = 0;
/** 接收的总长度(有可能是两帧) */
int receiveLen = 0;
receiveLen = result.length;
HHDLog.d("接收的总长度(有可能是两帧)=" + receiveLen);
/** 是否校验结束:false=校验结束 */
boolean isCheck = true;
while (isCheck) {
if (isAgain) {
if (result[0] == (byte) 0xA5) {//是A5开头
if (frameLen>=num){//限制接收的长度为有效长度
if (num < 3) {//拼接前三
bufTemp[num] = result[num];
num++;
} else if (num == 3) {//拼接四
// len = DataUtil.hexToTen(bufTemp[1]) + DataUtil.hexToTen(bufTemp[2]) * 256;
bufTemp[num] = result[num];
num++;
} else if (num > 3) {//拼接四后面
if (num < frameLen + 3 && num < result.length) {//解析不到最后一位时
bufTemp[num] = result[num];
num++;
} else {//解析到最后一位时
if (num < result.length) {
bufTemp[num] = result[num];
num++;
}
for (int i = 1; i < num - 1; i++) {//解析完成开始校验
int temp = bufTemp[i];
if (temp < 0) {
temp += 256;
}
checkSUM += temp;
}
if (DataUtil.hexToTen(bufTemp[num - 1]) == (checkSUM % 256)) {//对比校验码
if (frameLen==num){
matching(bufTemp, num);
}
isCheck = false;
return true;
} else {//校验不通过结束校验
if (frameLen > 0) {
isCheck = false;
}
}
if (frameLen > 0) {//不开始再次校验
isAgain = false;
num = 0;
}
}
}
} else {
//
}
} else {
HHDLog.d("不是A5开头,是=" + byte2HexString(result[0]));
}
} else {//不是不开始再次校验状态
/** 转换一个地址码:用于替换 */
byte addressCode = (byte) 0xA5;
/** 缓存地址码 */
byte addressCodeTemp = result[0];
if (addressCodeTemp == addressCode) {
num = 0;
bufTemp[num] = addressCodeTemp;
isAgain = true;
num++;
timeCnt = 0;
Config.timeCntHeart = 0;
RecTimeOut = false;
} else {
//
}
}
}
} catch (Exception e) {
e.printStackTrace();
Config.SERVER_HOST_NAME = "";
if (receiver != null) {
receiver.onFailure(0);
}
ConFalg = false;
return false;
}
return false;
}
});
/**
* 检查Socket连接状态连接
*/
Handler connectHandler = new Handler(new Callback() {
@Override
public boolean handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
if (!isConnected && connectTimes > 0) {
connectTimes--;
connectHandler.sendEmptyMessage(1);
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
closeSocket();
initClientSocket();
splitInstruction(Config.bufConnect, null);
new Handler().postDelayed(new Runnable() {/** 延迟2秒执行此线程 */
@Override
public void run() {
connectHandler.sendEmptyMessage(0);
}
}, 2000);
Looper.loop();
}
}).start();
} else {
if (!isConnected) {
if (receiver != null) {
receiver.onFailure(0);
}
KappAppliction.state = 2;
KappUtils.showToast(context, "与PMS连接已经断开");
}
}
break;
case 1:
// HHDLog.i("重连剩余次数:" + connectTimes);
break;
}
return false;
}
});
/**
* 心跳计时类(重发指令、心跳)
*/
class HeartTimeCount extends CountDownTimer {
/**
* 倒计时构造方法
*
* @param millisInFuture 从开始调用start()到倒计时完成并onFinish()方法被调用的毫秒数(单位毫秒)
* @param countDownInterval 接收onTick(long)回调的间隔时间(单位毫秒)
*/
HeartTimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
/** 倒计时完成时被调用 */
@Override
public void onFinish() {
//
}
/**
* 固定间隔被调用(不会在之前一次调用完成前被调用)
* @param millisUntilFinished 倒计时剩余时间
*
* start ():启动倒计时
*/
@Override
public void onTick(long millisUntilFinished) {
try {
if (!TextUtils.isEmpty(Config.SERVER_HOST_NAME) && socket != null && socket.isConnected()) {
timeCnt++;
if (timeCnt > 9) {
RecTimeOut = true;
timeCnt = 0;
}
if (ConFalg) {
if (RecTimeOut && isSendCMD) {// 如果是发送超时等,三次重发机会,否则尝试重连
MaxReCnt++;
// sendMessage(bufLastTemp);
sendFrame(bufLastTemp);
isSendCMD = true;
timeCnt = 0;
RecTimeOut = false;
if (MaxReCnt > 2) {
MaxReCnt = 0;
ConFalg = false;
KappUtils.showToast(context, "操作失败,进行重连");
Config.SERVER_HOST_NAME = "";
connectTimes = 3;
isConnected = false;
connectHandler.sendEmptyMessage(0);
}
}
Config.timeCntHeart++;/** 心跳计时,30S无操作发送心跳指令 */
HHDLog.v("当前心跳时间(timeCntHeart)="+Config.timeCntHeart);
if (Config.timeCntHeart >= 30) {
splitInstruction(Config.bufHearbeat, null);
// Config.timeCntHeart = 0;
}
}
}
} catch (Exception e) {
//
}
}
}
/**
* 监听进度条等
*/
public interface OnReceiver {
/**
* flag 0: 不处理,1:下载成功,2:下载失败,3:下载数据的百分比,4:连接成功,5:删除文件成功,6:获取设备状态成功, 7 :传文件到智能锅成功,8:传文件到智能锅的百分比 ,9:对时功能
*/
void onSuccess(List<String> cookBookFileList, int flag, int now, int all);
/**
* flag 默认为0;-1:下载文件,文件大小=0;
*/
void onFailure(int flag);
}
/** 判断是否正在心跳 */
public boolean isStartHeartTimer() {
return startHeart;
}
/**
* 启动心跳计时
*/
public void startHeartTimer() {
if (heartTimer!=null){//20161028HHD
heartTimer.cancel();
heartTimer=null;
}
heartTimer = new HeartTimeCount(Long.MAX_VALUE, 1000);
heartTimer.start();
startHeart = true;
ConFalg = true;
}
/**
* 将当前获取第几帧的值转化为byte数组来传
*/
private void ACK(int index) {
bufACK[0] = (byte) (index % 256);
bufACK[1] = (byte) (index / 256);
}
/**
* 字节转哈希字符串
*
* @param b 需要转换的byte
* @return 相应的String
*/
public static String byte2HexString(byte b) {
StringBuffer buffer = new StringBuffer();
buffer.append(HexCode[(b >>> 4) & 0x0f]);
buffer.append(HexCode[b & 0x0f]);
return buffer.toString();
}
/**
* 哈希字符串转二进制字符串
*
* @param hexString 哈希字符串
* @return 二进制字符串
*/
private String hexString2binaryString(String hexString) {
if (hexString == null || hexString.length() % 2 != 0)
return "";
String bString = "", tmp;
for (int i = 0; i < hexString.length(); i++) {
tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
}
return bString;
}
/***
* 字节转哈希字符串
*
* @param b 需要转的字节
* @return 哈希字符串
*/
public static String bytetoHexString(byte b) {
String result = Integer.toHexString(b & 0xFF);
if (result.length() == 1) {
result = '0' + result;
}
return result;
}
/** 哈希表 */
private static char[] HexCode = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 字节转整数
*
* @param res 需要转换的字节数组
* @return 整数
*/
public static int bytes2int(byte[] res) {// 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) | ((res[2] << 24) >>> 8) | (res[3] << 24);// “|” 表示按位或
return targets;
}
/**
* 字节数组转对象// bytearray to object
*
* @param bytes 需要转换的字节数组
* @return 对象
*/
public static Object byte2Object(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
bi.close();
oi.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 对象转字节数组// object to bytearray
*
* @param obj 需要转换的对象
* @return 相应的字节数组
*/
public static byte[] object2Byte(java.lang.Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
}
| apache-2.0 |
NanYoMy/redis-cache | src/main/java/org/mybatis/caches/redis/RedisConfigurationBuilder.java | 4476 | /**
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.caches.redis;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.cache.CacheException;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
/**
* Converter from the Config to a proper {@link ConfigWithHost}.
*
* @author Eduardo Macarron
*/
final class RedisConfigurationBuilder {
/**
* This class instance.
*/
private static final RedisConfigurationBuilder INSTANCE = new RedisConfigurationBuilder();
private static final String SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME = "redis.properties.filename";
private static final String REDIS_RESOURCE = "redis.properties";
private final String redisPropertiesFilename;
/**
* Hidden constructor, this class can't be instantiated.
*/
private RedisConfigurationBuilder() {
redisPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME, REDIS_RESOURCE);
}
/**
* Return this class instance.
*
* @return this class instance.
*/
public static RedisConfigurationBuilder getInstance() {
return INSTANCE;
}
/**
* Parses the Config and builds a new {@link ConfigWithHost}.
*
* @return the converted {@link ConfigWithHost}.
*/
public ConfigWithHost parseConfiguration() {
return parseConfiguration(getClass().getClassLoader());
}
/**
* Parses the Config and builds a new {@link ConfigWithHost}.
*
* @param the
* {@link ClassLoader} used to load the
* {@code memcached.properties} file in classpath.
* @return the converted {@link ConfigWithHost}.
*/
public ConfigWithHost parseConfiguration(ClassLoader classLoader) {
Properties config = new Properties();
InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename);
if (input != null) {
try {
config.load(input);
} catch (IOException e) {
throw new RuntimeException(
"An error occurred while reading classpath property '"
+ redisPropertiesFilename
+ "', see nested exceptions", e);
} finally {
try {
input.close();
} catch (IOException e) {
// close quietly
}
}
}
ConfigWithHost jedisConfig = new ConfigWithHost();
jedisConfig.setHost("localhost");
setConfigProperties(config, jedisConfig);
return jedisConfig;
}
private void setConfigProperties(Properties properties,
ConfigWithHost jedisConfig) {
if (properties != null) {
MetaObject metaCache = SystemMetaObject.forObject(jedisConfig);
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
String value = (String) entry.getValue();
if (metaCache.hasSetter(name)) {
Class<?> type = metaCache.getSetterType(name);
if (String.class == type) {
metaCache.setValue(name, value);
} else if (int.class == type || Integer.class == type) {
metaCache.setValue(name, Integer.valueOf(value));
} else if (long.class == type || Long.class == type) {
metaCache.setValue(name, Long.valueOf(value));
} else if (short.class == type || Short.class == type) {
metaCache.setValue(name, Short.valueOf(value));
} else if (byte.class == type || Byte.class == type) {
metaCache.setValue(name, Byte.valueOf(value));
} else if (float.class == type || Float.class == type) {
metaCache.setValue(name, Float.valueOf(value));
} else if (boolean.class == type || Boolean.class == type) {
metaCache.setValue(name, Boolean.valueOf(value));
} else if (double.class == type || Double.class == type) {
metaCache.setValue(name, Double.valueOf(value));
} else {
throw new CacheException("Unsupported property type: '"
+ name + "' of type " + type);
}
}
}
}
}
}
| apache-2.0 |