hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
4fb2ad569553f8ca87a1266663ff91f28d7f5401 | 309 | package org.lxp.design.pattern.chain.responsibility;
public class ManagerInterviewHandler extends AbstractInterviewHandler {
public ManagerInterviewHandler(String name) {
super(name);
}
@Override
public int getLevel() {
return AbstractInterviewHandler.LEVEL_MANAGER;
}
} | 23.769231 | 71 | 0.731392 |
6e0497f21b3fd065c0aef0fdd31b2a8f0d14b430 | 7,271 | package ru.swayfarer.swl2.ioc;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import ru.swayfarer.swl2.classes.ReflectionUtils;
import ru.swayfarer.swl2.collections.CollectionsSWL;
import ru.swayfarer.swl2.collections.extended.IExtendedMap;
import ru.swayfarer.swl2.collections.streams.DataStream;
import ru.swayfarer.swl2.collections.streams.IDataStream;
import ru.swayfarer.swl2.exceptions.ExceptionsUtils;
import ru.swayfarer.swl2.functions.GeneratedFunctions.IFunction1;
import ru.swayfarer.swl2.ioc.DIManager.DISwL;
import ru.swayfarer.swl2.ioc.componentscan.DISwlComponent;
import ru.swayfarer.swl2.ioc.componentscan.DISwlSource;
import ru.swayfarer.swl2.ioc.context.elements.ContextElementType;
import ru.swayfarer.swl2.logger.ILogger;
import ru.swayfarer.swl2.logger.LoggingManager;
public class DIAnnotation {
public static ILogger logger = LoggingManager.getLogger();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> sourcesContextFun = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> findsContextFun = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> elementNameFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> elementContextFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, Boolean>> elementUsingNameFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, ContextElementType>> elementTypeFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> componentNameFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, String>> componentContextFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, Boolean>> componentUsingNameFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, ContextElementType>> componentTypeFuns = CollectionsSWL.createExtendedMap();
public static IExtendedMap<Class<?>, IFunction1<Annotation, Class<?>>> componentAssociatedClassFuns = CollectionsSWL.createExtendedMap();
public static String getFindAnnotationContextName(Annotation annotation)
{
return getByNamedFun(annotation, "context", String.class, findsContextFun, FindInContext.class);
}
public static String getSourceContextName(Annotation annotation)
{
return getByNamedFun(annotation, "context", String.class, sourcesContextFun, DISwlSource.class);
}
public static ContextElementType getComponentType(Annotation annotation)
{
return getByNamedFun(annotation, "type", ContextElementType.class, componentTypeFuns, DISwlComponent.class);
}
public static String getComponentName(Annotation annotation)
{
return getByNamedFun(annotation, "name", String.class, componentNameFuns, DISwlComponent.class);
}
public static String getComponentContextName(Annotation annotation)
{
return getByNamedFun(annotation, "context", String.class, componentContextFuns, DISwlComponent.class);
}
public static Class<?> getComponentAssociatedClass(Annotation annotation)
{
return getByNamedFun(annotation, "associated", Class.class, componentAssociatedClassFuns, DISwlComponent.class);
}
public static boolean isComponentUsingName(Annotation annotation)
{
return getByNamedFun(annotation, "usingName", boolean.class, componentUsingNameFuns, DISwlComponent.class);
}
public static ContextElementType getElementType(Annotation annotation)
{
return getByNamedFun(annotation, "type", ContextElementType.class, elementTypeFuns);
}
public static String getElementName(Annotation annotation)
{
return getByNamedFun(annotation, "name", String.class, elementNameFuns);
}
public static String getElementContextName(Annotation annotation)
{
return getByNamedFun(annotation, "context", String.class, elementContextFuns);
}
public static boolean isElementUsingName(Annotation annotation)
{
return getByNamedFun(annotation, "usingName", boolean.class, elementUsingNameFuns);
}
public static <T> T getByNamedFun(Annotation annotation, String paramName, Class<?> filterClass, IExtendedMap<Class<?>, IFunction1<Annotation, T>> elements)
{
return getByNamedFun(annotation, paramName, filterClass, elements, DISwL.class);
}
public static <T> T getByNamedFun(Annotation annotation, String paramName, Class<?> filterClass, IExtendedMap<Class<?>, IFunction1<Annotation, T>> elements, Class<? extends Annotation> markerAnnotationCl)
{
Class<? extends Annotation> annotationClass = annotation.getClass();
IFunction1<Annotation, T> fun = elements.get(annotationClass);
if (fun == null)
{
fun = createNamedFun(paramName, annotation, filterClass, markerAnnotationCl);
elements.put(annotationClass, fun);
}
return fun.apply(annotation);
}
public static <Ret_Type> IFunction1<Annotation, Ret_Type> createNamedFun(String name, Annotation annotation, Class<?> retTypeFilter, Class<? extends Annotation> markerAnnotationCl)
{
Class<? extends Annotation> annotationType = annotation.annotationType();
Method nameMethod = ReflectionUtils.methods(annotationType)
.named(name)
.noArgs()
.returnType(retTypeFilter)
.first();
if (nameMethod != null)
return (a) -> ExceptionsUtils.safeReturn(() -> (Ret_Type) nameMethod.invoke(a), null);
Annotation diswl = ReflectionUtils.findAnnotationRec(annotationType, markerAnnotationCl);
if (diswl != null)
return (a) -> ReflectionUtils.invokeMethod(diswl, name).getResult();
return null;
}
public static Annotation findDIAnnotation(Class<?> cl)
{
return findByDISwl(cl.getAnnotations());
}
public static Annotation findDIAnnotation(Method method)
{
return findByDISwl(method.getAnnotations());
}
public static Annotation findDIAnnotation(Parameter param)
{
return findByDISwl(param.getAnnotations());
}
public static Annotation findDIAnnotation(Field field)
{
return findByDISwl(field.getAnnotations());
}
public static Annotation findDIComponentAnnotation(Class<?> cl)
{
return findByAnnotation(cl, DISwlComponent.class);
}
public static Annotation findDISourceAnnotation(Class<?> cl)
{
return findByAnnotation(cl, DISwlSource.class);
}
public static Annotation findByAnnotation(Class<?> cl, Class<? extends Annotation> classOfAnnotation)
{
return DataStream.of(cl.getAnnotations()).first((annotation) -> annotation.annotationType().equals(classOfAnnotation) || ReflectionUtils.findAnnotationRec(annotation.annotationType(), classOfAnnotation) != null);
}
public static Annotation findByDISwl(Annotation[] annotations)
{
return findByDISwl(DataStream.of(annotations));
}
public static Annotation findByDISwl(IDataStream<Annotation> annotations)
{
return annotations.first((annotation) -> {
return annotation.annotationType().equals(DISwL.class) || ReflectionUtils.findAnnotationRec(annotation.annotationType(), DISwL.class) != null;
});
}
}
| 39.516304 | 214 | 0.789575 |
4f128f0537e1acf005f0b178d0fd1f9c608fb14a | 1,896 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecordServicingResourceRecord;
import javax.validation.Valid;
/**
* CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecord
*/
public class CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecord {
private String servicingResourceReference = null;
private CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecordServicingResourceRecord servicingResourceRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a servicing resource
* @return servicingResourceReference
**/
public String getServicingResourceReference() {
return servicingResourceReference;
}
public void setServicingResourceReference(String servicingResourceReference) {
this.servicingResourceReference = servicingResourceReference;
}
/**
* Get servicingResourceRecord
* @return servicingResourceRecord
**/
public CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecordServicingResourceRecord getServicingResourceRecord() {
return servicingResourceRecord;
}
public void setServicingResourceRecord(CRCustomerServicingResourceAllocationInitiateInputModelCustomerServicingResourceAllocationInstanceRecordServicingResourceRecord servicingResourceRecord) {
this.servicingResourceRecord = servicingResourceRecord;
}
}
| 37.92 | 195 | 0.858122 |
40ce54af5fb773f7c9d51c8f107cda859c9ae0ee | 921 | package ru.kpfu.itis.group11501.volkov.infopoisk.domain;
import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.UUID;
import static lombok.AccessLevel.PRIVATE;
@Entity
@Table(name ="articles")
@Getter
@Builder
@AllArgsConstructor
@FieldDefaults(level = PRIVATE)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
public class Article {
public static final String KEYWORD_DELIMITER = ";";
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(
name = "uuid",
strategy = "org.hibernate.id.UUIDGenerator"
)
UUID id;
String title;
//list of keyword with ';' delimiter
String keywords;
String content;
String url;
@ManyToOne
@JoinColumn(name = "student_id")
@Setter Student student;
}
| 20.466667 | 56 | 0.714441 |
d7d4b454884002ca67e45235b5423fca533f3922 | 2,474 | /*
* Copyright 2011 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.openehealth.ipf.platform.camel.ihe.mllp.core.mbean;
import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.ErrorCode;
import ca.uhn.hl7v2.Version;
import org.openehealth.ipf.commons.ihe.hl7v2.Hl7v2TransactionConfiguration;
import org.openehealth.ipf.commons.ihe.hl7v2.NakFactory;
import org.openehealth.ipf.commons.ihe.hl7v2.audit.MllpAuditDataset;
import org.openehealth.ipf.platform.camel.ihe.mllp.core.MllpTransactionComponent;
/**
* Test MLLP Component implementation
*/
public class SomeMllpItiComponent extends MllpTransactionComponent<MllpAuditDataset> {
private static final Hl7v2TransactionConfiguration<MllpAuditDataset> CONFIGURATION =
new Hl7v2TransactionConfiguration<>(
"foo",
"Some MLLP Component",
false,
null,
null,
new Version[] {Version.V25},
"Some MLLP adapter",
"IPF-Test",
ErrorCode.APPLICATION_INTERNAL_ERROR,
ErrorCode.APPLICATION_INTERNAL_ERROR,
new String[] { "ADT" },
new String[] { "A01 A04" },
new String[] { "ACK" },
new String[] { "*" },
new boolean[] { true },
new boolean[] { false },
new DefaultHapiContext());
public SomeMllpItiComponent() {
super(null);
}
private static final NakFactory<MllpAuditDataset> NAK_FACTORY = new NakFactory<>(CONFIGURATION);
@Override
public NakFactory<MllpAuditDataset> getNakFactory() {
return NAK_FACTORY;
}
@Override
public Hl7v2TransactionConfiguration<MllpAuditDataset> getHl7v2TransactionConfiguration() {
return CONFIGURATION;
}
}
| 36.382353 | 101 | 0.643088 |
94f55a92c6ff52f8baa8abbf5ba3fedcdddc2d33 | 13,856 | // Copyright 2006, 2007, 2008, 2009 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal;
import org.apache.tapestry5.*;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.Defense;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Shared utility methods used by various implementation classes.
*/
public class TapestryInternalUtils
{
private static final String SLASH = "/";
private static final Pattern SLASH_PATTERN = Pattern.compile(SLASH);
private static final Pattern NON_WORD_PATTERN = Pattern.compile("[^\\w]");
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
private static final int BUFFER_SIZE = 5000;
private static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* Capitalizes the string, and inserts a space before each upper case character (or sequence of upper case
* characters). Thus "userId" becomes "User Id", etc. Also, converts underscore into space (and capitalizes the
* following word), thus "user_id" also becomes "User Id".
*/
public static String toUserPresentable(String id)
{
StringBuilder builder = new StringBuilder(id.length() * 2);
char[] chars = id.toCharArray();
boolean postSpace = true;
boolean upcaseNext = true;
for (char ch : chars)
{
if (upcaseNext)
{
builder.append(Character.toUpperCase(ch));
upcaseNext = false;
continue;
}
if (ch == '_')
{
builder.append(' ');
upcaseNext = true;
continue;
}
boolean upperCase = Character.isUpperCase(ch);
if (upperCase && !postSpace) builder.append(' ');
builder.append(ch);
postSpace = upperCase;
}
return builder.toString();
}
public static Map<String, String> mapFromKeysAndValues(String... keysAndValues)
{
Map<String, String> result = CollectionFactory.newMap();
int i = 0;
while (i < keysAndValues.length)
{
String key = keysAndValues[i++];
String value = keysAndValues[i++];
result.put(key, value);
}
return result;
}
/**
* Converts a string to an {@link OptionModel}. The string is of the form "value=label". If the equals sign is
* omitted, then the same value is used for both value and label.
*
* @param input
* @return
*/
public static OptionModel toOptionModel(String input)
{
Defense.notNull(input, "input");
int equalsx = input.indexOf('=');
if (equalsx < 0) return new OptionModelImpl(input);
String value = input.substring(0, equalsx);
String label = input.substring(equalsx + 1);
return new OptionModelImpl(label, value);
}
/**
* Parses a string input into a series of value=label pairs compatible with {@link #toOptionModel(String)}. Splits
* on commas. Ignores whitespace around commas.
*
* @param input comma seperated list of terms
* @return list of option models
*/
public static List<OptionModel> toOptionModels(String input)
{
Defense.notNull(input, "input");
List<OptionModel> result = CollectionFactory.newList();
for (String term : input.split(","))
result.add(toOptionModel(term.trim()));
return result;
}
/**
* Wraps the result of {@link #toOptionModels(String)} as a {@link SelectModel} (with no option groups).
*
* @param input
* @return
*/
public static SelectModel toSelectModel(String input)
{
List<OptionModel> options = toOptionModels(input);
return new SelectModelImpl(null, options);
}
/**
* Converts a map entry to an {@link OptionModel}.
*
* @param input
* @return
*/
public static OptionModel toOptionModel(Map.Entry input)
{
Defense.notNull(input, "input");
String label = input.getValue() != null ? String.valueOf(input.getValue()) : "";
return new OptionModelImpl(label, input.getKey());
}
/**
* Processes a map input into a series of map entries compatible with {@link #toOptionModel(Map.Entry)}.
*
* @param input map of elements
* @return list of option models
*/
public static <K, V> List<OptionModel> toOptionModels(Map<K, V> input)
{
Defense.notNull(input, "input");
List<OptionModel> result = CollectionFactory.newList();
for (Map.Entry entry : input.entrySet())
result.add(toOptionModel(entry));
return result;
}
/**
* Wraps the result of {@link #toOptionModels(Map)} as a {@link SelectModel} (with no option groups).
*
* @param input
* @return
*/
public static <K, V> SelectModel toSelectModel(Map<K, V> input)
{
List<OptionModel> options = toOptionModels(input);
return new SelectModelImpl(null, options);
}
/**
* Converts an object to an {@link OptionModel}.
*
* @param input
* @return
*/
public static OptionModel toOptionModel(Object input)
{
String label = (input != null ? String.valueOf(input) : "");
return new OptionModelImpl(label, input);
}
/**
* Processes a list input into a series of objects compatible with {@link #toOptionModel(Object)}.
*
* @param input list of elements
* @return list of option models
*/
public static <E> List<OptionModel> toOptionModels(List<E> input)
{
Defense.notNull(input, "input");
List<OptionModel> result = CollectionFactory.newList();
for (E element : input)
result.add(toOptionModel(element));
return result;
}
/**
* Wraps the result of {@link #toOptionModels(List)} as a {@link SelectModel} (with no option groups).
*
* @param input
* @return
*/
public static <E> SelectModel toSelectModel(List<E> input)
{
List<OptionModel> options = toOptionModels(input);
return new SelectModelImpl(null, options);
}
/**
* Parses a key/value pair where the key and the value are seperated by an equals sign. The key and value are
* trimmed of leading and trailing whitespace, and returned as a {@link KeyValue}.
*
* @param input
* @return
*/
public static KeyValue parseKeyValue(String input)
{
int pos = input.indexOf('=');
if (pos < 1) throw new IllegalArgumentException(InternalMessages.badKeyValue(input));
String key = input.substring(0, pos);
String value = input.substring(pos + 1);
return new KeyValue(key.trim(), value.trim());
}
/**
* Used to convert a property expression into a key that can be used to locate various resources (Blocks, messages,
* etc.). Strips out any punctuation characters, leaving just words characters (letters, number and the
* underscore).
*
* @param expression a property expression
* @return the expression with punctuation removed
*/
public static String extractIdFromPropertyExpression(String expression)
{
return replace(expression, NON_WORD_PATTERN, "");
}
/**
* Looks for a label within the messages based on the id. If found, it is used, otherwise the name is converted to a
* user presentable form.
*/
public static String defaultLabel(String id, Messages messages, String propertyExpression)
{
String key = id + "-label";
if (messages.contains(key)) return messages.get(key);
return toUserPresentable(extractIdFromPropertyExpression(lastTerm(propertyExpression)));
}
/**
* Strips a dotted sequence (such as a property expression, or a qualified class name) down to the last term of that
* expression, by locating the last period ('.') in the string.
*/
public static String lastTerm(String input)
{
int dotx = input.lastIndexOf('.');
return input.substring(dotx + 1);
}
/**
* Converts an list of strings into a space-separated string combining them all, suitable for use as an HTML class
* attribute value.
*
* @param classes classes to combine
* @return the joined classes, or null if classes is empty
*/
public static String toClassAttributeValue(List<String> classes)
{
if (classes.isEmpty()) return null;
return InternalUtils.join(classes, " ");
}
/**
* Converts an enum to a label string, allowing for overrides from a message catalog.
* <p/>
* <ul> <li>As key <em>prefix</em>.<em>name</em> if present. Ex: "ElementType.LOCAL_VARIABLE" <li>As key
* <em>name</em> if present, i.e., "LOCAL_VARIABLE". <li>As a user-presentable version of the name, i.e., "Local
* Variable". </ul>
*
* @param messages the messages to search for the label
* @param prefix
* @param value to get a label for
* @return the label
*/
public static String getLabelForEnum(Messages messages, String prefix, Enum value)
{
String name = value.name();
String key = prefix + "." + name;
if (messages.contains(key)) return messages.get(key);
if (messages.contains(name)) return messages.get(name);
return toUserPresentable(name.toLowerCase());
}
public static String getLabelForEnum(Messages messages, Enum value)
{
String prefix = lastTerm(value.getClass().getName());
return getLabelForEnum(messages, prefix, value);
}
private static String replace(String input, Pattern pattern, String replacement)
{
return pattern.matcher(input).replaceAll(replacement);
}
/**
* Determines if the two values are equal. They are equal if they are the exact same value (including if they are
* both null). Otherwise standard equals() comparison is used.
*
* @param <T>
* @param left value to compare, possibly null
* @param right value to compare, possibly null
* @return true if same value, both null, or equal
*/
public static <T> boolean isEqual(T left, T right)
{
if (left == right) return true;
if (left == null) return right == null;
return left.equals(right);
}
/**
* Splits a path at each slash.
*/
public static String[] splitPath(String path)
{
return SLASH_PATTERN.split(path);
}
/**
* Splits a value around commas. Whitespace around the commas is removed, as is leading and trailing whitespace.
*
* @since 5.1.0.0
*/
public static String[] splitAtCommas(String value)
{
if (InternalUtils.isBlank(value))
return EMPTY_STRING_ARRAY;
return COMMA_PATTERN.split(value.trim());
}
/**
* Copies some content from an input stream to an output stream. It is the caller's responsibility to close the
* streams.
*
* @param in source of data
* @param out sink of data
* @throws IOException
* @since 5.1.0.0
*/
public static void copy(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[BUFFER_SIZE];
while (true)
{
int length = in.read(buffer);
if (length < 0) break;
out.write(buffer, 0, length);
}
// TAPESTRY-2415: WebLogic needs this flush() call.
out.flush();
}
public static boolean isEqual(EventContext left, EventContext right)
{
if (left == right) return true;
int count = left.getCount();
if (count != right.getCount()) return false;
for (int i = 0; i < count; i++)
{
if (!left.get(Object.class, i).equals(right.get(Object.class, i)))
return false;
}
return true;
}
/**
* Converts an Asset to an Asset2 if necessary. When actually wrapping an Asset as an Asset2, the asset is assumed
* to be variant (i.e., not cacheable).
*
* @since 5.1.0.0
*/
public static Asset2 toAsset2(final Asset asset)
{
if (asset instanceof Asset2)
return (Asset2) asset;
return new Asset2()
{
/** Returns false. */
public boolean isInvariant()
{
return false;
}
public Resource getResource()
{
return asset.getResource();
}
public String toClientURL()
{
return asset.toClientURL();
}
@Override
public String toString()
{
return asset.toString();
}
};
}
}
| 28.987448 | 120 | 0.613092 |
c9aec18740a0c34841e66789eba7dcd652f3bb87 | 312 | package com.floryt.auth.util;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.Task;
public interface CredentialTaskApi {
Task<Status> disableAutoSignIn();
Task<Status> delete(Credential credential);
}
| 26 | 62 | 0.788462 |
d06c03421ecb28ed49ab8c0d33313621b41b6f4d | 3,526 | package gamepad.scenes;
import gamepad.Camera;
import gamepad.Prefabs;
import gamepad.object.GameObject;
import gamepad.object.components.*;
import gamepad.renderer.DebugDraw;
import gamepad.utils.AssetPool;
import gamepad.utils.Transform;
import imgui.ImGui;
import imgui.ImVec2;
import org.joml.Vector2f;
import org.joml.Vector3f;
import org.joml.Vector4f;
public class LevelEditorScene extends Scene {
private Spritesheet sprites;
// private GameObject obj1;
public GameObject levelEditorComponents = new GameObject("Level Editor", new Transform(new Vector2f()), 0);
@Override
public void init() {
levelEditorComponents.addComponent(new MouseControls());
levelEditorComponents.addComponent(new GridLines());
loadResources();
this.camera = new Camera(new Vector2f(0, 0));
sprites = AssetPool.getSpritesheet("assets/images/spritesheets/decorationsAndBlocks.png");
if(levelLoaded) {
this.activeGameObject = gameObjects.get(0);
return;
}
//
// obj1 = new GameObject("Object 1", new Transform(new Vector2f(200, 100), new Vector2f(256, 256)), 2);
// SpriteRenderer obj1SpriteRenderer = new SpriteRenderer();
// obj1SpriteRenderer.setColor(new Vector4f(1, 0, 0, 1));
// obj1.addComponent(obj1SpriteRenderer);
// obj1.addComponent(new Rigidbody());
// this.addGameObjectToScene(obj1);
}
private void loadResources() {
AssetPool.getShader("assets/shaders/default.glsl");
AssetPool.addSpritesheet("assets/images/spritesheets/decorationsAndBlocks.png",
new Spritesheet(AssetPool.getTexture("assets/images/spritesheets/decorationsAndBlocks.png"), 16, 16,
81, 0));
}
@Override
public void update(float deltaTime) {
levelEditorComponents.update(deltaTime);
for(GameObject gameObject : this.gameObjects) {
gameObject.update(deltaTime);
}
this.renderer.render();
}
@Override
public void imgui() {
ImGui.begin("Test Window");
ImVec2 windowPos = new ImVec2();
ImGui.getWindowPos(windowPos);
ImVec2 windowSize = new ImVec2();
ImGui.getWindowSize(windowSize);
ImVec2 itemSpacing = new ImVec2();
ImGui.getStyle().getItemSpacing(itemSpacing);
float windowX2 = windowPos.x + windowSize.x;
for(int i = 0; i < sprites.size(); i++) {
Sprite sprite = sprites.getSprite(i);
float spriteWidth = sprite.getWidth() * 2;
float spriteHeight = sprite.getHeight() * 2;
int id = sprite.getTexId();
Vector2f[] texCoords = sprite.getTexCoords();
ImGui.pushID(i);
if(ImGui.imageButton(id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) {
GameObject object = Prefabs.generateSpriteObject(sprite, spriteWidth, spriteHeight);
levelEditorComponents.getComponent(MouseControls.class).pickupObject(object);
}
ImGui.popID();
ImVec2 lastButtonPosition = new ImVec2();
ImGui.getItemRectMax(lastButtonPosition);
float lastButtonX2 = lastButtonPosition.x;
float nexButtonX2 = lastButtonX2 + itemSpacing.x + spriteWidth;
if(i + 1 < sprites.size() && nexButtonX2 < windowX2) {
ImGui.sameLine();
}
}
ImGui.end();
}
}
| 33.580952 | 130 | 0.64152 |
808000374a343db53373d19b4d3223d4bea4625a | 664 | package com.betomaluje.miband.bluetooth;
/**
* Created by Lewis on 10/01/15.
*/
public class WaitAction implements BLEAction {
private final long duration;
public WaitAction(final long duration) {
this.duration = duration;
}
@Override
public boolean expectsResult() {
return false;
}
@Override
public boolean run(BTCommandManager btCommandManager) {
return threadWait(duration);
}
private boolean threadWait(final long duration) {
try {
Thread.sleep(duration);
return true;
} catch (InterruptedException e) {
return false;
}
}
}
| 20.75 | 59 | 0.615964 |
521ba7fb173bc4630d8bb1f945a2c4470abcbe09 | 896 | package com.example.stockmarket.event;
public class StockPriceChangedEvent {
private String symbol;
private double oldPrice;
private double newPrice;
public StockPriceChangedEvent() {
}
public StockPriceChangedEvent(String symbol, double oldPrice, double newPrice) {
this.symbol = symbol;
this.oldPrice = oldPrice;
this.newPrice = newPrice;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public double getOldPrice() {
return oldPrice;
}
public void setOldPrice(double oldPrice) {
this.oldPrice = oldPrice;
}
public double getNewPrice() {
return newPrice;
}
public void setNewPrice(double newPrice) {
this.newPrice = newPrice;
}
@Override
public String toString() {
return "StockPriceChangedEvent [symbol=" + symbol + ", oldPrice=" + oldPrice + ", newPrice=" + newPrice + "]";
}
}
| 19.06383 | 112 | 0.717634 |
cffb2fe2fa59c5ab13c5a07e3ac87facd5eb5624 | 1,609 | package net.dreamingworld.core.chat.commands;
import net.dreamingworld.DreamingWorld;
import net.dreamingworld.core.chat.ChannelType;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class InstantMessageCommands implements CommandExecutor, TabCompleter {
public InstantMessageCommands() {
Bukkit.getPluginCommand("global").setExecutor(this);
Bukkit.getPluginCommand("global").setTabCompleter(this);
Bukkit.getPluginCommand("local").setExecutor(this);
Bukkit.getPluginCommand("local").setTabCompleter(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdLine, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("aaaaa");
return true;
}
if (args.length < 1) {
return false;
}
String message = ""; // Why not I use StringBuilder? Because I don`t use StringBuilder
for (String arg : args) {
message += arg + " ";
}
DreamingWorld.getInstance().getChatManager().sendMessage(message, (Player) sender, cmd.getName().equals("local") ? ChannelType.LOCAL : ChannelType.GLOBAL);
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String cmdLine, String[] args) {
return new ArrayList<>();
}
}
| 32.18 | 163 | 0.687383 |
bfbe1d62294b4edcdb724c0fc013dfa3580546c1 | 2,395 | package io.renren.modules.generator.controller;
import java.util.Arrays;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.renren.modules.generator.entity.AimUserAccountEntity;
import io.renren.modules.generator.service.AimUserAccountService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
/**
*
*
* @author chenshun
* @email [email protected]
* @date 2019-08-13 19:32:21
*/
@RestController
@RequestMapping("generator/aimuseraccount")
public class AimUserAccountController {
@Autowired
private AimUserAccountService aimUserAccountService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("generator:aimuseraccount:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = aimUserAccountService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
@RequiresPermissions("generator:aimuseraccount:info")
public R info(@PathVariable("id") Integer id){
AimUserAccountEntity aimUserAccount = aimUserAccountService.getById(id);
return R.ok().put("aimUserAccount", aimUserAccount);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("generator:aimuseraccount:save")
public R save(@RequestBody AimUserAccountEntity aimUserAccount){
aimUserAccountService.save(aimUserAccount);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("generator:aimuseraccount:update")
public R update(@RequestBody AimUserAccountEntity aimUserAccount){
aimUserAccountService.updateById(aimUserAccount);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("generator:aimuseraccount:delete")
public R delete(@RequestBody Integer[] ids){
aimUserAccountService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
| 26.318681 | 74 | 0.720251 |
6b865b653b9159143fec9790a04ca46a596c2e35 | 1,439 | package weTubeBotLogic;
import me.duncte123.botcommons.messaging.EmbedUtils;
import me.duncte123.botcommons.web.WebUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import javax.security.auth.login.LoginException;
import java.util.EnumSet;
public class Bot {
private Bot() throws LoginException {
WebUtils.setUserAgent("WeTubeBot - Adriel#4266");
EmbedUtils.setEmbedBuilder(
() -> new EmbedBuilder()
.setColor(0xFF0000)
);
JDABuilder.createDefault(
System.getenv("TOKEN"),
GatewayIntent.GUILD_MESSAGES,
GatewayIntent.GUILD_VOICE_STATES
)
.disableCache(EnumSet.of(
CacheFlag.CLIENT_STATUS,
CacheFlag.ACTIVITY,
CacheFlag.EMOTE
))
.enableCache(CacheFlag.VOICE_STATE)
.addEventListeners(new Listener())
.setActivity(Activity.watching("A propaganda Soviética"))
.setStatus(OnlineStatus.ONLINE)
.build();
}
public static void main(String[] args) throws LoginException {
new Bot();
}
}
| 31.282609 | 73 | 0.62196 |
ee6631cf05a475c15a167152d2141204b59cb18d | 2,428 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("15")
class Record_1851 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1851: FirstName is Allene")
void FirstNameOfRecord1851() {
assertEquals("Allene", customers.get(1850).getFirstName());
}
@Test
@DisplayName("Record 1851: LastName is Hirth")
void LastNameOfRecord1851() {
assertEquals("Hirth", customers.get(1850).getLastName());
}
@Test
@DisplayName("Record 1851: Company is Mcadams, Shylah H Esq")
void CompanyOfRecord1851() {
assertEquals("Mcadams, Shylah H Esq", customers.get(1850).getCompany());
}
@Test
@DisplayName("Record 1851: Address is 29 Domino Dr")
void AddressOfRecord1851() {
assertEquals("29 Domino Dr", customers.get(1850).getAddress());
}
@Test
@DisplayName("Record 1851: City is Concord")
void CityOfRecord1851() {
assertEquals("Concord", customers.get(1850).getCity());
}
@Test
@DisplayName("Record 1851: County is Middlesex")
void CountyOfRecord1851() {
assertEquals("Middlesex", customers.get(1850).getCounty());
}
@Test
@DisplayName("Record 1851: State is MA")
void StateOfRecord1851() {
assertEquals("MA", customers.get(1850).getState());
}
@Test
@DisplayName("Record 1851: ZIP is 1742")
void ZIPOfRecord1851() {
assertEquals("1742", customers.get(1850).getZIP());
}
@Test
@DisplayName("Record 1851: Phone is 978-371-1854")
void PhoneOfRecord1851() {
assertEquals("978-371-1854", customers.get(1850).getPhone());
}
@Test
@DisplayName("Record 1851: Fax is 978-371-3874")
void FaxOfRecord1851() {
assertEquals("978-371-3874", customers.get(1850).getFax());
}
@Test
@DisplayName("Record 1851: Email is [email protected]")
void EmailOfRecord1851() {
assertEquals("[email protected]", customers.get(1850).getEmail());
}
@Test
@DisplayName("Record 1851: Web is http://www.allenehirth.com")
void WebOfRecord1851() {
assertEquals("http://www.allenehirth.com", customers.get(1850).getWeb());
}
}
| 25.291667 | 75 | 0.730643 |
644cfbf611baa6779a1a75e9b7a7d7c65f2d01f8 | 949 | package com.example.owner.ppkrinc;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ConfirmationPage extends AppCompatActivity {
private Bundle extraMatchData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation_page);
extraMatchData = getIntent().getExtras();
Button cancelButton = (Button) findViewById(R.id.CancelMatch);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
return;
}
});
}
public void goToMessaging(View view) {
Intent intent = new Intent(this, Users.class);
startActivity(intent);
}
}
| 27.911765 | 70 | 0.668072 |
e3419dfc2ce3c4ae2ccec853151fc90ad58e2b8f | 739 | package effectivejava.chapter5.item30;
import java.util.*;
// Using a recursive type bound to express mutual comparability (Pages 137-8)
public class RecursiveTypeBound {
// Returns max value in a collection - uses recursive type bound
public static <E extends Comparable<E>> E max(Collection<E> c) {
if (c.isEmpty())
throw new IllegalArgumentException("Empty collection");
E result = null;
for (E e : c)
if (result == null || e.compareTo(result) > 0)
result = Objects.requireNonNull(e);
return result;
}
public static void main(String[] args) {
List<String> argList = Arrays.asList(args);
System.out.println(max(argList));
}
} | 32.130435 | 77 | 0.631935 |
22ffd7fa5296cdcb38da97b9690cdd66203a7b88 | 8,452 | /*
* Harbor API
* These APIs provide services for manipulating Harbor project.
*
* OpenAPI spec version: 1.10.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.kathra.harbor.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.kathra.harbor.client.model.Label;
import org.kathra.harbor.client.model.ScanOverview;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* DetailedTag
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-20T18:34:04.523Z")
public class DetailedTag {
@SerializedName("digest")
private String digest = null;
@SerializedName("name")
private String name = null;
@SerializedName("size")
private Integer size = null;
@SerializedName("architecture")
private String architecture = null;
@SerializedName("os")
private String os = null;
@SerializedName("docker_version")
private String dockerVersion = null;
@SerializedName("author")
private String author = null;
@SerializedName("created")
private String created = null;
@SerializedName("signature")
private Object signature = null;
@SerializedName("scan_overview")
private ScanOverview scanOverview = null;
@SerializedName("labels")
private List<Label> labels = null;
public DetailedTag digest(String digest) {
this.digest = digest;
return this;
}
/**
* The digest of the tag.
* @return digest
**/
@ApiModelProperty(value = "The digest of the tag.")
public String getDigest() {
return digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public DetailedTag name(String name) {
this.name = name;
return this;
}
/**
* The name of the tag.
* @return name
**/
@ApiModelProperty(value = "The name of the tag.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DetailedTag size(Integer size) {
this.size = size;
return this;
}
/**
* The size of the image.
* @return size
**/
@ApiModelProperty(value = "The size of the image.")
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public DetailedTag architecture(String architecture) {
this.architecture = architecture;
return this;
}
/**
* The architecture of the image.
* @return architecture
**/
@ApiModelProperty(value = "The architecture of the image.")
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public DetailedTag os(String os) {
this.os = os;
return this;
}
/**
* The os of the image.
* @return os
**/
@ApiModelProperty(value = "The os of the image.")
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public DetailedTag dockerVersion(String dockerVersion) {
this.dockerVersion = dockerVersion;
return this;
}
/**
* The version of docker which builds the image.
* @return dockerVersion
**/
@ApiModelProperty(value = "The version of docker which builds the image.")
public String getDockerVersion() {
return dockerVersion;
}
public void setDockerVersion(String dockerVersion) {
this.dockerVersion = dockerVersion;
}
public DetailedTag author(String author) {
this.author = author;
return this;
}
/**
* The author of the image.
* @return author
**/
@ApiModelProperty(value = "The author of the image.")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public DetailedTag created(String created) {
this.created = created;
return this;
}
/**
* The build time of the image.
* @return created
**/
@ApiModelProperty(value = "The build time of the image.")
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public DetailedTag signature(Object signature) {
this.signature = signature;
return this;
}
/**
* The signature of image, defined by RepoSignature. If it is null, the image is unsigned.
* @return signature
**/
@ApiModelProperty(value = "The signature of image, defined by RepoSignature. If it is null, the image is unsigned.")
public Object getSignature() {
return signature;
}
public void setSignature(Object signature) {
this.signature = signature;
}
public DetailedTag scanOverview(ScanOverview scanOverview) {
this.scanOverview = scanOverview;
return this;
}
/**
* The overview of the scan result.
* @return scanOverview
**/
@ApiModelProperty(value = "The overview of the scan result.")
public ScanOverview getScanOverview() {
return scanOverview;
}
public void setScanOverview(ScanOverview scanOverview) {
this.scanOverview = scanOverview;
}
public DetailedTag labels(List<Label> labels) {
this.labels = labels;
return this;
}
public DetailedTag addLabelsItem(Label labelsItem) {
if (this.labels == null) {
this.labels = new ArrayList<Label>();
}
this.labels.add(labelsItem);
return this;
}
/**
* The label list.
* @return labels
**/
@ApiModelProperty(value = "The label list.")
public List<Label> getLabels() {
return labels;
}
public void setLabels(List<Label> labels) {
this.labels = labels;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DetailedTag detailedTag = (DetailedTag) o;
return Objects.equals(this.digest, detailedTag.digest) &&
Objects.equals(this.name, detailedTag.name) &&
Objects.equals(this.size, detailedTag.size) &&
Objects.equals(this.architecture, detailedTag.architecture) &&
Objects.equals(this.os, detailedTag.os) &&
Objects.equals(this.dockerVersion, detailedTag.dockerVersion) &&
Objects.equals(this.author, detailedTag.author) &&
Objects.equals(this.created, detailedTag.created) &&
Objects.equals(this.signature, detailedTag.signature) &&
Objects.equals(this.scanOverview, detailedTag.scanOverview) &&
Objects.equals(this.labels, detailedTag.labels);
}
@Override
public int hashCode() {
return Objects.hash(digest, name, size, architecture, os, dockerVersion, author, created, signature, scanOverview, labels);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DetailedTag {\n");
sb.append(" digest: ").append(toIndentedString(digest)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" size: ").append(toIndentedString(size)).append("\n");
sb.append(" architecture: ").append(toIndentedString(architecture)).append("\n");
sb.append(" os: ").append(toIndentedString(os)).append("\n");
sb.append(" dockerVersion: ").append(toIndentedString(dockerVersion)).append("\n");
sb.append(" author: ").append(toIndentedString(author)).append("\n");
sb.append(" created: ").append(toIndentedString(created)).append("\n");
sb.append(" signature: ").append(toIndentedString(signature)).append("\n");
sb.append(" scanOverview: ").append(toIndentedString(scanOverview)).append("\n");
sb.append(" labels: ").append(toIndentedString(labels)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 25.080119 | 127 | 0.67132 |
75dd85b3b2d03e60ee1c5c7f6be19472e5308d81 | 1,644 | package org.tensorflow.demo;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.tensorflow.demo.MainActivity;
import org.tensorflow.demo.R;
import org.tensorflow.demo.RecognitionScoreView;
/**
* Created by Kshitij on 2018-04-09.
*/
public class Results extends MainActivity {
Button btnHome;
questionnaireAgent qA = new questionnaireAgent();
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
showResult();
btnHome = findViewById(R.id.goBack);
btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent classifyIntent = new Intent(Results.this, MainActivity.class);
startActivity(classifyIntent);
}
});
}
private void showResult() {
int classNumber = Integer.parseInt(RecognitionScoreView.title.split(" ")[1]);
for (int i = 0; i < nearbyRoadSigns.length; i ++){
System.out.println("Before: " + nearbyRoadSigns[i]);
}
DecisionController finalDecision = new DecisionController(qA.questionnaireAgent(), nearbyRoadSigns, classNumber);
String finalConsensus = finalDecision.comeToConsensus();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Top Match: " + finalConsensus);
builder.setPositiveButton("Done", null);
builder.create().show();
}
}
| 31.018868 | 121 | 0.675791 |
2af0172a314075bc626695610affbd7698810e71 | 3,067 | package com.salesianostriana.dam.hoteluxe.controller;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.lowagie.text.DocumentException;
import com.salesianostriana.dam.hoteluxe.model.Reserva;
import com.salesianostriana.dam.hoteluxe.model.ReservaPDFExporter;
import com.salesianostriana.dam.hoteluxe.service.ReservaServicio;
import lombok.RequiredArgsConstructor;
@Controller
@RequestMapping("/admin/reserva")
@RequiredArgsConstructor
public class ReservaController {
private final ReservaServicio reservaServicio;
@GetMapping("/")
public String indexReserva(Model model,
@RequestParam("q") Optional<String> consulta) {
List<Reserva> reservas;
if(consulta.isEmpty()) {
reservas=reservaServicio.findAll();
}
else {
reservas=reservaServicio.buscarPorApellidos(consulta.get());
}
model.addAttribute("reservas", reservas);
return "admin/reservas";
}
@GetMapping("/nueva")
public String nuevaReserva(Model model) {
model.addAttribute("reserva", new Reserva());
model.addAttribute("habitaciones", reservaServicio.mostrarHabitacionesLibres());
return "admin/form_reserva";
}
@PostMapping("/nueva/submit")
public String submitNuevaReserva(@ModelAttribute("reserva") Reserva reserva, Model model) {
reservaServicio.save(reserva);
return "redirect:/admin/reserva/";
}
@GetMapping("/editar/{id}")
public String editarReserva(@PathVariable("id") Long id, Model model) {
Reserva r=reservaServicio.findById(id);
if(r!=null) {
model.addAttribute("reserva", r);
model.addAttribute("habitaciones", reservaServicio.mostrarHabitacionesLibres());
return "admin/form_reserva";
}
return "redirect:/admin/reserva/";
}
@GetMapping("/borrar/{id}")
public String borrarReserva(@PathVariable("id") Long id, Model model) {
Reserva r=reservaServicio.findById(id);
if(r!=null) {
reservaServicio.delete(r);
}
return "redirect:/admin/reserva/";
}
@GetMapping("/exportar")
public void generarPDFReservas(HttpServletResponse response) throws DocumentException, IOException {
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=reservas_" + LocalDate.now() + ".pdf";
response.setHeader(headerKey, headerValue);
List<Reserva> listaReservas = reservaServicio.findAll();
ReservaPDFExporter exporter = new ReservaPDFExporter(listaReservas);
exporter.export(response);
}
}
| 31.618557 | 101 | 0.759048 |
4f33d1c31105db5a8b1919e1470c7d7997c72ad2 | 92 | package com.megait.artrade.member;
public enum MemberType {
일반회원,
휴먼회원,
작가
}
| 9.2 | 34 | 0.641304 |
7611356dab153674acab97ca4d6751d6dcd11602 | 2,117 | /********************************6-33**********************************
(current date and time) Invoking System.currentTimeMillis() returns the elapsed
time since in milliseconds since midnight of Jan 1, 1970(epoch).Write a program
that displays the date and time.
*****************************************************************************/
package practice;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Milliseconds {
public static void main(String[] args) {
getDate();
getTime();
}
/** displays the current time in GMT(Greenwich Mean Time) in format: h:m:s */
public static void getManuelTime() {
// returns the total milliseconds since Jan 1, 1970
long totalMillis = System.currentTimeMillis();
// obtain total seconds
long totalSeconds = totalMillis / 1000;
// compute current second
long currentSeconds = totalSeconds % 60;
// obtain the total minutes
long totalMins = totalSeconds / 60;
// compute the current minute
long currentMin = totalMins % 60;
// obtain the total hours
long totalHours = totalMins / 60;
// compute the current hour
long currentHour = totalHours % 24;
// obtain hour in EST(Eastern Standard Time)
long est = currentHour + 19;
// display the result
System.out.println(est + ":" + currentMin + ":"
+ currentSeconds + " GMT");
}
/** retrieves the current date */
private static void getDate() {
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate));
}
private static void getTime() {
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime localTime = LocalTime.now();
System.out.println(dtf.format(localTime));
}
}
| 30.242857 | 81 | 0.563061 |
1b1cfc3207d131b42b04b3f5118f79a0c2e46c41 | 11,205 | package com.dslplatform.json;
import android.graphics.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
public abstract class AndroidGeomConverter {
public static final JsonReader.ReadObject<PointF> LOCATION_READER = new JsonReader.ReadObject<PointF>() {
@Nullable
@Override
public PointF read(JsonReader reader) throws IOException {
return reader.wasNull() ? null : deserializeLocation(reader);
}
};
public static final JsonWriter.WriteObject<PointF> LOCATION_WRITER = new JsonWriter.WriteObject<PointF>() {
@Override
public void write(JsonWriter writer, @Nullable PointF value) {
serializeLocationNullable(value, writer);
}
};
public static final JsonReader.ReadObject<Point> POINT_READER = new JsonReader.ReadObject<Point>() {
@Nullable
@Override
public Point read(JsonReader reader) throws IOException {
return reader.wasNull() ? null : deserializePoint(reader);
}
};
public static final JsonWriter.WriteObject<Point> POINT_WRITER = new JsonWriter.WriteObject<Point>() {
@Override
public void write(JsonWriter writer, @Nullable Point value) {
serializePointNullable(value, writer);
}
};
public static final JsonReader.ReadObject<Rect> RECTANGLE_READER = new JsonReader.ReadObject<Rect>() {
@Nullable
@Override
public Rect read(JsonReader reader) throws IOException {
return reader.wasNull() ? null : deserializeRectangle(reader);
}
};
public static final JsonWriter.WriteObject<Rect> RECTANGLE_WRITER = new JsonWriter.WriteObject<Rect>() {
@Override
public void write(JsonWriter writer, @Nullable Rect value) {
serializeRectangleNullable(value, writer);
}
};
public static final JsonReader.ReadObject<Bitmap> IMAGE_READER = new JsonReader.ReadObject<Bitmap>() {
@Nullable
@Override
public Bitmap read(JsonReader reader) throws IOException {
return reader.wasNull() ? null : deserializeImage(reader);
}
};
public static final JsonWriter.WriteObject<Bitmap> IMAGE_WRITER = new JsonWriter.WriteObject<Bitmap>() {
@Override
public void write(JsonWriter writer, @Nullable Bitmap value) {
serialize(value, writer);
}
};
public static void serializeLocationNullable(@Nullable final PointF value, final JsonWriter sw) {
if (value == null) {
sw.writeNull();
} else {
serializeLocation(value, sw);
}
}
public static void serializeLocation(final PointF value, final JsonWriter sw) {
sw.writeAscii("{\"X\":");
NumberConverter.serialize(value.x, sw);
sw.writeAscii(",\"Y\":");
NumberConverter.serialize(value.y, sw);
sw.writeByte(JsonWriter.OBJECT_END);
}
public static PointF deserializeLocation(final JsonReader reader) throws IOException {
if (reader.last() != '{') throw reader.newParseError("Expecting '{' for object start");
byte nextToken = reader.getNextToken();
if (nextToken == '}') return new PointF();
float x = 0;
float y = 0;
String name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
float value = NumberConverter.deserializeFloat(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
}
while ((nextToken = reader.getNextToken()) == ',') {
reader.getNextToken();
name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
value = NumberConverter.deserializeFloat(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
}
}
if (nextToken != '}') throw reader.newParseError("Expecting '}' for object end");
return new PointF(x, y);
}
public static ArrayList<PointF> deserializeLocationCollection(final JsonReader reader) throws IOException {
return reader.deserializeCollection(LOCATION_READER);
}
public static void deserializeLocationCollection(final JsonReader reader, final Collection<PointF> res) throws IOException {
reader.deserializeCollection(LOCATION_READER, res);
}
public static ArrayList<PointF> deserializeLocationNullableCollection(final JsonReader reader) throws IOException {
return reader.deserializeNullableCollection(LOCATION_READER);
}
public static void deserializeLocationNullableCollection(final JsonReader reader, final Collection<PointF> res) throws IOException {
reader.deserializeNullableCollection(LOCATION_READER, res);
}
public static void serializePointNullable(@Nullable final Point value, final JsonWriter sw) {
if (value == null) {
sw.writeNull();
} else {
serializePoint(value, sw);
}
}
public static void serializePoint(final Point value, final JsonWriter sw) {
sw.writeAscii("{\"X\":");
NumberConverter.serialize(value.x, sw);
sw.writeAscii(",\"Y\":");
NumberConverter.serialize(value.y, sw);
sw.writeByte(JsonWriter.OBJECT_END);
}
public static Point deserializePoint(final JsonReader reader) throws IOException {
if (reader.last() != '{') throw reader.newParseError("Expecting '{' for object start");
byte nextToken = reader.getNextToken();
if (nextToken == '}') return new Point();
int x = 0;
int y = 0;
String name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
int value = NumberConverter.deserializeInt(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
}
while ((nextToken = reader.getNextToken()) == ',') {
reader.getNextToken();
name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
value = NumberConverter.deserializeInt(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
}
}
if (nextToken != '}') throw reader.newParseError("Expecting '}' for object end");
return new Point(x, y);
}
public static ArrayList<Point> deserializePointCollection(final JsonReader reader) throws IOException {
return reader.deserializeCollection(POINT_READER);
}
public static void deserializePointCollection(final JsonReader reader, final Collection<Point> res) throws IOException {
reader.deserializeCollection(POINT_READER, res);
}
public static ArrayList<Point> deserializePointNullableCollection(final JsonReader reader) throws IOException {
return reader.deserializeNullableCollection(POINT_READER);
}
public static void deserializePointNullableCollection(final JsonReader reader, final Collection<Point> res) throws IOException {
reader.deserializeNullableCollection(POINT_READER, res);
}
public static void serializeRectangleNullable(@Nullable final Rect value, final JsonWriter sw) {
if (value == null) {
sw.writeNull();
} else {
serializeRectangle(value, sw);
}
}
public static void serializeRectangle(final Rect value, final JsonWriter sw) {
sw.writeAscii("{\"X\":");
NumberConverter.serialize(value.left, sw);
sw.writeAscii(",\"Y\":");
NumberConverter.serialize(value.top, sw);
sw.writeAscii(",\"Width\":");
NumberConverter.serialize(value.width(), sw);
sw.writeAscii(",\"Height\":");
NumberConverter.serialize(value.height(), sw);
sw.writeByte(JsonWriter.OBJECT_END);
}
public static Rect deserializeRectangle(final JsonReader reader) throws IOException {
if (reader.last() != '{') throw reader.newParseError("Expecting '{' for object start");
byte nextToken = reader.getNextToken();
if (nextToken == '}') return new Rect();
int x = 0;
int y = 0;
int width = 0;
int height = 0;
String name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
int value = NumberConverter.deserializeInt(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
} else if ("Width".equalsIgnoreCase(name)) {
width = value;
} else if ("Height".equalsIgnoreCase(name)) {
height = value;
}
while ((nextToken = reader.getNextToken()) == ',') {
reader.getNextToken();
name = StringConverter.deserialize(reader);
nextToken = reader.getNextToken();
if (nextToken != ':') throw reader.newParseError("Expecting ':' after attribute name");
reader.getNextToken();
value = NumberConverter.deserializeInt(reader);
if ("X".equalsIgnoreCase(name)) {
x = value;
} else if ("Y".equalsIgnoreCase(name)) {
y = value;
} else if ("Width".equalsIgnoreCase(name)) {
width = value;
} else if ("Height".equalsIgnoreCase(name)) {
height = value;
}
}
if (nextToken != '}') throw reader.newParseError("Expecting '}' for object end");
return new Rect(x, y, x + width, y + height);
}
public static ArrayList<Rect> deserializeRectangleCollection(final JsonReader reader) throws IOException {
return reader.deserializeCollection(RECTANGLE_READER);
}
public static void deserializeRectangleCollection(final JsonReader reader, final Collection<Rect> res) throws IOException {
reader.deserializeCollection(RECTANGLE_READER, res);
}
public static ArrayList<Rect> deserializeRectangleNullableCollection(final JsonReader reader) throws IOException {
return reader.deserializeNullableCollection(RECTANGLE_READER);
}
public static void deserializeRectangleNullableCollection(final JsonReader reader, final Collection<Rect> res) throws IOException {
reader.deserializeNullableCollection(RECTANGLE_READER, res);
}
public static void serialize(@Nullable final Bitmap value, final JsonWriter sw) {
if (value == null) {
sw.writeNull();
} else {
final ByteArrayOutputStream stream = new ByteArrayOutputStream(value.getByteCount());
value.compress(Bitmap.CompressFormat.PNG, 100, stream);
BinaryConverter.serialize(stream.toByteArray(), sw);
}
}
public static Bitmap deserializeImage(final JsonReader reader) throws IOException {
final byte[] content = BinaryConverter.deserialize(reader);
return BitmapFactory.decodeByteArray(content, 0, content.length);
}
public static ArrayList<Bitmap> deserializeImageCollection(final JsonReader reader) throws IOException {
return reader.deserializeCollection(IMAGE_READER);
}
public static void deserializeImageCollection(final JsonReader reader, final Collection<Bitmap> res) throws IOException {
reader.deserializeCollection(IMAGE_READER, res);
}
public static ArrayList<Bitmap> deserializeImageNullableCollection(final JsonReader reader) throws IOException {
return reader.deserializeNullableCollection(IMAGE_READER);
}
public static void deserializeImageNullableCollection(final JsonReader reader, final Collection<Bitmap> res) throws IOException {
reader.deserializeNullableCollection(IMAGE_READER, res);
}
}
| 36.617647 | 133 | 0.736368 |
c53753593840f781b6c921622d066d7642fcacf8 | 834 | package com.github.rochedo098.libradioactive.api.pollution;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
/**
* Extends this class to create a PollutionType;
*
* spreadRate is the speed at which the pollution spreads;
*
* The affectedEntity method you write what will happen to the affected entity;
* and
* The affectedWorld method you write what will happen to the affected world;
*/
public abstract class PollutionType {
protected int spreadRate;
public PollutionType(int spreadRate) {
this.spreadRate = spreadRate;
}
public int getPollutionSpreadRate() {
return spreadRate;
}
public abstract void affectedEntity(LivingEntity entity);
public abstract void affectedWorld(World world, ChunkPos pos);
} | 28.758621 | 80 | 0.745803 |
224e5e2634e00b348bea6a0fc58ad0425f6aa43b | 113 | package zhushen.com.shejimoshi.chapter20.example2;
/**
* Created by Zhushen on 2018/6/4.
*/
class Article {
}
| 14.125 | 50 | 0.707965 |
b21d6ddd52856191c7aedd25373160b8466c7744 | 100 | package com.inmobi.nativead.sample.photopages;
public final class PageItem {
String imageUrl;
} | 20 | 46 | 0.78 |
3da7aac47d2b30ff71d8fdf62da56c3bd43762d7 | 476 | package com.games.rasta.randomadventure.models;
public class Player {
private String name;
private int level;
private int xp;
private int attack;
private int defense;
private int speed;
private int maxHealth;
private int currentHealth;
public Player(String name) {
this.name = name;
this.level = 1;
this.xp = 0;
this.attack = 10;
this.defense = 10;
this.speed = 10;
this.maxHealth = 100;
this.currentHealth = 100;
}
}
| 17 | 47 | 0.661765 |
e52ef6ec98d25dde2928d4a4a9bf4afbd6d8fb41 | 338 | package slate.items;
import slate.Player;
import slate.bases.ItemBase;
public class StickyBaby extends ItemBase {
public StickyBaby() {
name = "Sticky Baby";
weight = 5;
is_consumable = true;
verb = "ate";
}
@Override
public void use(Player player) {
//Eat sticky baby
System.out.println("I'm just a monster.");
}
}
| 15.363636 | 44 | 0.683432 |
4cb077a735092192d591a4b32641c52753d91aa2 | 12,170 | package org.cbsa.api.controller.metadata;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.cbsa.api.bgmapr.WordCount;
import org.cbsa.api.model.FileMetadata;
import org.cbsa.api.model.Keyword;
import org.cbsa.api.model.KeywordDetails;
import org.cbsa.api.model.MetaSchema;
@SuppressWarnings("deprecation")
public class MetadataManager {
private final Logger logger = Logger.getLogger(WordCount.class.getName());
private Configuration config;
private HBaseAdmin admin;
private HTable fileInfoTable;
private HTable fileKeywordsTable;
/***
* Use this to create meta data tables and start connection to database to
* store meta data of files. This constructor will create meta data tables
* to HBase database if not exists and print error if fails to create
* database tables.
*/
public MetadataManager() {
logger.setLevel(Level.INFO);
if (!MetadataTables.createTables()) {
logger.info("metadata table creation failed");
return;
}
config = HBaseConfiguration.create();
try {
fileInfoTable = new HTable(config, MetaSchema.TB_FILE_INFO);
fileKeywordsTable = new HTable(config, MetaSchema.TB_FILE_KEYWORDS);
} catch (IOException e) {
e.printStackTrace();
}
try {
admin = new HBaseAdmin(config);
} catch (IOException e) {
e.printStackTrace();
}
}
/***
* Use this method to add new meta data of file to database.
*
* @param fileMetadata
*/
public void addNewFileMetadata(FileMetadata fileMetadata) {
Put putFileInfo = new Put(Bytes.toBytes(fileMetadata.getFileID()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_GENERAL),
Bytes.toBytes(MetaSchema.CO_FILE_NAME),
Bytes.toBytes(fileMetadata.getFileName()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_GENERAL),
Bytes.toBytes(MetaSchema.CO_FILE_PATH),
Bytes.toBytes(fileMetadata.getFilePath()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_GENERAL),
Bytes.toBytes(MetaSchema.CO_FILE_SIZE),
Bytes.toBytes(fileMetadata.getFileSize()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_GENERAL),
Bytes.toBytes(MetaSchema.CO_TOTAL_PAGES),
Bytes.toBytes(fileMetadata.getTotalPages()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_DOMAIN),
Bytes.toBytes(MetaSchema.CO_SUB_DOMAIN),
Bytes.toBytes(fileMetadata.getFileDomain()));
putFileInfo.add(Bytes.toBytes(MetaSchema.CF_FILE_ID),
Bytes.toBytes(MetaSchema.CO_ID),
Bytes.toBytes(fileMetadata.getFileID()));
List<Put> putKeywordsList = new ArrayList<Put>();
List<Keyword> fileKeywords = fileMetadata.getKeywords();
for (int i = 0; i < fileKeywords.size(); i++) {
Put putKeywords = new Put(Bytes.toBytes(fileMetadata.getFileID()
+ "_" + String.valueOf(i)));
putKeywords.add(Bytes.toBytes(MetaSchema.CF_FILE_ID),
Bytes.toBytes(MetaSchema.CO_ID),
Bytes.toBytes(fileMetadata.getFileID()));
putKeywords.add(Bytes.toBytes(MetaSchema.CF_KEYWORDS),
Bytes.toBytes(MetaSchema.CO_KEYWORD),
Bytes.toBytes(fileKeywords.get(i).getKeyword()));
putKeywords.add(Bytes.toBytes(MetaSchema.CF_KEYWORDS),
Bytes.toBytes(MetaSchema.CO_FREQUENCY),
Bytes.toBytes(fileKeywords.get(i).getFrequency()));
putKeywordsList.add(putKeywords);
}
try {
fileInfoTable.put(putFileInfo);
for (int i = 0; i < fileKeywords.size(); i++) {
fileKeywordsTable.put(putKeywordsList.get(i));
}
fileInfoTable.close();
fileKeywordsTable.close();
} catch (IOException e) {
e.printStackTrace();
logger.info("file metadata insertion failed");
}
logger.info("file metadata insertion successful");
}
public List<FileMetadata> getFileMetadata() throws IOException {
List<FileMetadata> fileMetadataList = null;
Scan scanFileInfo = null;
Scan scanFileKeywords = null;
ResultScanner scannerFileInfo = null;
ResultScanner scannerFileKeywords = null;
boolean skip = true;
scanFileInfo = new Scan();
scanFileInfo.addFamily(Bytes.toBytes(MetaSchema.CF_GENERAL));
scanFileInfo.addFamily(Bytes.toBytes(MetaSchema.CF_DOMAIN));
scanFileKeywords = new Scan();
scanFileKeywords.addFamily(Bytes.toBytes(MetaSchema.CF_KEYWORDS));
try {
scannerFileInfo = fileInfoTable.getScanner(scanFileInfo);
scannerFileKeywords = fileKeywordsTable
.getScanner(scanFileKeywords);
} catch (IOException e) {
e.printStackTrace();
}
for (Result result = scannerFileInfo.next(); result != null; result = scannerFileInfo
.next()) {
for (KeyValue keyValue : result.list()) {
// System.out.print(Bytes.toString(keyValue.getValue()) + " ");
}
System.out.println();
}
for (Result result = scannerFileKeywords.next(); result != null; result = scannerFileKeywords
.next()) {
for (KeyValue keyValue : result.list()) {
System.out.println(Bytes.toString(keyValue.getValue()) + " ");
}
}
scannerFileInfo.close();
scannerFileKeywords.close();
return fileMetadataList;
}
public List<String> getDocumentsWithKeywords(List<String> searchKeywordsList)
throws IOException {
List<String> documentPathList = new ArrayList<String>();
List<KeywordDetails> keywordDetailsList = new ArrayList<KeywordDetails>();
Scan scanFileInfo = null;
Scan scanFileKeywords = null;
ResultScanner scannerFileInfo = null;
ResultScanner scannerFileKeywords = null;
Get filePathGetter = null;
Result filePathResult = null;
// retrieve keywords list
scanFileKeywords = new Scan();
scanFileKeywords.addFamily(Bytes.toBytes(MetaSchema.CF_FILE_ID));
scanFileKeywords.addFamily(Bytes.toBytes(MetaSchema.CF_KEYWORDS));
try {
scannerFileKeywords = fileKeywordsTable
.getScanner(scanFileKeywords);
} catch (IOException e) {
e.printStackTrace();
}
for (Result result = scannerFileKeywords.next(); result != null; result = scannerFileKeywords
.next()) {
Iterator<KeyValue> iterator = result.list().iterator();
while (iterator.hasNext()) {
/*
* System.out.println(Bytes.toString(iterator.next().getValue())
* + " " + Bytes.toString(iterator.next().getValue()) + " " +
* Bytes.toString(iterator.next().getValue()));
*/
KeywordDetails tempKeywordDetails = new KeywordDetails(
Bytes.toString(iterator.next().getValue()),
Bytes.toString(iterator.next().getValue()),
Bytes.toString(iterator.next().getValue()));
keywordDetailsList.add(tempKeywordDetails);
}
}
// System.out.println();
// System.out.println("Before Filtering");
//
// for (KeywordDetails keywordDetails : keywordDetailsList) {
//
// System.out.println(keywordDetails.getFileID() + " "
// + keywordDetails.getFrequency() + " "
// + keywordDetails.getKeyword());
// }
// filter the keywordDetails list as per searchKeywords
Iterator<KeywordDetails> keywordDetailsIterator = keywordDetailsList
.iterator();
while (keywordDetailsIterator.hasNext()) {
boolean keywordPresent = false;
KeywordDetails tempKeywordDetails = keywordDetailsIterator.next();
String currentkeyword = tempKeywordDetails.getKeyword();
for (String keyword : searchKeywordsList) {
if (keyword.equals(currentkeyword)) {
keywordPresent = true;
break;
}
}
if (!keywordPresent) {
keywordDetailsIterator.remove();
}
}
/*
System.out.println("After Filtering");
for (KeywordDetails keywordDetails : keywordDetailsList) {
System.out.println(keywordDetails.getFileID() + " "
+ keywordDetails.getFrequency() + " "
+ keywordDetails.getKeyword());
}
*/
// Sort According to frequency of keywords
Collections.sort(keywordDetailsList, new FrequencyComparator());
/*
System.out.println("After Sorting");
for (KeywordDetails keywordDetails : keywordDetailsList) {
System.out.println(keywordDetails.getFileID() + " "
+ keywordDetails.getFrequency() + " "
+ keywordDetails.getKeyword());
}
*/
// get fileID of selected keywords list
Set<String> uniqueFileList = new LinkedHashSet<String>();
for (KeywordDetails keywordDetails : keywordDetailsList) {
uniqueFileList.add(keywordDetails.getFileID());
}
/*
for (String fileID : uniqueFileList) {
System.out.println(fileID);
}
*/
// save paths of documents with those fileID
for (String fileID : uniqueFileList) {
filePathGetter = new Get(Bytes.toBytes(fileID));
filePathResult = fileInfoTable.get(filePathGetter);
String tempPath = Bytes.toString(filePathResult.getValue(
Bytes.toBytes(MetaSchema.CF_GENERAL),
Bytes.toBytes(MetaSchema.CO_FILE_PATH)));
documentPathList.add(tempPath);
}
// save paths of documents with those fileID
/*
scanFileInfo = new Scan();
scanFileInfo.addFamily(Bytes.toBytes(MetaSchama.CF_FILE_ID));
scanFileInfo.addColumn(Bytes.toBytes(MetaSchama.CF_GENERAL),
Bytes.toBytes(MetaSchama.CO_FILE_PATH));
try {
scannerFileInfo = fileInfoTable.getScanner(scanFileInfo);
} catch (IOException e) {
e.printStackTrace();
}
for (Result result = scannerFileInfo.next(); result != null; result = scannerFileInfo
.next()) {
Iterator<KeyValue> iterator = result.list().iterator();
while (iterator.hasNext()) {
String fileID = Bytes.toString(iterator.next().getValue());
String filePath = Bytes.toString(iterator.next().getValue());
if (uniqueFileList.contains(fileID)) {
documentPathList.add(filePath);
}
}
}
scannerFileInfo.close();
*/
scannerFileKeywords.close();
return documentPathList;
}
}
| 31.285347 | 101 | 0.60493 |
2247688db30eb7334c98994cbfc78f175e4bd7fa | 4,331 | package com.bits;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.amazonaws.mobile.auth.core.IdentityManager;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.config.AWSConfiguration;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
public class FeedActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DynamoDBMapper dynamoDBMapper;
String userId, title, description;
double transactionId, requestAmount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
// going to populate feed here
void populateFeed(){
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
this.dynamoDBMapper = DynamoDBMapper.builder()
.dynamoDBClient(dynamoDBClient)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.build();
final Context context = getApplicationContext();
AWSConfiguration awsConfiguration = new AWSConfiguration(context);
final IdentityManager identityManager = new IdentityManager(context, awsConfiguration);
final ProfileDO profile = new ProfileDO();
profile.setUserId(identityManager.getCachedUserID());
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
startActivity(new Intent(FeedActivity.this, Profile_Activity.class));
// Handle the camera action
} else if (id == R.id.nav_gallery) {
startActivity(new Intent(FeedActivity.this, HistoryPage_Activity_.class));
} else if (id == R.id.create_request) {
startActivity(new Intent(FeedActivity.this, MakeRequestTab.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| 36.394958 | 127 | 0.706765 |
dbd60ba3adef4be34be58bf6454fa197f8a4b452 | 6,103 | package co.unruly.config;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static co.unruly.config.Configuration.*;
import static co.unruly.config.SecretsManagerTest.storeSecret;
import static co.unruly.matchers.OptionalMatchers.contains;
import static co.unruly.matchers.OptionalMatchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
public class ConfigurationTest {
@Test
public void shouldReturnEmptyOptionalIfValueNotFound() {
Map<String, String> input = Collections.emptyMap();
Configuration config = Configuration.from(map(input));
assertThat(config.get("some-variable"), is(empty()));
}
@Test
public void shouldReturnDefaultValueIfProvidedAndValueNotFound() {
Map<String, String> input = Collections.emptyMap();
Configuration config = Configuration.from(map(input));
assertThat(config.get("some-variable", "default-value"), is("default-value"));
}
@Test(expected = ConfigurationMissing.class)
public void shouldThrowIfRequiredValueNotFound() {
Map<String, String> input = Collections.emptyMap();
Configuration config = Configuration.from(map(input));
config.require("some-variable");
}
@Test
public void shouldReturnOptionalIfValueIsPresent() {
Map<String, String> input = new HashMap<>();
input.put("some-variable", "dfsadad");
Configuration config = Configuration.from(map(input));
assertThat(config.get("some-variable"), contains("dfsadad"));
}
@Test
public void shouldReadFromFileFirstIfValueIsPresent() {
Map<String, String> input = new HashMap<>();
input.put("some-variable", "dfsadad");
Configuration config = Configuration
.from(properties("src/test/resources/test.properties"))
.or(map(input));
assertThat(config.get("some-variable"), contains("blah"));
}
@Test
public void shouldSupportVarargsOrdering() {
Map<String, String> input = new HashMap<>();
input.put("some-variable", "dfsadad");
Configuration config = Configuration.of(
properties("src/test/resources/test.properties"),
map(input)
);
assertThat(config.get("some-variable"), contains("blah"));
}
@Test
public void shouldFallBackToNextConfigurationSource_Map() {
Map<String, String> input = new HashMap<>();
input.put("map-scenario-user", "from-a-map");
Configuration config = Configuration.of(
map(new HashMap<>()),
map(input)
);
assertThat(config.get("map-scenario-user"), contains("from-a-map"));
}
@Test
public void shouldFallBackToNextConfigurationSource_Properties() {
Configuration config = Configuration.of(
properties("this-file-does-not-exist.properties"),
properties("src/test/resources/test.properties")
);
assertThat(config.get("some-variable"), contains("blah"));
}
@Test
public void shouldFallBackToNextConfigurationSource_SecretsManager() {
Configuration config = Configuration.of(
secretsManager("my-secret-1", "eu-west-1", storeSecret("not actually JSON")),
secretsManager("my-secret-2", "eu-west-1", storeSecret("{\"my-key\":\"my-value\"}"))
);
assertThat(config.get("my-key"), contains("my-value"));
}
@Test
public void shouldThrowExceptionIfProblemOpeningPropertiesFile() {
Configuration config = Configuration
.from(properties("src/test/resources/doesNotExist.properties"));
assertThat(config.get("anything"), is(empty()));
}
@Test
public void shouldNotCallSubsequentSourcesIfEarlierSourceProvidesValue() {
Map<String, String> input = new HashMap<>();
input.put("some-variable", "dfsadad");
ConfigurationSource secondarySource = mock(ConfigurationSource.class);
Configuration config = Configuration.of(
map(input),
secondarySource
);
assertThat(config.get("some-variable"), contains("dfsadad"));
verifyZeroInteractions(secondarySource);
}
// VARIABLE=foo is set via maven-surefire-plugin in the POM
@Test
public void shouldUseEnvironmentVariables_ToUpperCase() {
Configuration config = Configuration.of(
environment()
);
assertThat(config.get("variable"), contains("foo"));
}
@Test
public void shouldUseEnvironmentVariables_ExactCase() {
Configuration config = Configuration.of(
environment()
);
assertThat(config.get("VARIABLE"), contains("foo"));
}
@Test
public void shouldReturnEmptyOptionalIfNotFoundInSecretsManager() {
AWSSecretsManager awsMockClient = storeSecret("");
Configuration config = Configuration.of(
secretsManager("some_secret_that_does_not_exist", "eu-west-1", awsMockClient)
);
assertThat(config.get("user"), is(empty()));
assertThat(config.get("pass"), is(empty()));
}
@Test
public void shouldUseSystemProperties() {
System.setProperty("my.system.property", "my-value");
Configuration config = Configuration.of(systemProperties());
assertThat(config.get("my.system.property"), contains("my-value"));
}
@Test
public void shouldUseSystemProperties_isEmptyWhenMissing() {
// This is a separate test because we want to explicitly clear my.system.property
// Otherwise running e.g. `mvn clean test -Dmy.system.property=foo` would cause this test to fail
System.clearProperty("my.system.property");
Configuration config = Configuration.of(systemProperties());
assertThat(config.get("my.system.property"), is(empty()));
}
}
| 32.291005 | 105 | 0.655907 |
c7c331e3b58131f84fbe120878e8524cde387b08 | 4,023 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.expression.function.scalar.script;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyList;
/**
* Parameters for a script
*
* This class mainly exists to handle the different aggregation cases.
* While aggs can appear in scripts like regular parameters, they are not passed
* as parameters but rather as bucket_path.
* However in some cases (like count), it's not the agg path that is relevant but rather
* its property (_count).
* As the agg name still needs to be remembered to properly associate the script with.
*
* Hence why this class supports aggRef (which always returns the agg names) and aggPaths
* (which returns the agg property if it exists or the agg name/reference).
*
* Also the parameter names support late binding/evaluation since the agg reference (like function id)
* can be changed during the optimization phase (for example min agg -> stats.min).
*/
public class Params {
public static final Params EMPTY = new Params(emptyList());
private final List<Param<?>> params;
Params(List<Param<?>> params) {
// flatten params
this.params = flatten(params);
}
// return vars and aggs in the declared order for binding them to the script
List<String> asCodeNames() {
if (params.isEmpty()) {
return emptyList();
}
List<String> names = new ArrayList<>(params.size());
int aggs = 0, vars = 0;
for (Param<?> p : params) {
names.add(p.prefix() + (p instanceof Agg ? aggs++ : vars++));
}
return names;
}
// return only the vars (as parameter for a script)
// agg refs are returned separately to be provided as bucket_paths
Map<String, Object> asParams() {
Map<String, Object> map = new LinkedHashMap<>(params.size());
int count = 0;
for (Param<?> p : params) {
if (p instanceof Var) {
map.put(p.prefix() + count++, p.value());
}
}
return map;
}
// return agg refs in a format suitable for bucket_paths
Map<String, String> asAggPaths() {
Map<String, String> map = new LinkedHashMap<>();
int aggs = 0;
for (Param<?> p : params) {
if (p instanceof Agg) {
Agg a = (Agg) p;
String s = a.aggProperty() != null ? a.aggProperty() : a.aggName();
map.put(p.prefix() + aggs++, s);
}
}
return map;
}
// return the agg refs
List<String> asAggRefs() {
List<String> refs = new ArrayList<>();
for (Param<?> p : params) {
if (p instanceof Agg) {
refs.add(((Agg) p).aggName());
}
}
return refs;
}
private static List<Param<?>> flatten(List<Param<?>> params) {
List<Param<?>> flatten = emptyList();
if (!params.isEmpty()) {
flatten = new ArrayList<>();
for (Param<?> p : params) {
if (p instanceof Script) {
flatten.addAll(flatten(((Script) p).value().params));
}
else if (p instanceof Agg) {
flatten.add(p);
}
else if (p instanceof Var) {
flatten.add(p);
}
else {
throw new SqlIllegalArgumentException("Unsupported field {}", p);
}
}
}
return flatten;
}
@Override
public String toString() {
return params.toString();
}
}
| 29.8 | 102 | 0.578424 |
4bfe8a92fef72da7451a51d6076f6c09f3f9edc3 | 1,614 | /*
Copyright 2019, 2021-2022 WeAreFrank!
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 nl.nn.adapterframework.extensions.aspose.services.conv.impl;
import java.io.IOException;
import org.apache.tika.Tika;
import org.apache.tika.io.TikaInputStream;
import org.springframework.http.MediaType;
import nl.nn.adapterframework.stream.Message;
/**
* Specific class to detect media type used by CisConversionServiceImpl
*
*/
class MediaTypeValidator {
private Tika tika;
/**
* Package default access because it specific for the conversion.
*/
public MediaTypeValidator() {
// Create only once. Tika seems to be thread safe
// (see
// http://stackoverflow.com/questions/10190980/spring-tika-integration-is-my-approach-thread-safe)
tika = new Tika();
}
/**
* Detects media type from input stream
*/
public MediaType getMediaType(Message message, String filename) throws IOException {
message.preserve();
try (TikaInputStream tis = TikaInputStream.get(message.asInputStream())) {
String type = tika.detect(tis, filename);
return MediaType.valueOf(type);
}
}
} | 29.345455 | 100 | 0.745973 |
8de5eda2befe4e16c53a09d1d2fdbf82dbbdeaed | 34,219 | package de.dlyt.yanndroid.oneui.preference;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.AbsSavedState;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.widget.TextView;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.res.TypedArrayUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import de.dlyt.yanndroid.oneui.R;
import de.dlyt.yanndroid.oneui.preference.internal.SeslPreferenceImageView;
public class Preference implements Comparable<de.dlyt.yanndroid.oneui.preference.Preference> {
public static final int DEFAULT_ORDER = Integer.MAX_VALUE;
private final OnClickListener mClickListener;
public boolean mIsSolidRoundedCorner;
boolean mIsPreferenceRoundedBg;
boolean mIsRoundChanged;
int mSubheaderColor;
boolean mSubheaderRound;
int mWhere;
private boolean mAllowDividerAbove;
private boolean mAllowDividerBelow;
private boolean mBaseMethodCalled;
private boolean mChangedSummaryColor;
private boolean mChangedSummaryColorStateList;
private Context mContext;
private Object mDefaultValue;
private String mDependencyKey;
private boolean mDependencyMet;
private List<de.dlyt.yanndroid.oneui.preference.Preference> mDependents;
private boolean mEnabled;
private Bundle mExtras;
private String mFragment;
private boolean mHasId;
private boolean mHasSingleLineTitleAttr;
private Drawable mIcon;
private int mIconResId;
private boolean mIconSpaceReserved;
private long mId;
private Intent mIntent;
private String mKey;
private int mLayoutResId;
private de.dlyt.yanndroid.oneui.preference.Preference.OnPreferenceChangeInternalListener mListener;
private de.dlyt.yanndroid.oneui.preference.Preference.OnPreferenceChangeListener mOnChangeListener;
private de.dlyt.yanndroid.oneui.preference.Preference.OnPreferenceClickListener mOnClickListener;
private int mOrder;
private boolean mParentDependencyMet;
private PreferenceGroup mParentGroup;
private boolean mPersistent;
private PreferenceDataStore mPreferenceDataStore;
private PreferenceManager mPreferenceManager;
private boolean mSelectable;
private boolean mShouldDisableView;
private boolean mSingleLineTitle;
private CharSequence mSummary;
private int mSummaryColor;
private ColorStateList mSummaryColorStateList;
private ColorStateList mTextColorSecondary;
private CharSequence mTitle;
private int mViewId;
private boolean mVisible;
private boolean mWasDetached;
private int mWidgetLayoutResId;
@SuppressLint("RestrictedApi")
public Preference(Context var1, AttributeSet var2) {
this(var1, var2, TypedArrayUtils.getAttr(var1, R.attr.preferenceStyle, 16842894));
}
public Preference(Context var1, AttributeSet var2, int var3) {
this(var1, var2, var3, 0);
}
@SuppressLint("RestrictedApi")
public Preference(Context var1, AttributeSet var2, int var3, int var4) {
this.mOrder = 2147483647;
this.mViewId = 0;
this.mEnabled = true;
this.mSelectable = true;
this.mPersistent = true;
this.mDependencyMet = true;
this.mParentDependencyMet = true;
this.mVisible = true;
this.mAllowDividerAbove = true;
this.mAllowDividerBelow = true;
this.mSingleLineTitle = true;
this.mIsSolidRoundedCorner = false;
this.mIsPreferenceRoundedBg = false;
this.mSubheaderRound = false;
this.mWhere = 0;
this.mIsRoundChanged = false;
this.mChangedSummaryColor = false;
this.mChangedSummaryColorStateList = false;
this.mShouldDisableView = true;
this.mLayoutResId = R.layout.sesl_preference;
this.mClickListener = new OnClickListener() {
public void onClick(View var1) {
de.dlyt.yanndroid.oneui.preference.Preference.this.performClick(var1);
}
};
this.mContext = var1;
TypedArray var5 = var1.obtainStyledAttributes(var2, R.styleable.Preference, var3, var4);
this.mIconResId = TypedArrayUtils.getResourceId(var5, R.styleable.Preference_icon, R.styleable.Preference_android_icon, 0);
this.mKey = TypedArrayUtils.getString(var5, R.styleable.Preference_key, R.styleable.Preference_android_key);
this.mTitle = TypedArrayUtils.getText(var5, R.styleable.Preference_title, R.styleable.Preference_android_title);
this.mSummary = TypedArrayUtils.getText(var5, R.styleable.Preference_summary, R.styleable.Preference_android_summary);
this.mOrder = TypedArrayUtils.getInt(var5, R.styleable.Preference_order, R.styleable.Preference_android_order, 2147483647);
this.mFragment = TypedArrayUtils.getString(var5, R.styleable.Preference_fragment, R.styleable.Preference_android_fragment);
this.mLayoutResId = TypedArrayUtils.getResourceId(var5, R.styleable.Preference_layout, R.styleable.Preference_android_layout, R.layout.sesl_preference);
this.mWidgetLayoutResId = TypedArrayUtils.getResourceId(var5, R.styleable.Preference_widgetLayout, R.styleable.Preference_android_widgetLayout, 0);
this.mEnabled = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_enabled, R.styleable.Preference_android_enabled, true);
this.mSelectable = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_selectable, R.styleable.Preference_android_selectable, true);
this.mPersistent = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_persistent, R.styleable.Preference_android_persistent, true);
this.mDependencyKey = TypedArrayUtils.getString(var5, R.styleable.Preference_dependency, R.styleable.Preference_android_dependency);
this.mAllowDividerAbove = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_allowDividerAbove, R.styleable.Preference_allowDividerAbove, this.mSelectable);
this.mAllowDividerBelow = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_allowDividerBelow, R.styleable.Preference_allowDividerBelow, this.mSelectable);
if (var5.hasValue(R.styleable.Preference_defaultValue)) {
this.mDefaultValue = this.onGetDefaultValue(var5, R.styleable.Preference_defaultValue);
} else if (var5.hasValue(R.styleable.Preference_android_defaultValue)) {
this.mDefaultValue = this.onGetDefaultValue(var5, R.styleable.Preference_android_defaultValue);
}
this.mShouldDisableView = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_shouldDisableView, R.styleable.Preference_android_shouldDisableView, true);
this.mHasSingleLineTitleAttr = var5.hasValue(R.styleable.Preference_singleLineTitle);
if (this.mHasSingleLineTitleAttr) {
this.mSingleLineTitle = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_singleLineTitle, R.styleable.Preference_android_singleLineTitle, true);
}
this.mIconSpaceReserved = TypedArrayUtils.getBoolean(var5, R.styleable.Preference_iconSpaceReserved, R.styleable.Preference_android_iconSpaceReserved, false);
var5.recycle();
TypedValue var6 = new TypedValue();
var1.getTheme().resolveAttribute(16842808, var6, true);
if (var6.resourceId > 0) {
this.mTextColorSecondary = var1.getResources().getColorStateList(var6.resourceId, null);
}
}
private void dispatchSetInitialValue() {
if (this.getPreferenceDataStore() != null) {
this.onSetInitialValue(true, this.mDefaultValue);
} else if (this.shouldPersist() && this.getSharedPreferences().contains(this.mKey)) {
this.onSetInitialValue(true, (Object) null);
} else if (this.mDefaultValue != null) {
this.onSetInitialValue(false, this.mDefaultValue);
}
}
public boolean persistStringSet(Set<String> var1) {
if (!this.shouldPersist()) {
return false;
} else if (var1.equals(this.getPersistedStringSet((Set<String>) null))) {
return true;
} else {
PreferenceDataStore var2 = this.getPreferenceDataStore();
if (var2 != null) {
var2.putStringSet(this.mKey, var1);
} else {
Editor var3 = this.mPreferenceManager.getEditor();
var3.putStringSet(this.mKey, var1);
this.tryCommit(var3);
}
return true;
}
}
private void registerDependency() {
if (!TextUtils.isEmpty(this.mDependencyKey)) {
de.dlyt.yanndroid.oneui.preference.Preference var1 = this.findPreferenceInHierarchy(this.mDependencyKey);
if (var1 == null) {
throw new IllegalStateException("Dependency \"" + this.mDependencyKey + "\" not found for preference \"" + this.mKey + "\" (title: \"" + this.mTitle + "\"");
}
var1.registerDependent(this);
}
}
private void registerDependent(de.dlyt.yanndroid.oneui.preference.Preference var1) {
if (this.mDependents == null) {
this.mDependents = new ArrayList();
}
this.mDependents.add(var1);
var1.onDependencyChanged(this, this.shouldDisableDependents());
}
private void setEnabledStateOnViews(View var1, boolean var2) {
var1.setEnabled(var2);
if (var1 instanceof ViewGroup) {
ViewGroup var4 = (ViewGroup) var1;
for (int var3 = var4.getChildCount() - 1; var3 >= 0; --var3) {
this.setEnabledStateOnViews(var4.getChildAt(var3), var2);
}
}
}
private void tryCommit(Editor var1) {
if (this.mPreferenceManager.shouldCommit()) {
var1.apply();
}
}
private void unregisterDependency() {
if (this.mDependencyKey != null) {
de.dlyt.yanndroid.oneui.preference.Preference var1 = this.findPreferenceInHierarchy(this.mDependencyKey);
if (var1 != null) {
var1.unregisterDependent(this);
}
}
}
private void unregisterDependent(de.dlyt.yanndroid.oneui.preference.Preference var1) {
if (this.mDependents != null) {
this.mDependents.remove(var1);
}
}
void assignParent(PreferenceGroup var1) {
this.mParentGroup = var1;
}
public boolean callChangeListener(Object var1) {
boolean var2;
if (this.mOnChangeListener != null && !this.mOnChangeListener.onPreferenceChange(this, var1)) {
var2 = false;
} else {
var2 = true;
}
return var2;
}
protected void callClickListener() {
if (this.mOnClickListener != null) {
this.mOnClickListener.onPreferenceClick(this);
}
}
public final void clearWasDetached() {
this.mWasDetached = false;
}
public int compareTo(de.dlyt.yanndroid.oneui.preference.Preference var1) {
int var2;
if (this.mOrder != var1.mOrder) {
var2 = this.mOrder - var1.mOrder;
} else if (this.mTitle == var1.mTitle) {
var2 = 0;
} else if (this.mTitle == null) {
var2 = 1;
} else if (var1.mTitle == null) {
var2 = -1;
} else {
var2 = this.mTitle.toString().compareToIgnoreCase(var1.mTitle.toString());
}
return var2;
}
void dispatchRestoreInstanceState(Bundle var1) {
if (this.hasKey()) {
Parcelable var2 = var1.getParcelable(this.mKey);
if (var2 != null) {
this.mBaseMethodCalled = false;
this.onRestoreInstanceState(var2);
if (!this.mBaseMethodCalled) {
throw new IllegalStateException("Derived class did not call super.onRestoreInstanceState()");
}
}
}
}
void dispatchSaveInstanceState(Bundle var1) {
if (this.hasKey()) {
this.mBaseMethodCalled = false;
Parcelable var2 = this.onSaveInstanceState();
if (!this.mBaseMethodCalled) {
throw new IllegalStateException("Derived class did not call super.onSaveInstanceState()");
}
if (var2 != null) {
var1.putParcelable(this.mKey, var2);
}
}
}
protected de.dlyt.yanndroid.oneui.preference.Preference findPreferenceInHierarchy(String var1) {
de.dlyt.yanndroid.oneui.preference.Preference var2;
if (!TextUtils.isEmpty(var1) && this.mPreferenceManager != null) {
var2 = this.mPreferenceManager.findPreference(var1);
} else {
var2 = null;
}
return var2;
}
public Context getContext() {
return this.mContext;
}
public Bundle getExtras() {
if (this.mExtras == null) {
this.mExtras = new Bundle();
}
return this.mExtras;
}
StringBuilder getFilterableStringBuilder() {
StringBuilder var1 = new StringBuilder();
CharSequence var2 = this.getTitle();
if (!TextUtils.isEmpty(var2)) {
var1.append(var2).append(' ');
}
var2 = this.getSummary();
if (!TextUtils.isEmpty(var2)) {
var1.append(var2).append(' ');
}
if (var1.length() > 0) {
var1.setLength(var1.length() - 1);
}
return var1;
}
public String getFragment() {
return this.mFragment;
}
long getId() {
return this.mId;
}
public Intent getIntent() {
return this.mIntent;
}
public void setIntent(Intent var1) {
this.mIntent = var1;
}
public String getKey() {
return this.mKey;
}
public final int getLayoutResource() {
return this.mLayoutResId;
}
public void setLayoutResource(int var1) {
this.mLayoutResId = var1;
}
public int getOrder() {
return this.mOrder;
}
public void setOrder(int var1) {
if (var1 != this.mOrder) {
this.mOrder = var1;
this.notifyHierarchyChanged();
}
}
public PreferenceGroup getParent() {
return this.mParentGroup;
}
protected boolean getPersistedBoolean(boolean var1) {
if (this.shouldPersist()) {
PreferenceDataStore var2 = this.getPreferenceDataStore();
if (var2 != null) {
var1 = var2.getBoolean(this.mKey, var1);
} else {
var1 = this.mPreferenceManager.getSharedPreferences().getBoolean(this.mKey, var1);
}
}
return var1;
}
protected int getPersistedInt(int var1) {
if (this.shouldPersist()) {
PreferenceDataStore var2 = this.getPreferenceDataStore();
if (var2 != null) {
var1 = var2.getInt(this.mKey, var1);
} else {
var1 = this.mPreferenceManager.getSharedPreferences().getInt(this.mKey, var1);
}
}
return var1;
}
protected String getPersistedString(String var1) {
if (this.shouldPersist()) {
PreferenceDataStore var2 = this.getPreferenceDataStore();
if (var2 != null) {
var1 = var2.getString(this.mKey, var1);
} else {
var1 = this.mPreferenceManager.getSharedPreferences().getString(this.mKey, var1);
}
}
return var1;
}
public Set<String> getPersistedStringSet(Set<String> var1) {
if (!this.shouldPersist()) {
return var1;
} else {
PreferenceDataStore var2 = this.getPreferenceDataStore();
return var2 != null ? var2.getStringSet(this.mKey, var1) : this.mPreferenceManager.getSharedPreferences().getStringSet(this.mKey, var1);
}
}
public PreferenceDataStore getPreferenceDataStore() {
PreferenceDataStore var1;
if (this.mPreferenceDataStore != null) {
var1 = this.mPreferenceDataStore;
} else if (this.mPreferenceManager != null) {
var1 = this.mPreferenceManager.getPreferenceDataStore();
} else {
var1 = null;
}
return var1;
}
public PreferenceManager getPreferenceManager() {
return this.mPreferenceManager;
}
public SharedPreferences getSharedPreferences() {
SharedPreferences var1;
if (this.mPreferenceManager != null && this.getPreferenceDataStore() == null) {
var1 = this.mPreferenceManager.getSharedPreferences();
} else {
var1 = null;
}
return var1;
}
public CharSequence getSummary() {
return this.mSummary;
}
public void setSummary(CharSequence summary) {
if (!TextUtils.equals(mSummary, summary)) {
mSummary = summary;
notifyChanged();
}
}
public void setSummary(int summaryResId) {
setSummary(mContext.getString(summaryResId));
}
public CharSequence getTitle() {
return this.mTitle;
}
public void setTitle(CharSequence title) {
if (!TextUtils.equals(mTitle, title)) {
mTitle = title;
notifyChanged();
}
}
public void setTitle(int titleResId) {
setTitle(mContext.getString(titleResId));
}
public final int getWidgetLayoutResource() {
return this.mWidgetLayoutResId;
}
public void setWidgetLayoutResource(int var1) {
this.mWidgetLayoutResId = var1;
this.notifyChanged();
}
public boolean hasKey() {
boolean var1;
if (!TextUtils.isEmpty(this.mKey)) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
public void seslSetSummaryColor(int color) {
mSummaryColor = color;
mChangedSummaryColor = true;
mChangedSummaryColorStateList = false;
}
public void seslSetSummaryColor(ColorStateList colorStateList) {
mSummaryColorStateList = colorStateList;
mChangedSummaryColorStateList = true;
mChangedSummaryColor = false;
}
public void seslSetRoundedBg(int where) {
mIsPreferenceRoundedBg = true;
mWhere = where;
mSubheaderRound = false;
mIsRoundChanged = true;
}
public boolean isEnabled() {
boolean var1;
if (this.mEnabled && this.mDependencyMet && this.mParentDependencyMet) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
public void setEnabled(boolean enabled) {
if (mEnabled != enabled) {
mEnabled = enabled;
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
}
public boolean isPersistent() {
return this.mPersistent;
}
public boolean isSelectable() {
return this.mSelectable;
}
public void setSelectable(boolean selectable) {
if (mSelectable != selectable) {
mSelectable = selectable;
notifyChanged();
}
}
public void setShouldDisableView(boolean shouldDisableView) {
this.mShouldDisableView = shouldDisableView;
notifyChanged();
}
protected boolean isTalkBackIsRunning() {
AccessibilityManager var1 = (AccessibilityManager) this.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
boolean var2;
if (var1 != null && var1.isEnabled()) {
String var3 = Secure.getString(this.getContext().getContentResolver(), "enabled_accessibility_services");
if (var3 != null && (var3.matches("(?i).*com.samsung.accessibility/com.samsung.android.app.talkback.TalkBackService.*") || var3.matches("(?i).*com.google.android.marvin.talkback.TalkBackService.*") || var3.matches("(?i).*com.samsung.accessibility/com.samsung.accessibility.universalswitch.UniversalSwitchService.*"))) {
var2 = true;
return var2;
}
}
var2 = false;
return var2;
}
public final boolean isVisible() {
return this.mVisible;
}
public void notifyChanged() {
if (this.mListener != null) {
this.mListener.onPreferenceChange(this);
}
}
public void notifyDependencyChange(boolean var1) {
List var2 = this.mDependents;
if (var2 != null) {
int var3 = var2.size();
for (int var4 = 0; var4 < var3; ++var4) {
((de.dlyt.yanndroid.oneui.preference.Preference) var2.get(var4)).onDependencyChanged(this, var1);
}
}
}
protected void notifyHierarchyChanged() {
if (this.mListener != null) {
this.mListener.onPreferenceHierarchyChange(this);
}
}
public void onAttached() {
this.registerDependency();
}
protected void onAttachedToHierarchy(PreferenceManager var1) {
this.mPreferenceManager = var1;
if (!this.mHasId) {
this.mId = var1.getNextId();
}
this.dispatchSetInitialValue();
}
protected void onAttachedToHierarchy(PreferenceManager var1, long var2) {
this.mId = var2;
this.mHasId = true;
try {
this.onAttachedToHierarchy(var1);
} finally {
this.mHasId = false;
}
}
@SuppressLint("WrongConstant")
public void onBindViewHolder(PreferenceViewHolder var1) {
byte var2 = 4;
var1.itemView.setOnClickListener(this.mClickListener);
var1.itemView.setId(this.mViewId);
var1.seslSetPreferenceBackgroundType(this.mIsPreferenceRoundedBg, this.mWhere, this.mSubheaderRound);
TextView var3 = (TextView) var1.findViewById(16908310);
if (var3 != null) {
CharSequence var4 = this.getTitle();
if (!TextUtils.isEmpty(var4)) {
var3.setText(var4);
var3.setVisibility(0);
if (this.mHasSingleLineTitleAttr) {
var3.setSingleLine(this.mSingleLineTitle);
}
} else if (TextUtils.isEmpty(var4) && this instanceof PreferenceCategory) {
var3.setVisibility(0);
if (this.mHasSingleLineTitleAttr) {
var3.setSingleLine(this.mSingleLineTitle);
}
} else {
var3.setVisibility(8);
}
}
TextView var9 = (TextView) var1.findViewById(16908304);
if (var9 != null) {
CharSequence var7 = this.getSummary();
if (!TextUtils.isEmpty(var7)) {
var9.setText(var7);
if (this.mChangedSummaryColor) {
var9.setTextColor(this.mSummaryColor);
Log.d("Preference", "set Summary Color : " + this.mSummaryColor);
} else if (this.mChangedSummaryColorStateList) {
var9.setTextColor(this.mSummaryColorStateList);
Log.d("Preference", "set Summary ColorStateList : " + this.mSummaryColorStateList);
} else if (this.mTextColorSecondary != null) {
var9.setTextColor(this.mTextColorSecondary);
}
var9.setVisibility(0);
} else {
var9.setVisibility(8);
}
}
SeslPreferenceImageView imageView = (SeslPreferenceImageView) var1.findViewById(16908294);
byte var6;
if (imageView != null) {
if (!(this.mIconResId == 0 && this.mIcon == null)) {
if (this.mIcon == null) {
this.mIcon = AppCompatResources.getDrawable(this.mContext, this.mIconResId);
}
Drawable drawable = this.mIcon;
if (drawable != null) {
imageView.setImageDrawable(drawable);
}
}
if (this.mIcon != null) {
imageView.setVisibility(0);
} else {
if (this.mIconSpaceReserved) {
var6 = 4;
} else {
var6 = 8;
}
imageView.setVisibility(var6);
}
}
View var8 = var1.findViewById(R.id.icon_frame);
View var11 = var8;
if (var8 == null) {
var11 = var1.findViewById(16908350);
}
if (var11 != null) {
if (this.mIcon != null) {
var11.setVisibility(0);
} else {
if (this.mIconSpaceReserved) {
var6 = var2;
} else {
var6 = 8;
}
var11.setVisibility(var6);
}
}
if (this.mShouldDisableView) {
this.setEnabledStateOnViews(var1.itemView, this.isEnabled());
} else {
this.setEnabledStateOnViews(var1.itemView, true);
}
boolean var5 = this.isSelectable();
var1.itemView.setFocusable(var5);
var1.itemView.setClickable(var5);
var1.setDividerAllowedAbove(this.mAllowDividerAbove);
var1.setDividerAllowedBelow(this.mAllowDividerBelow);
}
protected void onClick() {
}
public void onDependencyChanged(de.dlyt.yanndroid.oneui.preference.Preference var1, boolean var2) {
if (this.mDependencyMet == var2) {
if (!var2) {
var2 = true;
} else {
var2 = false;
}
this.mDependencyMet = var2;
this.notifyDependencyChange(this.shouldDisableDependents());
this.notifyChanged();
}
}
public void onDetached() {
this.unregisterDependency();
this.mWasDetached = true;
}
protected Object onGetDefaultValue(TypedArray var1, int var2) {
return null;
}
public void onParentChanged(de.dlyt.yanndroid.oneui.preference.Preference var1, boolean var2) {
if (this.mParentDependencyMet == var2) {
if (!var2) {
var2 = true;
} else {
var2 = false;
}
this.mParentDependencyMet = var2;
this.notifyDependencyChange(this.shouldDisableDependents());
this.notifyChanged();
}
}
protected void onPrepareForRemoval() {
this.unregisterDependency();
}
protected void onRestoreInstanceState(Parcelable var1) {
this.mBaseMethodCalled = true;
if (var1 != de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState.EMPTY_STATE && var1 != null) {
throw new IllegalArgumentException("Wrong state class -- expecting Preference State");
}
}
protected Parcelable onSaveInstanceState() {
this.mBaseMethodCalled = true;
return de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState.EMPTY_STATE;
}
protected void onSetInitialValue(boolean var1, Object var2) {
}
public void performClick() {
if (this.isEnabled()) {
this.onClick();
if (this.mOnClickListener == null || !this.mOnClickListener.onPreferenceClick(this)) {
PreferenceManager var1 = this.getPreferenceManager();
if (var1 != null) {
PreferenceManager.OnPreferenceTreeClickListener var2 = var1.getOnPreferenceTreeClickListener();
if (var2 != null && var2.onPreferenceTreeClick(this)) {
return;
}
}
if (this.mIntent != null) {
this.getContext().startActivity(this.mIntent);
}
}
}
}
protected void performClick(View var1) {
this.performClick();
}
protected boolean persistBoolean(boolean var1) {
boolean var2 = false;
boolean var3 = true;
boolean var4;
if (!this.shouldPersist()) {
var4 = false;
} else {
if (!var1) {
var2 = true;
}
var4 = var3;
if (var1 != this.getPersistedBoolean(var2)) {
PreferenceDataStore var5 = this.getPreferenceDataStore();
if (var5 != null) {
var5.putBoolean(this.mKey, var1);
var4 = var3;
} else {
Editor var6 = this.mPreferenceManager.getEditor();
var6.putBoolean(this.mKey, var1);
this.tryCommit(var6);
var4 = var3;
}
}
}
return var4;
}
protected boolean persistInt(int var1) {
boolean var2 = true;
boolean var3;
if (!this.shouldPersist()) {
var3 = false;
} else {
var3 = var2;
if (var1 != this.getPersistedInt(~var1)) {
PreferenceDataStore var4 = this.getPreferenceDataStore();
if (var4 != null) {
var4.putInt(this.mKey, var1);
var3 = var2;
} else {
Editor var5 = this.mPreferenceManager.getEditor();
var5.putInt(this.mKey, var1);
this.tryCommit(var5);
var3 = var2;
}
}
}
return var3;
}
protected boolean persistString(String var1) {
boolean var2 = true;
boolean var3;
if (!this.shouldPersist()) {
var3 = false;
} else {
var3 = var2;
if (!TextUtils.equals(var1, this.getPersistedString((String) null))) {
PreferenceDataStore var4 = this.getPreferenceDataStore();
if (var4 != null) {
var4.putString(this.mKey, var1);
var3 = var2;
} else {
Editor var5 = this.mPreferenceManager.getEditor();
var5.putString(this.mKey, var1);
this.tryCommit(var5);
var3 = var2;
}
}
}
return var3;
}
public void restoreHierarchyState(Bundle var1) {
this.dispatchRestoreInstanceState(var1);
}
public void saveHierarchyState(Bundle var1) {
this.dispatchSaveInstanceState(var1);
}
public void seslSetSubheaderColor(int var1) {
this.mSubheaderColor = var1;
}
public void seslSetSubheaderRoundedBg(int var1) {
this.mIsPreferenceRoundedBg = true;
this.mWhere = var1;
this.mSubheaderRound = true;
this.mIsRoundChanged = true;
}
final void setOnPreferenceChangeInternalListener(de.dlyt.yanndroid.oneui.preference.Preference.OnPreferenceChangeInternalListener var1) {
this.mListener = var1;
}
public OnPreferenceChangeListener getOnPreferenceChangeListener() {
return this.mOnChangeListener;
}
public void setOnPreferenceChangeListener(OnPreferenceChangeListener var1) {
this.mOnChangeListener = var1;
}
public OnPreferenceClickListener getOnPreferenceClickListener() {
return this.mOnClickListener;
}
public void setOnPreferenceClickListener(de.dlyt.yanndroid.oneui.preference.Preference.OnPreferenceClickListener var1) {
this.mOnClickListener = var1;
}
public boolean shouldDisableDependents() {
boolean var1;
if (!this.isEnabled()) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
protected boolean shouldPersist() {
boolean var1;
if (this.mPreferenceManager != null && this.isPersistent() && this.hasKey()) {
var1 = true;
} else {
var1 = false;
}
return var1;
}
public String toString() {
return this.getFilterableStringBuilder().toString();
}
interface OnPreferenceChangeInternalListener {
void onPreferenceChange(de.dlyt.yanndroid.oneui.preference.Preference var1);
void onPreferenceHierarchyChange(de.dlyt.yanndroid.oneui.preference.Preference var1);
}
public interface OnPreferenceChangeListener {
boolean onPreferenceChange(de.dlyt.yanndroid.oneui.preference.Preference var1, Object var2);
}
public interface OnPreferenceClickListener {
boolean onPreferenceClick(de.dlyt.yanndroid.oneui.preference.Preference var1);
}
public static class BaseSavedState extends AbsSavedState {
public static final Creator<de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState> CREATOR = new Creator<de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState>() {
public de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState createFromParcel(Parcel var1) {
return new de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState(var1);
}
public de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState[] newArray(int var1) {
return new de.dlyt.yanndroid.oneui.preference.Preference.BaseSavedState[var1];
}
};
public BaseSavedState(Parcel var1) {
super(var1);
}
public BaseSavedState(Parcelable var1) {
super(var1);
}
}
}
| 33.254616 | 331 | 0.613197 |
87b59516521b64d96e6e96688e90b05ae7ebbc23 | 2,132 | /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/*
* Copyright 2014 AT&T
*
* 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.att.api.aab.service;
import org.json.JSONObject;
public final class Phone {
private final String type;
private final String number;
private final Boolean preferred;
public Phone(String type, String number, Boolean preferred) {
this.type = type;
this.number = number;
this.preferred = preferred;
}
public String getType() {
return type;
}
public String getNumber() {
return number;
}
public Boolean getPreferred() {
return preferred;
}
public Boolean isPreferred() {
return preferred;
}
public JSONObject toJson() {
JSONObject jobj = new JSONObject();
final String[] keys = { "type", "number", "preferred" };
String prefString = null;
if (getPreferred() != null) {
prefString = isPreferred() ? "TRUE" : "FALSE";
}
final String[] values = { getType(), getNumber(), prefString };
for (int i = 0; i < keys.length; ++i) {
if (values[i] == null) continue;
jobj.put(keys[i], values[i]);
}
return jobj;
}
public static Phone valueOf(JSONObject jobj) {
String type = jobj.has("type") ? jobj.getString("type") : null;
String number = jobj.has("number") ? jobj.getString("number") : null;
Boolean pref = jobj.has("preferred") ? jobj.getBoolean("preferred") : null;
return new Phone(type, number, pref);
}
}
| 28.810811 | 83 | 0.626642 |
ccdd6d671d76f095a7e72c167995182f2fe8e024 | 1,627 | package com.github.yglll.funlive.api;
/**
* 作者:YGL
* 版本号:1.0
* 类描述:API地址
* 备注消息:
* 创建时间:2017/12/13 7:15
**/
public class APILocation {
//base地址
public static final String baseUrl="http://open.douyucdn.cn/";
//获取直播房间列表
//http://open.douyucdn.cn/api/RoomApi/live/{分类 ID 戒者分类别名}
public static final String roomList="api/RoomApi/live/";
//http://open.douyucdn.cn/api/RoomApi/live获取所有直播列表
public static final String allRoom="api/RoomApi/live";
//颜值房间列表
public static final String faceScoreRoomList="api/RoomApi/live/201";
//获取直播房间详情信息/api/RoomApi/room/{房间 Id 或者房间别名}
public static final String details="api/RoomApi/room/";
//获取所有分类 /api/RoomApi/game
public static final String allCategory="api/RoomApi/game";
//****************************************************************
//旧base地址
public static final String baseUrl_capi = "http://capi.douyucdn.cn/";
//*********************首页****************************
//栏目>类别>房间
//轮播图
public static final String getCarousel = "api/v1/slide/6";
//首页最热
public static final String getHomeHotColumn = "/api/v1/getbigDataRoom";
//热门类别列表
public static final String getRecommendHotCate = "api/v1/getHotCate";
//栏目列表
public static final String getCateList = "/api/v1/getColumnList";
//获取栏目中的类别列表
public static final String getCate = "/api/v1/getColumnDetail";
//**********************************************************
public static final String baseUrl_m="https://m.douyu.com/";
//通过roomId获取视频播放地址
public static final String getVideoUrl="html5/live";
} | 33.204082 | 75 | 0.61094 |
4dc8576cd691f59ce5ab2358aa859e8d29523e4d | 16,585 | /*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2020, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.constraints.nary.sum;
import gnu.trove.map.hash.TIntIntHashMap;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ConstraintsName;
import org.chocosolver.solver.constraints.Operator;
import org.chocosolver.solver.constraints.extension.TuplesFactory;
import org.chocosolver.solver.constraints.ternary.PropXplusYeqZ;
import org.chocosolver.solver.exception.SolverException;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.util.tools.VariableUtils;
import java.util.Arrays;
/**
* A factory to reduce and detect specific cases related to integer linear combinations.
* <p>
* It aims at first reducing the input (merge coefficients) and then select the right implementation (for performance concerns).
* <p>
* 2015.09.24 (cprudhom)
* <q>
* dealing with tuples is only relevant for scalar in some very specific cases (eg. mzn 2014, elitserien+handball+handball14.fzn)
* </q>
* <p>
* Created by cprudhom on 13/11/14.
* Project: choco.
* @author Charles Prud'homme
*/
public class IntLinCombFactory {
private IntLinCombFactory() {
}
/**
* Reduce coefficients, and variables if required, when dealing with a sum (all coefficients are implicitly equal to 1)
*
* @param VARS array of integer variables
* @param OPERATOR an operator among "=", "!=", ">", "<", ">=",>" and "<="
* @param SUM the resulting variable
* @return a constraint to post or reify
*/
public static Constraint reduce(IntVar[] VARS, Operator OPERATOR, IntVar SUM, int minCardForDecomposition) {
int[] COEFFS = new int[VARS.length];
Arrays.fill(COEFFS, 1);
return reduce(VARS, COEFFS, OPERATOR, SUM, minCardForDecomposition);
}
/**
* Reduce coefficients, and variables if required, when dealing with a scalar product
*
* @param VARS array of integer variables
* @param COEFFS array of integers
* @param OPERATOR an operator among "=", "!=", ">", "<", ">=",>" and "<="
* @param SCALAR the resulting variable
* @return a constraint to post or reify
*/
public static Constraint reduce(IntVar[] VARS, int[] COEFFS, Operator OPERATOR, IntVar SCALAR,
int minCardForDecomposition) {
// 0. normalize data
Model model = SCALAR.getModel();
if (VARS.length > minCardForDecomposition) {
int k = VARS.length;
int d1 = (int) Math.sqrt(k);
int d2 = k / d1 + (k % d1 == 0?0:1);
IntVar[] intermVar = new IntVar[d1];
IntVar[] copyV;
int[] copyC;
int[] bounds;
for (int i = 0, z = 0; i < k; i += d2, z++) {
int size = Math.min(i + d2, k);
copyV = Arrays.copyOfRange(VARS, i, size);
copyC = Arrays.copyOfRange(COEFFS, i, size);
bounds = VariableUtils.boundsForScalar(copyV, copyC);
intermVar[z] = model.intVar(bounds[0], bounds[1]);
model.scalar(copyV, copyC, "=", intermVar[z]).post();
}
return model.sum(intermVar, OPERATOR.toString(), SCALAR);
}
IntVar[] NVARS;
int[] NCOEFFS;
long RESULT = 0;
if (VariableUtils.isConstant(SCALAR)) {
RESULT = SCALAR.getValue();
NVARS = VARS.clone();
NCOEFFS = COEFFS.clone();
} else {
NVARS = new IntVar[VARS.length + 1];
System.arraycopy(VARS, 0, NVARS, 0, VARS.length);
NVARS[VARS.length] = SCALAR;
NCOEFFS = new int[COEFFS.length + 1];
System.arraycopy(COEFFS, 0, NCOEFFS, 0, COEFFS.length);
NCOEFFS[COEFFS.length] = -1;
}
int k = 0;
int nbools = 0;
int nones = 0, nmones = 0;
int ldom = 0, lidx = -1;
// 1. reduce coefficients and variables
// a. first loop to detect constant and merge duplicate variable/coefficient
TIntIntHashMap map = new TIntIntHashMap(NVARS.length, 1.5f, -1, -1);
for (int i = 0; i < NVARS.length; i++) {
if (VariableUtils.isConstant(NVARS[i])) {
RESULT -= (long)NVARS[i].getValue() * NCOEFFS[i]; // potential overflow
NCOEFFS[i] = 0;
} else if (NCOEFFS[i] != 0) {
int id = NVARS[i].getId();
int pos = map.get(id);
if (pos == -1) {
map.put(id, k);
NVARS[k] = NVARS[i];
NCOEFFS[k] = NCOEFFS[i];
k++;
} else {
NCOEFFS[pos] += NCOEFFS[i];
NCOEFFS[i] = 0;
}
}
}
// b. second step to remove variable with coeff set to 0
int _k = k;
k = 0;
long slb = 0, sub = 0;
for (int i = 0; i < _k; i++) {
if (NCOEFFS[i] != 0) {
if(NCOEFFS[i]>0){
slb += (long)NVARS[i].getLB() * NCOEFFS[i]; // potential overflow
sub += (long)NVARS[i].getUB() * NCOEFFS[i]; // potential overflow
}else{
slb += (long)NVARS[i].getUB() * NCOEFFS[i]; // potential overflow
sub += (long)NVARS[i].getLB() * NCOEFFS[i]; // potential overflow
}
if (NVARS[i].isBool()) nbools++; // count number of boolean variables
if (NCOEFFS[i] == 1) nones++; // count number of coeff set to 1
if (NCOEFFS[i] == -1) nmones++; // count number of coeff set to -1
NVARS[k] = NVARS[i];
NCOEFFS[k] = NCOEFFS[i];
if (NVARS[k].getDomainSize() > ldom) {
lidx = k;
ldom = NVARS[k].getDomainSize();
}
k++;
}
}
// b. resize arrays if needed
if (k == 0) {
switch (OPERATOR) {
case EQ:
return RESULT == 0 ? model.trueConstraint() : model.falseConstraint();
case NQ:
return RESULT != 0 ? model.trueConstraint() : model.falseConstraint();
case LE:
return RESULT >= 0 ? model.trueConstraint() : model.falseConstraint();
case LT:
return RESULT > 0 ? model.trueConstraint() : model.falseConstraint();
case GE:
return RESULT <= 0 ? model.trueConstraint() : model.falseConstraint();
case GT:
return RESULT < 0 ? model.trueConstraint() : model.falseConstraint();
default:
throw new SolverException("Unexpected operator " + OPERATOR
+ " (should be in {\"=\", \"!=\", \">\",\"<\",\">=\",\"<=\"})");
}
}
if(slb < Integer.MIN_VALUE || slb> Integer.MAX_VALUE){
throw new SolverException("Sum of lower bounds under/overflows. Consider reducing variables' domain to prevent this.");
}
if(sub < Integer.MIN_VALUE || sub > Integer.MAX_VALUE){
throw new SolverException("Sum of upper bounds under/overflows. Consider reducing variables' domain to prevent this.");
}
if(RESULT< Integer.MIN_VALUE || RESULT> Integer.MAX_VALUE){
throw new SolverException("RHS under/overflows. Consider reducing it to prevent this.");
}
if(RESULT - slb < Integer.MIN_VALUE || RESULT - slb > Integer.MAX_VALUE
|| sub - RESULT < Integer.MIN_VALUE || sub - RESULT> Integer.MAX_VALUE){
throw new SolverException("Integer under/overflow detected. Consider reducing variables' domain and/or RHS to prevent this.");
}
// 2. resize NVARS and NCOEFFS
if (k < NVARS.length) {
NVARS = Arrays.copyOf(NVARS, k, IntVar[].class);
NCOEFFS = Arrays.copyOf(NCOEFFS, k);
}
// and move the variable with the largest domain at the end, it helps when considering extension representation
if (ldom > 2 && lidx < k - 1) {
IntVar t = NVARS[k - 1];
NVARS[k - 1] = NVARS[lidx];
NVARS[lidx] = t;
int i = NCOEFFS[k - 1];
NCOEFFS[k - 1] = NCOEFFS[lidx];
NCOEFFS[lidx] = i;
}
if (nones + nmones == NVARS.length) {
return selectSum(NVARS, NCOEFFS, OPERATOR, (int)RESULT, nbools);
} else {
return selectScalar(NVARS, NCOEFFS, OPERATOR, (int)RESULT);
}
}
/**
* Select the most relevant Sum constraint to return
*
* @param VARS array of integer variables
* @param COEFFS array of integers
* @param OPERATOR on operator
* @param RESULT an integer
* @param nbools number of boolean variables
* @return a constraint
*/
public static Constraint selectSum(IntVar[] VARS, int[] COEFFS, Operator OPERATOR, int RESULT, int nbools) {
// if the operator is "="
// 4. detect and return small arity constraints
Model s = VARS[0].getModel();
switch (VARS.length) {
case 1:
if (COEFFS[0] == 1) {
return s.arithm(VARS[0], OPERATOR.toString(), RESULT);
} else {
assert COEFFS[0] == -1;
return s.arithm(VARS[0], Operator.getFlip(OPERATOR.toString()), -RESULT);
}
case 2:
if (COEFFS[0] == 1 && COEFFS[1] == 1) {
return s.arithm(VARS[0], "+", VARS[1], OPERATOR.toString(), RESULT);
} else if (COEFFS[0] == 1 && COEFFS[1] == -1) {
return s.arithm(VARS[0], "-", VARS[1], OPERATOR.toString(), RESULT);
} else if (COEFFS[0] == -1 && COEFFS[1] == 1) {
return s.arithm(VARS[1], "-", VARS[0], OPERATOR.toString(), RESULT);
} else {
assert COEFFS[0] == -1 && COEFFS[1] == -1;
return s.arithm(VARS[0], "+", VARS[1], Operator.getFlip(OPERATOR.toString()), -RESULT);
}
case 3:
if(RESULT == 0 && OPERATOR == Operator.EQ) {
// deal with X + Y = Z
if ((COEFFS[0] == 1 && COEFFS[1] == 1 && COEFFS[2] == -1)
|| (COEFFS[0] == -1 && COEFFS[1] == -1 && COEFFS[2] == 1)) {
return new Constraint(ConstraintsName.SUM,
new PropXplusYeqZ(VARS[0], VARS[1], VARS[2],
VARS[0].getModel().getSettings().enableACOnTernarySum()));
}
// deal with X + Z = Y
if ((COEFFS[0] == 1 && COEFFS[1] == -1 && COEFFS[2] == 1)
|| (COEFFS[0] == -1 && COEFFS[1] == 1 && COEFFS[2] == -1)) {
return new Constraint(ConstraintsName.SUM,
new PropXplusYeqZ(VARS[0], VARS[2], VARS[1],
VARS[0].getModel().getSettings().enableACOnTernarySum()));
}
// deal with Y + Z = X
if ((COEFFS[0] == -1 && COEFFS[1] == 1 && COEFFS[2] == 1)
|| (COEFFS[0] == 1 && COEFFS[1] == -1 && COEFFS[2] == -1)) {
return new Constraint(ConstraintsName.SUM,
new PropXplusYeqZ(VARS[1], VARS[2], VARS[0],
VARS[0].getModel().getSettings().enableACOnTernarySum()));
}
}
default:
int b = 0, e = VARS.length;
IntVar[] tmpV = new IntVar[e];
// go down to 0 to ensure that the largest domain variable is on last position
for (int i = VARS.length - 1; i >= 0; i--) {
IntVar key = VARS[i];
if (COEFFS[i] > 0) {
tmpV[b++] = key;
} else if (COEFFS[i] < 0) {
tmpV[--e] = key;
}
}
if (OPERATOR == Operator.GT) {
OPERATOR = Operator.GE;
RESULT++;
} else if (OPERATOR == Operator.LT) {
OPERATOR = Operator.LE;
RESULT--;
}
//TODO: deal with clauses and reification
Model model = VARS[0].getModel();
if (nbools == VARS.length) {
if (model.getSettings().enableIncrementalityOnBoolSum(tmpV.length)) {
return new SumConstraint(new PropSumFullBoolIncr(model.toBoolVar(tmpV), b, OPERATOR, RESULT));
} else {
return new SumConstraint(new PropSumFullBool(model.toBoolVar(tmpV), b, OPERATOR, RESULT));
}
}
if (nbools == VARS.length - 1 && !tmpV[tmpV.length - 1].isBool() && COEFFS[VARS.length - 1] == -1) {
// the large domain variable is on the last idx
if (model.getSettings().enableIncrementalityOnBoolSum(tmpV.length)) {
return new SumConstraint(new PropSumBoolIncr(model.toBoolVar(Arrays.copyOf(tmpV, tmpV.length - 1)),
b, OPERATOR, tmpV[tmpV.length - 1], RESULT));
} else {
return new SumConstraint(new PropSumBool(model.toBoolVar(Arrays.copyOf(tmpV, tmpV.length - 1)),
b, OPERATOR, tmpV[tmpV.length - 1], RESULT));
}
}
return new SumConstraint( new PropSum(tmpV, b, OPERATOR, RESULT));
}
}
/**
* Select the most relevant ScalarProduct constraint to return
*
* @param VARS array of integer variables
* @param COEFFS array of integers
* @param OPERATOR on operator
* @param RESULT an integer
* @return a constraint
*/
public static Constraint selectScalar(IntVar[] VARS, int[] COEFFS, Operator OPERATOR, int RESULT) {
Model s = VARS[0].getModel();
if (VARS.length == 1 && OPERATOR == Operator.EQ) {
return s.times(VARS[0], COEFFS[0], s.intVar(RESULT));
}
if (VARS.length == 2 && OPERATOR == Operator.EQ && RESULT == 0) {
if (COEFFS[0] == 1) {
return s.times(VARS[1], -COEFFS[1], VARS[0]);
}
if (COEFFS[0] == -1) {
return s.times(VARS[1], COEFFS[1], VARS[0]);
}
if (COEFFS[1] == 1) {
return s.times(VARS[0], -COEFFS[0], VARS[1]);
}
if (COEFFS[1] == -1) {
return s.times(VARS[0], COEFFS[0], VARS[1]);
}
}
if (Operator.EQ == OPERATOR && VARS[VARS.length - 1].hasEnumeratedDomain() && TuplesFactory.canBeTupled(Arrays.copyOf(VARS, VARS.length - 1))) {
return s.table(VARS, TuplesFactory.scalar(Arrays.copyOf(VARS, VARS.length - 1), Arrays.copyOf(COEFFS, COEFFS.length - 1),
OPERATOR.toString(), VARS[VARS.length - 1], -COEFFS[COEFFS.length - 1], RESULT));
}
int b = 0, e = VARS.length;
IntVar[] tmpV = new IntVar[e];
int[] tmpC = new int[e];
for (int i = 0; i < VARS.length; i++) {
IntVar key = VARS[i];
if (COEFFS[i] > 0) {
tmpV[b] = key;
tmpC[b++] = COEFFS[i];
} else if (COEFFS[i] < 0) {
tmpV[--e] = key;
tmpC[e] = COEFFS[i];
}
}
if (OPERATOR == Operator.GT) {
OPERATOR = Operator.GE;
RESULT++;
} else if (OPERATOR == Operator.LT) {
OPERATOR = Operator.LE;
RESULT--;
}
return new SumConstraint(new PropScalar(tmpV, tmpC, b, OPERATOR, RESULT));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
| 44.945799 | 152 | 0.500874 |
dfef25ffaf5d94a10b9e3e7a8b0aa5094f366d79 | 3,308 | import java.util.Arrays;
import java.util.Iterator;
/**
* Partial implementation of IntList that works only for Integer objects.
* Precisely, it stores them as {@code int}s.
*/
public class MaxMinIntList extends IntList {
private final int[] elements;
private final int max, min;
public MaxMinIntList() {
elements = new int[0];
max = 69;
min = 420;
}
/*
* Abstraction Function: AF() = elements, with max = max and min = min;
*
* Representation Invariant: elements is non null; elements.length=0 or (max is
* the maximum of the elements in elements, min is the minimum of the elements
* in elements).
*/
/**
* Returns the maximum of this MaxMinIntList.
*
* @return the maximum.
* @throws EmptyException if the list is empty.
*/
public Integer max() {
if (elements.length == 0)
throw new EmptyException();
return max;
}
/**
* Returns the minimum of this MaxMinIntList.
*
* @return the minimum.
* @throws EmptyException if the list is empty.
*/
public Integer min() {
if (elements.length == 0)
throw new EmptyException();
return min;
}
@Override
public Integer first() throws EmptyException {
return elements[0];
}
private MaxMinIntList(int[] elements, int max, int min) {
this.elements = elements;
this.max = max;
this.min = min;
}
private int findMax(int start) {
int res = elements[start];
for (int i = start + 1; i < elements.length; i++)
if (elements[i] > res)
res = elements[i];
return res;
}
private int findMin(int start) {
int res = elements[start];
for (int i = start + 1; i < elements.length; i++)
if (elements[i] < res)
res = elements[i];
return res;
}
@Override
public IntList rest() throws EmptyException {
if (elements.length == 0)
throw new EmptyException();
int newMax = 69, newMin = 420;
if (elements.length > 1) {
if (first() == max)
newMax = findMax(1);
else
newMax = max;
if (first() == min)
newMin = findMin(1);
else
newMin = min;
}
return new MaxMinIntList(Arrays.copyOfRange(elements, 1, elements.length), newMax, newMin);
}
@Override
public IntList addEl(Object x) {
if (x instanceof Integer)
return addEl((Integer) x);
throw new UnsupportedOperationException();
}
/**
* EFFECTS: Adds x to the beginning of this.
*/
public IntList addEl(Integer x) {
int[] newArr = Arrays.copyOf(elements, elements.length + 1);
newArr[elements.length] = x;
if (elements.length == 0)
return new MaxMinIntList(newArr, x, x);
return new MaxMinIntList(newArr, x > max ? x : max, x < min ? x : min);
}
@Override
public int size() {
return elements.length;
}
@Override
public boolean repOK() {
if (elements == null)
return false;
return elements.length == 0 || findMax(0) == max && findMin(0) == min;
}
@Override
public Iterator<Object> elements() {
return new Iterator<Object>() {
private int nextIndex = 0;
@Override
public boolean hasNext() {
return nextIndex < elements.length;
}
@Override
public Integer next() {
return elements[nextIndex++];
}
};
}
@Override
public String toString() {
String res = "";
for (int i = 0; i < elements.length - 1; i++) {
res += elements[i] + ", ";
}
res += elements[elements.length - 1];
return res;
}
}
| 21.620915 | 93 | 0.642382 |
006d08368c5560704318b5a2eba6ff1309aa2e3b | 12,162 | /*
* Copyright 2008-2009 LinkedIn, 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 voldemort.serialization.json;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import voldemort.serialization.SerializationException;
/**
* Read in JSON objects from a java.io.Reader
*
*
*/
public class JsonReader {
// The java.io.Reader to use to get characters
private final Reader reader;
// the character to use to count line breaks
private final char lineBreak;
// the current line number
private int line;
// the index into the current line
private int lineOffset;
// the number of characters read
private int charsRead;
// the current character
private int current;
// a circular buffer of recent characters for error message context
private final char[] contextBuffer;
// the offset into the contextBuffer where we are at currently.
private int contextOffset;
public JsonReader(Reader reader) {
this(reader, 50);
}
public JsonReader(Reader reader, int contextBufferSize) {
this.reader = reader;
String newline = System.getProperty("line.separator");
if(newline.contains("\n"))
lineBreak = '\n';
else
lineBreak = '\r';
this.line = 1;
this.lineOffset = 0;
this.charsRead = 0;
// initialize contextBuffer to all whitespace
this.contextBuffer = new char[contextBufferSize];
for(int i = 0; i < contextBufferSize; i++)
this.contextBuffer[i] = ' ';
next();
}
public boolean hasMore() {
return current() != -1;
}
public Object read() {
skipWhitespace();
Object o = null;
switch(current()) {
case '{':
o = readObject();
break;
case '[':
o = readArray();
break;
case '"':
case '\'':
o = readString();
break;
case 't':
case 'f':
o = readBoolean();
break;
case 'n':
o = readNull();
break;
case -1:
throw new EndOfFileException();
default:
if(Character.isDigit(current()) || current() == '-') {
o = readNumber();
} else {
throw new SerializationException("Unacceptable initial character "
+ currentChar()
+ " found when parsing object at line "
+ getCurrentLineNumber() + " character "
+ getCurrentLineOffset());
}
}
skipWhitespace();
return o;
}
public Map<String, ?> readObject() {
skip('{');
skipWhitespace();
Map<String, Object> values = new HashMap<String, Object>();
while(current() != '}') {
skipWhitespace();
String key = readString();
skipWhitespace();
skip(':');
skipWhitespace();
Object value = read();
values.put(key, value);
skipWhitespace();
if(current() == ',') {
next();
skipWhitespace();
} else if(current() == '}') {
break;
} else {
throw new SerializationException("Unexpected character '"
+ currentChar()
+ "' in object definition, expected '}' or ',' but found: "
+ getCurrentContext());
}
}
skip('}');
return values;
}
public List<?> readArray() {
skip('[');
skipWhitespace();
List<Object> l = new ArrayList<Object>();
while(current() != ']' && hasMore()) {
l.add(read());
skipWhitespace();
if(current() == ',') {
next();
skipWhitespace();
}
}
skip(']');
return l;
}
public Object readNull() {
skip("null");
return null;
}
public Boolean readBoolean() {
if(current() == 't') {
skip("true");
return Boolean.TRUE;
} else {
skip("false");
return Boolean.FALSE;
}
}
public String readString() {
int quote = current();
StringBuilder buffer = new StringBuilder();
next();
while(current() != quote && hasMore()) {
if(current() == '\\')
appendControlSequence(buffer);
else
buffer.append(currentChar());
next();
}
skip(quote);
return buffer.toString();
}
private void appendControlSequence(StringBuilder buffer) {
skip('\\');
switch(current()) {
case '"':
case '\\':
case '/':
buffer.append(currentChar());
break;
case 'b':
buffer.append('\b');
break;
case 'f':
buffer.append('\f');
break;
case 'n':
buffer.append('\n');
break;
case 'r':
buffer.append('\r');
break;
case 't':
buffer.append('\t');
break;
case 'u':
buffer.append(readUnicodeLiteral());
break;
default:
throw new SerializationException("Unrecognized control sequence on line "
+ getCurrentLineNumber() + ": '\\" + currentChar()
+ "'.");
}
}
private char readUnicodeLiteral() {
int value = 0;
for(int i = 0; i < 4; i++) {
next();
value <<= 4;
if(Character.isDigit(current()))
value += current() - '0';
else if('a' <= current() && 'f' >= current())
value += 10 + current() - 'a';
else if('A' <= current() && 'F' >= current())
value += 10 + current() - 'A';
else
throw new SerializationException("Invalid character in unicode sequence on line "
+ getCurrentLineNumber() + ": " + currentChar());
}
return (char) value;
}
public Number readNumber() {
skipWhitespace();
int intPiece = readInt();
// if int is all we have, return it
if(isTerminator(current()))
return intPiece;
// okay its a double, check for exponent
double doublePiece = intPiece;
if(current() == '.')
doublePiece += readFraction();
if(current() == 'e' || current() == 'E') {
next();
skipIf('+');
int frac = readInt();
doublePiece *= Math.pow(10, frac);
}
if(isTerminator(current()))
return doublePiece;
else
throw new SerializationException("Invalid number format for number on line "
+ lineOffset + ": " + getCurrentContext());
}
private boolean isTerminator(int ch) {
return Character.isWhitespace(ch) || ch == '{' || ch == '}' || ch == '[' || ch == ']'
|| ch == ',' || ch == -1;
}
public int readInt() {
skipWhitespace();
int val = 0;
boolean isPositive;
if(current() == '-') {
isPositive = false;
next();
} else if(current() == '+') {
isPositive = true;
next();
} else {
isPositive = true;
}
skipWhitespace();
if(!Character.isDigit(current()))
throw new SerializationException("Expected a digit while trying to parse number, but got '"
+ currentChar()
+ "' at line "
+ getCurrentLineNumber()
+ " character "
+ getCurrentLineOffset() + ": " + getCurrentContext());
while(Character.isDigit(current())) {
val *= 10;
val += (current() - '0');
next();
}
if(!isPositive)
val = -val;
return val;
}
public double readFraction() {
skip('.');
double position = 0.1;
double val = 0;
while(Character.isDigit(current())) {
val += position * (current() - '0');
position *= 0.1;
next();
}
return val;
}
private int current() {
return this.current;
}
private char currentChar() {
return (char) this.current;
}
private int next() {
try {
// read a character
this.current = this.reader.read();
// increment the character count and maybe line number
this.charsRead++;
this.lineOffset++;
if(this.current == this.lineBreak) {
this.line++;
this.lineOffset = 1;
}
// add to context buffer
this.contextBuffer[this.contextOffset] = (char) this.current;
this.contextOffset = (contextOffset + 1) % this.contextBuffer.length;
return this.current;
} catch(IOException e) {
throw new SerializationException("Error reading from JSON stream.", e);
}
}
private void skipIf(char c) {
if(current() == c)
next();
}
private void skip(String s) {
for(int i = 0; i < s.length(); i++)
skip(s.charAt(i));
}
private void skipWhitespace() {
while(Character.isWhitespace(current()))
next();
}
private void skip(int c) {
if(current() != c)
throw new SerializationException("Expected '" + ((char) c)
+ "' but current character is '" + currentChar()
+ "' on line " + line + " character " + lineOffset
+ ": " + getCurrentContext());
next();
}
public int getCurrentLineNumber() {
return this.line;
}
public int getCurrentLineOffset() {
return this.lineOffset;
}
public String getCurrentContext() {
StringBuilder builder = new StringBuilder(this.contextBuffer.length);
for(int i = this.contextOffset; i < this.contextBuffer.length; i++)
builder.append(this.contextBuffer[i]);
for(int i = 0; i < contextOffset; i++)
builder.append(this.contextBuffer[i]);
if(this.charsRead < this.contextBuffer.length)
return builder.toString().substring(this.contextBuffer.length - this.charsRead,
this.contextBuffer.length);
else
return builder.toString();
}
}
| 30.634761 | 108 | 0.467275 |
b7c962a5d96a907a20893212e285a2d27247823b | 669 | package pageObjects;
import elementMapper.ProductPageElementMapper;
import org.openqa.selenium.support.PageFactory;
import utils.Browser;
public class ProductPage extends ProductPageElementMapper {
public ProductPage () {
PageFactory.initElements(Browser.getCurrentDriver(), this);
}
public String getProductNamePDP() {
return productNamePDP.getText();
}
public String getTextProductPrice() {
return itemPrice.getText();
}
public void clickButtonAddToCart() {
buttonAddToCart.click();
}
public void clickButtonModalProceedToCheckout() {
buttonModalProceedToCheckout.click();
}
}
| 20.90625 | 67 | 0.710015 |
4ce53dd83c7f7bd6371b203a630fa35d13748c1b | 2,660 | package net.smelly.rolepooler.commands;
import net.dv8tion.jda.api.entities.Role;
import net.smelly.disparser.Command;
import net.smelly.disparser.CommandContext;
import net.smelly.disparser.arguments.java.EnumArgument;
import net.smelly.disparser.arguments.jda.RoleArgument;
import net.smelly.disparser.feedback.FeedbackHandler;
import net.smelly.disparser.feedback.exceptions.BiDynamicCommandExceptionCreator;
import net.smelly.rolepooler.Pool;
import net.smelly.rolepooler.RolePooler;
/**
* @author Luke Tonon
*/
public final class PoolRoleCommand extends Command {
private static final BiDynamicCommandExceptionCreator<Role, Pool> ALREADY_IN_POOL_EXCEPTION = BiDynamicCommandExceptionCreator.createInstance(((role, pool) -> {
return String.format("%1$s role is already in the `%2$s` pool!", role.getAsMention(), pool.name());
}));
private static final BiDynamicCommandExceptionCreator<Role, Pool> ALREADY_IN_OTHER_POOL_EXCEPTION = BiDynamicCommandExceptionCreator.createInstance(((role, pool) -> {
return String.format("%1$s role is already in another pool (`%2$s`)!", role.getAsMention(), pool.name());
}));
private static final BiDynamicCommandExceptionCreator<Role, Pool> NOT_IN_POOL_EXCEPTION = BiDynamicCommandExceptionCreator.createInstance(((role, pool) -> {
return String.format("%1$s role is not in the `%2$s` pool!", role.getAsMention(), pool.name());
}));
public PoolRoleCommand() {
super("pool", EnumArgument.get(Action.class), EnumArgument.get(Pool.class), RoleArgument.get());
}
@Override
public void processCommand(CommandContext context) throws Exception {
Action action = context.getParsedResult(0);
Pool pool = context.getParsedResult(1);
Role role = context.getParsedResult(2);
FeedbackHandler handler = context.getFeedbackHandler();
if (action == Action.ADD) {
Pool rolePool = RolePooler.DATA_MANAGER.getPoolForRole(role);
if (rolePool != null && rolePool != pool) {
throw ALREADY_IN_OTHER_POOL_EXCEPTION.create(role, rolePool);
} else if (RolePooler.DATA_MANAGER.putRole(pool, role)) {
RolePooler.DATA_MANAGER.writePooledRoles();
handler.sendSuccess(String.format("Successfully added %1$s role to the `%2$s` pool!", role.getAsMention(), pool.name()));
} else {
throw ALREADY_IN_POOL_EXCEPTION.create(role, pool);
}
} else {
if (RolePooler.DATA_MANAGER.removeRole(pool, role)) {
RolePooler.DATA_MANAGER.writePooledRoles();
handler.sendSuccess(String.format("Successfully removed %1$s role from `%2$s` pool!", role.getAsMention(), pool.name()));
} else {
throw NOT_IN_POOL_EXCEPTION.create(role, pool);
}
}
}
enum Action {
ADD,
REMOVE
}
}
| 42.903226 | 167 | 0.753759 |
7263d325ca165b27e98c933dd36ebabe30229226 | 1,307 | class Solution {
public List<Integer> diffWaysToCompute(String input) {
return helper(input, 0, input.length());
}
public List<Integer> helper(String input, int lo, int hi) {
boolean isdigit = true;
for(int i = lo; i < hi; ++i) {
if (!Character.isDigit(input.charAt(i))) {
isdigit = false;
break;
}
}
// System.out.println(input.substring(lo, hi));
List<Integer> ans = new ArrayList<>();
if (isdigit) {
ans.add(Integer.parseInt(input.substring(lo, hi)));
return ans;
}
for(int i = lo; i < hi; ++i) {
char ch = input.charAt(i);
if(!Character.isDigit(ch)) {
List<Integer> lefts = helper(input, lo, i);
List<Integer> rights = helper(input, i + 1, hi);
for(int left : lefts) {
for(int right : rights) {
ans.add(func(ch, left, right));
}
}
}
}
return ans;
}
public int func(char op, int left, int right) {
if (op == '+') return left + right;
else if (op == '-') return left - right;
else return left * right;
}
}
| 31.119048 | 64 | 0.456006 |
c3ba6692a925d5c7f725f130dde64dcdff534cce | 20,808 | /*
* 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.beam.sdk.io.gcp.spanner;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.io.common.IOITHelper;
import org.apache.beam.sdk.io.common.IOTestPipelineOptions;
import org.apache.beam.sdk.io.gcp.spanner.changestreams.model.DataChangeRecord;
import org.apache.beam.sdk.io.gcp.spanner.changestreams.model.Mod;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.StreamingOptions;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.state.BagState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.ValueState;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// To run this test, run the following command:
// ./gradlew :sdks:java:io:google-cloud-platform:integrationTest -PgcpSpannerInstance=changestream
// --tests=SpannerChangeStreamTransactionBoundariesIT --info
/** End-to-end test of Cloud Spanner Change Streams Transaction Boundaries. */
@RunWith(JUnit4.class)
public class SpannerChangeStreamTransactionBoundariesIT {
private static final int MAX_TABLE_NAME_LENGTH = 128;
private static final int MAX_CHANGE_STREAM_NAME_LENGTH = 30;
private static final String TABLE_NAME_PREFIX = "Singers";
private static final Logger LOG =
LoggerFactory.getLogger(SpannerChangeStreamTransactionBoundariesIT.class);
@Rule public final transient TestPipeline pipeline = TestPipeline.create();
/** Pipeline options for this test. */
public interface SpannerTestPipelineOptions extends IOTestPipelineOptions, StreamingOptions {
@Description("Project that hosts Spanner instance")
@Default.String("span-cloud-testing")
String getProjectId();
void setProjectId(String value);
@Description("Instance ID to write to in Spanner")
@Default.String("changestream")
String getInstanceId();
void setInstanceId(String value);
@Description("Database ID prefix to write to in Spanner")
@Default.String("changestream")
String getDatabaseId();
void setDatabaseId(String value);
@Description("Time to wait for the events to be processed by the read pipeline (in seconds)")
@Default.Integer(300)
@Validation.Required
Integer getReadTimeout();
void setReadTimeout(Integer readTimeout);
}
private static SpannerTestPipelineOptions options;
private static String projectId;
private static String instanceId;
private static String databaseId;
private static String tableName;
private static String changeStreamName;
private static Spanner spanner;
private static DatabaseAdminClient databaseAdminClient;
private static DatabaseClient databaseClient;
@BeforeClass
public static void setup() throws InterruptedException, ExecutionException, TimeoutException {
options = IOITHelper.readIOTestPipelineOptions(SpannerTestPipelineOptions.class);
projectId =
options.getProjectId() == null
? options.as(GcpOptions.class).getProject()
: options.getProjectId();
instanceId = options.getInstanceId();
databaseId = options.getDatabaseId();
tableName = generateTableName();
changeStreamName = generateChangeStreamName();
spanner = SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
databaseAdminClient = spanner.getDatabaseAdminClient();
databaseClient = spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId));
// Creating the data table and the change stream tracking the data table.
createTable(instanceId, databaseId, tableName);
createChangeStream(instanceId, databaseId, changeStreamName, tableName);
}
@AfterClass
public static void afterClass()
throws InterruptedException, ExecutionException, TimeoutException {
// Drop the change stream and the data table.
databaseAdminClient
.updateDatabaseDdl(
instanceId,
databaseId,
Arrays.asList("DROP CHANGE STREAM " + changeStreamName, "DROP TABLE " + tableName),
"op" + RandomUtils.randomAlphaNumeric(8))
.get(5, TimeUnit.MINUTES);
spanner.close();
}
@Test
public void testReadSpannerChangeStream() throws InterruptedException {
final SpannerConfig spannerConfig =
SpannerConfig.create()
.withProjectId(projectId)
.withInstanceId(instanceId)
.withDatabaseId(databaseId);
final Timestamp now = Timestamp.now();
List<Mutation> mutations = new ArrayList<>();
// Insert historical mutations into the data table to be returned by the Change Stream
// Connector.
// 1. Commit a transaction to insert Singer 1 and Singer 2 into the table.
mutations.add(insertRecordMutation(1, "FirstName1", "LastName2"));
mutations.add(insertRecordMutation(2, "FirstName2", "LastName2"));
Timestamp t1 = databaseClient.write(mutations);
LOG.debug("The first transaction committed with timestamp: " + t1.toString());
mutations.clear();
// 2. Commmit a transaction to insert Singer 3 and remove Singer 1 from the table.
mutations.add(insertRecordMutation(3, "FirstName3", "LastName3"));
mutations.add(deleteRecordMutation(1));
Timestamp t2 = databaseClient.write(mutations);
LOG.debug("The second transaction committed with timestamp: " + t2.toString());
mutations.clear();
// 3. Commit a transaction to insert Singer 4 and Singer 5 and Singer 6 into the table.
mutations.add(insertRecordMutation(4, "FirstName4", "LastName4"));
mutations.add(insertRecordMutation(5, "FirstName5", "LastName5"));
mutations.add(insertRecordMutation(6, "FirstName6", "LastName6"));
Timestamp t3 = databaseClient.write(mutations);
LOG.debug("The third transaction committed with timestamp: " + t3.toString());
mutations.clear();
pipeline.getOptions().as(SpannerTestPipelineOptions.class).setStreaming(true);
pipeline.getOptions().as(SpannerTestPipelineOptions.class).setBlockOnRun(false);
LOG.debug("Reading Spanner Change Stream from: " + now);
final PCollection<String> tokens =
pipeline
.apply(
SpannerIO.readChangeStream()
.withSpannerConfig(spannerConfig)
.withChangeStreamName(changeStreamName)
.withMetadataDatabase(databaseId)
.withInclusiveStartAt(now))
.apply(
ParDo.of(
new org.apache.beam.sdk.io.gcp.spanner
.SpannerChangeStreamTransactionBoundariesIT.KeyByTransactionIdFn()))
.apply(
ParDo.of(
new org.apache.beam.sdk.io.gcp.spanner
.SpannerChangeStreamTransactionBoundariesIT.TransactionBoundaryFn()))
.apply(
ParDo.of(
new org.apache.beam.sdk.io.gcp.spanner
.SpannerChangeStreamTransactionBoundariesIT.ToStringFn()));
// Assert that the returned PCollection contains all six transactions (in string representation)
// and that each transaction contains, in order, the list of mutations added.
PAssert.that(tokens)
.containsInAnyOrder(
// Insert Singer 1 and 2 into the table,
"{\"SingerId\":\"1\"}{\"SingerId\":\"2\"},INSERT\n",
// Delete Singer 1 and Insert Singer 3 into the table.
"{\"SingerId\":\"1\"},DELETE\n" + "{\"SingerId\":\"3\"},INSERT\n",
// Insert Singers 4, 5, 6 into the table.
"{\"SingerId\":\"4\"}{\"SingerId\":\"5\"}{\"SingerId\":\"6\"},INSERT\n",
// Update Singer 6 and Insert Singer 7
"{\"SingerId\":\"6\"},UPDATE\n" + "{\"SingerId\":\"7\"},INSERT\n",
// Update Singers 4 and 5 in the table.
"{\"SingerId\":\"4\"}{\"SingerId\":\"5\"},UPDATE\n",
// Delete Singers 3, 4, 5 from the table.
"{\"SingerId\":\"3\"}{\"SingerId\":\"4\"}{\"SingerId\":\"5\"},DELETE\n");
final PipelineResult pipelineResult = pipeline.run();
// Insert live mutations after the pipeline already started running.
// 4. Commit a transaction to insert Singer 7 and update Singer 6 in the table.
mutations.add(insertRecordMutation(7, "FirstName7", "LastName7"));
mutations.add(updateRecordMutation(6, "FirstName5", "LastName5"));
Timestamp t4 = databaseClient.write(mutations);
LOG.debug("The fourth transaction committed with timestamp: " + t4.toString());
mutations.clear();
// 5. Commit a transaction to update Singer 4 and Singer 5 in the table.
mutations.add(updateRecordMutation(4, "FirstName9", "LastName9"));
mutations.add(updateRecordMutation(5, "FirstName9", "LastName9"));
Timestamp t5 = databaseClient.write(mutations);
LOG.debug("The fifth transaction committed with timestamp: " + t5.toString());
mutations.clear();
// 6. Commit a transaction to delete Singers 3, 4, 5.
mutations.add(deleteRecordMutation(3));
mutations.add(deleteRecordMutation(4));
mutations.add(deleteRecordMutation(5));
Timestamp t6 = databaseClient.write(mutations);
LOG.debug("The sixth transaction committed with timestamp: " + t6.toString());
try {
pipelineResult.waitUntilFinish(org.joda.time.Duration.standardSeconds(30));
pipelineResult.cancel();
} catch (IOException e) {
LOG.debug("IOException while cancelling job");
}
}
// Create an update mutation.
private static Mutation updateRecordMutation(long singerId, String firstName, String lastName) {
return Mutation.newUpdateBuilder(tableName)
.set("SingerId")
.to(singerId)
.set("FirstName")
.to(firstName)
.set("LastName")
.to(lastName)
.build();
}
// Create an insert mutation.
private static Mutation insertRecordMutation(long singerId, String firstName, String lastName) {
return Mutation.newInsertBuilder(tableName)
.set("SingerId")
.to(singerId)
.set("FirstName")
.to(firstName)
.set("LastName")
.to(lastName)
.build();
}
// Create a delete mutation.
private static Mutation deleteRecordMutation(long singerId) {
return Mutation.delete(tableName, KeySet.newBuilder().addKey(Key.of(singerId)).build());
}
// Generate the table name.
private static String generateTableName() {
return TABLE_NAME_PREFIX
+ "_"
+ RandomUtils.randomAlphaNumeric(MAX_TABLE_NAME_LENGTH - 1 - TABLE_NAME_PREFIX.length());
}
// Generate the change stream name.
private static String generateChangeStreamName() {
return TABLE_NAME_PREFIX
+ "Stream"
+ RandomUtils.randomAlphaNumeric(
MAX_CHANGE_STREAM_NAME_LENGTH - 1 - (TABLE_NAME_PREFIX + "Stream").length());
}
// Create the data table.
private static void createTable(String instanceId, String databaseId, String tableName)
throws InterruptedException, ExecutionException, TimeoutException {
databaseAdminClient
.updateDatabaseDdl(
instanceId,
databaseId,
Collections.singletonList(
"CREATE TABLE "
+ tableName
+ " ("
+ " SingerId INT64 NOT NULL,"
+ " FirstName STRING(1024),"
+ " LastName STRING(1024),"
+ " SingerInfo BYTES(MAX)"
+ " ) PRIMARY KEY (SingerId)"),
"op" + RandomUtils.randomAlphaNumeric(8))
.get(5, TimeUnit.MINUTES);
}
// Create the change stream.
private static void createChangeStream(
String instanceId, String databaseId, String changeStreamName, String tableName)
throws InterruptedException, ExecutionException, TimeoutException {
databaseAdminClient
.updateDatabaseDdl(
instanceId,
databaseId,
Collections.singletonList(
"CREATE CHANGE STREAM " + changeStreamName + " FOR " + tableName),
"op" + RandomUtils.randomAlphaNumeric(8))
.get(5, TimeUnit.MINUTES);
}
// KeyByTransactionIdFn takes in a DataChangeRecord and outputs a key-value pair of
// {TransactionId, DataChangeRecord}
private static class KeyByTransactionIdFn
extends DoFn<DataChangeRecord, KV<String, DataChangeRecord>> {
private static final long serialVersionUID = 1270485392415293532L;
@ProcessElement
public void processElement(
@Element DataChangeRecord record,
OutputReceiver<KV<String, DataChangeRecord>> outputReceiver) {
outputReceiver.output(KV.of(record.getServerTransactionId(), record));
}
}
// TransactionBoundaryFn buffers received key-value pairs of {TransactionId, DataChangeRecord}
// from KeyByTransactionIdFn and buffers them in groups based on TransactionId.
// When the number of records buffered is equal to the number of records contained in the
// entire transaction, this function sorts the DataChangeRecords in the group by record sequence
// and outputs a key-value pair of SortKey(CommitTimestamp, TransactionId),
// Iterable<DataChangeRecord>.
private static class TransactionBoundaryFn
extends DoFn<
KV<String, DataChangeRecord>,
KV<
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT.SortKey,
Iterable<DataChangeRecord>>> {
private static final long serialVersionUID = 5050535558953049259L;
@SuppressWarnings("UnusedVariable")
@StateId("buffer")
private final StateSpec<BagState<DataChangeRecord>> buffer = StateSpecs.bag();
@SuppressWarnings("UnusedVariable")
@StateId("count")
private final StateSpec<ValueState<Integer>> countState = StateSpecs.value();
@ProcessElement
public void process(
ProcessContext context,
@StateId("buffer") BagState<DataChangeRecord> buffer,
@StateId("count") ValueState<Integer> countState) {
final KV<String, DataChangeRecord> element = context.element();
final DataChangeRecord record = element.getValue();
buffer.add(record);
int count = (countState.read() != null ? countState.read() : 0);
count = count + 1;
countState.write(count);
if (count == record.getNumberOfRecordsInTransaction()) {
final List<DataChangeRecord> sortedRecords =
StreamSupport.stream(buffer.read().spliterator(), false)
.sorted(Comparator.comparing(DataChangeRecord::getRecordSequence))
.collect(Collectors.toList());
context.output(
KV.of(
new org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT
.SortKey(
sortedRecords.get(0).getCommitTimestamp(),
sortedRecords.get(0).getServerTransactionId()),
sortedRecords));
buffer.clear();
countState.clear();
}
}
}
// ToStringFn takes in a key-value pair of SortKey, Iterable<DataChangeRecord> and outputs
// a string representation.
private static class ToStringFn
extends DoFn<
KV<
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT.SortKey,
Iterable<DataChangeRecord>>,
String> {
private static final long serialVersionUID = 2307936669684679038L;
@ProcessElement
public void processElement(
@Element
KV<
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT
.SortKey,
Iterable<DataChangeRecord>>
element,
OutputReceiver<String> outputReceiver) {
final StringBuilder builder = new StringBuilder();
final Iterable<DataChangeRecord> sortedRecords = element.getValue();
sortedRecords.forEach(
record -> {
// Output the string representation of the mods and the mod type for each data change
// record.
String modString = "";
for (Mod mod : record.getMods()) {
modString += mod.getKeysJson();
}
builder.append(String.join(",", modString, record.getModType().toString()));
builder.append("\n");
});
outputReceiver.output(builder.toString());
}
}
private static class SortKey
implements Serializable,
Comparable<
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT
.SortKey> {
private static final long serialVersionUID = 2105939115467195036L;
private Timestamp commitTimestamp;
private String transactionId;
public SortKey() {}
public SortKey(Timestamp commitTimestamp, String transactionId) {
this.commitTimestamp = commitTimestamp;
this.transactionId = transactionId;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Timestamp getCommitTimestamp() {
return commitTimestamp;
}
public void setCommitTimestamp(Timestamp commitTimestamp) {
this.commitTimestamp = commitTimestamp;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT.SortKey
sortKey =
(org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT
.SortKey)
o;
return Objects.equals(commitTimestamp, sortKey.commitTimestamp)
&& Objects.equals(transactionId, sortKey.transactionId);
}
@Override
public int hashCode() {
return Objects.hash(commitTimestamp, transactionId);
}
@Override
public int compareTo(
org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT.SortKey
other) {
return Comparator
.<org.apache.beam.sdk.io.gcp.spanner.SpannerChangeStreamTransactionBoundariesIT.SortKey>
comparingLong(sortKey -> sortKey.getCommitTimestamp().getSeconds())
.thenComparing(sortKey -> sortKey.getTransactionId())
.compare(this, other);
}
}
}
| 39.334594 | 100 | 0.686082 |
2c7c89059a20edcb8ac02c36906c8dfa89b3b7ef | 11,519 | package io.quarkus.runtime.configuration;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.config.spi.Converter;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.Converters;
import io.smallrye.config.SmallRyeConfig;
/**
* Utility class for manually instantiating a config object
* <p>
* This should only be used in specific circumstances, generally when normal start
* has failed and we are attempting to do some form of recovery via hot deployment
* <p>
* TODO: fully implement this as required, at the moment this is mostly to read the HTTP config when startup fails
* or for basic logging setup in non-Quarkus tests
*/
public class ConfigInstantiator {
// certain well-known classname suffixes that we support
private static Set<String> SUPPORTED_CLASS_NAME_SUFFIXES = Set.of("Config", "Configuration");
private static final String QUARKUS_PROPERTY_PREFIX = "quarkus.";
private static final Pattern SEGMENT_EXTRACTION_PATTERN = Pattern.compile("(\"[^\"]+\"|[^.\"]+).*");
public static <T> T handleObject(Supplier<T> supplier) {
T o = supplier.get();
handleObject(o);
return o;
}
public static void handleObject(Object o) {
final SmallRyeConfig config = (SmallRyeConfig) ConfigProvider.getConfig();
final String clsNameSuffix = getClassNameSuffix(o);
if (clsNameSuffix == null) {
// unsupported object type
return;
}
final Class<?> cls = o.getClass();
final String name;
ConfigRoot configRoot = cls.getAnnotation(ConfigRoot.class);
if (configRoot != null && !configRoot.name().equals(ConfigItem.HYPHENATED_ELEMENT_NAME)) {
name = configRoot.name();
if (name.startsWith("<<")) {
throw new IllegalArgumentException("Found unsupported @ConfigRoot.name = " + name + " on " + cls);
}
} else {
name = dashify(cls.getSimpleName().substring(0, cls.getSimpleName().length() - clsNameSuffix.length()));
}
handleObject(QUARKUS_PROPERTY_PREFIX + name, o, config, gatherQuarkusPropertyNames(config));
}
private static List<String> gatherQuarkusPropertyNames(SmallRyeConfig config) {
var names = new ArrayList<String>(50);
for (String name : config.getPropertyNames()) {
if (name.startsWith(QUARKUS_PROPERTY_PREFIX)) {
names.add(name);
}
}
return names;
}
private static void handleObject(String prefix, Object o, SmallRyeConfig config, List<String> quarkusPropertyNames) {
try {
final Class<?> cls = o.getClass();
if (!isClassNameSuffixSupported(o)) {
return;
}
for (Field field : cls.getDeclaredFields()) {
if (field.isSynthetic() || Modifier.isFinal(field.getModifiers())) {
continue;
}
field.setAccessible(true);
ConfigItem configItem = field.getDeclaredAnnotation(ConfigItem.class);
final Class<?> fieldClass = field.getType();
if (configItem == null || fieldClass.isAnnotationPresent(ConfigGroup.class)) {
Constructor<?> constructor = fieldClass.getConstructor();
constructor.setAccessible(true);
Object newInstance = constructor.newInstance();
field.set(o, newInstance);
handleObject(prefix + "." + dashify(field.getName()), newInstance, config, quarkusPropertyNames);
} else {
String name = configItem.name();
if (name.equals(ConfigItem.HYPHENATED_ELEMENT_NAME)) {
name = dashify(field.getName());
} else if (name.equals(ConfigItem.ELEMENT_NAME)) {
name = field.getName();
}
String fullName = prefix + "." + name;
final Type genericType = field.getGenericType();
if (fieldClass == Map.class) {
field.set(o, handleMap(fullName, genericType, config, quarkusPropertyNames));
continue;
}
final Converter<?> conv = getConverterFor(genericType, config);
try {
Optional<?> value = config.getOptionalValue(fullName, conv);
if (value.isPresent()) {
field.set(o, value.get());
} else if (!configItem.defaultValue().equals(ConfigItem.NO_DEFAULT)) {
//the runtime config source handles default automatically
//however this may not have actually been installed depending on where the failure occured
field.set(o, conv.convert(configItem.defaultValue()));
}
} catch (NoSuchElementException ignored) {
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Map<?, ?> handleMap(String fullName, Type genericType, SmallRyeConfig config,
List<String> quarkusPropertyNames) throws ReflectiveOperationException {
var map = new HashMap<>();
if (typeOfParameter(genericType, 0) != String.class) { // only support String keys
return map;
}
var processedSegments = new HashSet<String>();
// infer the map keys from existing property names
for (String propertyName : quarkusPropertyNames) {
var fullNameWithDot = fullName + ".";
String withoutPrefix = propertyName.replace(fullNameWithDot, "");
if (withoutPrefix.equals(propertyName)) {
continue;
}
Matcher matcher = SEGMENT_EXTRACTION_PATTERN.matcher(withoutPrefix);
if (!matcher.find()) {
continue; // should not happen, but be lenient
}
var segment = matcher.group(1);
if (!processedSegments.add(segment)) {
continue;
}
var mapKey = segment.replace("\"", "");
var nextFullName = fullNameWithDot + segment;
var mapValueType = typeOfParameter(genericType, 1);
Object mapValue;
if (mapValueType instanceof ParameterizedType
&& ((ParameterizedType) mapValueType).getRawType().equals(Map.class)) {
mapValue = handleMap(nextFullName, mapValueType, config, quarkusPropertyNames);
} else {
Class<?> mapValueClass = mapValueType instanceof Class ? (Class<?>) mapValueType : null;
if (mapValueClass != null && mapValueClass.isAnnotationPresent(ConfigGroup.class)) {
Constructor<?> constructor = mapValueClass.getConstructor();
constructor.setAccessible(true);
mapValue = constructor.newInstance();
handleObject(nextFullName, mapValue, config, quarkusPropertyNames);
} else {
final Converter<?> conv = getConverterFor(mapValueType, config);
mapValue = config.getOptionalValue(nextFullName, conv).orElse(null);
}
}
map.put(mapKey, mapValue);
}
return map;
}
private static Converter<?> getConverterFor(Type type, SmallRyeConfig config) {
// hopefully this is enough
Class<?> rawType = rawTypeOf(type);
if (Enum.class.isAssignableFrom(rawType)) {
return new HyphenateEnumConverter(rawType);
} else if (rawType == Optional.class) {
return Converters.newOptionalConverter(getConverterFor(typeOfParameter(type, 0), config));
} else if (rawType == List.class) {
return Converters.newCollectionConverter(getConverterFor(typeOfParameter(type, 0), config), ArrayList::new);
} else {
return config.requireConverter(rawTypeOf(type));
}
}
// cribbed from io.quarkus.deployment.util.ReflectUtil
private static Class<?> rawTypeOf(final Type type) {
if (type instanceof Class<?>) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
return rawTypeOf(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
return Array.newInstance(rawTypeOf(((GenericArrayType) type).getGenericComponentType()), 0).getClass();
} else {
throw new IllegalArgumentException("Type has no raw type class: " + type);
}
}
static Type typeOfParameter(final Type type, final int paramIdx) {
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments()[paramIdx];
} else {
throw new IllegalArgumentException("Type is not parameterized: " + type);
}
}
// Configuration keys are normally derived from the field names that they are tied to.
// This is done by de-camel-casing the name and then joining the segments with hyphens (-).
// Some examples:
// bindAddress becomes bind-address
// keepAliveTime becomes keep-alive-time
// requestDNSTimeout becomes request-dns-timeout
private static String dashify(String substring) {
final StringBuilder ret = new StringBuilder();
final char[] chars = substring.toCharArray();
for (int i = 0; i < chars.length; i++) {
final char c = chars[i];
if (i != 0 && i != (chars.length - 1) && c >= 'A' && c <= 'Z') {
ret.append('-');
}
ret.append(Character.toLowerCase(c));
}
return ret.toString();
}
private static String getClassNameSuffix(final Object o) {
if (o == null) {
return null;
}
final String klassName = o.getClass().getName();
for (final String supportedSuffix : SUPPORTED_CLASS_NAME_SUFFIXES) {
if (klassName.endsWith(supportedSuffix)) {
return supportedSuffix;
}
}
return null;
}
private static boolean isClassNameSuffixSupported(final Object o) {
if (o == null) {
return false;
}
final String klassName = o.getClass().getName();
for (final String supportedSuffix : SUPPORTED_CLASS_NAME_SUFFIXES) {
if (klassName.endsWith(supportedSuffix)) {
return true;
}
}
return false;
}
}
| 43.467925 | 121 | 0.601615 |
6be70109bf62249df2627ed6bb08ea7b210c8af5 | 10,643 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.gateway.filter.rewrite.impl.html;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.EndTag;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.StartTag;
import net.htmlparser.jericho.StreamedSource;
import net.htmlparser.jericho.Tag;
import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterReader;
import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil;
import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
import org.apache.hadoop.gateway.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class HtmlFilterReaderBase extends Reader implements UrlRewriteFilterReader {
private static final String SCRIPTTAG = "script";
private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
private Document document;
private Stack<Level> stack;
private Reader reader;
private StreamedSource parser;
private Iterator<Segment> iterator;
private int lastSegEnd;
private int offset;
private StringWriter writer;
private StringBuffer buffer;
private UrlRewriteFilterContentDescriptor config = null;
protected HtmlFilterReaderBase( Reader reader ) throws IOException, ParserConfigurationException {
this.reader = reader;
document = XmlUtils.createDocument( false );
stack = new Stack<Level>();
parser = new StreamedSource( reader );
iterator = parser.iterator();
writer = new StringWriter();
buffer = writer.getBuffer();
offset = 0;
}
protected HtmlFilterReaderBase( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
this(reader);
this.config = config;
}
protected abstract String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName );
protected abstract String filterText( QName elementName, String text, String ruleName );
@Override
public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
int count = 0;
int available = buffer.length() - offset;
if( available == 0 ) {
if( iterator.hasNext() ) {
iterator.next();
processCurrentSegment();
available = buffer.length() - offset;
} else {
count = -1;
}
}
if( available > 0 ) {
count = Math.min( destCount, available );
buffer.getChars( offset, offset + count, destBuffer, destOffset );
offset += count;
if( offset == buffer.length() ) {
offset = 0;
buffer.setLength( 0 );
}
}
return count;
}
private void processCurrentSegment() {
Segment segment = parser.getCurrentSegment();
// If this tag is inside the previous tag (e.g. a server tag) then
// ignore it as it was already output along with the previous tag.
if( segment.getEnd() <= lastSegEnd ) {
return;
}
lastSegEnd = segment.getEnd();
if( segment instanceof Tag ) {
if( segment instanceof StartTag ) {
processStartTag( (StartTag)segment );
} else if ( segment instanceof EndTag ) {
processEndTag( (EndTag)segment );
} else {
writer.write( segment.toString() );
}
} else {
processText( segment );
}
}
private void processEndTag( EndTag tag ) {
while( !stack.isEmpty() ) {
Level popped = stack.pop();
if( popped.getTag().getName().equalsIgnoreCase( tag.getName() ) ) {
break;
}
}
writer.write( tag.toString() );
}
private void processStartTag( StartTag tag ) {
if( "<".equals( tag.getTagType().getStartDelimiter() ) ) {
Element e = document.createElement( tag.getNameSegment().toString() );
stack.push( new Level( tag ) );
writer.write( "<" );
writer.write( tag.getNameSegment().toString() );
Attributes attributes = tag.getAttributes();
if( !attributes.isEmpty() ) {
for( Attribute attribute : attributes ) {
processAttribute( attribute );
}
}
if( tag.toString().trim().endsWith( "/>" ) || tag.isEmptyElementTag() ) {
stack.pop();
writer.write( "/>" );
} else {
writer.write( ">" );
}
} else {
writer.write( tag.toString() );
}
}
private void processAttribute( Attribute attribute ) {
writer.write( " " );
writer.write( attribute.getName() );
if(attribute.hasValue()) {
/*
* non decoded value, return the raw value of the attribute as it appears
* in the source document, without decoding, see KNOX-791.
*/
String inputValue = attribute.getValueSegment().toString();
String outputValue = inputValue;
try {
Level tag = stack.peek();
String name = getRuleName(inputValue);
outputValue = filterAttribute( tag.getQName(), tag.getQName( attribute.getName() ), inputValue, name );
if( outputValue == null ) {
outputValue = inputValue;
}
} catch ( Exception e ) {
LOG.failedToFilterAttribute( attribute.getName(), e );
}
writer.write( "=" );
writer.write( attribute.getQuoteChar() );
writer.write( outputValue );
writer.write( attribute.getQuoteChar() );
}
}
private String getRuleName(String inputValue) {
if( config != null && !config.getSelectors().isEmpty() ) {
for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
if ( selector instanceof UrlRewriteFilterApplyDescriptor ) {
UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
Matcher matcher = apply.compiledPath( REGEX_COMPILER ).matcher( inputValue );
if (matcher.matches()) {
return apply.rule();
}
}
}
}
return null;
}
private void processText( Segment segment ) {
String inputValue = segment.toString();
String outputValue = inputValue;
try {
if( stack.isEmpty() ) {
// This can happen for whitespace outside of the root element.
//outputValue = filterText( null, inputValue );
} else {
String tagName = stack.peek().getTag().getName();
if (SCRIPTTAG.equals(tagName) && config != null && !config.getSelectors().isEmpty() ) {
// embedded javascript content
outputValue = UrlRewriteUtil.filterJavaScript( inputValue, config, this, REGEX_COMPILER );
} else {
outputValue = filterText( stack.peek().getQName(), inputValue, getRuleName(inputValue) );
}
}
if( outputValue == null ) {
outputValue = inputValue;
}
} catch ( Exception e ) {
LOG.failedToFilterValue( inputValue, null, e );
}
writer.write( outputValue );
}
@Override
public void close() throws IOException {
parser.close();
reader.close();
writer.close();
stack.clear();
}
private String getNamespace( String prefix ) {
String namespace = null;
for( Level level : stack ) {
namespace = level.getNamespace( prefix );
if( namespace != null ) {
break;
}
}
return namespace;
}
private static class Level {
private StartTag tag;
private QName name;
private Map<String,String> namespaces;
private Level( StartTag tag ) {
this.tag = tag;
this.name = null;
this.namespaces = null;
}
private StartTag getTag() {
return tag;
}
private QName getQName() {
if( name == null ) {
name = getQName( tag.getName() );
}
return name;
}
private String getNamespace( String prefix ) {
return getNamespaces().get( prefix );
}
private QName getQName( String name ) {
String prefix;
String local;
int colon = ( name == null ? -1 : name.indexOf( ':' ) );
if( colon < 0 ) {
prefix = "";
local = name;
} else {
prefix = name.substring( 0, colon );
local = ( colon + 1 < name.length() ? name.substring( colon + 1 ) : "" );
}
String namespace = getNamespace( prefix );
return new QName( namespace, local, prefix );
}
private Map<String,String> getNamespaces() {
if( namespaces == null ) {
namespaces = new HashMap<>();
parseNamespaces();
}
return namespaces;
}
private void parseNamespaces() {
Attributes attributes = tag.getAttributes();
if( attributes != null ) {
for( Attribute attribute : tag.getAttributes() ) {
String name = attribute.getName();
if( name.toLowerCase().startsWith( "xmlns" ) ) {
int colon = name.indexOf( ":", 5 );
String prefix;
if( colon <= 0 ) {
prefix = "";
} else {
prefix = name.substring( colon );
}
namespaces.put( prefix, attribute.getValue() );
}
}
}
}
}
}
| 32.547401 | 142 | 0.648126 |
4c316c39d6c8373a0056b7083ee17a53ae3be1ef | 3,766 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.permissions.nfc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.os.Process;
import android.provider.Settings;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.task.PostTask;
import org.chromium.content_public.browser.UiThreadTaskTraits;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.WindowAndroid;
/**
* Provides methods for querying NFC sytem-level setting on Android.
*
* This class should be used only on the UI thread.
*/
public class NfcSystemLevelSetting {
private static Boolean sNfcSupportForTesting;
private static Boolean sSystemNfcSettingForTesting;
@CalledByNative
public static boolean isNfcAccessPossible() {
if (sNfcSupportForTesting != null) {
return sNfcSupportForTesting;
}
Context context = ContextUtils.getApplicationContext();
int permission =
context.checkPermission(Manifest.permission.NFC, Process.myPid(), Process.myUid());
if (permission != PackageManager.PERMISSION_GRANTED) {
return false;
}
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
return nfcAdapter != null;
}
@CalledByNative
public static boolean isNfcSystemLevelSettingEnabled() {
if (sSystemNfcSettingForTesting != null) {
return sSystemNfcSettingForTesting;
}
if (!isNfcAccessPossible()) return false;
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(ContextUtils.getApplicationContext());
return nfcAdapter.isEnabled();
}
@CalledByNative
private static void promptToEnableNfcSystemLevelSetting(
WebContents webContents, final long nativeCallback) {
WindowAndroid window = webContents.getTopLevelNativeWindow();
if (window == null) {
// Consuming code may not expect a sync callback to happen.
PostTask.postTask(UiThreadTaskTraits.DEFAULT,
()
-> NfcSystemLevelSettingJni.get().onNfcSystemLevelPromptCompleted(
nativeCallback));
return;
}
NfcSystemLevelPrompt prompt = new NfcSystemLevelPrompt();
prompt.show(window,
()
-> NfcSystemLevelSettingJni.get().onNfcSystemLevelPromptCompleted(
nativeCallback));
}
public static Intent getNfcSystemLevelSettingIntent() {
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
Context context = ContextUtils.getApplicationContext();
if (intent.resolveActivity(context.getPackageManager()) == null) {
return null;
}
return intent;
}
/** Disable/enable Android NFC setting for testing use only. */
@VisibleForTesting
public static void setNfcSettingForTesting(Boolean enabled) {
sSystemNfcSettingForTesting = enabled;
}
/** Disable/enable Android NFC support for testing use only. */
@VisibleForTesting
public static void setNfcSupportForTesting(Boolean enabled) {
sNfcSupportForTesting = enabled;
}
@NativeMethods
interface Natives {
void onNfcSystemLevelPromptCompleted(long callback);
}
}
| 34.550459 | 99 | 0.690388 |
e60c4d973f3e8879f6a6e3c97c20679eb60eca84 | 4,286 | package PizzaShop.Controller.SecurityControllers;
import PizzaShop.Entities.Order;
import PizzaShop.Entities.Product;
import PizzaShop.Models.UserDetails;
import PizzaShop.Repositories.ItemRepository;
import PizzaShop.Repositories.OrderRepository;
import PizzaShop.Repositories.ProductRepository;
import PizzaShop.Repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.security.Principal;
import java.util.List;
@SessionAttributes({"UserDetails","email"})
@Controller
public class AdministratorController {
private final ProductRepository productRepository;
private final UserRepository userRepository;
private final ItemRepository itemRepository;
private final OrderRepository orderRepository;
@Autowired
public AdministratorController(ProductRepository productRepository, UserRepository userRepository, ItemRepository itemRepository, OrderRepository orderRepository) {
this.productRepository = productRepository;
this.userRepository = userRepository;
this.itemRepository = itemRepository;
this.orderRepository = orderRepository;
}
@GetMapping("/admin/home")
public String home(Model model, RedirectAttributes redirectAttributes, Principal principal){
UserDetails userDetails = this.userRepository.findOneByEmail(principal.getName());
model.addAttribute("UserDetails", userDetails);
model.addAttribute("email", userDetails.getEmail());
redirectAttributes.addFlashAttribute("UserDetails",userDetails);
redirectAttributes.addFlashAttribute("email",userDetails.getEmail());
return "redirect:/admin/orders";
}
@GetMapping("/admin/orders")
public ModelAndView orders(ModelAndView modelAndView){
modelAndView.setViewName("base-layout");
modelAndView.addObject("view", "views/AdminViews/orders");
List<Order> orders = this.orderRepository.findAllByStatus("not completed");
modelAndView.addObject("orders", orders);
return modelAndView;
}
@PostMapping("/admin/orders/complete/{id}")
public String completeOrder(@PathVariable(value = "id") Integer id){
Order order = this.orderRepository.findOneById(id);
order.setStatus("completed");
this.orderRepository.save(order);
return "redirect:/admin/orders";
}
@GetMapping("/admin/product/status")
public ModelAndView status(ModelAndView modelAndView){
modelAndView.setViewName("base-layout");
modelAndView.addObject("view", "views/AdminViews/status");
List<Product> products = productRepository.findAll();
modelAndView.addObject("products", products);
return modelAndView;
}
@PostMapping("/admin/product/disable/{id}")
public String disable(@PathVariable(value ="id")Integer id){
Product product = this.productRepository.findOneById(id);
product.setStatus("disabled");
this.productRepository.save(product);
return "redirect:/admin/product/status";
}
@PostMapping("/admin/product/enable/{id}")
public String enable(@PathVariable(value ="id")Integer id){
Product product = this.productRepository.findOneById(id);
product.setStatus("enabled");
this.productRepository.save(product);
return "redirect:/admin/product/status";
}
@GetMapping("/admin/product/add")
public ModelAndView addProduct(ModelAndView modelAndView){
modelAndView.setViewName("base-layout");
modelAndView.addObject("view", "views/AdminViews/addproduct");
return modelAndView;
}
@PostMapping("/admin/product/add")
public String addProduct(Product product){
this.productRepository.saveAndFlush(product);
return "redirect:/admin/product/add";
}
}
| 39.685185 | 168 | 0.742184 |
a94d92da1b072e75a6e57e3bc830a537247607ef | 4,555 | /*
* Copyright (C) 2016 Clover Network, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clover.sdk.internal.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ScrollView;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* For internal use only.
*/
public final class Views {
private static final String TAG = Views.class.getSimpleName();
private Views() { }
// Short enough to always fit in heap, matches seiko printer max height
private static final int BITMAP_MAX_HEIGHT = 2048;
// NOTE: All view operations must occur on the main thread, enable strict mode to test
public static ArrayList<String> writeBitmapChucks(final View view, OutputUriFactory outputUriFactory) throws IOException {
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
throw new RuntimeException("Long running operation should not be executed on the main thread");
}
Point viewWH = runSynchronouslyOnMainThread(() -> {
Point wh = new Point();
wh.x = view.getMeasuredWidth();
wh.y = getContentHeight(view);
return wh;
});
final int measuredWidth = viewWH == null ? 0 : viewWH.x;
final int contentHeight = viewWH == null ? 0 : viewWH.y;
if (measuredWidth <= 0 || contentHeight <= 0) {
throw new IllegalArgumentException("Measured view width or height is 0");
}
Bitmap bitmap = null;
ArrayList<String> outUris = new ArrayList<String>();
for (int top = 0; top < contentHeight; top += BITMAP_MAX_HEIGHT) {
int bitmapHeight = Math.min(contentHeight - top, BITMAP_MAX_HEIGHT);
if (bitmap == null || bitmapHeight < BITMAP_MAX_HEIGHT) {
if (bitmap != null) {
bitmap.recycle();
}
bitmap = Bitmap.createBitmap(measuredWidth, bitmapHeight, Bitmap.Config.RGB_565);
}
bitmap.eraseColor(0xFFFFFFFF);
final Canvas canvas = new Canvas(bitmap);
canvas.translate(0, -top);
runSynchronouslyOnMainThread(() -> {
view.draw(canvas);
return null;
});
Uri outUri = outputUriFactory.createNewOutputUri();
BufferedOutputStream bos = new BufferedOutputStream(outputUriFactory.getOutputStreamForUri(outUri));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
outUris.add(outUri.toString());
}
return outUris;
}
private static final Handler sMainHandler = new Handler(Looper.getMainLooper());
/**
* Runs the given callable on the main thread synchronously. This method should be invoked on a
* background thread, the callable must complete very quickly to prevent an ANR, generally used
* when manipulating Views which Android requires to be on the main thread. This method eats
* exceptions and returns null.
*/
private static <T> T runSynchronouslyOnMainThread(Callable<T> callable) {
try {
FutureTask<T> futureTask = new FutureTask<>(callable);
sMainHandler.post(futureTask);
return futureTask.get();
} catch (Exception e) {
Log.w(TAG, e);
return null;
}
}
@SuppressWarnings("deprecation")
private static int getContentHeight(View view) {
if (view instanceof WebView) {
WebView wv = (WebView) view;
float scale = wv.getScale(); // Deprecated but works
// Just in case future Android platform breaks getScale, use default scale of 100%
if (scale <= 0.0f) {
scale = 1.0f;
}
return (int) (wv.getContentHeight() * scale);
} else if (view instanceof ScrollView) {
return ((ScrollView) view).getChildAt(0).getMeasuredHeight();
} else {
return view.getMeasuredHeight();
}
}
}
| 32.535714 | 124 | 0.692426 |
866ae50322858a7813e58888f434e61f0344850e | 177 | package com.buptse.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.buptse.pojo.Carimg;
public interface CarimgMapper extends BaseMapper<Carimg> {
}
| 22.125 | 58 | 0.819209 |
2c6448d022c0c7eadcc1211662e3da56f6f0ced6 | 382 | package net.halflite.resteasy.web.resource;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.jboss.resteasy.plugins.providers.html.Renderable;
import org.jboss.resteasy.plugins.providers.html.View;
@Singleton
@Path("/")
public class IndexResource {
@GET
public Renderable index() {
return new View("index.ftl");
}
}
| 20.105263 | 60 | 0.732984 |
0325c1d3d1270f3f887c121642b91d56dc989a14 | 20,869 | package org.andengine.extension.physics.box2d;
import static org.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
import java.util.List;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.shape.IAreaShape;
import org.andengine.entity.shape.IShape;
import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.andengine.util.Constants;
import org.andengine.util.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.Filter;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:59:03 - 15.07.2010
*/
public class PhysicsFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* create FixtureDef based on parameters given
* @param pDensity
* @param pElasticity
* @param pFriction
* @return
*/
public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction) {
return PhysicsFactory.createFixtureDef(pDensity, pElasticity, pFriction, false);
}
/**
* create FixtureDef based on parameters given
* @param pDensity
* @param pElasticity
* @param pFriction
* @param pSensor
* @return
*/
public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction, final boolean pSensor) {
final FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = pDensity;
fixtureDef.restitution = pElasticity;
fixtureDef.friction = pFriction;
fixtureDef.isSensor = pSensor;
return fixtureDef;
}
/**
* create FixtureDef based on parameters given
* @param pDensity
* @param pElasticity
* @param pFriction
* @param pSensor
* @param pCategoryBits
* @param pMaskBits
* @param pGroupIndex
* @return
*/
public static FixtureDef createFixtureDef(final float pDensity, final float pElasticity, final float pFriction, final boolean pSensor, final short pCategoryBits, final short pMaskBits, final short pGroupIndex) {
final FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = pDensity;
fixtureDef.restitution = pElasticity;
fixtureDef.friction = pFriction;
fixtureDef.isSensor = pSensor;
final Filter filter = fixtureDef.filter;
filter.categoryBits = pCategoryBits;
filter.maskBits = pMaskBits;
filter.groupIndex = pGroupIndex;
return fixtureDef;
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pAreaShape
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final IAreaShape pAreaShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createBoxBody(pPhysicsWorld, pAreaShape, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pAreaShape
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final IAreaShape pAreaShape, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final float[] sceneCenterCoordinates = pAreaShape.getSceneCenterCoordinates();
final float centerX = sceneCenterCoordinates[Constants.VERTEX_INDEX_X];
final float centerY = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y];
return PhysicsFactory.createBoxBody(pPhysicsWorld, centerX, centerY, pAreaShape.getWidthScaled(), pAreaShape.getHeightScaled(), pAreaShape.getRotation(), pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pWidth
* @param pHeight
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createBoxBody(pPhysicsWorld, pCenterX, pCenterY, pWidth, pHeight, 0, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pWidth
* @param pHeight
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createBoxBody(pPhysicsWorld, pCenterX, pCenterY, pWidth, pHeight, pRotation, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pWidth
* @param pHeight
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
return PhysicsFactory.createBoxBody(pPhysicsWorld, pCenterX, pCenterY, pWidth, pHeight, 0, pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* create Body of box shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pWidth
* @param pHeight
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createBoxBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pWidth, final float pHeight, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef boxBodyDef = new BodyDef();
boxBodyDef.type = pBodyType;
boxBodyDef.position.x = pCenterX / pPixelToMeterRatio;
boxBodyDef.position.y = pCenterY / pPixelToMeterRatio;
final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
final PolygonShape boxPoly = new PolygonShape();
final float halfWidth = pWidth * 0.5f / pPixelToMeterRatio;
final float halfHeight = pHeight * 0.5f / pPixelToMeterRatio;
boxPoly.setAsBox(halfWidth, halfHeight);
pFixtureDef.shape = boxPoly;
boxBody.createFixture(pFixtureDef);
boxPoly.dispose();
boxBody.setTransform(boxBody.getWorldCenter(), MathUtils.degToRad(pRotation));
return boxBody;
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pAreaShape
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final IAreaShape pAreaShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createCircleBody(pPhysicsWorld, pAreaShape, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pAreaShape
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final IAreaShape pAreaShape, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final float[] sceneCenterCoordinates = pAreaShape.getSceneCenterCoordinates();
final float centerX = sceneCenterCoordinates[Constants.VERTEX_INDEX_X];
final float centerY = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y];
return PhysicsFactory.createCircleBody(pPhysicsWorld, centerX, centerY, pAreaShape.getWidthScaled() * 0.5f, pAreaShape.getRotation(), pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pRadius
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return createCircleBody(pPhysicsWorld, pCenterX, pCenterY, pRadius, 0, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pRadius
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return createCircleBody(pPhysicsWorld, pCenterX, pCenterY, pRadius, pRotation, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pRadius
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
return createCircleBody(pPhysicsWorld, pCenterX, pCenterY, pRadius, 0, pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* create Body of circle shape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param pRadius
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createCircleBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final float pRadius, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef circleBodyDef = new BodyDef();
circleBodyDef.type = pBodyType;
circleBodyDef.position.x = pCenterX / pPixelToMeterRatio;
circleBodyDef.position.y = pCenterY / pPixelToMeterRatio;
circleBodyDef.angle = MathUtils.degToRad(pRotation);
final Body circleBody = pPhysicsWorld.createBody(circleBodyDef);
final CircleShape circlePoly = new CircleShape();
pFixtureDef.shape = circlePoly;
final float radius = pRadius / pPixelToMeterRatio;
circlePoly.setRadius(radius);
circleBody.createFixture(pFixtureDef);
circlePoly.dispose();
return circleBody;
}
/**
* deprecated, left for backward compatibility
*/
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final Line pLine, final FixtureDef pFixtureDef) {
return PhysicsFactory.createLineBody(pPhysicsWorld, pLine, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* deprecated, left for backward compatibility
*/
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final Line pLine, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final float[] sceneCoordinates = pLine.convertLocalToSceneCoordinates(0, 0);
final float x1 = sceneCoordinates[Constants.VERTEX_INDEX_X];
final float y1 = sceneCoordinates[Constants.VERTEX_INDEX_Y];
pLine.convertLocalToSceneCoordinates(pLine.getX2() - pLine.getX1(), pLine.getY2() - pLine.getY1());
final float x2 = sceneCoordinates[Constants.VERTEX_INDEX_X];
final float y2 = sceneCoordinates[Constants.VERTEX_INDEX_Y];
return PhysicsFactory.createLineBody(pPhysicsWorld, x1, y1, x2, y2, pFixtureDef, pPixelToMeterRatio);
}
/**
* deprecated, left for backward compatibility
*/
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final float pX1, final float pY1, final float pX2, final float pY2, final FixtureDef pFixtureDef) {
return PhysicsFactory.createLineBody(pPhysicsWorld, pX1, pY1, pX2, pY2, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* deprecated, left for backward compatibility
*/
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final float pX1, final float pY1, final float pX2, final float pY2, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef lineBodyDef = new BodyDef();
lineBodyDef.type = BodyType.StaticBody;
final Body boxBody = pPhysicsWorld.createBody(lineBodyDef);
final EdgeShape linePoly = new EdgeShape();
linePoly.set(new Vector2(pX1 / pPixelToMeterRatio, pY1 / pPixelToMeterRatio), new Vector2(pX2 / pPixelToMeterRatio, pY2 / pPixelToMeterRatio));
pFixtureDef.shape = linePoly;
boxBody.createFixture(pFixtureDef);
linePoly.dispose();
return boxBody;
}
/**
* @param pPhysicsWorld
* @param pShape
* @param pVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied.
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createPolygonBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final Vector2[] pVertices, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, pVertices, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* @param pPhysicsWorld
* @param pShape
* @param pVertices are to be defined relative to the center of the pShape.
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createPolygonBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final Vector2[] pVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef boxBodyDef = new BodyDef();
boxBodyDef.type = pBodyType;
final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates();
boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio;
boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio;
final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
final PolygonShape boxPoly = new PolygonShape();
boxPoly.set(pVertices);
pFixtureDef.shape = boxPoly;
boxBody.createFixture(pFixtureDef);
boxPoly.dispose();
return boxBody;
}
/**
* @param pPhysicsWorld
* @param pShape
* @param pTriangleVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied.
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef) {
return PhysicsFactory.createTrianglulatedBody(pPhysicsWorld, pShape, pTriangleVertices, pBodyType, pFixtureDef, PIXEL_TO_METER_RATIO_DEFAULT);
}
/**
* @param pPhysicsWorld
* @param pShape
* @param pTriangleVertices are to be defined relative to the center of the pShape and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied.
* The vertices will be triangulated and for each triangle a {@link Fixture} will be created.
* @param pBodyType
* @param pFixtureDef
* @return
*/
public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IShape pShape, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final Vector2[] TMP_TRIANGLE = new Vector2[3];
final BodyDef boxBodyDef = new BodyDef();
boxBodyDef.type = pBodyType;
final float[] sceneCenterCoordinates = pShape.getSceneCenterCoordinates();
boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio;
boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio;
final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
final int vertexCount = pTriangleVertices.size();
for(int i = 0; i < vertexCount; /* */) {
final PolygonShape boxPoly = new PolygonShape();
TMP_TRIANGLE[2] = pTriangleVertices.get(i++);
TMP_TRIANGLE[1] = pTriangleVertices.get(i++);
TMP_TRIANGLE[0] = pTriangleVertices.get(i++);
boxPoly.set(TMP_TRIANGLE);
pFixtureDef.shape = boxPoly;
boxBody.createFixture(pFixtureDef);
boxPoly.dispose();
}
return boxBody;
}
/**
* Box2D introduced ChainShape - this method creates body for it
* @param pPhysicsWorld
* @param vertices
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createChainBody(final PhysicsWorld pPhysicsWorld, final Vector2[] vertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
return PhysicsFactory.createChainBody(pPhysicsWorld, 0, 0, vertices, 0, pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* Box2D introduced ChainShape - this method creates body for it
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param vertices
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createChainBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final Vector2[] vertices, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef chainBodyDef = new BodyDef();
chainBodyDef.type = pBodyType;
chainBodyDef.position.x = pCenterX / pPixelToMeterRatio;
chainBodyDef.position.y = pCenterY / pPixelToMeterRatio;
chainBodyDef.angle = MathUtils.degToRad(pRotation);
final Body chainBody = pPhysicsWorld.createBody(chainBodyDef);
final ChainShape chainPoly = new ChainShape();
pFixtureDef.shape = chainPoly;
chainPoly.createChain(vertices);
chainBody.createFixture(pFixtureDef);
chainPoly.dispose();
return chainBody;
}
/**
* Box2D introduced EdgeShape instead of LineShape
* @param pPhysicsWorld
* @param v1
* @param v2
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createEdgeBody(final PhysicsWorld pPhysicsWorld, final Vector2 v1, final Vector2 v2, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
return PhysicsFactory.createEdgeBody(pPhysicsWorld, 0, 0, v1, v2, 0, pBodyType, pFixtureDef, pPixelToMeterRatio);
}
/**
* Box2D introduced EdgeShape instead of LineShape
* @param pPhysicsWorld
* @param pCenterX
* @param pCenterY
* @param v1
* @param v2
* @param pRotation
* @param pBodyType
* @param pFixtureDef
* @param pPixelToMeterRatio
* @return
*/
public static Body createEdgeBody(final PhysicsWorld pPhysicsWorld, final float pCenterX, final float pCenterY, final Vector2 v1, final Vector2 v2, final float pRotation, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
final BodyDef edgeBodyDef = new BodyDef();
edgeBodyDef.type = pBodyType;
edgeBodyDef.position.x = pCenterX / pPixelToMeterRatio;
edgeBodyDef.position.y = pCenterY / pPixelToMeterRatio;
edgeBodyDef.angle = MathUtils.degToRad(pRotation);
final Body edgeBody = pPhysicsWorld.createBody(edgeBodyDef);
final EdgeShape edgePoly = new EdgeShape();
pFixtureDef.shape = edgePoly;
edgePoly.set(v1, v2);
edgeBody.createFixture(pFixtureDef);
edgePoly.dispose();
return edgeBody;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 36.612281 | 265 | 0.734199 |
5106d343aefea2319b70bf5dcdb073f8fd12db6a | 5,256 | package org.cam.core.parser;
import org.antlr.v4.runtime.misc.NotNull;
import org.cam.core.FactoryHelper;
import org.cam.core.dao.CamDao;
import org.cam.core.exception.EntityNotFoundException;
import org.cam.core.exception.ParserException;
import org.cam.core.mapping.EntityMapping;
import org.cam.core.mapping.EntityTableMapping;
import org.cam.core.parser.antlr.PermissionBaseVisitor;
import org.cam.core.parser.antlr.PermissionParser;
import org.cam.core.util.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
/**
* Created by wuyaohui on 14-9-27.
*/
public abstract class AbstractPermissionVisitor<T> extends PermissionBaseVisitor<T>{
private static final Logger LOG = LoggerFactory.getLogger(AbstractPermissionVisitor.class);
protected static final String VAR_USER = "User";
protected String objectType = null;
protected EntityMapping currentEntityMapping;
protected void switchCurrentEntity(String entityName){
EntityTableMapping entityTableMapping = FactoryHelper.factory().getEntityTableMapping();
LOG.trace("Switch current entity to {}",entityName);
currentEntityMapping = entityTableMapping.getEntity(entityName);
if(currentEntityMapping == null){
throw new EntityNotFoundException(entityName);
}
}
protected void switchBack(){
if(objectType!=null){
switchCurrentEntity(objectType);
}
}
protected String getTableByEntity(String entityName){
EntityTableMapping entityTableMapping = FactoryHelper.factory().getEntityTableMapping();
return entityTableMapping.getTableNameByEntity(entityName);
}
/**
* 根据属性名得到字段名
* @param fieldName
* @return
*/
protected String getColumnByField(String fieldName){
return currentEntityMapping.getFieldColumnMap().get(fieldName);
}
protected String getCurrentEntityFieldType(String fieldName){
return currentEntityMapping.getFieldType(fieldName);
}
public String getId(PermissionParser.IdAliasContext idAliasCtx){
if(idAliasCtx!=null){
return idAliasCtx.ID(0).getText();
}
throw new ParserException("Bad queryListCtx");
}
/**
* 获取用户变量的值。
*
* @param scalarVariableCtx
* @return
*/
protected Object getScalarValue(PermissionParser.ScalarVariableContext scalarVariableCtx){
String innerObjectName = scalarVariableCtx.innerObject().getText();
if(VAR_USER.equals(innerObjectName)){
String innerAttrName = scalarVariableCtx.ID().getText();
return getAttrValue(FactoryHelper.currentUser(), innerAttrName);
}
throw new ParserException("unknown variable ["+innerObjectName+"]");
}
protected Object getAttrValue(Object object,String attributeName){
return ObjectUtils.getter(object,attributeName);
}
protected Object toValueObject(PermissionParser.ValueContext ctx){
String text = ctx.getText();
if(isInt(ctx)){
return Integer.valueOf(text);
}else if(isFloat(ctx)){
return Double.valueOf(text);
}else if(isBoolean(ctx)){
return Boolean.valueOf(text);
}else if(isString(ctx)) {
return ObjectUtils.trimWith(text,"'");
}else if(isScalarVar(ctx)){
return getScalarValue(ctx.scalarVariable());
}else{
return text;
}
}
protected String toValueString(Object value){
if(value instanceof String){
return ObjectUtils.toSqlString((String)value);
}else{
return value.toString();
}
}
protected boolean isFloat(PermissionParser.ValueContext ctx){
return ctx.FLOAT()!=null;
}
protected boolean isInt(PermissionParser.ValueContext ctx){
return ctx.INT()!=null;
}
protected boolean isString(PermissionParser.ValueContext ctx){
return ctx.STRING()!=null;
}
protected boolean isBoolean(PermissionParser.ValueContext ctx){
return ctx.boo!=null;
}
protected boolean isId(PermissionParser.ValueContext ctx){
return ctx.ID()!=null;
}
protected boolean isScalarVar(PermissionParser.ValueContext ctx){
return ctx.scalarVariable()!=null;
}
protected boolean isNull(PermissionParser.ValueContext ctx){
return ctx.NULL()!=null;
}
@Override
public T visitObjectType(@NotNull PermissionParser.ObjectTypeContext ctx) {
objectType = ctx.getText();
EntityTableMapping entityTableMapping = FactoryHelper.factory().getEntityTableMapping();
currentEntityMapping = entityTableMapping.getEntity(objectType);
if(currentEntityMapping == null){
LOG.error("Can't find mapping info for objectType: {}", objectType);
throw new ParserException("Can't find mapping info for objectType: "+objectType);
}
return super.visitObjectType(ctx);
}
protected Collection<String> evaluateQueryList(String literalQueryString){
CamDao camDao = FactoryHelper.factory().getCamDao();
return camDao.singleColumnListQuery(literalQueryString);
}
}
| 32.444444 | 96 | 0.687785 |
56694694bbb593634a64c271c0982b83efbf5bd6 | 10,311 | /*******************************************************************************
* Copyright 2013 SAP AG
*
* 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.sap.core.odata.core.ep;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathExists;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.custommonkey.xmlunit.SimpleNamespaceContext;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import com.sap.core.odata.api.edm.Edm;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmTyped;
import com.sap.core.odata.api.edm.provider.EdmProvider;
import com.sap.core.odata.api.ep.EntityProviderException;
import com.sap.core.odata.api.processor.ODataResponse;
import com.sap.core.odata.core.commons.ContentType;
import com.sap.core.odata.testutil.helper.StringHelper;
import com.sap.core.odata.testutil.mock.EdmTestProvider;
import com.sap.core.odata.testutil.mock.MockFacade;
/**
* @author SAP AG
*/
public class BasicProviderTest extends AbstractProviderTest {
public BasicProviderTest(final StreamWriterImplType type) {
super(type);
}
protected static BasicEntityProvider provider = new BasicEntityProvider();
@Test
public void writeMetadata() throws Exception {
Map<String, String> predefinedNamespaces = new HashMap<String, String>();
predefinedNamespaces.put("annoPrefix", "http://annoNamespace");
predefinedNamespaces.put("sap", "http://sap");
predefinedNamespaces.put("annoPrefix2", "http://annoNamespace");
predefinedNamespaces.put("annoPrefix", "http://annoNamespace");
ODataResponse response = provider.writeMetadata(null, predefinedNamespaces);
assertNotNull(response);
assertNotNull(response.getEntity());
assertEquals(ContentType.APPLICATION_XML_CS_UTF_8.toString(), response.getContentHeader());
String metadata = StringHelper.inputStreamToString((InputStream) response.getEntity());
assertTrue(metadata.contains("xmlns:sap=\"http://sap\""));
assertTrue(metadata.contains("xmlns:annoPrefix=\"http://annoNamespace\""));
assertTrue(metadata.contains("xmlns:annoPrefix2=\"http://annoNamespace\""));
}
private void setNamespaces() {
Map<String, String> prefixMap = new HashMap<String, String>();
prefixMap.put("edmx", Edm.NAMESPACE_EDMX_2007_06);
prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
prefixMap.put("a", Edm.NAMESPACE_EDM_2008_09);
prefixMap.put("annoPrefix", "http://annoNamespace");
prefixMap.put("prefix", "namespace");
prefixMap.put("b", "RefScenario");
prefixMap.put("pre", "namespaceForAnno");
XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
}
@Test
public void writeMetadata2() throws Exception {
EdmProvider testProvider = new EdmTestProvider();
Map<String, String> predefinedNamespaces = new HashMap<String, String>();
predefinedNamespaces.put("annoPrefix", "http://annoNamespace");
predefinedNamespaces.put("sap", "http://sap");
predefinedNamespaces.put("annoPrefix2", "http://annoNamespace");
predefinedNamespaces.put("annoPrefix", "http://annoNamespace");
predefinedNamespaces.put("prefix", "namespace");
predefinedNamespaces.put("pre", "namespaceForAnno");
ODataResponse response = provider.writeMetadata(testProvider.getSchemas(), predefinedNamespaces);
assertNotNull(response);
assertNotNull(response.getEntity());
assertEquals(ContentType.APPLICATION_XML_CS_UTF_8.toString(), response.getContentHeader());
String metadata = StringHelper.inputStreamToString((InputStream) response.getEntity());
setNamespaces();
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name and @Type and @Nullable and @annoPrefix:annoName]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name and @Type and @m:FC_TargetPath and @annoPrefix:annoName]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]/a:propertyAnnoElement", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]/a:propertyAnnoElement2", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/b:schemaElementTest2", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/prefix:schemaElementTest3", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/a:schemaElementTest4[@rel=\"self\" and @pre:href=\"http://google.com\"]", metadata);
}
@Test
public void writeMetadata3() throws Exception {
EdmProvider testProvider = new EdmTestProvider();
ODataResponse response = provider.writeMetadata(testProvider.getSchemas(), null);
assertNotNull(response);
assertNotNull(response.getEntity());
assertEquals(ContentType.APPLICATION_XML_CS_UTF_8.toString(), response.getContentHeader());
String metadata = StringHelper.inputStreamToString((InputStream) response.getEntity());
setNamespaces();
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name and @Type and @Nullable and @annoPrefix:annoName]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name and @Type and @m:FC_TargetPath and @annoPrefix:annoName]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]/a:propertyAnnoElement", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:EntityType/a:Property[@Name=\"EmployeeName\"]/a:propertyAnnoElement2", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/b:schemaElementTest2", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/prefix:schemaElementTest3", metadata);
assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/a:schemaElementTest4[@rel=\"self\" and @pre:href=\"http://google.com\"]", metadata);
}
@Test
public void writePropertyValue() throws Exception {
EdmTyped edmTyped = MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");
EdmProperty edmProperty = (EdmProperty) edmTyped;
ODataResponse response = provider.writePropertyValue(edmProperty, employeeData.get("Age"));
assertNotNull(response);
assertNotNull(response.getEntity());
assertEquals(ContentType.TEXT_PLAIN_CS_UTF_8.toString(), response.getContentHeader());
String value = StringHelper.inputStreamToString((InputStream) response.getEntity());
assertEquals(employeeData.get("Age").toString(), value);
}
@Test
public void readPropertyValue() throws Exception {
final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");
final Integer age = (Integer) provider.readPropertyValue(property, new ByteArrayInputStream("42".getBytes("UTF-8")), null);
assertEquals(Integer.valueOf(42), age);
}
@Test
public void readPropertyValueWithMapping() throws Exception {
final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");
final Long age = (Long) provider.readPropertyValue(property, new ByteArrayInputStream("42".getBytes("UTF-8")), Long.class);
assertEquals(Long.valueOf(42), age);
}
@Test(expected = EntityProviderException.class)
public void readPropertyValueWithInvalidMapping() throws Exception {
final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");
final Float age = (Float) provider.readPropertyValue(property, new ByteArrayInputStream("42".getBytes("UTF-8")), Float.class);
assertEquals(Float.valueOf(42), age);
}
@Test
public void readPropertyBinaryValue() throws Exception {
final byte[] bytes = new byte[] { 1, 2, 3, 4, -128 };
final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario2", "Photo").getProperty("Image");
assertTrue(Arrays.equals(bytes, (byte[]) provider.readPropertyValue(property, new ByteArrayInputStream(bytes), null)));
}
@Test
public void writeBinary() throws Exception {
final byte[] bytes = new byte[] { 49, 50, 51, 52, 65 };
final ODataResponse response = provider.writeBinary(ContentType.TEXT_PLAIN_CS_UTF_8.toString(), bytes);
assertNotNull(response);
assertNotNull(response.getEntity());
assertEquals(ContentType.TEXT_PLAIN_CS_UTF_8.toString(), response.getContentHeader());
final String value = StringHelper.inputStreamToString((InputStream) response.getEntity());
assertEquals("1234A", value);
}
@Test
public void readBinary() throws Exception {
final byte[] bytes = new byte[] { 1, 2, 3, 4, -128 };
assertTrue(Arrays.equals(bytes, provider.readBinary(new ByteArrayInputStream(bytes))));
}
}
| 51.298507 | 166 | 0.745805 |
e313020e6058af821f9a1d52af6400dc18465eaf | 1,299 | package com.jakduk.api.common.rabbitmq;
import com.jakduk.api.exception.ServiceError;
import com.jakduk.api.exception.ServiceException;
import java.util.Arrays;
/**
* Created by pyohwanjang on 2017. 7. 3..
*/
public enum ElasticsearchRoutingKey {
ELASTICSEARCH_INDEX_DOCUMENT_ARTICLE("elasticsearch-index-document-article"),
ELASTICSEARCH_DELETE_DOCUMENT_ARTICLE("elasticsearch-delete-document-article"),
ELASTICSEARCH_INDEX_DOCUMENT_ARTICLE_COMMENT("elasticsearch-index-document-article-comment"),
ELASTICSEARCH_DELETE_DOCUMENT_ARTICLE_COMMENT("elasticsearch-delete-document-article-comment"),
ELASTICSEARCH_INDEX_DOCUMENT_GALLERY("elasticsearch-index-document-gallery"),
ELASTICSEARCH_DELETE_DOCUMENT_GALLERY("elasticsearch-delete-document-gallery"),
ELASTICSEARCH_INDEX_DOCUMENT_SEARCH_WORD("elasticsearch-index-document-search-word");
private String routingKey;
ElasticsearchRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
static public ElasticsearchRoutingKey find(String value) {
return Arrays.stream(ElasticsearchRoutingKey.values())
.filter(routingKey -> routingKey.routingKey.equals(value))
.findFirst()
.orElseThrow(() -> new ServiceException(ServiceError.ILLEGAL_ARGUMENT));
}
public String getRoutingKey() {
return routingKey;
}
}
| 33.307692 | 96 | 0.816012 |
245ec968472d2c615d7c081d851e420008dca3b9 | 6,440 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package com.kauailabs.navx.ftc;
public final class R {
public static final class color {
public static final int bright_red = 0x7f090010;
}
public static final class id {
public static final int loadingIndicator = 0x7f0c00a0;
public static final int loadingIndicatorOverlay = 0x7f0c009f;
}
public static final class layout {
public static final int loading_indicator_overlay = 0x7f030025;
}
public static final class raw {
public static final int color_fragment_shader = 0x7f050002;
public static final int cube_mesh_fragment_shader = 0x7f050003;
public static final int cube_mesh_vertex_shader = 0x7f050004;
public static final int simple_vertex_shader = 0x7f050007;
public static final int texture_fragment_shader = 0x7f050008;
public static final int texture_vertex_shader = 0x7f050009;
}
public static final class string {
public static final int VUFORIA_INIT_ERROR_DEVICE_NOT_SUPPORTED = 0x7f0a0000;
public static final int VUFORIA_INIT_ERROR_NO_CAMERA_ACCESS = 0x7f0a0001;
public static final int VUFORIA_INIT_LICENSE_ERROR_CANCELED_KEY = 0x7f0a0002;
public static final int VUFORIA_INIT_LICENSE_ERROR_INVALID_KEY = 0x7f0a0003;
public static final int VUFORIA_INIT_LICENSE_ERROR_MISMATCH_KEY = 0x7f0a0004;
public static final int VUFORIA_INIT_LICENSE_ERROR_MISSING_KEY = 0x7f0a0005;
public static final int VUFORIA_INIT_LICENSE_ERROR_NO_NETWORK_PERMANENT = 0x7f0a0006;
public static final int VUFORIA_INIT_LICENSE_ERROR_NO_NETWORK_TRANSIENT = 0x7f0a0007;
public static final int VUFORIA_INIT_LICENSE_ERROR_PRODUCT_TYPE_MISMATCH = 0x7f0a0008;
public static final int VUFORIA_INIT_LICENSE_ERROR_UNKNOWN_ERROR = 0x7f0a0009;
public static final int app_name = 0x7f0a0032;
public static final int configGivingUpOnCommand = 0x7f0a0056;
public static final int configTypeAdafruitColorSensor = 0x7f0a0061;
public static final int configTypeAnalogInput = 0x7f0a0062;
public static final int configTypeAnalogOutput = 0x7f0a0063;
public static final int configTypeColorSensor = 0x7f0a0064;
public static final int configTypeContinuousRotationServo = 0x7f0a0065;
public static final int configTypeDeviceInterfaceModule = 0x7f0a0066;
public static final int configTypeDigitalDevice = 0x7f0a0067;
public static final int configTypeGyro = 0x7f0a0068;
public static final int configTypeI2cDevice = 0x7f0a0070;
public static final int configTypeI2cDeviceSynch = 0x7f0a0071;
public static final int configTypeIrSeekerV3 = 0x7f0a0072;
public static final int configTypeLED = 0x7f0a0073;
public static final int configTypeLegacyModuleController = 0x7f0a0074;
public static final int configTypeMatrixController = 0x7f0a007b;
public static final int configTypeMotor = 0x7f0a007c;
public static final int configTypeMotorController = 0x7f0a007d;
public static final int configTypeNothing = 0x7f0a0080;
public static final int configTypeOpticalDistanceSensor = 0x7f0a0081;
public static final int configTypePulseWidthDevice = 0x7f0a0082;
public static final int configTypeServo = 0x7f0a0083;
public static final int configTypeServoController = 0x7f0a0084;
public static final int configTypeUnknown = 0x7f0a0085;
public static final int controllerPortConnectionInfoFormat = 0x7f0a0090;
public static final int defaultOpModeName = 0x7f0a0098;
public static final int deviceDisplayNameUnknownUSBDevice = 0x7f0a009b;
public static final int errorOpModeStuck = 0x7f0a00b9;
public static final int incompatibleAppsError = 0x7f0a00d0;
public static final int moduleDisplayNameCDIM = 0x7f0a00fd;
public static final int moduleDisplayNameLegacyModule = 0x7f0a00fe;
public static final int moduleDisplayNameMotorController = 0x7f0a0100;
public static final int moduleDisplayNameServoController = 0x7f0a0101;
public static final int networkStatusActive = 0x7f0a010f;
public static final int networkStatusCreatedAPConnection = 0x7f0a0110;
public static final int networkStatusEnabled = 0x7f0a0111;
public static final int networkStatusError = 0x7f0a0112;
public static final int networkStatusInactive = 0x7f0a0114;
public static final int networkStatusInternalError = 0x7f0a0115;
public static final int networkStatusUnknown = 0x7f0a0116;
public static final int noSerialNumber = 0x7f0a0120;
public static final int nxtDcMotorControllerName = 0x7f0a0127;
public static final int nxtServoControllerName = 0x7f0a0128;
public static final int peerStatusConnected = 0x7f0a012d;
public static final int peerStatusDisconnected = 0x7f0a012e;
public static final int robotStateEmergencyStop = 0x7f0a018b;
public static final int robotStateInit = 0x7f0a018c;
public static final int robotStateInternalError = 0x7f0a018d;
public static final int robotStateNotStarted = 0x7f0a018e;
public static final int robotStateRunning = 0x7f0a018f;
public static final int robotStateStopped = 0x7f0a0190;
public static final int robotStateUnknown = 0x7f0a0191;
public static final int robotStatusInternalError = 0x7f0a0193;
public static final int robotStatusNetworkTimedOut = 0x7f0a0194;
public static final int robotStatusScanningUSB = 0x7f0a0195;
public static final int robotStatusStartingRobot = 0x7f0a0196;
public static final int robotStatusUnknown = 0x7f0a0198;
public static final int toastOpModeStuck = 0x7f0a01e1;
public static final int warningProblemCommunicatingWithUSBDevice = 0x7f0a01f7;
public static final int warningUnableToOpen = 0x7f0a01f9;
}
public static final class style {
public static final int AppBaseTheme = 0x7f070000;
public static final int AppTheme = 0x7f070001;
}
}
| 61.333333 | 95 | 0.741149 |
59cabeb26f0c7e9b6c745b3ece912af9b2173cb4 | 2,011 | package com.yourcompany.yourproject.security.user.register;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.u2ware.springfield.repository.EntityRepository;
import com.u2ware.springfield.service.EntityServiceImpl;
import com.yourcompany.yourproject.security.AuthenticationContext;
import com.yourcompany.yourproject.security.Authorities;
import com.yourcompany.yourproject.security.Users;
import com.yourcompany.yourproject.security.Users.Role;
@Service("userRegisterService")
public class UserRegisterService extends EntityServiceImpl<UserRegister, UserRegister>{
@Autowired
protected AuthenticationContext authenticationContext;
@Autowired @Qualifier("usersRepository")
private EntityRepository<Users, String> usersRepository;
@Autowired @Qualifier("authoritiesRepository")
private EntityRepository<Authorities, Integer> authoritiesRepository;
@Transactional
public UserRegister create(UserRegister entity) {
String username = entity.getUsername();
String salt = authenticationContext.getPasswordSalt();
String password = authenticationContext.getPassword(entity.getPassword1(), salt);
String description = entity.getDescription();
Role role = entity.getRole();
Users user = new Users();
user.setSalt(salt);
user.setUsername(username);
user.setPassword(password);
user.setDescription(description);
user.setRole(role.toString());
usersRepository.save(user);
for(GrantedAuthority authority : role.getAuthorities()){
authoritiesRepository.save(new Authorities(username, authority.getAuthority()));
}
logger.warn(user.toString());
logger.warn(user.toString());
logger.warn(user.toString());
logger.warn(user.toString());
authenticationContext.logoff();
return entity;
}
}
| 32.435484 | 87 | 0.80358 |
3f2ed1792ebe8317574670727ce5d9ae7cd5d822 | 1,175 | /**
* Classe <strong>Rationnel</strong>, implémente l'interface IRationnel
* @author Corentin MACHET
* @version 1.0
*/
public class Rationnel implements IRationnel, IAffiche
{
private int numerateur;
private int denominateur;
/**
*
*/
public Rationnel()
{
}
/**
*
*/
public Rationnel(int numerateur, int denominateur)
{
}
/**
*
*/
public Rationnel(Rationnel ref)
{
}
/**
*
*/
public int getNumerateur()
{
return numerateur;
}
/**
*
*/
public int getDenominateur()
{
return denominateur;
}
/**
*
*/
public void setNumerateur(int numerateur)
{
this.numerateur = numerateur;
}
/**
*
*/
public void setDenominateur(int denominateur)
{
this.denominateur = denominateur;
}
/**
*
*/
public void changerValeur(int numerateur, int denominateur)
{
this.numerateur = numerateur;
this.denominateur = denominateur;
}
/**
*
*/
public boolean egalA(Rationnel r)
{
}
/**
*
*/
public void ajouter(Rationnel r)
{
}
@Override
/**
*
*/
public String toString()
{
}
/**
*
*/
public void afficher()
{
System.out.println(this);
}
} | 10.779817 | 78 | 0.594043 |
08fdeba640a93cf094e1c469f34b3aa4133aef03 | 956 | package mj;
public class Lab10_ex30 {
public static void main(String[] args) {
// 문제 30.
// Multiplication Table
System.out.println("\t 1 \t 2 \t 3 \t 4 \t 5 \t 6 \t 7 \t 8 \t 9");
System.out.println("-------------------------------------------------");
int gugu1 = 0;
int gugu2 = 0;
int gugu3 = 0;
int gugu4 = 0;
int gugu5 = 0;
int gugu6 = 0;
int gugu7 = 0;
int gugu8 = 0;
int gugu9 = 0;
for (int i = 1, j = 1; i < 10; i++) {
gugu1 = i * j;
System.out.print(" \t" + gugu1);
}
for (int i = 1, j = 2; i < 10; i++) {
gugu2 = i * j;
System.out.print("\t" + gugu2);
}
for (int i = 1, j = 3; i < 10; i++) {
gugu3 = i * j;
System.out.print(gugu3);
}
for (int i = 1, j = 4; i < 10; i++) {
gugu4 = i * j;
System.out.print(gugu4);
}
for (int i = 1, j = 5; i < 10; i++) {
gugu5 = i * j;
System.out.print(gugu5);
}
}
}
| 17.381818 | 75 | 0.435146 |
554f1a21664c1305c5763f89138678b51ee186be | 9,560 | package com.gildedrose;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GildedRoseAssertJTest {
@Test
public void dexterity() {
Item[] items = new Item[] { new Item("+5 Dexterity Vest", 10, 20) };
Item[] itemsGolden = new Item[] { new Item("+5 Dexterity Vest", 10, 20) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(9);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(19);
}
@Test
public void conjured() {
Item[] items = new Item[] { new Item("Conjured Mana Cake", 10, 20) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertThat(items[0].sellIn).isEqualTo(9);
assertThat(items[0].quality).isEqualTo(18);
}
@Test
public void conjuredAfterSellin() {
Item[] items = new Item[] { new Item("Conjured Mana Cake", -1, 20) };
GildedRose app = new GildedRose(items);
app.updateQuality();
assertThat(items[0].sellIn).isEqualTo(-2);
assertThat(items[0].quality).isEqualTo(16);
}
@Test
public void dexterityAfterSelli() {
Item[] items = new Item[] { new Item("+5 Dexterity Vest", -1, 20) };
Item[] itemsGolden = new Item[] { new Item("+5 Dexterity Vest", -1, 20) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(-2);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(18);
}
@Test
public void agedBrieAges1Day() {
Item[] items = new Item[] { new Item("Aged Brie", 2, 0) };
Item[] itemsGolden = new Item[] { new Item("Aged Brie", 2, 0) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(1);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(1);
}
@Test
public void agedBrieAgesPastSellin() {
Item[] items = new Item[] { new Item("Aged Brie", 1, 0) };
Item[] itemsGolden = new Item[] { new Item("Aged Brie", 1, 0) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
app.updateQuality();
appGolden.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(-1);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(3);
}
@Test
public void agedBrieAgesPastSellinQualityShouldNeverBeMoreThan50() {
Item[] items = new Item[] { new Item("Aged Brie", -1, 50) };
Item[] itemsGolden = new Item[] { new Item("Aged Brie", -1, 50) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(-2);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(50);
}
@Test
public void sulfurasBeforeSellin() {
Item[] items = new Item[] { new Item("Sulfuras, Hand of Ragnaros", 0, 80) };
Item[] itemsGolden = new Item[] { new Item("Sulfuras, Hand of Ragnaros", 0, 80) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(0);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(80);
}
@Test
public void sulfurasAfterSellin() {
Item[] items = new Item[] { new Item("Sulfuras, Hand of Ragnaros", -1, 80) };
Item[] itemsGolden = new Item[] { new Item("Sulfuras, Hand of Ragnaros", -1, 80) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(-1);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(80);
}
@Test
public void backStagePasses() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(14);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(21);
}
@Test
public void backStagePasses11() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 11, 24) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 11, 24) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(10);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(25);
}
@Test
public void backStagePassesBellow11() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(9);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(50);
}
@Test
public void backStagePassesBellow11IncBy2() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 10, 47) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 10, 47) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(9);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(49);
}
@Test
public void backStagePassesBellow6() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 5, 45) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", 5, 45) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(4);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(48);
}
@Test
public void backStagePassesAfterConcert() {
Item[] items = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", -1, 45) };
Item[] itemsGolden = new Item[] { new Item("Backstage passes to a TAFKAL80ETC concert", -1, 45) };
GildedRose app = new GildedRose(items);
GildedRoseGolden appGolden = new GildedRoseGolden(itemsGolden);
app.updateQuality();
appGolden.updateQuality();
assertThat(items[0].sellIn).isEqualTo(itemsGolden[0].sellIn);
assertThat(items[0].sellIn).isEqualTo(-2);
assertThat(items[0].quality).isEqualTo(itemsGolden[0].quality);
assertThat(items[0].quality).isEqualTo(0) ;
}
}
| 39.341564 | 106 | 0.643096 |
ab06b7cd4abcdadfee9359dade98a9904a8a5f89 | 2,182 | package io.vertx.ext.discovery.types;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.discovery.Record;
import io.vertx.ext.discovery.Service;
import io.vertx.ext.discovery.spi.ServiceType;
import java.util.Objects;
/**
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class HttpEndpoint implements ServiceType {
public static final String TYPE = "http-endpoint";
@Override
public String name() {
return TYPE;
}
@Override
public Service get(Vertx vertx, Record record) {
return new HttpAPI(vertx, record);
}
public static Record createRecord(String name, String host, int port, String root, JsonObject metadata) {
Objects.requireNonNull(name);
Objects.requireNonNull(host);
Objects.requireNonNull(root);
Record record = new Record().setName(name)
.setType(TYPE)
.setLocation(new HttpLocation().setHost(host).setPort(port).setRoot(root).toJson());
if (metadata != null) {
record.setMetadata(metadata);
}
return record;
}
public static Record createRecord(String name, String host, int port, String root) {
return createRecord(name, host, port, root, null);
}
public static Record createRecord(String name, String host) {
return createRecord(name, host, 80, "/", null);
}
private class HttpAPI implements Service {
private final Vertx vertx;
private final HttpLocation location;
private HttpClient client;
public HttpAPI(Vertx vertx, Record record) {
this.vertx = vertx;
this.location = new HttpLocation(record.getLocation());
}
@Override
public synchronized <T> T get() {
if (client != null) {
return (T) client;
} else {
client = vertx.createHttpClient(
new HttpClientOptions().setDefaultPort(location.getPort())
.setDefaultHost(location.getHost()));
return (T) client;
}
}
@Override
public synchronized void release() {
client.close();
}
}
}
| 26.289157 | 107 | 0.681485 |
96045db2da1005472a47803cceeb5a97858285f8 | 1,218 | package ru.job4j.io;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Search {
private List<File> result = new ArrayList<>();
List<File> files(String parent, List<String> exts) {
File file = new File(parent);
File[] list = file.listFiles();
if (list != null && !file.isDirectory()) {
throw new IllegalArgumentException(
"Cannot list content of "
+ file.getPath()
+ ": Not a directory");
}
Queue<File> data = new LinkedList<>();
data.offer(file);
while (!data.isEmpty()) {
File elem = data.poll();
if (elem.isDirectory()) {
for (File fl : elem.listFiles()) {
for (String ext : exts) {
if (!fl.isDirectory()
&& ext == null || fl.getName().endsWith(ext)) {
result.add(fl);
}
}
data.offer(fl);
}
}
}
return result;
}
} | 29 | 79 | 0.450739 |
9ceb84536ba6181526bbbb6e210cd08319cbee7c | 1,356 | package com.polluxframework.maven.plugin.constant;
/**
* @author zhumin0508
* created in 2018/8/23 15:03
* modified By:
*/
public class Constants {
private Constants() {
}
/**
* 点
*/
public static final String STR_DOT = ".";
public static final char CHAR_DOT = '.';
/**
* 单左划线
*/
public static final String STR_SLASH = "/";
public static final char CHAR_SLASH = '/';
/**
* 空格
*/
public static final String STR_BLANK_SPACE = " ";
public static final char CHAR_BLANK_SPACE = ' ';
public static final String EMPTY_STR = "";
/**
* 回车 return
*/
public static final char CHAR_ENTER_SIGN = '\r';
/**
* 换行 newline
*/
public static final char CHAR_NEWLINE_SIGN = '\n';
/**
* 单右斜线
*/
public static final String STR_SLANT_LINE = "\\";
public static final char CHAR_SLANT_LINE = '\\';
/**
* 中括号(左)
*/
public final static String PARENTHESES_LEFT = "[";
public final static String STR_QUESTION_MARK = "?";
public final static String STR_AND_MARK = "&";
/**
* 问号的正则表达式
*/
public final static String STR_QUESTION_MARK_REGEX = "\\?";
/**
* 单引号
*/
public final static char CHAR_SINGLE_QUOTE_MARK = '\'';
/**
* 双引号
*/
public final static char CHAR_DOUBLE_QUOTE_MARK = '"';
public static final String HTTP_START_HEARD = "http://";
public static final String HTTPS_START_HEARD = "https://";
}
| 19.941176 | 60 | 0.651917 |
518f2c2a64b0531874f23962f52dcdc769b6a959 | 4,539 | package com.malin.volley.fragment;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.malin.volley.R;
import com.malin.volley.request.ChartStringRequest;
import com.malin.volley.utils.StringUtil;
import com.malin.volley.utils.VolleyUtil;
import com.orhanobut.logger.Logger;
/**
* Created by malin on 16-5-30.
*/
public class StringRequestGetUFT8Fragment extends Fragment {
private static final String TAG = StringRequestGetUFT8Fragment.class.getSimpleName();
private StringRequestGetUFT8Fragment mStringFragment;
private Bundle mBundle;
private String mType;
private RequestQueue mRequestQueue;
private static final String URL_JSON = "http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html?from=toutiao&size=20&passport=&devId=44t6%2B5mG3ACAOlQOCLuIHg%3D%3D&lat=&lon=&version=8.0&net=wifi&ts=1464663640&sign=c2mMvacbYvxLYEGlQOKGkT10e6%2FfbSzmjj%2B%2B6LQ%2BIIF48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=wandoujia_news&mac=h4YFZU1G3D7MIqgTTfUI9ahnYB%2BxK6YGLcdcZR%2BsrK8%3D";//查询北京天气信息
private TextView mTextView;
public StringRequestGetUFT8Fragment newFragemnt(Bundle bundle) {
mStringFragment = new StringRequestGetUFT8Fragment();
mStringFragment.setArguments(bundle);
return mStringFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.string_uft_8_layout, null);
initView(rootView);
return rootView;
}
private void initView(View view) {
mTextView = (TextView) view.findViewById(R.id.tv_utf_8_result);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = getArguments();
if (mBundle != null) {
mType = mBundle.getString("");
}
mRequestQueue = VolleyUtil.getRequestQueue(getActivity());
}
private void getDataUseVolleyGetUFT8() {
// 1. 创建一个RequestQueue对象。
// 2. 创建一个StringRequest对象。
// 3. 将StringRequest对象添加到RequestQueue里面。
/**
* 1.创建一个RequestQueue对象
*
* RequestQueue是一个请求队列对象,它可以缓存所有的HTTP请求,然后按照一定的算法并发地发出这些请求。
* RequestQueue内部的设计就是非常合适高并发的,因此我们不必为每一次HTTP请求都创建一个RequestQueue对象,
* 这是非常浪费资源的,基本上在每一个需要和网络交互的Activity中创建一个RequestQueue对象就足够了
*/
//RequestQueue mRequestQueue = Volley.newRequestQueue(mContext);
/**
* 2.创建一个StringRequest对象
*
* StringRequest的构造函数需要传入三个参数
*
* 第一个:目标服务器的URL地址,
* 第二个:服务器响应成功的回调,
* 第三个:服务器响应失败的回调。
*/
ChartStringRequest stringRequest = new ChartStringRequest(
URL_JSON,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
boolean isMainUi = Looper.getMainLooper()== Looper.myLooper();
Logger.d("isMainUi:" + isMainUi);
Logger.d("成功");
if (!TextUtils.isEmpty(response)){
Logger.json(response);
mTextView.setText(StringUtil.formatString(response));
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
boolean isMainUi = Looper.getMainLooper()== Looper.myLooper();
Logger.e("isMainUi:" + isMainUi);
Logger.e("失败");
Logger.e(error.getMessage(), error);
}
});
/**
* 3.将StringRequest对象添加到RequestQueue里面
* StringRequest对象添加到RequestQueue
*/
mRequestQueue.add(stringRequest);
}
@Override
public void onResume() {
super.onResume();
getDataUseVolleyGetUFT8();
}
@Override
public void onStop() {
super.onStop();
if (mRequestQueue!=null){
mRequestQueue.cancelAll(TAG);
}
}
}
| 33.375 | 401 | 0.632298 |
eb0ad92dd60c23fd06c727a0582404408b183c52 | 11,884 | package test.catan.mlp;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.deeplearning4j.eval.ActionGuessFeaturesEvaluation;
import org.deeplearning4j.eval.CatanEvaluation;
import org.deeplearning4j.eval.CatanPlotter;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.multilayer.CatanMlp;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import data.CatanDataSet;
import data.CatanDataSetIterator;
import data.Normaliser;
import data.PreloadedCatanDataSetIterator;
import model.CatanMlpConfig;
import util.CatanFeatureMaskingUtil;
import util.CrossValidationUtils;
import util.DataUtils;
import util.NNConfigParser;
public class CVMlpFullDataSetTest {
private static Logger log = LoggerFactory.getLogger(CVMlpFullDataSetTest.class);
private static final String METADATA_SEPARATOR = ":";
private static String PATH;
private static String DATA_TYPE;
private static NNConfigParser parser;
private static int nTasks = 6;
private static boolean NORMALISATION;
public static void main(String[] args) throws Exception {
parser = new NNConfigParser(null);
DATA_TYPE = parser.getDataType();
DATA_TYPE = DATA_TYPE + "CV";
PATH = parser.getDataPath();
NORMALISATION = parser.getNormalisation();
int FOLDS = 10; //standard 10 fold validation
//the features used are the same across the tasks so we just use the final ones, but we need to read them as they are present in all metadata files
int numInputs = 0;
int actInputSize = 0;
int[] trainMaxActions = new int[nTasks];//this is different for each task;
log.info("Load data for each task....");
File[] data = new File[nTasks];
for(int i= 0; i < nTasks; i++){
data[i] = new File(PATH + DATA_TYPE + "/alldata-" + i + ".txt");
//read metadata and feed in all the required info
Scanner scanner = new Scanner(new File(PATH + DATA_TYPE + "/alldata-" + i + "-metadata.txt"));
if(!scanner.hasNextLine()){
scanner.close();
throw new RuntimeException("Metadata not found; Cannot initialise network parameters");
}
numInputs = Integer.parseInt(scanner.nextLine().split(METADATA_SEPARATOR)[1]);
actInputSize = Integer.parseInt(scanner.nextLine().split(METADATA_SEPARATOR)[1]);
trainMaxActions[i] = Integer.parseInt(scanner.nextLine().split(METADATA_SEPARATOR)[1]);
scanner.close();
}
int nSamples = parser.getNumberOfSamples();
//Set specific params
int epochs = parser.getEpochs();
int miniBatchSize = parser.getMiniBatchSize();
double labelW = parser.getLabelWeight();
double metricW = parser.getMetricWeight();
double learningRate = parser.getLearningRate();
//debugging params (these can be set here)
int iterations = 1; //iterations over each batch
long seed = 123;
//data iterators
CatanDataSetIterator[] fullIter = new CatanDataSetIterator[nTasks];
for(int i= 0; i < nTasks; i++){
fullIter[i] = new CatanDataSetIterator(data[i],nSamples,miniBatchSize,numInputs+1,numInputs+actInputSize+1,true,parser.getMaskHiddenFeatures());
}
Normaliser norm = new Normaliser(PATH + DATA_TYPE,parser.getMaskHiddenFeatures());
if(NORMALISATION){
log.info("Check normalisation parameters for dataset ....");
norm.init(fullIter);
}
//if the input is masked/postprocessed update the input size for the model creation
if(parser.getMaskHiddenFeatures()) {
numInputs -= CatanFeatureMaskingUtil.droppedFeaturesCount;
actInputSize -= CatanFeatureMaskingUtil.droppedFeaturesCount;
}
log.info("Initialise cross-validation for each task....");
CrossValidationUtils[] cv = new CrossValidationUtils[nTasks];
for(int i= 0; i < nTasks; i++){
cv[i] = new CrossValidationUtils(fullIter[i], FOLDS, nSamples);
}
//NOTE: when training we iterate for each fold over each task, but we need to be able to pass the data for each task over each fold, hence this order
CatanPlotter[][] plotter = new CatanPlotter[nTasks][FOLDS];
double[] totalEvalAccuracy = new double[epochs];
Arrays.fill(totalEvalAccuracy, 0);
for(int k = 0; k < FOLDS; k++){
log.info("Starting fold " + k);
for(int i= 0; i < nTasks; i++){
cv[i].setCurrentFold(k);
}
// log.info("Load test data for each task....");
PreloadedCatanDataSetIterator[] trainIter = new PreloadedCatanDataSetIterator[nTasks];
PreloadedCatanDataSetIterator[] testIter = new PreloadedCatanDataSetIterator[nTasks];
CatanEvaluation[] eval = new CatanEvaluation[nTasks];
CatanEvaluation[] tEval = new CatanEvaluation[nTasks];
ActionGuessFeaturesEvaluation[] tagfe = new ActionGuessFeaturesEvaluation[nTasks];
ActionGuessFeaturesEvaluation[] agfe = new ActionGuessFeaturesEvaluation[nTasks];;
for(int i= 0; i < nTasks; i++){
trainIter[i] = cv[i].getTrainIterator();
testIter[i] = cv[i].getTestIterator();
plotter[i][k] = new CatanPlotter(i);
eval[i] = new CatanEvaluation(trainMaxActions[i]);
tEval[i] = new CatanEvaluation(trainMaxActions[i]);
}
// log.info("Build model....");
//remove the biases, since dl4j adds it's own and the iterator removes the bias from the data
CatanMlpConfig netConfig = new CatanMlpConfig(numInputs + actInputSize-2, 1, seed, iterations, WeightInit.XAVIER, Updater.RMSPROP, learningRate, LossFunction.MCXENT, OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT);
CatanMlp network = netConfig.init();
INDArray output;
// log.info("Train model....");
for( int i=0; i<epochs; i++ ) {
//fitting one batch from each task repeatedly until we cover all samples
while (trainIter[2].hasNext()) { //task 2 always has the most data
for(int j= 0; j < nTasks; j++){
if(!trainIter[j].hasNext())
continue;
if(j == 4 && parser.getMaskHiddenFeatures())//we can't train on discard task when the input is masked since there is no difference between the actions
continue;
CatanDataSet d = trainIter[j].next();
DataSet ds = DataUtils.turnToSAPairsDS(d,metricW,labelW);
if(NORMALISATION)
norm.normalizeZeroMeanUnitVariance(ds);
network.fit(ds,d.getSizeOfLegalActionSet());//set the labels we want to fit to
}
}
// log.info("*** Completed epoch {} ***", i);
// log.info("Evaluate model....");
double totalCorrect = 0;
double totalSamples = 0;
for(int j= 0; j < nTasks; j++){
if(j == 4 && parser.getMaskHiddenFeatures())//we can't evaluate on discard task when the input is masked since there is no difference between the actions
continue;
// log.info("Evaluate model on evaluation set for task " + j + "....");
eval[j] = new CatanEvaluation(trainMaxActions[j]);
agfe[j] = new ActionGuessFeaturesEvaluation(actInputSize-1);//get rid of the bias
while (testIter[j].hasNext()) {
CatanDataSet d = testIter[j].next();
DataSet ds = DataUtils.turnToSAPairsDS(d,metricW,labelW);
if(NORMALISATION)
norm.normalizeZeroMeanUnitVariance(ds);
output = network.output(ds, d.getSizeOfLegalActionSet());
eval[j].eval(DataUtils.computeLabels(d), output.transposei());
agfe[j].eval(d.getTargetAction(), d.getActionFeatures().getRow(Nd4j.getBlasWrapper().iamax(output)));
}
testIter[j].reset();
//once finished just output the result
// System.out.println(eval[j].stats());
//do the below across all tasks to average as in the standard approach
totalCorrect += eval[j].correct();
totalSamples += eval[j].getNumRowCounter();
// log.info("Evaluate model on training set for task " + j + "....");
tEval[j] = new CatanEvaluation(trainMaxActions[j]);
tagfe[j] = new ActionGuessFeaturesEvaluation(actInputSize-1);//get rid of the bias
trainIter[j].reset();
while (trainIter[j].hasNext()) {
CatanDataSet d = trainIter[j].next(1);
DataSet ds = DataUtils.turnToSAPairsDS(d,metricW,labelW);
if(NORMALISATION)
norm.normalizeZeroMeanUnitVariance(ds);
output = network.output(ds, d.getSizeOfLegalActionSet());
tEval[j].eval(DataUtils.computeLabels(d), output.transposei());
tagfe[j].eval(d.getTargetAction(), d.getActionFeatures().getRow(Nd4j.getBlasWrapper().iamax(output)));
}
trainIter[j].reset();
//once finished just output the result
// System.out.println(tEval[j].stats());
plotter[j][k].addData(eval[j].score(), tEval[j].score(), eval[j].accuracy(), tEval[j].accuracy());
plotter[j][k].addRanks(tEval[j].getRank(), eval[j].getRank());
plotter[j][k].addFeatureConfusion(agfe[j].getStats(), tagfe[j].getStats());
}
totalEvalAccuracy[i] += totalCorrect/totalSamples;
}
//write current results and move files so these won't be overwritten
for(int j= 0; j < nTasks; j++){
if(j == 4 && parser.getMaskHiddenFeatures())//there is nothing to write so we should avoid an exception
continue;
plotter[j][k].writeAll();
}
File dirFrom = new File(CatanPlotter.RESULTS_DIR);
File[] files = dirFrom.listFiles();
File dirTo = new File("" + k);
dirTo.mkdirs();
for(File f : files){
FileUtils.moveFileToDirectory(f, dirTo, false);
}
}
for(int i= 0; i < nTasks; i++){
if(i == 4 && parser.getMaskHiddenFeatures())
continue;
cv[i].writeResults(plotter[i], i);
}
//write the results for the total evaluation accuracy
for(int i= 0; i < totalEvalAccuracy.length; i++){
totalEvalAccuracy[i] /= FOLDS;
}
try {
File write = new File("TotalEvaluation.txt");
write.delete();
write.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(write,true));
StringBuilder sb = new StringBuilder();
for(Object value : totalEvalAccuracy) {
sb.append(String.format("%.10f", (Double) value));
sb.append(",");
}
String line = sb.toString();
line = line.substring(0, line.length()-1);
bos.write(line.getBytes());
bos.write(line.getBytes());
bos.flush();
bos.close();
} catch(IOException e){
throw new RuntimeException(e);
}
}
}
| 46.062016 | 226 | 0.620162 |
6a11b9141a6da7f1722d2c1d2809d5ca8e82ae8d | 12,173 | package com.smart.cloud.fire.mvp.electric;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.smart.cloud.fire.adapter.DateNumericAdapter;
import com.smart.cloud.fire.global.ConstantValues;
import com.smart.cloud.fire.utils.T;
import com.smart.cloud.fire.utils.TimePickerDialog;
import com.smart.cloud.fire.utils.VolleyHelper;
import com.smart.cloud.fire.view.OnWheelScrollListener;
import com.smart.cloud.fire.view.WheelView;
import com.smart.cloud.fire.view.XCDropDownListView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import butterknife.Bind;
import butterknife.ButterKnife;
import fire.cloud.smart.com.smartcloudfire.R;
public class AutoTimeSettingActivity extends Activity{
@Bind(R.id.ontime_edit)
TextView ontime_edit;
@Bind(R.id.add_fire_dev_btn)
RelativeLayout addFireDevBtn;//添加设备按钮。。
@Bind(R.id.mProgressBar)
ProgressBar mProgressBar;//加载进度。。
@Bind(R.id.swich)
CheckBox swich;
@Bind(R.id.swich_cycle)
Switch swich_cycle;
@Bind(R.id.week1)
CheckBox week1;
@Bind(R.id.week2)
CheckBox week2;
@Bind(R.id.week3)
CheckBox week3;
@Bind(R.id.week4)
CheckBox week4;
@Bind(R.id.week5)
CheckBox week5;
@Bind(R.id.week6)
CheckBox week6;
@Bind(R.id.week7)
CheckBox week7;
@Bind(R.id.cycle_line)
RelativeLayout cycle_line;
@Bind(R.id.timer_cycle_rg)
RadioGroup timer_cycle_rg;
@Bind(R.id.date_year)
WheelView dateYear;
@Bind(R.id.date_month)
WheelView dateMonth;
@Bind(R.id.date_day)
WheelView dateDay;
@Bind(R.id.date_hour)
WheelView dateHour;
@Bind(R.id.date_minute)
WheelView dateMinute;
@Bind(R.id.everyday_rb)
RadioButton everyday_rb;
@Bind(R.id.custom_rb)
RadioButton custom_rb;
private Context mContext;
int state=2;
String cycle="0";
private String mac;
private String devType;
private static final int DATE_DIALOG_ID = 1;
private static final int SHOW_DATAPICK = 0;
private int mYear;
private int mMonth;
private int mDay;
String getDate;
private boolean wheelScrolled = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_time_setting);
ButterKnife.bind(this);
mContext=this;
mac=getIntent().getStringExtra("mac");
devType=getIntent().getStringExtra("devType");
initView();
}
private void initView() {
initWheel();
timer_cycle_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==R.id.everyday_rb){
cycle_line.setVisibility(View.GONE);
}else{
cycle_line.setVisibility(View.VISIBLE);
}
}
});
swich.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
state=1;
} else {
state=2;
}
}
});
swich_cycle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
timer_cycle_rg.setVisibility(View.VISIBLE);
} else {
timer_cycle_rg.setVisibility(View.GONE);
}
}
});
addFireDevBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(state==1&&(ontime_edit.getText().length()==0)){
T.showShort(mContext,"请输入时间");
return;
}
if(!swich_cycle.isChecked()){
cycle="0";//single
}else if(everyday_rb.isChecked()){
cycle="8";//every day
}else{//custom
if(week1.isChecked()){
cycle+="1";
}
if(week2.isChecked()){
cycle+="2";
}
if(week3.isChecked()){
cycle+="3";
}
if(week4.isChecked()){
cycle+="4";
}
if(week5.isChecked()){
cycle+="5";
}
if(week6.isChecked()){
cycle+="6";
}
if(week7.isChecked()){
cycle+="7";
}
}
String url= null;
try {
url = ConstantValues.SERVER_IP_NEW+"addElectrTimer?mac="+mac
+"&state="+state
+"&time="+ URLEncoder.encode(ontime_edit.getText()+":00","GBK")
+"&cycle="+cycle+"&devType="+devType;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
int errorCode=response.getInt("errorCode");
if(errorCode==0){
T.showShort(mContext,"设置成功");
}else{
T.showShort(mContext,"设置失败");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
T.showShort(mContext,"网络错误");
}
});
mQueue.add(jsonObjectRequest);
}
});
}
private void initWheel() {
Calendar calendar = Calendar.getInstance();
int curYear = calendar.get(Calendar.YEAR) - 2010;
initWheelView(dateYear, new DateNumericAdapter(mContext, 2010, 2036), curYear);
int curMonth = calendar.get(Calendar.MONTH);
initWheelView(dateMonth, new DateNumericAdapter(mContext, 1, 12), curMonth);
int curDay = calendar.get(Calendar.DAY_OF_MONTH) - 1;
initWheelView(dateDay, new DateNumericAdapter(mContext, 1, 31), curDay);
int curHour = calendar.get(Calendar.HOUR_OF_DAY);
initWheelView(dateHour, new DateNumericAdapter(mContext, 0, 23), curHour);
int curMinute = calendar.get(Calendar.MINUTE);
initWheelView(dateMinute, new DateNumericAdapter(mContext, 0, 59), curMinute);
ontime_edit.setText(getStringOfday(calendar.getTime()));
}
public static String getStringOfday(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateString = formatter.format(date);
return dateString;
}
private void initWheelView(WheelView wv, DateNumericAdapter dateNumericAdapter, int type) {
wv.setViewAdapter(dateNumericAdapter);
wv.setCurrentItem(type);
wv.addScrollingListener(scrolledListener);
wv.setCyclic(true);
}
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
updateStatus();
updateSearchEdit();
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
updateStatus();
updateSearchEdit();
}
};
private void updateStatus() {
int year = dateYear.getCurrentItem() + 2010;
int month = dateMonth.getCurrentItem() + 1;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
|| month == 10 || month == 12) {
dateDay.setViewAdapter(new DateNumericAdapter(mContext, 1, 31));
} else if (month == 2) {
boolean isLeapYear = false;
if (year % 100 == 0) {
if (year % 400 == 0) {
isLeapYear = true;
} else {
isLeapYear = false;
}
} else {
if (year % 4 == 0) {
isLeapYear = true;
} else {
isLeapYear = false;
}
}
if (isLeapYear) {
if (dateDay.getCurrentItem() > 28) {
dateDay.scroll(30, 2000);
}
dateDay.setViewAdapter(new DateNumericAdapter(mContext, 1, 29));
} else {
if (dateDay.getCurrentItem() > 27) {
dateDay.scroll(30, 2000);
}
dateDay.setViewAdapter(new DateNumericAdapter(mContext, 1, 28));
}
} else {
if (dateDay.getCurrentItem() > 29) {
dateDay.scroll(30, 2000);
}
dateDay.setViewAdapter(new DateNumericAdapter(mContext, 1, 30));
}
}
public void updateSearchEdit() {
Timestamp now = new Timestamp(System.currentTimeMillis());
int year = dateYear.getCurrentItem() + 2010;
int month = dateMonth.getCurrentItem() + 1;
int day = dateDay.getCurrentItem() + 1;
int hour = dateHour.getCurrentItem();
int minute = dateMinute.getCurrentItem();
StringBuilder sb = new StringBuilder();
sb.append(year + "-");
if (month < 10) {
sb.append("0" + month + "-");
} else {
sb.append(month + "-");
}
if (day < 10) {
sb.append("0" + day + " ");
} else {
sb.append(day + " ");
}
if (hour < 10) {
sb.append("0" + hour + ":");
} else {
sb.append(hour + ":");
}
if (minute < 10) {
sb.append("0" + minute);
} else {
sb.append("" + minute);
}
ontime_edit.setText(sb.toString());
}
}
| 32.548128 | 95 | 0.545223 |
b79f7994183db1092f6557ea747739f52429885c | 6,528 | /**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.util.datastructure.array.sparse;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.IntBinaryOperator;
import gedi.app.Config;
import gedi.util.ArrayUtils;
import gedi.util.io.randomaccess.BinaryReader;
import gedi.util.io.randomaccess.BinaryWriter;
import gedi.util.io.randomaccess.serialization.BinarySerializable;
public class AutoSparseDenseIntArrayCollector implements BinarySerializable {
private static final double MARGIN = 2;
private int length;
private int[] indices;
private int[] values;
private int count;
private boolean aggregated = true;
private int[] dense;
public AutoSparseDenseIntArrayCollector() {}
public AutoSparseDenseIntArrayCollector(int expectedCapacity, int length) {
int initialCap = (int) (expectedCapacity*MARGIN);
this.length = length;
if (length*Integer.BYTES<initialCap*(Integer.BYTES+Integer.BYTES)) {
// start with dense!
dense = new int[length];
}
else {
indices = new int[initialCap];
values = new int[initialCap];
}
}
/**
* Iterates over all non-zero entries (ordered) and applies op. first is index, second is value
* @param op
*/
public void process(IntBinaryOperator op) {
if (dense!=null) {
for (int i=0; i<dense.length; i++)
if (dense[i]!=0)
dense[i] = op.applyAsInt(i, dense[i]);
}
else {
aggregate();
for (int i=0; i<count; i++)
values[i] = op.applyAsInt(indices[i], values[i]);
}
}
public int get(int index) {
if (dense!=null)
return dense[index];
aggregate();
int ind = Arrays.binarySearch(indices, 0,count,index);
if (ind<0) return 0;
return values[ind];
}
public int length() {
return length;
}
public void add(AutoSparseDenseIntArrayCollector o) {
if (this.dense!=null && o.dense!=null) {
for (int i=0; i<dense.length; i++)
this.dense[i]+=o.dense[i];
}
else if (this.dense!=null) {
for (int i=0; i<o.indices.length; i++)
this.dense[o.indices[i]]+=o.values[i];
}
else if (o.dense!=null) {
this.dense = o.dense.clone();
for (int i=0; i<indices.length; i++)
this.dense[indices[i]]+=values[i];
this.indices = null;
this.values = null;
}
else {
for (int i=0; i<o.indices.length; i++)
add(o.indices[i],o.values[i]);
}
}
public void add(int index, int value) {
if (index<0 || index>=length) throw new ArrayIndexOutOfBoundsException(index);
if (value==0) return;
if (dense!=null) {
dense[index]+=value;
}
else {
if (count==indices.length) {
aggregate();
if (count==indices.length) {
int newCapacity = indices.length + (indices.length >> 1) + 1;
if (length*Integer.BYTES<newCapacity*(Integer.BYTES+Integer.BYTES)) {
// switch to dense!
enforceDense();
dense[index]+=value;
}
else {
int[] nindices = new int[newCapacity];
int[] nvalues = new int[newCapacity];
System.arraycopy(indices, 0, nindices, 0, count);
System.arraycopy(values, 0, nvalues, 0, count);
this.indices = nindices;
this.values = nvalues;
if (count>0 && indices[count-1]>=index)
aggregated = false;
indices[count]=index;
values[count++]=value;
}
}
else {
if (count>0 && indices[count-1]>=index)
aggregated = false;
indices[count]=index;
values[count++]=value;
}
}
else {
if (count>0 && indices[count-1]>=index)
aggregated = false;
indices[count]=index;
values[count++]=value;
}
}
}
public int[] enforceDense() {
dense = getDense();
this.indices = null;
this.values = null;
return dense;
}
private int[] getDense() {
if (dense!=null) return dense;
int[] re = new int[length];
for (int i=0; i<indices.length; i++)
re[indices[i]]+=values[i];
return re;
}
private void aggregate() {
if (dense==null && !aggregated) {
ArrayUtils.parallelSort(indices, values, 0, count);
int index = 0;
for (int i=index+1; i<count; i++) {
if (indices[i]!=indices[index]) {
index++;
values[index]=values[i];
indices[index]=indices[i];
} else
values[index]+=values[i];
}
count = index+1;
aggregated = true;
}
}
@Override
public String toString() {
aggregate();
StringBuilder sb = new StringBuilder();
sb.append("[");
if (dense!=null) {
for (int i=0; i<dense.length; i++) {
if (i>0) sb.append(",");
sb.append(String.format(Config.getInstance().getRealFormat(),dense[i]));
}
}
else {
for (int i=0; i<count; i++) {
if (i>0) sb.append(",");
sb.append(indices[i]).append(":").append(String.format(Config.getInstance().getRealFormat(),values[i]));
}
}
sb.append("]");
return sb.toString();
}
@Override
public void serialize(BinaryWriter out) throws IOException {
aggregate();
out.putInt(dense==null?length:-length);
if (dense==null) {
out.putCInt(count);
for (int i=0; i<count; i++)
out.putCInt(indices[i]);
for (int i=0; i<count; i++)
out.putInt(values[i]);
}
else {
for (int i=0; i<dense.length; i++)
out.putInt(dense[i]);
}
}
@Override
public void deserialize(BinaryReader in) throws IOException {
dense = null;
this.length = in.getInt();
if (this.length<0) {
this.length = -this.length;
// dense mode
this.dense = new int[length];
for (int i=0; i<length; i++)
this.dense[i] = in.getInt();
}
else {
count = in.getCInt();
this.indices = new int[count];
this.values = new int[count];
for (int i=0; i<count; i++)
indices[i]=in.getCInt();
for (int i=0; i<count; i++)
values[i]=in.getInt();
}
}
public static AutoSparseDenseIntArrayCollector wrap(int... a) {
AutoSparseDenseIntArrayCollector re = new AutoSparseDenseIntArrayCollector(Math.max(50, a.length>>3),a.length);
for (int i=0; i<a.length; i++)
re.add(i, a[i]);
return re;
}
}
| 24.358209 | 113 | 0.631434 |
60066d84f8136cd80df517c8674c5a690e055daa | 380 | package com.DesignPatterns.CreationalPatterns.factoryMethod.sharp;
import com.DesignPatterns.CreationalPatterns.factoryMethod.matcha.Controller;
import com.DesignPatterns.CreationalPatterns.factoryMethod.matcha.ViewEngine;
public class SharpController extends Controller {
@Override
protected ViewEngine createViewEngine(){
return new SharpViewEngine();
}
}
| 31.666667 | 77 | 0.815789 |
7d53f22fa686f63faa1b9c82ef5c493270403bc7 | 1,725 | // Copyright 2008 Google Inc. All Rights Reserved.
package com.google.appengine.demos.helloorm;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Max Ross <[email protected]>
*/
public class UpdateFlight extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String key = req.getParameter("key");
String orig = req.getParameter("orig");
String dest = req.getParameter("dest");
if (key == null) {
resp.getWriter().println("No key provided.");
return;
}
if (orig == null) {
resp.getWriter().println("No origin provided.");
return;
}
if (dest == null) {
resp.getWriter().println("No destination provided.");
return;
}
if (PersistenceStandard.get() == PersistenceStandard.JPA) {
doPostJPA(Long.valueOf(key), orig, dest);
} else {
doPostJDO(Long.valueOf(key), orig, dest);
}
resp.sendRedirect("/");
}
private void doPostJDO(long key, String orig, String dest) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Flight f = pm.getObjectById(Flight.class, key);
f.setOrig(orig);
f.setDest(dest);
} finally {
pm.close();
}
}
private void doPostJPA(long key, String orig, String dest) {
EntityManager em = EMF.get().createEntityManager();
try {
Flight f = em.find(Flight.class, key);
f.setOrig(orig);
f.setDest(dest);
} finally {
em.close();
}
}
}
| 25.746269 | 91 | 0.654493 |
669ed499d941cd0e77b9626f4ba3fa6f41b2daa2 | 481 | package com.meowu.commons.mybatis.mysql.page;
import com.meowu.commons.utils.security.page.Page;
import com.meowu.commons.utils.security.page.PageRequest;
import java.util.List;
public class MySqlPage<T> extends Page{
public MySqlPage(List<T> content, Long total, PageRequest pageRequest){
super(content, total, pageRequest);
}
@Override
public boolean hasNext(){
return getPageRequest().getOffset() + getContent().size() < getTotal();
}
}
| 25.315789 | 79 | 0.715177 |
10e5e9870a8bbdcf9ac2421bb03ddc27c9604a85 | 1,080 | package com.trifork.hotruby.ast;
import java.util.ArrayList;
import java.util.List;
import com.trifork.hotruby.interp.CompileContext;
public class HashExpression extends Expression implements AssocHolder {
static class Assoc {
public Assoc(Expression key, Expression value) {
this.key = key;
this.value = value;
}
Expression key, value;
}
List<Assoc> values = new ArrayList<Assoc>();
public HashExpression() {
}
public HashExpression(Expression key, Expression value) {
this();
addAssoc(key, value);
}
public void addAssoc(Expression key, Expression value) {
values.add(new Assoc(key, value));
}
@Override
void compile(CompileContext ctx, boolean push) {
if (push) {
ctx.emit_new_hash(values.size());
}
for (Assoc a : values) {
if (push) {
// dup hash
ctx.emit_dup();
}
a.key.compile(ctx, push);
if (a.value == null) {
if (push) ctx.emit_push_nil();
} else {
a.value.compile(ctx, push);
}
if (push) {
ctx.emit_send("[]=", 2, false, false, false, null);
}
}
}
}
| 17.419355 | 71 | 0.642593 |
09c240021a45e2d317f55cfd0b575a735ba970c2 | 10,066 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.vfs;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.sftp.SftpClientFactory;
import org.apache.commons.vfs2.provider.sftp.SftpFileProvider;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystem;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class SftpFileSystemWindows extends SftpFileSystem {
private static final LogChannelInterface log = new LogChannel("SftpFileSystemWindows");
private static final String WHO_AMI_GROUPS_FO_LIST = "Whoami /GROUPS /FO LIST"; //windows command for getting croups for current user
private static final String WHO_AMI = "Whoami "; ////windows command for getting current user
private static final String ICACLS = "icacls "; //windows command for getting permissions for file
private static final String VER = "ver"; //windows command for getting version OS
private static final String GROUP_NAME = "Group Name:";
private static final String WINDOWS = "WINDOWS";
private static final String N_DELIMITER = "\\n";
private static final String RN_DELIMITER = "\r\n";
private static final String WINDOWS_PATH_DELIMITER = "/";
private Session session;
private List<String> userGroups;
private Boolean windows;
SftpFileSystemWindows(GenericFileName rootName, Session session, FileSystemOptions fileSystemOptions) {
super(rootName, session, fileSystemOptions);
this.session = session;
}
@Override
protected FileObject createFile(AbstractFileName name) throws FileSystemException {
return new SftpFileObjectWithWindowsSupport(name, this);
}
@Override
protected void doCloseCommunicationLink() {
if (this.session != null) {
this.session.disconnect();
this.session = null;
}
super.doCloseCommunicationLink();
}
@Override
public boolean isReleaseable() {
return !isOpen();
}
/**
* get user group on remote windows host
*
* @return list of groups + user person
* @throws JSchException
* @throws IOException
*/
List<String> getUserGroups() throws JSchException, IOException {
if (userGroups == null) {
StringBuilder output = new StringBuilder();
int code = this.executeCommand(WHO_AMI_GROUPS_FO_LIST, output);
if (code != 0) {
throw new JSchException("Could not get the groups of the current user (error code: " + code + ")");
}
this.userGroups = getUserGroups(output.toString());
userGroups.add(getUser());
}
return this.userGroups;
}
/**
* cut user groups from output whoami
*
* @param commandOutput output from whoami
* @return list of user groups
*/
private List<String> getUserGroups(String commandOutput) {
List<String> result = new ArrayList<>();
int startIndex = 0;
int endIndex;
while (true) {
startIndex = StringUtils.indexOfIgnoreCase(commandOutput, GROUP_NAME, startIndex);
if (startIndex < 0) {
return result;
}
startIndex += GROUP_NAME.length();
endIndex = StringUtils.indexOfIgnoreCase(commandOutput, RN_DELIMITER, startIndex);
if (endIndex < 0) {
return result;
}
result.add(commandOutput.substring(startIndex, endIndex).toUpperCase().trim());
}
}
/**
* Get current user on remote host
*
* @return name of user on remote host
* @throws JSchException
* @throws IOException
*/
String getUser() throws JSchException, IOException {
StringBuilder output = new StringBuilder();
int code = this.executeCommand(WHO_AMI, output);
if (code != 0) {
throw new JSchException("Could not get user name on remote host (error code: " + code + ")");
}
return output.toString().trim().toUpperCase();
}
/**
* @param path path to file or directory
* @return Map Windows Group - permissions
* @throws JSchException
* @throws IOException
*/
Map<String, String> getFilePermission(String path) throws JSchException, IOException {
String windowsAbsPath;
if (path.startsWith(WINDOWS_PATH_DELIMITER)) {
//cut first "/" windows does not have it
//it mean first letter is name of disk
path = path.substring(WINDOWS_PATH_DELIMITER.length());
windowsAbsPath = path.substring(0, 1) + ":" + path.substring(1);
} else {
windowsAbsPath = path;
}
Map<String, String> result = new HashMap<>();
StringBuilder output = new StringBuilder();
int code = this.executeCommand(ICACLS + windowsAbsPath, output);
if (code != 0) {
return result;
}
String outputString = output.toString();
int indexOf = outputString.indexOf(windowsAbsPath);
if (indexOf > -1) {
outputString = outputString.substring(indexOf + windowsAbsPath.length());
}
String[] strings = outputString.toUpperCase().split(N_DELIMITER);
for (String string : strings) {
int index = string.indexOf(":");
if (index > -1) {
result.put(string.substring(0, index).trim(), string.substring(index + 1).trim());
}
}
return result;
}
/**
* check is remote host is windows
*
* @return true if host windows
* @throws JSchException
* @throws IOException
*/
boolean isRemoteHostWindows() throws JSchException, IOException {
if (this.windows == null) {
StringBuilder output = new StringBuilder();
int code = this.executeCommand(VER, output);
this.windows = code == 0 && output.toString().toUpperCase().contains(WINDOWS);
}
return this.windows;
}
/**
* {@link org.apache.commons.vfs2.provider.sftp.SftpFileSystem#getChannel() }
*/
private void ensureSession() throws FileSystemException {
if (this.session == null || !this.session.isConnected()) {
this.doCloseCommunicationLink();
UserAuthenticationData authData = null;
Session session;
try {
GenericFileName e = (GenericFileName) this.getRootName();
authData = UserAuthenticatorUtils.authenticate(this.getFileSystemOptions(), SftpFileProvider.AUTHENTICATOR_TYPES);
session = SftpClientFactory.createConnection(e.getHostName(), e.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar(e.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar(e.getPassword())), this.getFileSystemOptions());
} catch (Exception var7) {
throw new FileSystemException("vfs.provider.sftp/connect.error", this.getRootName(), var7);
} finally {
UserAuthenticatorUtils.cleanup(authData);
}
this.session = session;
}
}
/**
* {@link org.apache.commons.vfs2.provider.sftp.SftpFileSystem#executeCommand(java.lang.String, java.lang.StringBuilder) }
*/
private int executeCommand(String command, StringBuilder output) throws JSchException, IOException {
this.ensureSession();
ChannelExec channel = (ChannelExec) this.session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
InputStreamReader stream = new InputStreamReader(channel.getInputStream());
channel.setErrStream(System.err, true);
channel.connect();
char[] buffer = new char[128];
int read;
while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
output.append(buffer, 0, read);
}
stream.close();
while (!channel.isClosed()) {
try {
Thread.sleep(100L);
} catch (Exception exc) {
log.logMinimal("Warning: Error session closing. " + exc.getMessage());
}
}
channel.disconnect();
return channel.getExitStatus();
}
}
| 37.559701 | 164 | 0.632625 |
010b46b5807418cac64dcfa767219d851fdacbe3 | 4,445 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.text;
import walkingkooka.Cast;
import java.io.IOException;
import java.io.Reader;
import java.util.Objects;
/**
* A {@link CharSequence} that reads its characters from a {@link Reader} when the last character in its current buffer
* is read. Because this is mutable the hashcode and equals methods arent really worth using.
*/
final class ReaderConsumingCharSequence implements CharSequence {
static ReaderConsumingCharSequence with(final Reader reader, final int bufferSize) {
Objects.requireNonNull(reader, "reader");
if (bufferSize <= 0) {
throw new IllegalArgumentException("Buffersize " + bufferSize + " must be greater than 0");
}
return new ReaderConsumingCharSequence(reader, bufferSize);
}
private final Reader reader;
private final StringBuilder content = new StringBuilder();
// @VisibleForTesting
boolean eof = false;
private final char[] buffer;
private ReaderConsumingCharSequence(final Reader reader, final int bufferSize) {
this.reader = reader;
this.buffer = new char[bufferSize];
}
@Override
public int length() {
this.maybeFillBuffer(1);
return this.content.length();
}
@Override
public char charAt(final int index) {
if (index < 0) {
throw new StringIndexOutOfBoundsException("Invalid index " + index);
}
this.maybeFillBuffer(index + 1);
this.checkIndex(index, "Index", 0);
return this.content.charAt(index);
}
@Override
public CharSequence subSequence(final int start, final int end) {
if (start < 0 || start > end) {
throw new StringIndexOutOfBoundsException("Start index " + start + " must be between 0 and " + end);
}
this.maybeFillBuffer(end + 1);
this.checkIndex(end, "End index", start);
return this.content.subSequence(start, end);
}
private void checkIndex(final int index, final String label, final int start) {
final int lengthAfterFill = this.content.length();
if (index > lengthAfterFill) {
throw new StringIndexOutOfBoundsException(label + " " + index + " must be between " + start + " and " + lengthAfterFill);
}
}
private void maybeFillBuffer(final int untilCharCount) {
if (!this.eof) {
this.fillBuffer(untilCharCount);
}
}
private void fillBuffer(final int untilCharCount) {
try {
final char[] buffer = this.buffer;
for (; ; ) {
if (untilCharCount < this.content.length()) {
break;
}
final int read = this.reader.read(buffer,
0,
buffer.length);
if (-1 == read) {
this.eof = true;
break;
}
if (0 == read) {
break;
}
this.content.append(buffer, 0, read);
}
} catch (final IOException cause) {
throw new ReaderConsumingCharSequenceTextException("Failed to fill char sequence, message: " + cause.getMessage(), cause);
}
}
@Override
public int hashCode() {
return CharSequences.hash(this.content);
}
@Override
public boolean equals(final Object other) {
return this == other ||
other instanceof ReaderConsumingCharSequence &&
this.equals0(Cast.to(other));
}
private boolean equals0(final ReaderConsumingCharSequence other) {
return CharSequences.equals(this.content, other.content);
}
@Override
public String toString() {
return this.content.toString();
}
}
| 31.083916 | 134 | 0.614398 |
14c9e116b4d6e6ad00742e5791d5a05e393f3959 | 2,272 | package com.ghx.hackaton.analytics.model.dto;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by achumakov on 7/20/2015.
*/
public class Alert {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
private String application;
private String URL;
private String message;
private Status status;
private String startDate;
private String endDate;
public Alert(String application, String URL, String message, Status status) {
this.application = application;
this.URL = URL;
this.message = message;
this.status = status;
}
public String getApplication() {
return application;
}
public String getURL() {
return URL;
}
public String getMessage() {
return message;
}
public Status getStatus() {
return status;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public void setStartEndDates(Date start, Date end) {
startDate = dateFormat.format(start);
endDate = dateFormat.format(end);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Alert alert = (Alert) o;
if (application != null ? !application.equals(alert.application) : alert.application != null) return false;
if (URL != null ? !URL.equals(alert.URL) : alert.URL != null) return false;
return !(message != null ? !message.equals(alert.message) : alert.message != null);
}
@Override
public int hashCode() {
int result = application != null ? application.hashCode() : 0;
result = 31 * result + (URL != null ? URL.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Alert{" +
"application='" + application + '\'' +
", URL='" + URL + '\'' +
", message='" + message + '\'' +
'}';
}
public enum Status {
warning, danger;
}
}
| 23.666667 | 115 | 0.580106 |
e109bf716f433b538d345c422a14f6419c2550e0 | 1,066 | package skaianet.die.instructions;
import skaianet.die.back.ExecutionContext;
import skaianet.die.back.LoopContext;
import skaianet.die.front.Color;
import java.io.PrintStream;
public class EnterLoopInstruction extends Instruction {
private final int object;
private Integer label = null;
public EnterLoopInstruction(Color thread, int object) {
super(thread);
this.object = object;
}
public void bind(int label) {
if (this.label != null) {
throw new IllegalStateException("Branch already bound!");
}
this.label = label;
}
@Override
public void printInternal(int indent, PrintStream out) {
out.println("ENTER " + object + " -> " + label);
}
@Override
public void execute(ExecutionContext executionContext) {
LoopContext localContext = executionContext.loopContext(executionContext.get(object));
executionContext.put(object, localContext);
if (!localContext.setupLoop()) {
executionContext.jump(label);
}
}
}
| 27.333333 | 94 | 0.666041 |
6c1286b66bc653e8a8654ce83d6b3b0c63d8a3d7 | 7,826 | package slimeknights.tconstruct.tools.client;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.Util;
import slimeknights.tconstruct.library.materials.IMaterialStats;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.tinkering.IMaterialItem;
import slimeknights.tconstruct.library.tools.ToolPart;
import slimeknights.tconstruct.library.traits.ITrait;
import slimeknights.tconstruct.tools.client.module.GuiButtonsPartCrafter;
import slimeknights.tconstruct.tools.client.module.GuiInfoPanel;
import slimeknights.tconstruct.tools.client.module.GuiSideInventory;
import slimeknights.tconstruct.tools.inventory.ContainerPartBuilder;
import slimeknights.tconstruct.tools.inventory.ContainerPatternChest;
import slimeknights.tconstruct.tools.inventory.ContainerTinkerStation;
import slimeknights.tconstruct.tools.tileentity.TilePartBuilder;
@SideOnly(Side.CLIENT)
public class GuiPartBuilder extends GuiTinkerStation {
private static final ResourceLocation BACKGROUND = Util.getResource("textures/gui/partbuilder.png");
public static final int Column_Count = 4;
protected GuiButtonsPartCrafter buttons;
protected GuiInfoPanel info;
protected GuiSideInventory sideInventory;
protected ContainerPatternChest.DynamicChestInventory chestContainer;
public GuiPartBuilder(InventoryPlayer playerInv, World world, BlockPos pos, TilePartBuilder tile) {
super(world, pos, (ContainerTinkerStation) tile.createContainer(playerInv, world, pos));
if(inventorySlots instanceof ContainerPartBuilder) {
ContainerPartBuilder container = (ContainerPartBuilder) inventorySlots;
// has part crafter buttons?
if(container.isPartCrafter()) {
buttons = new GuiButtonsPartCrafter(this, container, container.patternChest);
this.addModule(buttons);
}
else {
// has pattern chest inventory?
chestContainer = container.getSubContainer(ContainerPatternChest.DynamicChestInventory.class);
if(chestContainer != null) {
sideInventory = new GuiSideInventory(this, chestContainer, chestContainer.getSlotCount(), chestContainer.columns);
this.addModule(sideInventory);
}
}
info = new GuiInfoPanel(this, container);
info.ySize = this.ySize;
this.addModule(info);
}
}
@Override
public void drawSlot(Slot slotIn) {
if(inventorySlots instanceof ContainerPartBuilder) {
ContainerPartBuilder container = (ContainerPartBuilder) inventorySlots;
if(container.isPartCrafter() && slotIn.inventory == container.patternChest)
return;
}
super.drawSlot(slotIn);
}
@Override
public boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) {
if(inventorySlots instanceof ContainerPartBuilder) {
ContainerPartBuilder container = (ContainerPartBuilder) inventorySlots;
if(container.isPartCrafter() && slotIn.inventory == container.patternChest)
return false;
}
return super.isMouseOverSlot(slotIn, mouseX, mouseY);
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
drawBackground(BACKGROUND);
if(sideInventory != null) {
sideInventory.updateSlotCount(chestContainer.getSizeInventory());
}
// draw slot icons
drawIconEmpty(container.getSlot(1), ICON_Shard);
drawIconEmpty(container.getSlot(2), ICON_Pattern);
drawIconEmpty(container.getSlot(3), ICON_Ingot);
drawIconEmpty(container.getSlot(4), ICON_Block);
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
}
@Override
public void updateDisplay() {
// check if we have an output
ItemStack output = container.getSlot(0).getStack();
if(output != null) {
if(output.getItem() instanceof ToolPart) {
ToolPart toolPart = (ToolPart) output.getItem();
Material material = toolPart.getMaterial(output);
// Material for the toolpart does not make sense, can't build anything out of it!
if(!toolPart.canUseMaterial(material)) {
String materialName = material.getLocalizedNameColored() + TextFormatting.WHITE;
String error = I18n
.translateToLocalFormatted("gui.error.useless_tool_part", materialName, (new ItemStack(toolPart)).getDisplayName());
warning(error);
}
// Material is OK, display material properties
else {
setDisplayForMaterial(material);
}
}
}
// no output, check input
else {
// is our input a material item?
Material material = getMaterial(container.getSlot(3).getStack(), container.getSlot(4).getStack());
if(material != null) {
setDisplayForMaterial(material);
}
// no, display general usage information
else {
info.setCaption(container.getInventoryDisplayName());
info.setText(I18n.translateToLocal("gui.partbuilder.info"));
}
}
}
@Override
public void error(String message) {
info.setCaption(I18n.translateToLocal("gui.error"));
info.setText(message);
}
@Override
public void warning(String message) {
info.setCaption(I18n.translateToLocal("gui.warning"));
info.setText(message);
}
public void updateButtons() {
if(buttons != null) {
// this needs to be done threadsafe, since the buttons may be getting rendered currently
Minecraft.getMinecraft().addScheduledTask(new Runnable() {
@Override
public void run() {
buttons.updatePosition(cornerX, cornerY, realWidth, realHeight);
}
});
}
}
protected void setDisplayForMaterial(Material material) {
info.setCaption(material.getLocalizedNameColored());
List<String> stats = Lists.newLinkedList();
List<String> tips = Lists.newArrayList();
for(IMaterialStats stat : material.getAllStats()) {
stats.add(TextFormatting.UNDERLINE + stat.getLocalizedName());
stats.addAll(stat.getLocalizedInfo());
stats.add(null);
tips.add(null);
tips.addAll(stat.getLocalizedDesc());
tips.add(null);
}
// Traits
for(ITrait trait : material.getAllTraits()) {
if(!trait.isHidden()) {
stats.add(material.getTextColor() + trait.getLocalizedName());
tips.add(material.getTextColor() + trait.getLocalizedDesc());
}
}
if(!stats.isEmpty() && stats.get(stats.size()-1) == null) {
// last empty line
stats.remove(stats.size()-1);
tips.remove(tips.size()-1);
}
info.setText(stats, tips);
}
protected Material getMaterial(ItemStack... stacks) {
for(ItemStack stack : stacks) {
if(stack == null || stack.getItem() == null) {
continue;
}
// material-item?
if(stack.getItem() instanceof IMaterialItem) {
return ((IMaterialItem) stack.getItem()).getMaterial(stack);
}
}
// regular item, check if it belongs to a material
for(Material material : TinkerRegistry.getAllMaterials()) {
if(material.matches(stacks) != null) {
return material;
}
}
// no material found
return null;
}
private Material getMaterialItem(ItemStack stack) {
return null;
}
}
| 34.324561 | 130 | 0.713519 |
d5cb63ac63e36d3680190a3822a2b5a51f1ea867 | 2,226 | package com.akshaykale.appimagepicker;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import com.akshaykale.imagepicker.ImagePickerFragment;
import com.akshaykale.imagepicker.ImagePickerListener;
import com.akshaykale.imagepicker.PhotoObject;
import com.bumptech.glide.Glide;
public class MainActivity extends AppCompatActivity implements ImagePickerListener, View.OnClickListener {
private ImagePickerFragment imagePickerFragment;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageview);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.fab){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
imagePickerFragment = new ImagePickerFragment();//.newInstance(mStackLevel);
imagePickerFragment.addOnClickListener(this);
//imagePickerFragment.setImageLoadEngine(new ILoad());
imagePickerFragment.show(ft, "dialog");
}
}
@Override
public void onPhotoClicked(PhotoObject photoObject) {
Glide.with(getApplicationContext()).clear(imageView);
Glide.with(getApplicationContext())
.load(photoObject.getPath())
.into(imageView);
imagePickerFragment.dismiss();
}
@Override
public void onCameraClicked(Bitmap image) {
imageView.setImageBitmap(image);
imagePickerFragment.dismiss();
}
}
| 33.727273 | 106 | 0.728212 |
b5bd47cb9e2f0294342afb983c079afadbc4605f | 2,493 | package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.Population;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.nwu.bioinformatics.commons.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
/**
* @author Rhett Sutphin
*/
@Transactional(readOnly = true)
public class PopulationDao extends StudyCalendarMutableDomainObjectDao<Population> implements DeletableDomainObjectDao<Population> {
@Override
public Class<Population> domainClass() {
return Population.class;
}
/**
* Finds the population based on study and the population abbreviation
*
* @param study the study which you want to search for the population
* @param abbreviation the abbreviation for the population
* @return the population that corresponds to the study and the abbreviation that was passed in
*/
@SuppressWarnings({"unchecked"})
public Population getByAbbreviation(Study study, String abbreviation) {
return (Population) CollectionUtils.firstElement(getHibernateTemplate().find(
"from Population p where p.abbreviation = ? and p.study = ?",
new Object[]{abbreviation, study}));
}
/**
* Collects and returns all the abbreviations for populations in the given study
*
* @param study the study to return the populations from
* @return populations retrieved from the given study
*/
@SuppressWarnings({"unchecked"})
public Set<String> getAbbreviations(Study study) {
return new HashSet<String>(getHibernateTemplate().find(
"select p.abbreviation from Population p where p.study = ?", study));
}
/**
* Find all the populations for a study
*
* @param study the study to return the populations from
* @return a list of all populations retrieved from the given study
*/
@SuppressWarnings({ "unchecked" })
public List<Population> getAllFor(Study study) {
return getHibernateTemplate().find(
"from Population p where p.study = ?", study);
}
@Transactional(readOnly = false)
public void delete(final Population population) {
getHibernateTemplate().delete(population);
}
public void deleteAll(List<Population> t) {
getHibernateTemplate().delete(t);
}
}
| 36.130435 | 132 | 0.701966 |
b6fd1f3710726bf3707af96ade2df9dc2221b6b9 | 2,229 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.amazonaws.mturk.model;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
/**
*
* @author Jeremy Custenborder
*/
public class QuestionFormTest extends BaseTest {
@Before
public void setup(){
SerializationHelper.FORMAT_OUTPUT = true;
}
@Test
public void validateQuestionForm_xml() throws SAXException, IOException {
InputStream input = getClass().getResourceAsStream("QuestionForm.xml");
QuestionForm.validate(input);
}
@Test
public void foo() throws IOException {
QuestionForm form = new QuestionForm();
form.overview.add(new TitleContent("Game 01523, \"X\" to play"));
form.overview.add(new TextContent("You are helping to decide the next move in a game of Tic-Tac-Toe. The board looks like this:"));
BinaryContent binaryContent = new BinaryContent();
binaryContent.mimeType = new MimeType("image", "gif");
binaryContent.dataURL = "http://tictactoe.amazon.com/game/01523/board.gif";
binaryContent.altText = "The game board, with \"X\" to move.";
form.overview.add(binaryContent);
form.overview.add(new TextContent("Player \"X\" has the next move."));
QuestionForm.save(form, System.out);
}
@Test
public void questionForm_xml() throws IOException {
InputStream input = getClass().getResourceAsStream("QuestionForm.xml");
QuestionForm questionForm = QuestionForm.load(input);
Assert.assertNotNull("questionForm should not be null", questionForm);
Assert.assertNotNull("questionForm.overView should not be null", questionForm.overview);
Assert.assertEquals(questionForm.overview.get(0).getClass(), TitleContent.class);
QuestionForm.save(questionForm, System.out);
// Assert.assertEquals("questionForm.overview.text does not match", "You are helping to decide the next move in a game of Tic-Tac-Toe. The board looks like this:", questionForm.overview.text);
}
}
| 34.292308 | 196 | 0.720951 |
f06c9a9c3d308b3b6987f35f41e678cf1bf64dc1 | 3,436 | package com.boliangshenghe.outteam.activemq;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.boliangshenghe.outteam.entity.Catalogcopy;
import com.boliangshenghe.outteam.entity.Company;
import com.boliangshenghe.outteam.service.CatalogcopyService;
import com.boliangshenghe.outteam.service.CompanyService;
import com.boliangshenghe.outteam.util.CommonUtils;
import com.boliangshenghe.outteam.util.HttpClientUtil;
import com.boliangshenghe.outteam.util.JsonUtils;
@Component
public class TopicReceiver implements MessageListener {
@Autowired
private CatalogcopyService catalogcopyService;
@Autowired
private CompanyService companyService;
public void onMessage(Message message) {
try {
System.out.println("maven ---TopicReceiver1接收到消息:"
+ ((TextMessage) message).getText());
String mes = ((TextMessage) message).getText();
if(mes.indexOf("cataId")!=-1){
Catalogcopy catalogcopy = JsonUtils.toBean(mes, Catalogcopy.class);//result对象
List<Catalogcopy> list = catalogcopyService.selectCatalogcopyList(catalogcopy);
if(null != list && list.size()>0){
}else{
Map<String,String> map = new HashMap<String,String>();
map.put("key", CommonUtils.GAODEKEY);
map.put("location",catalogcopy.getLon()+","+catalogcopy.getLat());
map.put("radius","1000");
map.put("extensions","all");
map.put("batch","false");
map.put("roadlevel","0");
String retu = HttpClientUtil.doGet("http://restapi.amap.com/v3/geocode/regeo",map);
String province = retu.substring(retu.indexOf("province")+11, retu.indexOf("city")-3);
if(!province.trim().equals("")){
String pro = province.substring(0, 2);
Company record = new Company();
record.setProvince(pro);
List<Company> companyList = companyService.selectCompanyList(record);
if(null!=companyList && companyList.size()>0){
Company company = companyList.get(0);
catalogcopy.setProvince(company.getProvince());
catalogcopy.setCid(company.getId());
catalogcopy.setArea(getArea(company.getProvince()));
System.out.println(company.getProvince()+" zhen省份");
catalogcopy.setIsouttem("2");//默认不出队
try {
catalogcopyService.insertSelective(catalogcopy);
} catch (Exception c) {
// TODO: handle exception
c.printStackTrace();
}
}
}
}
}
/*Earthquake earthquake = new Earthquake();
earthquake.setCreatetime(new Date());
earthquake.setCreator("管理员");
earthquake.setState("2");//1演练 2 eqim触发
//earthquake.setProvince(company.getProvince());
earthquakeService.insertSelective(earthquake);*/
} catch (JMSException e) {
e.printStackTrace();
}
}
/**
* 根据省份判断 华北地区
* @param provice
* @return
*/
public String getArea(String provice){
if(provice.equals("北京")||provice.equals("天津")
||provice.equals("山西")||provice.equals("河北")
||provice.equals("内蒙古")||provice.equals("山东")
||provice.equals("河南")){
return "华北";
}else{
return "非华北";
}
}
} | 32.11215 | 92 | 0.672002 |
615ae18f4a40213bc0c9bbdbf543c037a9a6e9b5 | 910 | package com.gakshintala.bookmybook.restexchange.patron.request;
import com.gakshintala.bookmybook.domain.catalogue.CatalogueBookInstanceId;
import com.gakshintala.bookmybook.domain.patron.HoldDuration;
import com.gakshintala.bookmybook.domain.patron.PatronId;
import com.gakshintala.bookmybook.usecases.patron.PatronPlaceBookOnHold.PlaceOnHoldCommand;
import lombok.Value;
import javax.validation.constraints.NotBlank;
import java.time.Instant;
@Value
public class PlaceBookOnHoldRequest {
@NotBlank
String patronId;
@NotBlank
String catalogueBookInstanceId;
Integer noOfDays;
public PlaceOnHoldCommand toCommand() {
return new PlaceOnHoldCommand(
Instant.now(),
PatronId.fromString(patronId),
CatalogueBookInstanceId.fromString(catalogueBookInstanceId),
HoldDuration.forNoOfDays(noOfDays)
);
}
}
| 30.333333 | 91 | 0.751648 |
7039c359b221c55dd7eac0528c66cebd5bf67291 | 9,952 | package com.alibaba.maxgraph.proto;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.0.0)",
comments = "Source: am.proto")
public class AppMasterApiGrpc {
private AppMasterApiGrpc() {}
public static final String SERVICE_NAME = "AppMasterApi";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.alibaba.maxgraph.proto.RestartWorkerRequest,
com.alibaba.maxgraph.proto.Response> METHOD_RESTART_WORKER =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"AppMasterApi", "restartWorker"),
io.grpc.protobuf.ProtoUtils.marshaller(com.alibaba.maxgraph.proto.RestartWorkerRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.alibaba.maxgraph.proto.Response.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.alibaba.maxgraph.proto.KillWorkerRequest,
com.alibaba.maxgraph.proto.Response> METHOD_KILL_WORKER =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"AppMasterApi", "killWorker"),
io.grpc.protobuf.ProtoUtils.marshaller(com.alibaba.maxgraph.proto.KillWorkerRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.alibaba.maxgraph.proto.Response.getDefaultInstance()));
/**
* Creates a new async stub that supports all call types for the service
*/
public static AppMasterApiStub newStub(io.grpc.Channel channel) {
return new AppMasterApiStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static AppMasterApiBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new AppMasterApiBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary and streaming output calls on the service
*/
public static AppMasterApiFutureStub newFutureStub(
io.grpc.Channel channel) {
return new AppMasterApiFutureStub(channel);
}
/**
*/
public static abstract class AppMasterApiImplBase implements io.grpc.BindableService {
/**
*/
public void restartWorker(com.alibaba.maxgraph.proto.RestartWorkerRequest request,
io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_RESTART_WORKER, responseObserver);
}
/**
*/
public void killWorker(com.alibaba.maxgraph.proto.KillWorkerRequest request,
io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_KILL_WORKER, responseObserver);
}
@java.lang.Override public io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
METHOD_RESTART_WORKER,
asyncUnaryCall(
new MethodHandlers<
com.alibaba.maxgraph.proto.RestartWorkerRequest,
com.alibaba.maxgraph.proto.Response>(
this, METHODID_RESTART_WORKER)))
.addMethod(
METHOD_KILL_WORKER,
asyncUnaryCall(
new MethodHandlers<
com.alibaba.maxgraph.proto.KillWorkerRequest,
com.alibaba.maxgraph.proto.Response>(
this, METHODID_KILL_WORKER)))
.build();
}
}
/**
*/
public static final class AppMasterApiStub extends io.grpc.stub.AbstractStub<AppMasterApiStub> {
private AppMasterApiStub(io.grpc.Channel channel) {
super(channel);
}
private AppMasterApiStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected AppMasterApiStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new AppMasterApiStub(channel, callOptions);
}
/**
*/
public void restartWorker(com.alibaba.maxgraph.proto.RestartWorkerRequest request,
io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_RESTART_WORKER, getCallOptions()), request, responseObserver);
}
/**
*/
public void killWorker(com.alibaba.maxgraph.proto.KillWorkerRequest request,
io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_KILL_WORKER, getCallOptions()), request, responseObserver);
}
}
/**
*/
public static final class AppMasterApiBlockingStub extends io.grpc.stub.AbstractStub<AppMasterApiBlockingStub> {
private AppMasterApiBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private AppMasterApiBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected AppMasterApiBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new AppMasterApiBlockingStub(channel, callOptions);
}
/**
*/
public com.alibaba.maxgraph.proto.Response restartWorker(com.alibaba.maxgraph.proto.RestartWorkerRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_RESTART_WORKER, getCallOptions(), request);
}
/**
*/
public com.alibaba.maxgraph.proto.Response killWorker(com.alibaba.maxgraph.proto.KillWorkerRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_KILL_WORKER, getCallOptions(), request);
}
}
/**
*/
public static final class AppMasterApiFutureStub extends io.grpc.stub.AbstractStub<AppMasterApiFutureStub> {
private AppMasterApiFutureStub(io.grpc.Channel channel) {
super(channel);
}
private AppMasterApiFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected AppMasterApiFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new AppMasterApiFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.alibaba.maxgraph.proto.Response> restartWorker(
com.alibaba.maxgraph.proto.RestartWorkerRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_RESTART_WORKER, getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.alibaba.maxgraph.proto.Response> killWorker(
com.alibaba.maxgraph.proto.KillWorkerRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_KILL_WORKER, getCallOptions()), request);
}
}
private static final int METHODID_RESTART_WORKER = 0;
private static final int METHODID_KILL_WORKER = 1;
private static class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AppMasterApiImplBase serviceImpl;
private final int methodId;
public MethodHandlers(AppMasterApiImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_RESTART_WORKER:
serviceImpl.restartWorker((com.alibaba.maxgraph.proto.RestartWorkerRequest) request,
(io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response>) responseObserver);
break;
case METHODID_KILL_WORKER:
serviceImpl.killWorker((com.alibaba.maxgraph.proto.KillWorkerRequest) request,
(io.grpc.stub.StreamObserver<com.alibaba.maxgraph.proto.Response>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
return new io.grpc.ServiceDescriptor(SERVICE_NAME,
METHOD_RESTART_WORKER,
METHOD_KILL_WORKER);
}
}
| 37.69697 | 119 | 0.720961 |
0999fb34e73dff1a286b456d967a85b17fabcdb9 | 619 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.eivanov.centralserver.thesis.web.controllers;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author killer
*/
public class ServerNotificationGroupControllerTest {
public ServerNotificationGroupControllerTest() {
}
/**
* Test of getNotificationList method, of class ServerNotificationGroupController.
*/
@Test
public void testGetNotificationList() {
}
}
| 22.107143 | 86 | 0.714055 |
2569d53937e1ad3938e8c0217fcaa07f280c0b0b | 4,344 | /*
* Copyright 2015 Google, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.examples.abelanav2.grpc;
import com.google.gson.JsonObject;
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall;
import io.grpc.ForwardingServerCallListener;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import net.oauth.jsontoken.JsonToken;
import java.util.logging.Logger;
/**
* A interceptor to handle server header.
*/
public class AuthHeaderServerInterceptor implements ServerInterceptor {
/**
* The Authorization custom header field that contains the user auth token.
*/
private static Metadata.Key<String> customHeadKey =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
/**
* The user ID when authenticated. This variable is shared betzeen the class
* {@link MyThreadLocalApplyingListener} and the overriden interceptCall
* method.
*/
private String authUserId = "";
/**
* Logger.
*/
private static Logger LOGGER = Logger.getLogger(AuthHeaderServerInterceptor.class.getName());
@Override
public final <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final String method,
final ServerCall<RespT> call, final Metadata.Headers requestHeaders,
final ServerCallHandler<ReqT, RespT> next) {
authUserId = requestHeaders.get(customHeadKey);
String userId;
try {
JsonToken token = AuthUtils.deserialize(authUserId);
JsonObject payload = token.getPayloadAsJsonObject();
JsonObject user = payload.get("user").getAsJsonObject();
userId = user.get("user_id").getAsString();
} catch (Exception e) {
userId = "";
}
LOGGER.info("Request received from userID=" + userId);
return new MyThreadLocalApplyingListener<>(
next.startCall(method, new SimpleForwardingServerCall<RespT>(call) {
private boolean sentHeaders = false;
@Override
public void sendHeaders(final Metadata.Headers
responseHeaders) {
AuthToken.set(authUserId);
responseHeaders.put(customHeadKey, "customRespondValue");
super.sendHeaders(responseHeaders);
sentHeaders = true;
}
@Override
public void sendPayload(final RespT payload) {
if (!sentHeaders) {
sendHeaders(new Metadata.Headers());
}
super.sendPayload(payload);
}
@Override
public void close(final Status status,
final Metadata.Trailers trailers) {
super.close(status, trailers);
}
}, requestHeaders));
}
/**
* Class that will set the User ID variable as global for the current thread
* before the server creates the response, and then unsets it.
*/
public class MyThreadLocalApplyingListener<ReqT> extends ForwardingServerCallListener<ReqT> {
/**
* The ServerCall.Listener to delegate most of the operations to.
*/
private final ServerCall.Listener<ReqT> delegate;
/**
*
* @param delegate the ServerCall.Listener to delegate operations to.
*/
protected MyThreadLocalApplyingListener(final ServerCall.Listener<ReqT> delegate) {
this.delegate = delegate;
}
@Override
protected final ServerCall.Listener<ReqT> delegate() {
return delegate;
}
@Override
public final void onPayload(final ReqT payload) {
AuthToken.set(authUserId);
super.onPayload(payload);
AuthToken.remove();
}
@Override
public final void onHalfClose() {
AuthToken.set(authUserId);
super.onHalfClose();
AuthToken.remove();
}
}
}
| 30.591549 | 95 | 0.679788 |
ee82becfd1734f86b3896ade0cbed8a1ba719145 | 5,782 | /*
* Copyright 2009 Inspire-Software.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yes.cart.shoppingcart.impl;
import org.junit.Test;
import org.yes.cart.BaseCoreDBTestCase;
import org.yes.cart.constants.AttributeNamesKeys;
import org.yes.cart.constants.ServiceSpringKeys;
import org.yes.cart.domain.entity.Customer;
import org.yes.cart.domain.entity.Shop;
import org.yes.cart.service.domain.ShopService;
import org.yes.cart.shoppingcart.*;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* User: Igor Azarny [email protected]
* Date: 09-May-2011
* Time: 14:12:54
*/
public class LoginCommandImplTest extends BaseCoreDBTestCase {
@Test
public void testExecute() {
ShopService shopService = (ShopService) ctx().getBean(ServiceSpringKeys.SHOP_SERVICE);
Shop shop10 = shopService.getById(10L);
Shop shop20 = shopService.getById(20L);
final Customer customer = createCustomer();
MutableShoppingCart shoppingCart = new ShoppingCartImpl();
shoppingCart.initialise(ctx().getBean("amountCalculationStrategy", AmountCalculationStrategy.class));
final ShoppingCartCommandFactory commands = ctx().getBean("shoppingCartCommandFactory", ShoppingCartCommandFactory.class);
Map<String, String> params = new HashMap<>();
shoppingCart.getShoppingContext().setShopCode(shop20.getCode());
shoppingCart.getShoppingContext().setShopId(shop20.getShopId());
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
params.put(ShoppingCartCommand.CMD_LOGIN_P_LOGIN, customer.getLogin());
params.put(ShoppingCartCommand.CMD_LOGIN_P_PASS, "rawpassword");
params.put(ShoppingCartCommand.CMD_LOGIN, "1");
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
shoppingCart.getShoppingContext().setShopCode(shop10.getCode());
shoppingCart.getShoppingContext().setShopId(shop10.getShopId());
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.LOGGED_IN, shoppingCart.getLogonState());
assertNull(shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_REF));
assertNull(shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_CHARGE_ID));
assertNull(shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_EMPLOYEE_ID));
assertEquals("false", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_APPROVE_ORDER));
assertEquals("false", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_BLOCK_CHECKOUT));
}
@Test
public void testExecuteB2B() {
ShopService shopService = (ShopService) ctx().getBean(ServiceSpringKeys.SHOP_SERVICE);
Shop shop10 = shopService.getById(10L);
Shop shop20 = shopService.getById(20L);
final Customer customer = createCustomerB2B();
MutableShoppingCart shoppingCart = new ShoppingCartImpl();
shoppingCart.initialise(ctx().getBean("amountCalculationStrategy", AmountCalculationStrategy.class));
final ShoppingCartCommandFactory commands = ctx().getBean("shoppingCartCommandFactory", ShoppingCartCommandFactory.class);
Map<String, String> params = new HashMap<>();
shoppingCart.getShoppingContext().setShopCode(shop20.getCode());
shoppingCart.getShoppingContext().setShopId(shop20.getShopId());
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
params.put(ShoppingCartCommand.CMD_LOGIN_P_LOGIN, customer.getLogin());
params.put(ShoppingCartCommand.CMD_LOGIN_P_PASS, "rawpassword");
params.put(ShoppingCartCommand.CMD_LOGIN, "1");
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.NOT_LOGGED, shoppingCart.getLogonState());
shoppingCart.getShoppingContext().setShopCode(shop10.getCode());
shoppingCart.getShoppingContext().setShopId(shop10.getShopId());
commands.execute(shoppingCart, (Map) params);
assertEquals(ShoppingCart.LOGGED_IN, shoppingCart.getLogonState());
assertEquals("REF-001", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_REF));
assertEquals("CHARGE-001", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_CHARGE_ID));
assertEquals("EMP-001", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_B2B_EMPLOYEE_ID));
assertEquals("true", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_APPROVE_ORDER));
assertEquals("false", shoppingCart.getOrderInfo().getDetailByKey(AttributeNamesKeys.Cart.ORDER_INFO_BLOCK_CHECKOUT));
}
}
| 48.588235 | 130 | 0.748703 |
404578d631c317539c2bb5554032f2ce5bdc4230 | 21,739 | package cn.aradin.spring.core.utils;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
/**
* Date Transfer Module
* @author liudaac
*
*/
public class DateUtil {
// 格式:年-月-日 小时:分钟:秒
public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
// 格式:年-月-日 小时:分钟
public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";
// 格式:年月日 小时分钟秒
public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";
public static final String FORMAT_FOUR = "yyyyMMddHHmmss";
public static final String FORMAT_FIVE = "yyyy.MM.dd HH:mm:ss";
public static final String FORMAT_SIX = "yyyy-MM-dd HH:mm:ss.SSS";
// 格式:年-月-日
public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";
public static final String LONG_DATE_FORMAT_1 = "yyyy/MM/dd";
public static final String LONG_DATE_FORMAT_2 = "yyyy.MM.dd";
// 格式:年(2位).月.日
public static final String LONG_DATE_FORMAT_3 = "yy.MM.dd";
// 格式:月-日
public static final String SHORT_DATE_FORMAT = "MM-dd";
// 格式:小时:分钟:秒
public static final String SHORT = "HH:mm:ss";
// 格式:小时:分钟
public static final String LONG_TIME_FORMAT = "HH:mm";
// 格式:年-月
public static final String MONTG_DATE_FORMAT = "yyyy-MM";
// 格式:年月日
public static final String SIMPLE_DATE_FORMAT = "yyyyMMdd";
// 年的加减
public static final int SUB_YEAR = Calendar.YEAR;
// 月加减
public static final int SUB_MONTH = Calendar.MONTH;
// 天的加减
public static final int SUB_DAY = Calendar.DATE;
// 小时的加减
public static final int SUB_HOUR = Calendar.HOUR;
// 分钟的加减
public static final int SUB_MINUTE = Calendar.MINUTE;
// 秒的加减
public static final int SUB_SECOND = Calendar.SECOND;
public DateUtil() {
}
//把符合日期格式的字符串转换为日期类型
public static java.util.Date stringtoDate(String dateStr, String format) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr);
} catch (Exception e) {
// log.error(e);
d = null;
}
return d;
}
//把符合日期格式的字符串转换为日期类型
public static java.util.Date stringtoDate(String dateStr, String format, ParsePosition pos) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr, pos);
} catch (Exception e) {
// log.error(e);
d = null;
}
return d;
}
//两个date数据比较大小
public static int isSameDate(Date date1, Date date2) {
int date1num = Integer.valueOf(dateToString(date1, SIMPLE_DATE_FORMAT));
int date2num = Integer.valueOf(dateToString(date2, SIMPLE_DATE_FORMAT));
if (date1num == date2num) {
return 0;
} else if (date1num > date2num) {
return 1;
} else {
return -1;
}
}
//将日期格式为为字符串,格式为 yyyy-MM-dd。如果出错,返回空串。
public static String dateToStringLong(java.util.Date date) {
return dateToString(date, LONG_DATE_FORMAT);
}
//把日期转换为字符串
public static String dateToString(java.util.Date date, String format) {
if (date == null) {
return null;
}
String result = "";
if (StringUtils.isBlank(format)) {
format = FORMAT_ONE;
}
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
result = formater.format(date);
} catch (Exception e) {
// log.error(e);
}
return result;
}
//获取两个日期中段的日期
public static List<String> getMidpieceDates(String startDate, String endDate, String format) {
List<String> list = new ArrayList<String>();
while (!startDate.equals(endDate)) {
list.add(startDate);
startDate = DateUtil.dateToString(DateUtil.nextDay(DateUtil.stringtoDate(startDate, format), 1), format);
}
return list;
}
//获取当前时间的指定格式
public static String getCurrDate(String format) {
return dateToString(new Date(), format);
}
/**
* 获取距离当天指定天数(月、年。。。)的日期
*
* @param field
* Calendar类的指定日历字段(例如Calendar.DATE, Calendar.MONTH)
* @param amount
* 数量,正数为未来,负数为过去
* @return 如果field不是Calendar类的指定日历字段,返回null
*/
public static Date dateSub(int field, int amount) {
try {
Calendar cal = Calendar.getInstance();
cal.add(field, amount);
return cal.getTime();
} catch (Exception e) {
return null;
}
}
public static String dateSub(int dateKind, String dateStr, int amount) {
Date date = stringtoDate(dateStr, FORMAT_ONE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(dateKind, amount);
return dateToString(calendar.getTime(), FORMAT_ONE);
}
//两个日期相减
public static long timeSub(String firstTime, String secTime) {
long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
long second = stringtoDate(secTime, FORMAT_ONE).getTime();
return (second - first) / 1000;
}
//获得某月的天数
public static int getDaysOfMonth(String year, String month) {
int days = 0;
if (month.equals("1") || month.equals("3") || month.equals("5") || month.equals("7") || month.equals("8")
|| month.equals("10") || month.equals("12")) {
days = 31;
} else if (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11")) {
days = 30;
} else {
if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
|| Integer.parseInt(year) % 400 == 0) {
days = 29;
} else {
days = 28;
}
}
return days;
}
//获取某年某月的天数
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
//获得当前日期
public static int getToday() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
}
//获得当前月份
public static int getToMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
//获得当前年份
public static int getToYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
//返回日期的天
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
//返回该日期为一周中的哪一天(周日为1,周一为2,依此类推)
public static int getDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
//返回该日期为当月第几天
public static int getDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
//返回该日期为当年第几天
public static int getDayOfYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_YEAR);
}
//返回当月最后一天
public static Date getLastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 0);
return calendar.getTime();
}
//返回日期的年
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
//返回日期的月份,1-12
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
//计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000;
}
//计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
public static long dayDiff(String date1, String date2, String format) {
return DateUtil.dayDiff(DateUtil.stringtoDate(date1, format), DateUtil.stringtoDate(date2, format));
}
public static long secondDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime());
}
public static long secondDiff(String date1, String date2, String format) {
return DateUtil.secondDiff(DateUtil.stringtoDate(date1, format), DateUtil.stringtoDate(date2, format));
}
//比较两个日期的年差
public static int yearDiff(String before, String after) {
Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(afterDay) - getYear(beforeDay);
}
//比较指定日期与当前日期的差
public static int yearDiffCurr(String after) {
Date beforeDay = new Date();
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(beforeDay) - getYear(afterDay);
}
/**
* 获取指定日期距离当天的天数。如果指定日期在未来,则返回负数。
*
* @param dateStr
* 指定日期,格式为"yyyy-MM-dd"
* @return 天数。如果dateStr格式错误,返回0
*/
public static long dayDiffCurr(String dateStr) {
// Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
Date currDate = new Date();
Date date = stringtoDate(dateStr, LONG_DATE_FORMAT);
return date == null ? 0 : (currDate.getTime() - date.getTime()) / 86400000;
}
public static int getFirstWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, 1);
return c.get(Calendar.DAY_OF_WEEK);
}
public static int getLastWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, getDaysOfMonth(year, month));
return c.get(Calendar.DAY_OF_WEEK);
}
//获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss"
public static String getNow() {
Calendar today = Calendar.getInstance();
return dateToString(today.getTime(), FORMAT_ONE);
}
//根据生日获取星座
public static String getAstro(String birth) {
if (!isDate(birth)) {
birth = "2000" + birth;
}
if (!isDate(birth)) {
return "";
}
int month = Integer.parseInt(birth.substring(birth.indexOf("-") + 1, birth.lastIndexOf("-")));
int day = Integer.parseInt(birth.substring(birth.lastIndexOf("-") + 1));
// logger.debug(month + "-" + day);
String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
int[] arr = { 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22 };
int start = month * 2 - (day < arr[month - 1] ? 2 : 0);
return s.substring(start, start + 2) + "座";
}
//判断日期是否有效,包括闰年的情况
public static boolean isDate(String date) {
StringBuffer reg = new StringBuffer("^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
Pattern p = Pattern.compile(reg.toString());
return p.matcher(date).matches();
}
/**
* 取得指定日期过 months 月后的日期 (当 months 为负数表示指定月之前);
*
* @param date
* 日期 为null时表示当天
* @param months
* 相加(相减)的月数
* @return The date
*/
public static Date nextMonth(Date date, int months) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.MONTH, months);
return cal.getTime();
}
/**
* 取得指定日期过 day 天后的日期 (当 day 为负数表示指定天之前);
*
* @param date
* 日期 为null时表示当天
* @param day
* 相加(相减)的天数
* @return The date
*/
public static Date nextDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.DAY_OF_YEAR, day);
return cal.getTime();
}
//取得指定日期过 day 周后的日期 (当 day 为负数表示指定月之前)
public static Date nextWeek(Date date, int week) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.WEEK_OF_MONTH, week);
return cal.getTime();
}
//获取当前的日期,格式为"yyyy-MM-dd"
public static String currDay() {
return DateUtil.dateToString(new Date(), DateUtil.LONG_DATE_FORMAT);
}
//获取当前的时间,格式为HH:mm
public static String currTime() {
return DateUtil.dateToString(new Date(), DateUtil.LONG_TIME_FORMAT);
}
//获取昨天的日期,格式为"yyyy-MM-dd"
public static String befoDay() {
return befoDay(DateUtil.LONG_DATE_FORMAT);
}
public static String befoDay(String format) {
return DateUtil.dateToString(DateUtil.nextDay(new Date(), -1), format);
}
//获取明天的日期
public static String afterDay() {
return DateUtil.dateToString(DateUtil.nextDay(new Date(), 1), DateUtil.LONG_DATE_FORMAT);
}
//取得当前时间距离1900/1/1的天数
public static int getDayNum() {
int daynum = 0;
GregorianCalendar gd = new GregorianCalendar();
Date dt = gd.getTime();
GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
Date dt1 = gd1.getTime();
daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
return daynum;
}
//getDayNum的逆方法(用于处理Excel取出的日期格式数据等)
public static Date getDateByNum(int day) {
GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
Date date = gd.getTime();
date = nextDay(date, day);
return date;
}
//针对yyyy-MM-dd HH:mm:ss格式,显示yyyymmdd
public static String getYmdDateCN(String datestr) {
if (datestr == null)
return "";
if (datestr.length() < 10)
return "";
StringBuffer buf = new StringBuffer();
buf.append(datestr.substring(0, 4)).append(datestr.substring(5, 7)).append(datestr.substring(8, 10));
return buf.toString();
}
//根据days天数计算出从****日到昨日为days天的日期组
public static Map<String, String> getTimeslice(int days) {
Map<String, String> map = new HashMap<String, String>();
String beforeday = DateUtil.dateToString(DateUtil.nextDay(new Date(), -(days + 1)), DateUtil.LONG_DATE_FORMAT);
String afterday = DateUtil.befoDay();
map.put("beforeday", beforeday);
map.put("afterday", afterday);
return map;
}
/**
* 获取最近datenum天的开始日期和结束日期,结束日期从前一天开始。
*
* @param datenum
* 最近天数,必须大于0
* @return 长度为2的数组,第一个元素为开始日期,第二个元素为结束日期,格式都为"yyyy-MM-dd"。datenum出错时返回null。
*/
public static String[] getDateRange(int datenum) {
if (datenum < 1) {
return null;
}
String startDate = DateUtil.dateToString(DateUtil.dateSub(Calendar.DATE, -datenum), DateUtil.LONG_DATE_FORMAT);
String endDate = DateUtil.befoDay();
return new String[] { startDate, endDate };
}
//获取近n天的日期数组
public static String[] getDates(int datenum, String format) {
if (StringUtils.isBlank(format)) {
format = DateUtil.LONG_DATE_FORMAT;
}
String[] dayrange = DateUtil.getDateRange(datenum - 1);
String startday = dayrange[0];
String[] xdata = new String[datenum];
for (int i = 0; i < datenum; i++) {
xdata[i] = String.valueOf(DateUtil.getDay(DateUtil.nextDay(DateUtil.stringtoDate(startday, format), i)));
}
return xdata;
}
/**
* 根据周期截取有效的时间段。
*
* @param period
* 时间周期。可选值为:day(日),week(周),month(月),season(季度)
* @param startDate
* 开始日期
* @param endDate
* 结束日期
* @return 长度为2的数组,分别为开始日期和结束日期,格式为"yyyy-MM-dd"。<br>
* 如果period参数错误,或者指定时间段不满一个周期,返回null。
*/
public static String[] getDateRangeByPeriod(String period, String startDate, String endDate) {
Date start = stringtoDate(startDate, LONG_DATE_FORMAT);
Date end = stringtoDate(endDate, LONG_DATE_FORMAT);
// 验证参数
if (start == null || end == null || !("day".equals(period) || "week".equals(period) || "month".equals(period)
|| "season".equals(period))) {
return null;
}
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
startCal.setTime(start);
endCal.setTime(end);
if ("day".equals(period)) {
return new String[] { startDate, endDate };
} else if ("week".equals(period)) {
startCal.add(Calendar.DATE, (9 - startCal.get(Calendar.DAY_OF_WEEK)) % 7); // 开始日期设置为下周一(如果当天已经是周一,则不变)
endCal.add(Calendar.DATE, 1 - endCal.get(Calendar.DAY_OF_WEEK)); // 结束日期设置为上周日(如果当天已经是周日,则不变)
} else if ("month".equals(period)) {
// 开始日期设置为下个月第一天(如果当天已经是当月第一天,则不变)
if (!(startCal.get(Calendar.DATE) == 1)) {
startCal.add(Calendar.MONTH, 1);
startCal.set(Calendar.DATE, 1);
}
// 结束日期设置为上个月最后一天(如果当天已经是当月最后一天,则不变)
endCal.add(Calendar.DATE, 1);
endCal.set(Calendar.DATE, 0);
} else if ("season".equals(period)) {
// 设置开始日期为下季度第一天(如果当天已经是当季度第一天,则不变)
if (!(startCal.get(Calendar.DATE) == 1 && startCal.get(Calendar.MONTH) % 3 == 0)) {
startCal.set(Calendar.DATE, 1);
startCal.add(Calendar.MONTH, 3 - startCal.get(Calendar.MONTH) % 3);
}
// 结束日期设置为上季度最后一天(如果当天已经是当季度最后一天,则不变)
endCal.add(Calendar.DATE, 1);
endCal.set(Calendar.DATE, 1);
endCal.add(Calendar.MONTH, -endCal.get(Calendar.MONTH) % 3);
endCal.add(Calendar.DATE, -1);
}
if (startCal.compareTo(endCal) > 0) { // 如果开始时间迟于结束时间,表示不满一个周期,返回null
return null;
}
return new String[] { dateToString(startCal.getTime(), LONG_DATE_FORMAT),
dateToString(endCal.getTime(), LONG_DATE_FORMAT) };
}
public static Date nextMinute(Date date, int min) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.MINUTE, min);
return cal.getTime();
}
//毫秒数转时间
public static String getDateByMillis(long millis, String format) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return (dateToString(calendar.getTime(), format));
}
//获取指定日期所在月份的第一天
public static Date getFirstDayOfMonth(Date date) {
String dateStr = dateToString(date, LONG_DATE_FORMAT) + " 00:00:00";
Date day = stringtoDate(dateStr, FORMAT_ONE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(day);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
//获取某天最小的时间
public static Date getDayMin(Date date) {
String dateStr = dateToString(date, LONG_DATE_FORMAT) + " 00:00:00";
Date day = stringtoDate(dateStr, FORMAT_ONE);
return day;
}
//获取某天的最大时间
public static Date getDayMax(Date date) {
String dateStr = dateToString(date, LONG_DATE_FORMAT) + " 23:59:59";
Date day = stringtoDate(dateStr, FORMAT_ONE);
return day;
}
public static Date getYesterday() {
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth - 1);
return calendar.getTime();
}
//获取近n天的日期数组
public static String[] getRecentDates(int datenum, String format) {
if (StringUtils.isBlank(format)) {
format = DateUtil.LONG_DATE_FORMAT;
}
String[] dayrange = DateUtil.getDateRange(datenum - 1);
String startday = dayrange[0];
String[] xdata = new String[datenum];
for (int i = 0; i < datenum; i++) {
Date date = DateUtil.stringtoDate(startday, LONG_DATE_FORMAT);
Date nextdate = DateUtil.nextDay(date, i);
xdata[i] = dateToString(nextdate, format);
}
return xdata;
}
//获取指定日期所在年的最后一天
public static Date getLastDateOfYear(Date date) {
Date dayMax = getDayMax(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dayMax);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
public static long getMillisByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTimeInMillis();
}
public static int getHour(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
public static int getMiniute(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
public static Date getFirstDateOfLastMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int lastmonth = calendar.get(Calendar.MONTH) - 1;
calendar.set(Calendar.MONTH, lastmonth);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
public static long getDaysApart(Date date1, Date date2) {
String date1String = dateToString(date1, LONG_DATE_FORMAT);
String date2String = dateToString(date2, LONG_DATE_FORMAT);
Date fstDate = stringtoDate(date1String, LONG_DATE_FORMAT);
Date sndDate = stringtoDate(date2String, LONG_DATE_FORMAT);
return (sndDate.getTime() - fstDate.getTime()) / 86400000;
}
//获取近n个月的值
public static String[] getRecentMonths(int monthnum, String format) {
if (StringUtils.isBlank(format)) {
format = DateUtil.LONG_DATE_FORMAT;
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -(monthnum + 1));
String[] months = new String[monthnum];
for(int i = 0; i < monthnum; i++) {
calendar.add(Calendar.MONTH, 1);
Date month = calendar.getTime();
months[i] = DateUtil.dateToString(month, format);
}
return months;
}
}
| 30.193056 | 114 | 0.667602 |
396fff1ab4735cb9406425ada1969e0c3ee0beb9 | 1,373 | package com.yt.mdm.controller;
import com.yt.mdm.mybatis.entity.User;
import com.yt.mdm.service.TestService;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.util.Properties;
@RestController
public class ComputeController {
private static final Logger logger = LoggerFactory.getLogger(ComputeController.class);
@Autowired
private TestService testService;
@RequestMapping(value = "/test" ,method = RequestMethod.GET)
public String test(int id) {
logger.info("test invoke......");
String mm = testService.getMyDate();
User user = testService.getUserById(id);
StringBuilder sb = new StringBuilder();
sb.append("hello world");
sb.append("<br>");
sb.append("<br>");
sb.append("<br>");
sb.append("(form DB)userName="+user.getName());
sb.append("<br>");
sb.append("(form DB)age="+user.getAge());
return sb.toString();
}
@RequestMapping(value = "/get" ,method = RequestMethod.GET)
public String get(int id) {
return "good job";
}
}
| 29.212766 | 88 | 0.723962 |
657d7fb30bcbc5fe484356bea63687a53a711423 | 2,004 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.yahoo.search.test.QueryTestCase;
import org.junit.Test;
import com.yahoo.search.Query;
/**
* Unit test for the helper methods placed in
* com.yahoo.prelude.query.ItemHelper.
*
* @author <a href="mailto:[email protected]">Steinar Knutsen</a>
*/
public class ItemHelperTestCase {
@Test
public final void testGetNumTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c"));
assertEquals(3, helper.getNumTerms(q.getModel().getQueryTree().getRoot()));
}
@Test
public final void testGetPositiveTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c \"d e\" -f"));
List<IndexedItem> l = new ArrayList<>();
System.out.println(q.getModel());
helper.getPositiveTerms(q.getModel().getQueryTree().getRoot(), l);
assertEquals(4, l.size());
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = false;
for (IndexedItem i : l) {
if (i instanceof PhraseItem) {
d = true;
} else if (i.getIndexedString().equals("a")) {
a = true;
} else if (i.getIndexedString().equals("b")) {
b = true;
} else if (i.getIndexedString().equals("c")) {
c = true;
}
}
assertFalse("An item is missing.", (a & b & c & d) == false);
}
private String enc(String s) {
try {
return URLEncoder.encode(s, "utf-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| 29.470588 | 104 | 0.585828 |
c236874d262ce98ff162e699fdaad419831d0b5e | 1,000 | package com.simibubi.create.lib.mixin.common;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.simibubi.create.lib.extensions.EntityCollisionContextExtensions;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.shapes.EntityCollisionContext;
@Mixin(EntityCollisionContext.class)
public abstract class EntityCollisionContextMixin implements EntityCollisionContextExtensions {
@Unique
private Entity create$cachedEntity;
@Inject(at = @At("TAIL"), method = "<init>(Lnet/minecraft/world/entity/Entity;)V")
private void create$onTailEntityInit(Entity entity, CallbackInfo ci) {
create$cachedEntity = entity;
}
@Override
@Nullable
public Entity create$getCachedEntity() {
return create$cachedEntity;
}
}
| 32.258065 | 95 | 0.817 |
27301660f6fcaf2e14ce8f137b53172d9e37af9d | 7,257 | package org.kuali.ole.ncip.service.impl;
import org.apache.log4j.Logger;
import org.extensiblecatalog.ncip.v2.service.*;
import org.kuali.ole.OLEConstants;
import org.kuali.ole.deliver.processor.LoanProcessor;
import org.kuali.ole.ncip.bo.OLENCIPConstants;
import org.kuali.ole.ncip.bo.OLERenewItem;
import org.kuali.ole.ncip.converter.OLERenewItemConverter;
import org.kuali.ole.ncip.service.OLECirculationService;
import org.kuali.ole.ncip.service.OLERenewItemService;
import org.kuali.ole.sys.context.SpringContext;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: maheswarang
* Date: 2/19/14
* Time: 4:00 PM
* To change this template use File | Settings | File Templates.
*/
public class OLERenewItemServiceImpl implements OLERenewItemService {
private static final Logger LOG = Logger.getLogger(OLERequestItemServiceImpl.class);
private OLECirculationService oleCirculationService;
private OLECirculationHelperServiceImpl oleCirculationHelperService;
private OLERenewItemConverter oleRenewItemConverter = new OLERenewItemConverter();
private LoanProcessor loanProcessor;
public LoanProcessor getLoanProcessor() {
if (loanProcessor == null) {
loanProcessor = SpringContext.getBean(LoanProcessor.class);
}
return loanProcessor;
}
public OLECirculationService getOleCirculationService() {
if (null == oleCirculationService) {
oleCirculationService = GlobalResourceLoader.getService(OLENCIPConstants.CIRCULATION_SERVICE);
}
return oleCirculationService;
}
public void setOleCirculationService(OLECirculationService oleCirculationService) {
this.oleCirculationService = oleCirculationService;
}
public OLECirculationHelperServiceImpl getOleCirculationHelperService() {
if (null == oleCirculationHelperService) {
oleCirculationHelperService = GlobalResourceLoader.getService(OLENCIPConstants.CIRCULATION_HELPER_SERVICE);
}
return oleCirculationHelperService;
}
public void setOleCirculationHelperService(OLECirculationHelperServiceImpl oleCirculationHelperService) {
this.oleCirculationHelperService = oleCirculationHelperService;
}
public OLERenewItemConverter getOleRenewItemConverter() {
return oleRenewItemConverter;
}
public void setOleRenewItemConverter(OLERenewItemConverter oleRenewItemConverter) {
this.oleRenewItemConverter = oleRenewItemConverter;
}
@Override
public RenewItemResponseData performService(RenewItemInitiationData renewItemInitiationData, ServiceContext serviceContext, RemoteServiceManager remoteServiceManager) throws ServiceException {
RenewItemResponseData renewItemResponseData = new RenewItemResponseData();
oleCirculationService = getOleCirculationService();
oleCirculationHelperService = getOleCirculationHelperService();
List<Problem> problems = new ArrayList<Problem>();
String responseString = null;
AgencyId agencyId = null;
Problem problem = new Problem();
ProblemType problemType = new ProblemType("");
if (renewItemInitiationData.getInitiationHeader() != null && renewItemInitiationData.getInitiationHeader().getFromAgencyId() != null && renewItemInitiationData.getInitiationHeader().getFromAgencyId().getAgencyId() != null && renewItemInitiationData.getInitiationHeader().getFromAgencyId().getAgencyId().getValue() != null && !renewItemInitiationData.getInitiationHeader().getFromAgencyId().getAgencyId().getValue().trim().isEmpty()) {
agencyId = new AgencyId(renewItemInitiationData.getInitiationHeader().getFromAgencyId().getAgencyId().getValue());
} else if (renewItemInitiationData.getInitiationHeader() != null && renewItemInitiationData.getInitiationHeader().getApplicationProfileType() != null && renewItemInitiationData.getInitiationHeader().getApplicationProfileType().getValue() != null && !renewItemInitiationData.getInitiationHeader().getApplicationProfileType().getValue().trim().isEmpty()) {
agencyId = new AgencyId(renewItemInitiationData.getInitiationHeader().getApplicationProfileType().getValue());
} else {
agencyId = new AgencyId(getLoanProcessor().getParameter(OLENCIPConstants.AGENCY_ID_PARAMETER));
}
HashMap<String, String> agencyPropertyMap = oleCirculationHelperService.getAgencyPropertyMap(agencyId.getValue());
if (agencyPropertyMap.size() > 0) {
String operatorId = agencyPropertyMap.get(OLENCIPConstants.OPERATOR_ID);
String patronId = renewItemInitiationData.getUserId().getUserIdentifierValue();
String itemBarcode = renewItemInitiationData.getItemId().getItemIdentifierValue();
LOG.info("Inside Renew Item Service . Patron Barcode : " + patronId + " Operator Id : " +operatorId + "Item Barcode : " + itemBarcode);
String response = oleCirculationService.renewItem(patronId, operatorId, itemBarcode,false);
LOG.info(response);
OLERenewItem oleRenewItem = (OLERenewItem) oleRenewItemConverter.generateRenewItemObject(response);
if (oleRenewItem != null && oleRenewItem.getMessage().contains(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RENEW_SUCCESS))) {
renewItemResponseData.setItemId(renewItemInitiationData.getItemId());
renewItemResponseData.setUserId(renewItemInitiationData.getUserId());
renewItemResponseData.setDateDue(oleCirculationHelperService.getGregorianCalendarDate(oleRenewItem.getPastDueDate()));
renewItemResponseData.setDateForReturn(oleCirculationHelperService.getGregorianCalendarDate(oleRenewItem.getNewDueDate()));
renewItemResponseData.setRenewalCount(new BigDecimal(oleRenewItem.getRenewalCount()));
} else {
if (oleRenewItem != null) {
problem.setProblemDetail(oleRenewItem.getMessage());
} else {
problem.setProblemDetail(ConfigContext.getCurrentContextConfig().getProperty(OLENCIPConstants.RENEW_FAIL));
}
problem.setProblemElement(OLENCIPConstants.ITEM);
problem.setProblemType(problemType);
problem.setProblemValue(itemBarcode);
problems.add(problem);
renewItemResponseData.setProblems(problems);
}
} else {
problem.setProblemDetail(ConfigContext.getCurrentContextConfig().getProperty(OLENCIPConstants.INVALID_AGENCY_ID));
problem.setProblemElement(OLENCIPConstants.AGENCY_ID);
problem.setProblemType(problemType);
problem.setProblemValue(agencyId.getValue());
problems.add(problem);
renewItemResponseData.setProblems(problems);
}
return renewItemResponseData; //To change body of implemented methods use File | Settings | File Templates.
}
}
| 55.396947 | 442 | 0.739286 |
f870e96f5f11915f90045caee72c4dce8f957260 | 1,656 | package io.ebeaninternal.server.type;
import io.ebean.config.JsonConfig;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
/**
* ScalarType for java.sql.Timestamp.
*/
public class ScalarTypeOffsetDateTime extends ScalarTypeBaseDateTime<OffsetDateTime> {
public ScalarTypeOffsetDateTime(JsonConfig.DateTime mode) {
super(mode, OffsetDateTime.class, false, Types.TIMESTAMP);
}
@Override
protected String toJsonNanos(OffsetDateTime value) {
return toJsonNanos(value.toEpochSecond(), value.getNano());
}
@Override
protected String toJsonISO8601(OffsetDateTime value) {
return value.toInstant().toString();
}
@Override
public long convertToMillis(OffsetDateTime value) {
return value.toInstant().toEpochMilli();
}
@Override
public OffsetDateTime convertFromMillis(long systemTimeMillis) {
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(systemTimeMillis), ZoneId.systemDefault());
}
@Override
public OffsetDateTime convertFromTimestamp(Timestamp ts) {
return OffsetDateTime.ofInstant(ts.toInstant(), ZoneId.systemDefault());
}
@Override
public Timestamp convertToTimestamp(OffsetDateTime t) {
return Timestamp.from(t.toInstant());
}
@Override
public Object toJdbcType(Object value) {
if (value instanceof Timestamp) return value;
return convertToTimestamp((OffsetDateTime) value);
}
@Override
public OffsetDateTime toBeanType(Object value) {
if (value instanceof OffsetDateTime) return (OffsetDateTime) value;
return convertFromTimestamp((Timestamp) value);
}
}
| 26.709677 | 100 | 0.76087 |
86b31085c010ab77768c220071d3c61f320b1822 | 39,257 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2022 the original author or authors.
*/
package org.assertj.core.api.assumptions;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.emptyList;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.assertj.core.api.BDDAssertions.as;
import static org.assertj.core.api.InstanceOfAssertFactories.ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.ARRAY_2D;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_BOOLEAN;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_INTEGER;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_INTEGER_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_INTEGER_FIELD_UPDATER;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_LONG;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_LONG_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_LONG_FIELD_UPDATER;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_MARKABLE_REFERENCE;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_REFERENCE;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_REFERENCE_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_REFERENCE_FIELD_UPDATER;
import static org.assertj.core.api.InstanceOfAssertFactories.ATOMIC_STAMPED_REFERENCE;
import static org.assertj.core.api.InstanceOfAssertFactories.BIG_DECIMAL;
import static org.assertj.core.api.InstanceOfAssertFactories.BIG_INTEGER;
import static org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN;
import static org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.BYTE;
import static org.assertj.core.api.InstanceOfAssertFactories.BYTE_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.BYTE_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.CHARACTER;
import static org.assertj.core.api.InstanceOfAssertFactories.CHAR_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.CHAR_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.CHAR_SEQUENCE;
import static org.assertj.core.api.InstanceOfAssertFactories.CLASS;
import static org.assertj.core.api.InstanceOfAssertFactories.COLLECTION;
import static org.assertj.core.api.InstanceOfAssertFactories.COMPLETABLE_FUTURE;
import static org.assertj.core.api.InstanceOfAssertFactories.COMPLETION_STAGE;
import static org.assertj.core.api.InstanceOfAssertFactories.DATE;
import static org.assertj.core.api.InstanceOfAssertFactories.DOUBLE;
import static org.assertj.core.api.InstanceOfAssertFactories.DOUBLE_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.DOUBLE_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.DOUBLE_PREDICATE;
import static org.assertj.core.api.InstanceOfAssertFactories.DOUBLE_STREAM;
import static org.assertj.core.api.InstanceOfAssertFactories.DURATION;
import static org.assertj.core.api.InstanceOfAssertFactories.FILE;
import static org.assertj.core.api.InstanceOfAssertFactories.FLOAT;
import static org.assertj.core.api.InstanceOfAssertFactories.FLOAT_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.FLOAT_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.FUTURE;
import static org.assertj.core.api.InstanceOfAssertFactories.INPUT_STREAM;
import static org.assertj.core.api.InstanceOfAssertFactories.INSTANT;
import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;
import static org.assertj.core.api.InstanceOfAssertFactories.INT_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.INT_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.INT_PREDICATE;
import static org.assertj.core.api.InstanceOfAssertFactories.INT_STREAM;
import static org.assertj.core.api.InstanceOfAssertFactories.ITERABLE;
import static org.assertj.core.api.InstanceOfAssertFactories.ITERATOR;
import static org.assertj.core.api.InstanceOfAssertFactories.LIST;
import static org.assertj.core.api.InstanceOfAssertFactories.LOCAL_DATE;
import static org.assertj.core.api.InstanceOfAssertFactories.LOCAL_DATE_TIME;
import static org.assertj.core.api.InstanceOfAssertFactories.LOCAL_TIME;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG_ADDER;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG_PREDICATE;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG_STREAM;
import static org.assertj.core.api.InstanceOfAssertFactories.MAP;
import static org.assertj.core.api.InstanceOfAssertFactories.OFFSET_DATE_TIME;
import static org.assertj.core.api.InstanceOfAssertFactories.OFFSET_TIME;
import static org.assertj.core.api.InstanceOfAssertFactories.OPTIONAL;
import static org.assertj.core.api.InstanceOfAssertFactories.OPTIONAL_DOUBLE;
import static org.assertj.core.api.InstanceOfAssertFactories.OPTIONAL_INT;
import static org.assertj.core.api.InstanceOfAssertFactories.OPTIONAL_LONG;
import static org.assertj.core.api.InstanceOfAssertFactories.PATH;
import static org.assertj.core.api.InstanceOfAssertFactories.PERIOD;
import static org.assertj.core.api.InstanceOfAssertFactories.PREDICATE;
import static org.assertj.core.api.InstanceOfAssertFactories.SHORT;
import static org.assertj.core.api.InstanceOfAssertFactories.SHORT_2D_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.SHORT_ARRAY;
import static org.assertj.core.api.InstanceOfAssertFactories.SPLITERATOR;
import static org.assertj.core.api.InstanceOfAssertFactories.STREAM;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING_BUFFER;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING_BUILDER;
import static org.assertj.core.api.InstanceOfAssertFactories.THROWABLE;
import static org.assertj.core.api.InstanceOfAssertFactories.URI_TYPE;
import static org.assertj.core.api.InstanceOfAssertFactories.URL_TYPE;
import static org.assertj.core.api.InstanceOfAssertFactories.ZONED_DATE_TIME;
import static org.assertj.core.api.InstanceOfAssertFactories.list;
import static org.assertj.core.util.AssertionsUtil.expectAssumptionNotMetException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Spliterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicMarkableReference;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.DoublePredicate;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
class Assumptions_assumeThat_with_extracting_and_narrowing_value_Test {
private TestData data = new TestData();
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_array() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::array, as(ARRAY)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_array2d() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::array2D, as(ARRAY_2D)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicBoolean() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicBoolean, as(ATOMIC_BOOLEAN)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicInteger() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicInteger, as(ATOMIC_INTEGER)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicIntegerArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicIntegerArray, as(ATOMIC_INTEGER_ARRAY))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicIntegerFieldUpdater() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicIntegerFieldUpdater,
as(ATOMIC_INTEGER_FIELD_UPDATER))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicLong() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicLong, as(ATOMIC_LONG)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicLongArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicLongArray, as(ATOMIC_LONG_ARRAY))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicLongFieldUpdater() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicLongFieldUpdater,
as(ATOMIC_LONG_FIELD_UPDATER))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicMarkableReference() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicMarkableReference,
as(ATOMIC_MARKABLE_REFERENCE))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicReference() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicReference, as(ATOMIC_REFERENCE))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicReferenceArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicReferenceArray, as(ATOMIC_REFERENCE_ARRAY))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicReferenceFieldUpdater() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicReferenceFieldUpdater,
as(ATOMIC_REFERENCE_FIELD_UPDATER))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_AtomicStampedReference() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::atomicStampedReference,
as(ATOMIC_STAMPED_REFERENCE))
.isNull());
}
// https://github.com/assertj/assertj-core/issues/2349
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_BigDecimal() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::bigDecimal, as(BIG_DECIMAL)).isZero());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_BigInteger() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::bigInteger, as(BIG_INTEGER)).isZero());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_boolean() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::booleanPrimitive, as(BOOLEAN)).isFalse());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Boolean() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getBoolean, as(BOOLEAN)).isFalse());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Boolean2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::boolean2DArray, as(BOOLEAN_2D_ARRAY))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_BooleanArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::booleanArray, as(BOOLEAN_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_byte() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::bytePrimitive, as(BYTE)).isZero());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Byte() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getByte, as(BYTE)).isZero());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Byte2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::byte2DArray, as(BYTE_2D_ARRAY))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_ByteArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::byteArray, as(BYTE_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_char() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getChar, as(CHARACTER)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Character() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::character, as(CHARACTER)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Char2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::char2DArray, as(CHAR_2D_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_CharArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::charArray, as(CHAR_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_CharSequence() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::charSequence, as(CHAR_SEQUENCE)).isBlank());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Class() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getClass, as(CLASS)).isFinal());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Collection() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::collection, as(COLLECTION)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_CompletableFuture() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::completableFuture, as(COMPLETABLE_FUTURE))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Future() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::future, as(FUTURE)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_CompletionStage() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::completionStage, as(COMPLETION_STAGE))
.isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Date() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::date, as(DATE)).isInTheFuture());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Double() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getDouble, as(DOUBLE)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_double() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::doublePrimitive, as(DOUBLE)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Double2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::double2DArray, as(DOUBLE_2D_ARRAY))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_DoubleArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::doubleArray, as(DOUBLE_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_DoublePredicate() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::doublePredicate, as(DOUBLE_PREDICATE))
.accepts(1));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_DoubleStream() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::doubleStream, as(DOUBLE_STREAM))
.isSorted());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Duration() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::duration, as(DURATION)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_File() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::file, as(FILE)).isDirectory());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Float() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getFloat, as(FLOAT)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_float() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::floatPrimitive, as(FLOAT)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Float2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::float2DArray, as(FLOAT_2D_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_FloatArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::floatArray, as(FLOAT_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_InputStream() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::inputStream, as(INPUT_STREAM)).hasContent("foo"));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_Instant() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::instant, as(INSTANT)).isAfter(Instant.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_int() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getInt, as(INTEGER)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_Integer() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::integer, as(INTEGER)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Integer2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::int2DArray, as(INT_2D_ARRAY))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_int_array() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::intArray, as(INT_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_IntegerPredicate() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::intPredicate, as(INT_PREDICATE)).accepts(1));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_IntegerStream() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::intStream, as(INT_STREAM)).isSorted());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_iterable() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::iterable, as(ITERABLE)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_iterator() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::iterator, as(ITERATOR)).hasNext());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_list() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::list, as(LIST)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_list_of_String() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::stringList, as(list(String.class))).isEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_localDate() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::localDate, as(LOCAL_DATE))
.isAfter(LocalDate.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_localDateTime() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::localDateTime, as(LOCAL_DATE_TIME))
.isAfter(LocalDateTime.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_localTime() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::localTime, as(LOCAL_TIME))
.isAfter(LocalTime.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_long() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::longPrimitive, as(LONG)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Long() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getLong, as(LONG)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Long2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::long2DArray, as(LONG_2D_ARRAY))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_LongAdder() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::longAdder, as(LONG_ADDER)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_LongArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::longArray, as(LONG_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_LongPredicate() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::longPredicate, as(LONG_PREDICATE)).accepts(1));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_LongStream() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::longStream, as(LONG_STREAM)).isSorted());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Map() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::map, as(MAP)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_offsetDateTime() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::offsetDateTime, as(OFFSET_DATE_TIME))
.isAfter(OffsetDateTime.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_offsetTime() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::offsetTime, as(OFFSET_TIME))
.isAfter(OffsetTime.MAX));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_optional() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::optional, as(OPTIONAL)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_optionalDouble() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::optionalDouble, as(OPTIONAL_DOUBLE))
.isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_optionalInt() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::optionalInt, as(OPTIONAL_INT)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_an_optionalLong() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::optionalLong, as(OPTIONAL_LONG)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_path() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::path, as(PATH)).isDirectory());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_period() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::period, as(PERIOD)).hasYears(2000));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_predicate() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::predicate, as(PREDICATE)).accepts(123));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_short() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::shortPrimitive, as(SHORT)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Short() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getShort, as(SHORT)).isNegative());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Short2DArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::short2DArray, as(SHORT_2D_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_ShortArray() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::shortArray, as(SHORT_ARRAY)).isNotEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Spliterator() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::spliterator, as(SPLITERATOR)).isNull());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Stream() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::stream, as(STREAM)).isEmpty());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_String() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::getString, as(STRING)).isBlank());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_StringBuffer() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::stringBuffer, as(STRING_BUFFER)).isBlank());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_StringBuilder() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::stringBuilder, as(STRING_BUILDER)).isBlank());
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_Throwable() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::throwable, as(THROWABLE)).hasMessage("foo"));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_URI() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::uri, as(URI_TYPE)).hasHost("google"));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_URL() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::url, as(URL_TYPE)).hasHost("google"));
}
@Test
void should_ignore_test_for_failing_assumption_extracting_and_narrowing_a_ZonedDateTime() {
expectAssumptionNotMetException(() -> assumeThat(data).extracting(TestData::zonedDateTime, as(ZONED_DATE_TIME))
.isAfter(ZonedDateTime.now()));
}
static class TestData {
volatile int foo;
volatile long fooLong;
volatile TestData fooTestData;
Object[] array() {
return new Object[0];
}
Object[][] array2D() {
return new Object[0][0];
}
AtomicBoolean atomicBoolean() {
return new AtomicBoolean(true);
}
AtomicInteger atomicInteger() {
return new AtomicInteger(1);
}
AtomicIntegerArray atomicIntegerArray() {
return new AtomicIntegerArray(0);
}
AtomicIntegerFieldUpdater<?> atomicIntegerFieldUpdater() {
return AtomicIntegerFieldUpdater.newUpdater(TestData.class, "foo");
}
AtomicLong atomicLong() {
return new AtomicLong(1);
}
AtomicLongArray atomicLongArray() {
return new AtomicLongArray(0);
}
AtomicLongFieldUpdater<?> atomicLongFieldUpdater() {
return AtomicLongFieldUpdater.newUpdater(TestData.class, "fooLong");
}
AtomicMarkableReference<?> atomicMarkableReference() {
return new AtomicMarkableReference<>("foo", true);
}
AtomicReference<?> atomicReference() {
return new AtomicReference<>(1);
}
AtomicReferenceArray<?> atomicReferenceArray() {
return new AtomicReferenceArray<>(0);
}
AtomicReferenceFieldUpdater<?, ?> atomicReferenceFieldUpdater() {
return AtomicReferenceFieldUpdater.newUpdater(TestData.class, TestData.class, "fooTestData");
}
AtomicStampedReference<?> atomicStampedReference() {
return new AtomicStampedReference<>("foo", 1);
}
BigDecimal bigDecimal() {
return BigDecimal.ONE;
}
BigInteger bigInteger() {
return BigInteger.ONE;
}
boolean booleanPrimitive() {
return Boolean.TRUE;
}
Boolean getBoolean() {
return Boolean.TRUE;
}
boolean[][] boolean2DArray() {
return new boolean[0][];
}
boolean[] booleanArray() {
return new boolean[0];
}
byte bytePrimitive() {
return 1;
}
Byte getByte() {
return 1;
}
byte[][] byte2DArray() {
return new byte[0][];
}
byte[] byteArray() {
return new byte[0];
}
char getChar() {
return 'a';
}
Character character() {
return 'a';
}
char[][] char2DArray() {
return new char[0][];
}
char[] charArray() {
return new char[0];
}
CharSequence charSequence() {
return "foo";
}
Collection<?> collection() {
return emptyList();
}
CompletableFuture<?> completableFuture() {
return completedFuture("foo");
}
CompletionStage<?> completionStage() {
return completedFuture("foo");
}
Date date() {
return new Date(0);
}
double doublePrimitive() {
return Double.MAX_VALUE;
}
Double getDouble() {
return Double.MAX_VALUE;
}
double[][] double2DArray() {
return new double[0][];
}
double[] doubleArray() {
return new double[0];
}
DoublePredicate doublePredicate() {
return d -> d == 0;
}
DoubleStream doubleStream() {
return DoubleStream.of(1.0, 0.0);
}
Duration duration() {
return Duration.ZERO;
}
File file() {
return new File("foo.txt");
}
Float getFloat() {
return Float.MAX_VALUE;
}
float floatPrimitive() {
return Float.MAX_VALUE;
}
float[][] float2DArray() {
return new float[0][];
}
float[] floatArray() {
return new float[0];
}
Future<?> future() {
return CompletableFuture.completedFuture("foo");
}
InputStream inputStream() {
return new ByteArrayInputStream(new byte[0]);
}
Instant instant() {
return Instant.EPOCH;
}
Integer integer() {
return Integer.MAX_VALUE;
}
int getInt() {
return 1;
}
int[][] int2DArray() {
return new int[0][];
}
int[] intArray() {
return new int[0];
}
IntPredicate intPredicate() {
return i -> i == 0;
}
IntStream intStream() {
return IntStream.of(1, 0);
}
Iterable<?> iterable() {
return emptyList();
}
Iterator<?> iterator() {
return emptyList().iterator();
}
List<?> list() {
return emptyList();
}
List<String> stringList() {
return Lists.list("foo");
}
LocalDate localDate() {
return LocalDate.MIN;
}
LocalDateTime localDateTime() {
return LocalDateTime.MIN;
}
LocalTime localTime() {
return LocalTime.MIN;
}
long longPrimitive() {
return Long.MAX_VALUE;
}
Long getLong() {
return Long.MAX_VALUE;
}
long[][] long2DArray() {
return new long[0][];
}
LongAdder longAdder() {
return new LongAdder();
}
long[] longArray() {
return new long[0];
}
LongPredicate longPredicate() {
return d -> d == 0;
}
LongStream longStream() {
return LongStream.of(1, 0);
}
Map<?, ?> map() {
return newHashMap();
}
OffsetDateTime offsetDateTime() {
return OffsetDateTime.MIN;
}
OffsetTime offsetTime() {
return OffsetTime.MIN;
}
Optional<?> optional() {
return Optional.empty();
}
OptionalDouble optionalDouble() {
return OptionalDouble.empty();
}
OptionalInt optionalInt() {
return OptionalInt.empty();
}
OptionalLong optionalLong() {
return OptionalLong.empty();
}
Path path() {
return Paths.get("src/test/resources/utf8.txt");
}
Period period() {
return Period.ZERO;
}
Predicate<?> predicate() {
return Predicate.isEqual("foo");
}
short shortPrimitive() {
return Short.MAX_VALUE;
}
Short getShort() {
return Short.MAX_VALUE;
}
short[][] short2DArray() {
return new short[0][];
}
short[] shortArray() {
return new short[0];
}
Spliterator<?> spliterator() {
return Stream.of(1, 2).spliterator();
}
Stream<?> stream() {
return Stream.of(1, 2);
}
String getString() {
return "foo";
}
StringBuffer stringBuffer() {
return new StringBuffer("foo");
}
StringBuilder stringBuilder() {
return new StringBuilder("foo");
}
Throwable throwable() {
return new Throwable("boom!");
}
URI uri() {
try {
return new URI("https://assertj.github.io/doc!");
} catch (URISyntaxException e) {
return null;
}
}
URL url() {
try {
return new URL("https://assertj.github.io/doc!");
} catch (MalformedURLException e) {
return null;
}
}
ZonedDateTime zonedDateTime() {
return ZonedDateTime.now().minusDays(1);
}
}
}
| 37.819846 | 130 | 0.738492 |
cebd13a6834607f199ac75c8a4030c619c0fb44f | 451 | package proxy.tradition;
import proxy.tradition.SchoolService;
import proxy.tradition.SchoolServiceImpl;
/**
* @Auther Carroll
* @Date 2020/4/7
* @e-mail [email protected]
*/
public class TestMain {
public static void main(String[] args) {
SchoolService schoolService = new SchoolServiceImpl();
System.out.println(schoolService.login("admin", "123456"));
System.out.println(schoolService.getAllClazzs());
}
}
| 22.55 | 67 | 0.702882 |
501a12837b04324490abeaf58838bbd5463caab7 | 1,443 | package org.sanjay.model;
import java.math.BigDecimal;
import java.util.Date;
public class Flight {
private Long flightId;
private String airline;
private String departure;
private String destination;
private Date departureDate;
private String flightClass;
private BigDecimal price;
public String getAirline() {
return airline;
}
public void setAirline(String airline) {
this.airline = airline;
}
public String getDeparture() {
return departure;
}
public void setDeparture(String departure) {
this.departure = departure;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Long getFlightId() {
return flightId;
}
public void setFlightId(Long flightId) {
this.flightId = flightId;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public String getFlightClass() {
return flightClass;
}
public void setFlightClass(String flightClass) {
this.flightClass = flightClass;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
| 19.767123 | 54 | 0.642412 |
1b2cade60b5911c76b522d8bac53fa5110c25245 | 3,589 | package org.basex.util;
import static org.basex.core.Text.*;
import static org.basex.util.Token.*;
import org.basex.core.*;
import org.basex.io.*;
/**
* Abstract class for parsing various inputs, such as database commands or queries.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public class InputParser {
/** Parsing exception. */
private static final String FOUND = ", found '%'";
/** Input to be parsed. */
public final String input;
/** Query length. */
public final int il;
/** File reference. */
public String file;
/** Current input position. */
public int ip;
/** Marked input position. */
public int im;
/**
* Constructor.
* @param in input
*/
public InputParser(final String in) {
input = in;
il = input.length();
}
/**
* Sets a file reference.
* @param f file
* @param c database context
*/
protected void file(final IO f, final Context c) {
file = f == null ? null : c.user.has(Perm.ADMIN) ? f.path() : f.name();
}
/**
* Checks if more characters are found.
* @return current character
*/
public final boolean more() {
return ip < il;
}
/**
* Returns the current character.
* @return current character
*/
public final char curr() {
final int i = ip;
return i < il ? input.charAt(i) : 0;
}
/**
* Checks if the current character equals the specified one.
* @param ch character to be checked
* @return result of check
*/
public final boolean curr(final int ch) {
final int i = ip;
return i < il && ch == input.charAt(i);
}
/**
* Remembers the current position.
*/
protected final void mark() {
im = ip;
}
/**
* Returns the next character.
* @return result of check
*/
protected final char next() {
final int i = ip + 1;
return i < il ? input.charAt(i) : 0;
}
/**
* Returns next character.
* @return next character
*/
public final char consume() {
return ip < il ? input.charAt(ip++) : 0;
}
/**
* Peeks forward and consumes the character if it equals the specified one.
* @param ch character to consume
* @return true if character was found
*/
public final boolean consume(final int ch) {
final int i = ip;
if(i >= il || ch != input.charAt(i)) return false;
++ip;
return true;
}
/**
* Checks if the specified character is a quote.
* @param ch character to be checked
* @return result
*/
protected static final boolean quote(final int ch) {
return ch == '"' || ch == '\'';
}
/**
* Peeks forward and consumes the string if it equals the specified one.
* @param str string to consume
* @return true if string was found
*/
public final boolean consume(final String str) {
int i = ip;
final int l = str.length();
if(i + l > il) return false;
for(int s = 0; s < l; ++s) {
if(input.charAt(i++) != str.charAt(s)) return false;
}
ip = i;
return true;
}
/**
* Returns a "found" string, containing the current character.
* @return completion
*/
protected final byte[] found() {
return curr() == 0 ? EMPTY : Util.inf(FOUND, curr());
}
/**
* Returns the remaining, unscanned query substring.
* @return query substring
*/
protected final String rest() {
final int ie = Math.min(il, ip + 15);
return input.substring(ip, ie) + (ie == il ? "" : DOTS);
}
/**
* Creates input information.
* @return input information
*/
public final InputInfo info() {
return new InputInfo(this);
}
}
| 22.154321 | 83 | 0.601839 |
105b725dd5ae9979a35d8f62dab863bd7a5036c7 | 49,392 | /*
* Copyright 2019-2022 The Polypheny 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.
*
* This file incorporates code covered by the following terms:
*
* 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.polypheny.db.prepare;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.DatabaseMetaData;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import org.apache.calcite.avatica.ColumnMetaData;
import org.apache.calcite.avatica.ColumnMetaData.AvaticaType;
import org.apache.calcite.avatica.ColumnMetaData.Rep;
import org.apache.calcite.avatica.Meta.CursorFactory;
import org.apache.calcite.avatica.Meta.StatementType;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.linq4j.Queryable;
import org.apache.calcite.linq4j.function.Function1;
import org.apache.calcite.linq4j.tree.BinaryExpression;
import org.apache.calcite.linq4j.tree.BlockStatement;
import org.apache.calcite.linq4j.tree.Blocks;
import org.apache.calcite.linq4j.tree.ConstantExpression;
import org.apache.calcite.linq4j.tree.Expression;
import org.apache.calcite.linq4j.tree.Expressions;
import org.apache.calcite.linq4j.tree.MemberExpression;
import org.apache.calcite.linq4j.tree.MethodCallExpression;
import org.apache.calcite.linq4j.tree.NewExpression;
import org.apache.calcite.linq4j.tree.ParameterExpression;
import org.polypheny.db.adapter.enumerable.EnumerableAlg;
import org.polypheny.db.adapter.enumerable.EnumerableAlg.Prefer;
import org.polypheny.db.adapter.enumerable.EnumerableBindable.EnumerableToBindableConverterRule;
import org.polypheny.db.adapter.enumerable.EnumerableCalc;
import org.polypheny.db.adapter.enumerable.EnumerableConvention;
import org.polypheny.db.adapter.enumerable.EnumerableInterpretable;
import org.polypheny.db.adapter.enumerable.EnumerableInterpreterRule;
import org.polypheny.db.adapter.enumerable.EnumerableRules;
import org.polypheny.db.adapter.enumerable.RexToLixTranslator;
import org.polypheny.db.adapter.java.JavaTypeFactory;
import org.polypheny.db.algebra.AlgCollation;
import org.polypheny.db.algebra.AlgCollationTraitDef;
import org.polypheny.db.algebra.AlgCollations;
import org.polypheny.db.algebra.AlgNode;
import org.polypheny.db.algebra.AlgRoot;
import org.polypheny.db.algebra.constant.ExplainFormat;
import org.polypheny.db.algebra.constant.ExplainLevel;
import org.polypheny.db.algebra.constant.Kind;
import org.polypheny.db.algebra.core.Sort;
import org.polypheny.db.algebra.operators.OperatorName;
import org.polypheny.db.algebra.rules.AggregateExpandDistinctAggregatesRule;
import org.polypheny.db.algebra.rules.AggregateReduceFunctionsRule;
import org.polypheny.db.algebra.rules.AggregateValuesRule;
import org.polypheny.db.algebra.rules.FilterAggregateTransposeRule;
import org.polypheny.db.algebra.rules.FilterJoinRule;
import org.polypheny.db.algebra.rules.FilterProjectTransposeRule;
import org.polypheny.db.algebra.rules.FilterTableScanRule;
import org.polypheny.db.algebra.rules.JoinAssociateRule;
import org.polypheny.db.algebra.rules.JoinCommuteRule;
import org.polypheny.db.algebra.rules.JoinPushExpressionsRule;
import org.polypheny.db.algebra.rules.JoinPushThroughJoinRule;
import org.polypheny.db.algebra.rules.ProjectFilterTransposeRule;
import org.polypheny.db.algebra.rules.ProjectMergeRule;
import org.polypheny.db.algebra.rules.ProjectTableScanRule;
import org.polypheny.db.algebra.rules.ProjectWindowTransposeRule;
import org.polypheny.db.algebra.rules.ReduceExpressionsRule;
import org.polypheny.db.algebra.rules.SortJoinTransposeRule;
import org.polypheny.db.algebra.rules.SortProjectTransposeRule;
import org.polypheny.db.algebra.rules.SortRemoveConstantKeysRule;
import org.polypheny.db.algebra.rules.SortUnionTransposeRule;
import org.polypheny.db.algebra.rules.TableScanRule;
import org.polypheny.db.algebra.rules.ValuesReduceRule;
import org.polypheny.db.algebra.stream.StreamRules;
import org.polypheny.db.algebra.type.AlgDataType;
import org.polypheny.db.algebra.type.AlgDataTypeFactory;
import org.polypheny.db.algebra.type.AlgDataTypeField;
import org.polypheny.db.catalog.Catalog.QueryLanguage;
import org.polypheny.db.config.RuntimeConfig;
import org.polypheny.db.interpreter.BindableConvention;
import org.polypheny.db.interpreter.Bindables;
import org.polypheny.db.interpreter.Interpreters;
import org.polypheny.db.languages.LanguageManager;
import org.polypheny.db.languages.NodeParseException;
import org.polypheny.db.languages.NodeToAlgConverter;
import org.polypheny.db.languages.NodeToAlgConverter.ConfigBuilder;
import org.polypheny.db.languages.OperatorRegistry;
import org.polypheny.db.languages.Parser;
import org.polypheny.db.languages.RexConvertletTable;
import org.polypheny.db.nodes.BinaryOperator;
import org.polypheny.db.nodes.ExecutableStatement;
import org.polypheny.db.nodes.Node;
import org.polypheny.db.nodes.Operator;
import org.polypheny.db.nodes.validate.Validator;
import org.polypheny.db.plan.AlgOptCluster;
import org.polypheny.db.plan.AlgOptCostFactory;
import org.polypheny.db.plan.AlgOptPlanner;
import org.polypheny.db.plan.AlgOptRule;
import org.polypheny.db.plan.AlgOptUtil;
import org.polypheny.db.plan.Contexts;
import org.polypheny.db.plan.Convention;
import org.polypheny.db.plan.ConventionTraitDef;
import org.polypheny.db.plan.hep.HepPlanner;
import org.polypheny.db.plan.hep.HepProgramBuilder;
import org.polypheny.db.plan.volcano.VolcanoPlanner;
import org.polypheny.db.prepare.Prepare.PreparedExplain;
import org.polypheny.db.prepare.Prepare.PreparedResult;
import org.polypheny.db.rex.RexBuilder;
import org.polypheny.db.rex.RexNode;
import org.polypheny.db.rex.RexProgram;
import org.polypheny.db.runtime.Bindable;
import org.polypheny.db.runtime.Hook;
import org.polypheny.db.runtime.Typed;
import org.polypheny.db.schema.PolyphenyDbSchema;
import org.polypheny.db.tools.Frameworks.PrepareAction;
import org.polypheny.db.type.ExtraPolyTypes;
import org.polypheny.db.type.PolyType;
import org.polypheny.db.util.Conformance;
import org.polypheny.db.util.ImmutableIntList;
import org.polypheny.db.util.Pair;
import org.polypheny.db.util.Util;
/**
* This class is public so that projects that create their own JDBC driver and server can fine-tune preferences.
* However, this class and its methods are subject to change without notice.
*/
public class PolyphenyDbPrepareImpl implements PolyphenyDbPrepare {
/**
* Whether to enable the collation trait. Some extra optimizations are possible if enabled, but queries should work
* either way. At some point this will become a preference, or we will run multiple phases: first disabled, then enabled.
*/
private static final boolean ENABLE_COLLATION_TRAIT = true;
/**
* Whether the bindable convention should be the root convention of any plan. If not, enumerable convention is the default.
*/
public final boolean enableBindable = Hook.ENABLE_BINDABLE.get( false );
/**
* Whether the enumerable convention is enabled.
*/
public static final boolean ENABLE_ENUMERABLE = true;
/**
* Whether the streaming is enabled.
*/
public static final boolean ENABLE_STREAM = true;
private static final Set<String> SIMPLE_SQLS =
ImmutableSet.of(
"SELECT 1",
"select 1",
"SELECT 1 FROM DUAL",
"select 1 from dual",
"values 1",
"VALUES 1" );
public static final List<AlgOptRule> ENUMERABLE_RULES =
ImmutableList.of(
EnumerableRules.ENUMERABLE_JOIN_RULE,
EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE,
EnumerableRules.ENUMERABLE_SEMI_JOIN_RULE,
EnumerableRules.ENUMERABLE_CORRELATE_RULE,
EnumerableRules.ENUMERABLE_CONDITIONAL_EXECUTE_RULE,
EnumerableRules.ENUMERABLE_CONDITIONAL_EXECUTE_TRUE_RULE,
EnumerableRules.ENUMERABLE_CONDITIONAL_EXECUTE_FALSE_RULE,
EnumerableRules.ENUMERABLE_PROJECT_RULE,
EnumerableRules.ENUMERABLE_FILTER_RULE,
EnumerableRules.ENUMERABLE_AGGREGATE_RULE,
EnumerableRules.ENUMERABLE_SORT_RULE,
EnumerableRules.ENUMERABLE_LIMIT_RULE,
EnumerableRules.ENUMERABLE_COLLECT_RULE,
EnumerableRules.ENUMERABLE_UNCOLLECT_RULE,
EnumerableRules.ENUMERABLE_UNION_RULE,
EnumerableRules.ENUMERABLE_MODIFY_COLLECT_RULE,
EnumerableRules.ENUMERABLE_INTERSECT_RULE,
EnumerableRules.ENUMERABLE_MINUS_RULE,
EnumerableRules.ENUMERABLE_TABLE_MODIFICATION_RULE,
EnumerableRules.ENUMERABLE_VALUES_RULE,
EnumerableRules.ENUMERABLE_WINDOW_RULE,
EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
EnumerableRules.ENUMERABLE_TABLE_FUNCTION_SCAN_RULE );
public static final List<AlgOptRule> DEFAULT_RULES =
ImmutableList.of(
TableScanRule.INSTANCE,
RuntimeConfig.JOIN_COMMUTE.getBoolean()
? JoinAssociateRule.INSTANCE
: ProjectMergeRule.INSTANCE,
FilterTableScanRule.INSTANCE,
ProjectFilterTransposeRule.INSTANCE,
FilterProjectTransposeRule.INSTANCE,
FilterJoinRule.FILTER_ON_JOIN,
JoinPushExpressionsRule.INSTANCE,
AggregateExpandDistinctAggregatesRule.INSTANCE,
AggregateReduceFunctionsRule.INSTANCE,
FilterAggregateTransposeRule.INSTANCE,
ProjectWindowTransposeRule.INSTANCE,
JoinCommuteRule.INSTANCE,
JoinPushThroughJoinRule.RIGHT,
JoinPushThroughJoinRule.LEFT,
SortProjectTransposeRule.INSTANCE,
SortJoinTransposeRule.INSTANCE,
SortRemoveConstantKeysRule.INSTANCE,
SortUnionTransposeRule.INSTANCE );
public static final List<AlgOptRule> CONSTANT_REDUCTION_RULES =
ImmutableList.of(
ReduceExpressionsRule.PROJECT_INSTANCE,
ReduceExpressionsRule.FILTER_INSTANCE,
ReduceExpressionsRule.CALC_INSTANCE,
ReduceExpressionsRule.JOIN_INSTANCE,
ValuesReduceRule.FILTER_INSTANCE,
ValuesReduceRule.PROJECT_FILTER_INSTANCE,
ValuesReduceRule.PROJECT_INSTANCE,
AggregateValuesRule.INSTANCE );
public PolyphenyDbPrepareImpl() {
}
@Override
public ParseResult parse( Context context, String sql ) {
return parse_( context, sql, false, false, false );
}
@Override
public ConvertResult convert( Context context, String sql ) {
return (ConvertResult) parse_( context, sql, true, false, false );
}
/**
* Shared implementation for {@link #parse} and {@link #convert}.
*/
private ParseResult parse_( Context context, String sql, boolean convert, boolean analyze, boolean fail ) {
final JavaTypeFactory typeFactory = context.getTypeFactory();
PolyphenyDbCatalogReader catalogReader = new PolyphenyDbCatalogReader(
context.getRootSchema(),
context.getDefaultSchemaPath(),
typeFactory );
Parser parser = createParser( sql );
Node sqlNode;
try {
sqlNode = parser.parseStmt();
} catch ( NodeParseException e ) {
throw new RuntimeException( "parse failed", e );
}
final Validator validator = LanguageManager.getInstance().createValidator( QueryLanguage.SQL, context, catalogReader );
Node sqlNode1 = validator.validate( sqlNode );
if ( convert ) {
return convert_( context, sql, analyze, fail, catalogReader, validator, sqlNode1 );
}
return new ParseResult( this, validator, sql, sqlNode1, validator.getValidatedNodeType( sqlNode1 ) );
}
private ParseResult convert_( Context context, String sql, boolean analyze, boolean fail, PolyphenyDbCatalogReader catalogReader, Validator validator, Node sqlNode1 ) {
final JavaTypeFactory typeFactory = context.getTypeFactory();
final Convention resultConvention =
enableBindable
? BindableConvention.INSTANCE
: EnumerableConvention.INSTANCE;
final HepPlanner planner = new HepPlanner( new HepProgramBuilder().build() );
planner.addAlgTraitDef( ConventionTraitDef.INSTANCE );
final ConfigBuilder configBuilder = NodeToAlgConverter.configBuilder().trimUnusedFields( true );
if ( analyze ) {
configBuilder.convertTableAccess( false );
}
final PolyphenyDbPreparingStmt preparingStmt = new PolyphenyDbPreparingStmt(
this,
context,
catalogReader,
typeFactory,
context.getRootSchema(),
null,
planner,
resultConvention,
createConvertletTable() );
final NodeToAlgConverter converter = preparingStmt.getSqlToRelConverter( validator, catalogReader, new ConfigBuilder().build() );
final AlgRoot root = converter.convertQuery( sqlNode1, false, true );
return new ConvertResult( this, validator, sql, sqlNode1, validator.getValidatedNodeType( sqlNode1 ), root );
}
@Override
public void executeDdl( Context context, Node node ) {
if ( node instanceof ExecutableStatement ) {
ExecutableStatement statement = (ExecutableStatement) node;
statement.execute( context, null, null );
return;
}
throw new UnsupportedOperationException();
}
/**
* Factory method for default SQL parser.
*/
protected Parser createParser( String sql ) {
return createParser( sql, createParserConfig() );
}
/**
* Factory method for SQL parser with a given configuration.
*/
protected Parser createParser( String sql, Parser.ConfigBuilder parserConfig ) {
return Parser.create( sql, parserConfig.build() );
}
/**
* Factory method for SQL parser configuration.
*/
protected Parser.ConfigBuilder createParserConfig() {
return Parser.configBuilder();
}
/**
* Factory method for default convertlet table.
*/
protected RexConvertletTable createConvertletTable() {
return LanguageManager.getInstance().getStandardConvertlet();
}
/**
* Factory method for cluster.
*/
protected AlgOptCluster createCluster( AlgOptPlanner planner, RexBuilder rexBuilder ) {
return AlgOptCluster.create( planner, rexBuilder );
}
/**
* Creates a collection of planner factories.
* <p>
* The collection must have at least one factory, and each factory must create a planner. If the collection has more
* than one planner, Polypheny-DB will try each planner in turn.
* <p>
* One of the things you can do with this mechanism is to try a simpler, faster, planner with a smaller rule set first,
* then fall back to a more complex planner for complex and costly queries.
* <p>
* The default implementation returns a factory that calls {@link #createPlanner(Context)}.
*/
protected List<Function1<Context, AlgOptPlanner>> createPlannerFactories() {
return Collections.singletonList( context -> createPlanner( context, null, null ) );
}
/**
* Creates a query planner and initializes it with a default set of rules.
*/
protected AlgOptPlanner createPlanner( Context prepareContext ) {
return createPlanner( prepareContext, null, null );
}
/**
* Creates a query planner and initializes it with a default set of rules.
*/
protected AlgOptPlanner createPlanner( final Context prepareContext, org.polypheny.db.plan.Context externalContext, AlgOptCostFactory costFactory ) {
if ( externalContext == null ) {
externalContext = Contexts.of( prepareContext.config() );
}
final VolcanoPlanner planner = new VolcanoPlanner( costFactory, externalContext );
planner.addAlgTraitDef( ConventionTraitDef.INSTANCE );
if ( ENABLE_COLLATION_TRAIT ) {
planner.addAlgTraitDef( AlgCollationTraitDef.INSTANCE );
planner.registerAbstractRelationalRules();
}
AlgOptUtil.registerAbstractAlgs( planner );
for ( AlgOptRule rule : DEFAULT_RULES ) {
planner.addRule( rule );
}
if ( enableBindable ) {
for ( AlgOptRule rule : Bindables.RULES ) {
planner.addRule( rule );
}
}
planner.addRule( Bindables.BINDABLE_TABLE_SCAN_RULE );
planner.addRule( ProjectTableScanRule.INSTANCE );
planner.addRule( ProjectTableScanRule.INTERPRETER );
if ( ENABLE_ENUMERABLE ) {
for ( AlgOptRule rule : ENUMERABLE_RULES ) {
planner.addRule( rule );
}
planner.addRule( EnumerableInterpreterRule.INSTANCE );
}
if ( enableBindable && ENABLE_ENUMERABLE ) {
planner.addRule( EnumerableToBindableConverterRule.INSTANCE );
}
if ( ENABLE_STREAM ) {
for ( AlgOptRule rule : StreamRules.RULES ) {
planner.addRule( rule );
}
}
// Change the below to enable constant-reduction.
if ( false ) {
for ( AlgOptRule rule : CONSTANT_REDUCTION_RULES ) {
planner.addRule( rule );
}
}
Hook.PLANNER.run( planner ); // allow test to add or remove rules
return planner;
}
/**
* Deduces the broad type of statement. Currently returns SELECT for most statement types, but this may change.
*
* @param kind Kind of statement
*/
private StatementType getStatementType( Kind kind ) {
switch ( kind ) {
case INSERT:
case DELETE:
case UPDATE:
return StatementType.IS_DML;
default:
return StatementType.SELECT;
}
}
/**
* Deduces the broad type of statement for a prepare result.
* Currently returns SELECT for most statement types, but this may change.
*
* @param preparedResult Prepare result
*/
private StatementType getStatementType( PreparedResult preparedResult ) {
if ( preparedResult.isDml() ) {
return StatementType.IS_DML;
} else {
return StatementType.SELECT;
}
}
/*<T> PolyphenyDbSignature<T> prepare2_( Context context, Query<T> query, Type elementType, long maxRowCount, PolyphenyDbCatalogReader catalogReader, AlgOptPlanner planner ) {
final JavaTypeFactory typeFactory = context.getTypeFactory();
final Prefer prefer;
if ( elementType == Object[].class ) {
prefer = Prefer.ARRAY;
} else {
prefer = Prefer.CUSTOM;
}
final Convention resultConvention =
enableBindable
? BindableConvention.INSTANCE
: EnumerableConvention.INSTANCE;
final PolyphenyDbPreparingStmt preparingStmt = new PolyphenyDbPreparingStmt(
this,
context,
catalogReader,
typeFactory,
context.getRootSchema(),
prefer,
planner,
resultConvention,
createConvertletTable() );
final AlgDataType x;
final PreparedResult preparedResult;
final StatementType statementType;
if ( query.sql != null ) {
final PolyphenyDbConnectionConfig config = context.config();
final Parser.ConfigBuilder parserConfig = createParserConfig()
.setQuotedCasing( config.quotedCasing() )
.setUnquotedCasing( config.unquotedCasing() )
.setQuoting( config.quoting() )
.setConformance( config.conformance() )
.setCaseSensitive( RuntimeConfig.CASE_SENSITIVE.getBoolean() );
final ParserFactory parserFactory = config.parserFactory( ParserFactory.class, null );
if ( parserFactory != null ) {
parserConfig.setParserFactory( parserFactory );
}
Parser parser = createParser( query.sql, parserConfig );
Node sqlNode;
try {
sqlNode = parser.parseStmt();
statementType = getStatementType( sqlNode.getKind() );
} catch ( NodeParseException e ) {
throw new RuntimeException( "parse failed: " + e.getMessage(), e );
}
Hook.PARSE_TREE.run( new Object[]{ query.sql, sqlNode } );
if ( sqlNode.getKind().belongsTo( Kind.DDL ) ) {
executeDdl( context, sqlNode );
return new PolyphenyDbSignature<>(
query.sql,
ImmutableList.of(),
ImmutableMap.of(),
null,
ImmutableList.of(),
CursorFactory.OBJECT,
null,
ImmutableList.of(),
-1,
null,
StatementType.OTHER_DDL,
new ExecutionTimeMonitor(),
SchemaType.RELATIONAL );
}
final Validator validator = LanguageManager.getInstance().createValidator( QueryLanguage.SQL, context, catalogReader );
validator.setIdentifierExpansion( true );
validator.setDefaultNullCollation( config.defaultNullCollation() );
preparedResult = preparingStmt.prepareSql( sqlNode, Object.class, validator, true );
switch ( sqlNode.getKind() ) {
case INSERT:
case DELETE:
case UPDATE:
case EXPLAIN:
// FIXME: getValidatedNodeType is wrong for DML
x = AlgOptUtil.createDmlRowType( sqlNode.getKind(), typeFactory );
break;
default:
x = validator.getValidatedNodeType( sqlNode );
}
} else if ( query.queryable != null ) {
x = context.getTypeFactory().createType( elementType );
preparedResult = preparingStmt.prepareQueryable( query.queryable, x );
statementType = getStatementType( preparedResult );
} else {
assert query.alg != null;
x = query.alg.getRowType();
preparedResult = preparingStmt.prepareRel( query.alg );
statementType = getStatementType( preparedResult );
}
final List<AvaticaParameter> parameters = new ArrayList<>();
final AlgDataType parameterRowType = preparedResult.getParameterRowType();
for ( AlgDataTypeField field : parameterRowType.getFieldList() ) {
AlgDataType type = field.getType();
parameters.add(
new AvaticaParameter(
false,
getPrecision( type ),
getScale( type ),
getTypeOrdinal( type ),
getTypeName( type ),
getClassName( type ),
field.getName() ) );
}
AlgDataType jdbcType = makeStruct( typeFactory, x );
final List<List<String>> originList = preparedResult.getFieldOrigins();
final List<ColumnMetaData> columns = getColumnMetaDataList( typeFactory, x, jdbcType, originList );
Class resultClazz = null;
if ( preparedResult instanceof Typed ) {
resultClazz = (Class) ((Typed) preparedResult).getElementType();
}
final CursorFactory cursorFactory =
preparingStmt.resultConvention == BindableConvention.INSTANCE
? CursorFactory.ARRAY
: CursorFactory.deduce( columns, resultClazz );
//noinspection unchecked
final Bindable<T> bindable = preparedResult.getBindable( cursorFactory );
return new PolyphenyDbSignature<>(
query.sql,
parameters,
preparingStmt.internalParameters,
jdbcType,
columns,
cursorFactory,
context.getRootSchema(),
preparedResult instanceof PreparedResultImpl
? ((PreparedResultImpl) preparedResult).collations
: ImmutableList.of(),
maxRowCount,
bindable,
statementType,
new ExecutionTimeMonitor(),
SchemaType.RELATIONAL );
}*/
private List<ColumnMetaData> getColumnMetaDataList( JavaTypeFactory typeFactory, AlgDataType x, AlgDataType jdbcType, List<List<String>> originList ) {
final List<ColumnMetaData> columns = new ArrayList<>();
for ( Ord<AlgDataTypeField> pair : Ord.zip( jdbcType.getFieldList() ) ) {
final AlgDataTypeField field = pair.e;
final AlgDataType type = field.getType();
final AlgDataType fieldType = x.isStruct() ? x.getFieldList().get( pair.i ).getType() : type;
columns.add( metaData( typeFactory, columns.size(), field.getName(), type, fieldType, originList.get( pair.i ) ) );
}
return columns;
}
private ColumnMetaData metaData( JavaTypeFactory typeFactory, int ordinal, String fieldName, AlgDataType type, AlgDataType fieldType, List<String> origins ) {
final AvaticaType avaticaType = avaticaType( typeFactory, type, fieldType );
return new ColumnMetaData(
ordinal,
false,
true,
false,
false,
type.isNullable()
? DatabaseMetaData.columnNullable
: DatabaseMetaData.columnNoNulls,
true,
type.getPrecision(),
fieldName,
origin( origins, 0 ),
origin( origins, 2 ),
getPrecision( type ),
getScale( type ),
origin( origins, 1 ),
null,
avaticaType,
true,
false,
false,
avaticaType.columnClassName() );
}
private AvaticaType avaticaType( JavaTypeFactory typeFactory, AlgDataType type, AlgDataType fieldType ) {
final String typeName = getTypeName( type );
if ( type.getComponentType() != null ) {
final AvaticaType componentType = avaticaType( typeFactory, type.getComponentType(), null );
final Type clazz = typeFactory.getJavaClass( type.getComponentType() );
final Rep rep = Rep.of( clazz );
assert rep != null;
return ColumnMetaData.array( componentType, typeName, rep );
} else {
int typeOrdinal = getTypeOrdinal( type );
switch ( typeOrdinal ) {
case Types.STRUCT:
final List<ColumnMetaData> columns = new ArrayList<>();
for ( AlgDataTypeField field : type.getFieldList() ) {
columns.add( metaData( typeFactory, field.getIndex(), field.getName(), field.getType(), null, null ) );
}
return ColumnMetaData.struct( columns );
case ExtraPolyTypes.GEOMETRY:
typeOrdinal = Types.VARCHAR;
// fall through
default:
final Type clazz = typeFactory.getJavaClass( Util.first( fieldType, type ) );
final Rep rep = Rep.of( clazz );
assert rep != null;
return ColumnMetaData.scalar( typeOrdinal, typeName, rep );
}
}
}
private static String origin( List<String> origins, int offsetFromEnd ) {
return origins == null || offsetFromEnd >= origins.size()
? null
: origins.get( origins.size() - 1 - offsetFromEnd );
}
private int getTypeOrdinal( AlgDataType type ) {
return type.getPolyType().getJdbcOrdinal();
}
private static String getClassName( AlgDataType type ) {
return Object.class.getName(); // POLYPHENYDB-2613
}
private static int getScale( AlgDataType type ) {
return type.getScale() == AlgDataType.SCALE_NOT_SPECIFIED
? 0
: type.getScale();
}
private static int getPrecision( AlgDataType type ) {
return type.getPrecision() == AlgDataType.PRECISION_NOT_SPECIFIED
? 0
: type.getPrecision();
}
/**
* Returns the type name in string form. Does not include precision, scale or whether nulls are allowed.
* Example: "DECIMAL" not "DECIMAL(7, 2)"; "INTEGER" not "JavaType(int)".
*/
private static String getTypeName( AlgDataType type ) {
final PolyType polyType = type.getPolyType();
switch ( polyType ) {
/*
case ARRAY:
case MULTISET:
case MAP:
case ROW:
return type.toString(); // e.g. "INTEGER ARRAY"
*/
case INTERVAL_YEAR_MONTH:
return "INTERVAL_YEAR_TO_MONTH";
case INTERVAL_DAY_HOUR:
return "INTERVAL_DAY_TO_HOUR";
case INTERVAL_DAY_MINUTE:
return "INTERVAL_DAY_TO_MINUTE";
case INTERVAL_DAY_SECOND:
return "INTERVAL_DAY_TO_SECOND";
case INTERVAL_HOUR_MINUTE:
return "INTERVAL_HOUR_TO_MINUTE";
case INTERVAL_HOUR_SECOND:
return "INTERVAL_HOUR_TO_SECOND";
case INTERVAL_MINUTE_SECOND:
return "INTERVAL_MINUTE_TO_SECOND";
default:
return polyType.getName(); // e.g. "DECIMAL", "INTERVAL_YEAR_MONTH"
}
}
private static AlgDataType makeStruct( AlgDataTypeFactory typeFactory, AlgDataType type ) {
if ( type.isStruct() ) {
return type;
}
return typeFactory.builder().add( "$0", null, type ).build();
}
/**
* Executes a prepare action.
*/
public <R> R perform( PrepareAction<R> action ) {
final Context prepareContext = action.getConfig().getPrepareContext();
final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
final PolyphenyDbSchema schema =
action.getConfig().getDefaultSchema() != null
? PolyphenyDbSchema.from( action.getConfig().getDefaultSchema() )
: prepareContext.getRootSchema();
PolyphenyDbCatalogReader catalogReader = new PolyphenyDbCatalogReader( schema.root(), schema.path( null ), typeFactory );
final RexBuilder rexBuilder = new RexBuilder( typeFactory );
final AlgOptPlanner planner = createPlanner( prepareContext, action.getConfig().getContext(), action.getConfig().getCostFactory() );
final AlgOptCluster cluster = createCluster( planner, rexBuilder );
return action.apply( cluster, catalogReader, prepareContext.getRootSchema().plus() );
}
/**
* Holds state for the process of preparing a SQL statement.
*/
public static class PolyphenyDbPreparingStmt extends Prepare {
protected final AlgOptPlanner planner;
protected final RexBuilder rexBuilder;
protected final PolyphenyDbPrepareImpl prepare;
protected final PolyphenyDbSchema schema;
protected final AlgDataTypeFactory typeFactory;
protected final RexConvertletTable convertletTable;
private final Prefer prefer;
private final Map<String, Object> internalParameters = new LinkedHashMap<>();
private int expansionDepth;
private Validator sqlValidator;
PolyphenyDbPreparingStmt(
PolyphenyDbPrepareImpl prepare,
Context context,
CatalogReader catalogReader,
AlgDataTypeFactory typeFactory,
PolyphenyDbSchema schema,
Prefer prefer,
AlgOptPlanner planner,
Convention resultConvention,
RexConvertletTable convertletTable ) {
super( context, catalogReader, resultConvention );
this.prepare = prepare;
this.schema = schema;
this.prefer = prefer;
this.planner = planner;
this.typeFactory = typeFactory;
this.convertletTable = convertletTable;
this.rexBuilder = new RexBuilder( typeFactory );
}
@Override
protected void init( Class runtimeContextClass ) {
}
public PreparedResult prepareQueryable( final Queryable queryable, AlgDataType resultType ) {
return prepare_( () -> {
final AlgOptCluster cluster = prepare.createCluster( planner, rexBuilder );
return new LixToAlgTranslator( cluster ).translate( queryable );
}, resultType );
}
public PreparedResult prepareRel( final AlgNode alg ) {
return prepare_( () -> alg, alg.getRowType() );
}
private PreparedResult prepare_( Supplier<AlgNode> fn, AlgDataType resultType ) {
Class runtimeContextClass = Object.class;
init( runtimeContextClass );
final AlgNode alg = fn.get();
final AlgDataType rowType = alg.getRowType();
final List<Pair<Integer, String>> fields = Pair.zip( ImmutableIntList.identity( rowType.getFieldCount() ), rowType.getFieldNames() );
final AlgCollation collation =
alg instanceof Sort
? ((Sort) alg).collation
: AlgCollations.EMPTY;
AlgRoot root = new AlgRoot( alg, resultType, Kind.SELECT, fields, collation );
if ( timingTracer != null ) {
timingTracer.traceTime( "end sql2rel" );
}
final AlgDataType jdbcType = makeStruct( rexBuilder.getTypeFactory(), resultType );
fieldOrigins = Collections.nCopies( jdbcType.getFieldCount(), null );
parameterRowType = rexBuilder.getTypeFactory().builder().build();
// Structured type flattening, view expansion, and plugging in physical storage.
root = root.withAlg( flattenTypes( root.alg, true ) );
// Trim unused fields.
root = trimUnusedFields( root );
root = optimize( root );
if ( timingTracer != null ) {
timingTracer.traceTime( "end optimization" );
}
return implement( root );
}
@Override
protected NodeToAlgConverter getSqlToRelConverter( Validator validator, CatalogReader catalogReader, NodeToAlgConverter.Config config ) {
final AlgOptCluster cluster = prepare.createCluster( planner, rexBuilder );
return LanguageManager.getInstance().createToRelConverter( QueryLanguage.SQL, validator, catalogReader, cluster, convertletTable, config );
}
@Override
public AlgNode flattenTypes( AlgNode rootRel, boolean restructure ) {
return rootRel;
}
@Override
protected AlgNode decorrelate( NodeToAlgConverter sqlToRelConverter, Node query, AlgNode rootRel ) {
return sqlToRelConverter.decorrelate( query, rootRel );
}
protected Validator createSqlValidator( CatalogReader catalogReader ) {
return LanguageManager.getInstance().createValidator( QueryLanguage.SQL, context, (PolyphenyDbCatalogReader) catalogReader );
}
@Override
protected Validator getSqlValidator() {
if ( sqlValidator == null ) {
sqlValidator = createSqlValidator( catalogReader );
}
return sqlValidator;
}
@Override
protected PreparedResult createPreparedExplanation( AlgDataType resultType, AlgDataType parameterRowType, AlgRoot root, ExplainFormat format, ExplainLevel detailLevel ) {
return new PolyphenyDbPreparedExplain( resultType, parameterRowType, root, format, detailLevel );
}
@Override
protected PreparedResult implement( AlgRoot root ) {
AlgDataType resultType = root.alg.getRowType();
boolean isDml = root.kind.belongsTo( Kind.DML );
final Bindable bindable;
final String generatedCode;
if ( resultConvention == BindableConvention.INSTANCE ) {
bindable = Interpreters.bindable( root.alg );
generatedCode = null;
} else {
EnumerableAlg enumerable = (EnumerableAlg) root.alg;
if ( !root.isRefTrivial() ) {
final List<RexNode> projects = new ArrayList<>();
final RexBuilder rexBuilder = enumerable.getCluster().getRexBuilder();
for ( int field : Pair.left( root.fields ) ) {
projects.add( rexBuilder.makeInputRef( enumerable, field ) );
}
RexProgram program = RexProgram.create(
enumerable.getRowType(),
projects,
null,
root.validatedRowType,
rexBuilder );
enumerable = EnumerableCalc.create( enumerable, program );
}
try {
CatalogReader.THREAD_LOCAL.set( catalogReader );
final Conformance conformance = context.config().conformance();
internalParameters.put( "_conformance", conformance );
Pair<Bindable<Object[]>, String> implementationPair = EnumerableInterpretable.toBindable(
internalParameters,
enumerable,
prefer,
null );
bindable = implementationPair.left;
generatedCode = implementationPair.right;
} finally {
CatalogReader.THREAD_LOCAL.remove();
}
}
if ( timingTracer != null ) {
timingTracer.traceTime( "end codegen" );
}
if ( timingTracer != null ) {
timingTracer.traceTime( "end compilation" );
}
return new PreparedResultImpl(
resultType,
parameterRowType,
fieldOrigins,
root.collation.getFieldCollations().isEmpty()
? ImmutableList.of()
: ImmutableList.of( root.collation ),
root.alg,
mapTableModOp( isDml, root.kind ),
isDml ) {
@Override
public String getCode() {
return generatedCode;
}
@Override
public Bindable getBindable( CursorFactory cursorFactory ) {
return bindable;
}
@Override
public Type getElementType() {
return ((Typed) bindable).getElementType();
}
};
}
}
/**
* An {@code EXPLAIN} statement, prepared and ready to execute.
*/
private static class PolyphenyDbPreparedExplain extends PreparedExplain {
PolyphenyDbPreparedExplain( AlgDataType resultType, AlgDataType parameterRowType, AlgRoot root, ExplainFormat format, ExplainLevel detailLevel ) {
super( resultType, parameterRowType, root, format, detailLevel );
}
@Override
public Bindable getBindable( final CursorFactory cursorFactory ) {
final String explanation = getCode();
return dataContext -> {
switch ( cursorFactory.style ) {
case ARRAY:
return Linq4j.singletonEnumerable( new String[]{ explanation } );
case OBJECT:
default:
return Linq4j.singletonEnumerable( explanation );
}
};
}
}
/**
* Translator from Java AST to {@link RexNode}.
*/
interface ScalarTranslator {
RexNode toRex( BlockStatement statement );
List<RexNode> toRexList( BlockStatement statement );
RexNode toRex( Expression expression );
ScalarTranslator bind( List<ParameterExpression> parameterList, List<RexNode> values );
}
/**
* Basic translator.
*/
static class EmptyScalarTranslator implements ScalarTranslator {
private final RexBuilder rexBuilder;
EmptyScalarTranslator( RexBuilder rexBuilder ) {
this.rexBuilder = rexBuilder;
}
public static ScalarTranslator empty( RexBuilder builder ) {
return new EmptyScalarTranslator( builder );
}
@Override
public List<RexNode> toRexList( BlockStatement statement ) {
final List<Expression> simpleList = simpleList( statement );
final List<RexNode> list = new ArrayList<>();
for ( Expression expression1 : simpleList ) {
list.add( toRex( expression1 ) );
}
return list;
}
@Override
public RexNode toRex( BlockStatement statement ) {
return toRex( Blocks.simple( statement ) );
}
private static List<Expression> simpleList( BlockStatement statement ) {
Expression simple = Blocks.simple( statement );
if ( simple instanceof NewExpression ) {
NewExpression newExpression = (NewExpression) simple;
return newExpression.arguments;
} else {
return Collections.singletonList( simple );
}
}
@Override
public RexNode toRex( Expression expression ) {
switch ( expression.getNodeType() ) {
case MemberAccess:
// Case-sensitive name match because name was previously resolved.
return rexBuilder.makeFieldAccess(
toRex( ((MemberExpression) expression).expression ),
((MemberExpression) expression).field.getName(),
true );
case GreaterThan:
return binary( expression, OperatorRegistry.get( OperatorName.GREATER_THAN, BinaryOperator.class ) );
case LessThan:
return binary( expression, OperatorRegistry.get( OperatorName.LESS_THAN, BinaryOperator.class ) );
case Parameter:
return parameter( (ParameterExpression) expression );
case Call:
MethodCallExpression call = (MethodCallExpression) expression;
Operator operator = RexToLixTranslator.JAVA_TO_SQL_METHOD_MAP.get( call.method );
if ( operator != null ) {
return rexBuilder.makeCall(
type( call ),
operator,
toRex( Expressions.<Expression>list()
.appendIfNotNull( call.targetExpression )
.appendAll( call.expressions ) ) );
}
throw new RuntimeException( "Could translate call to method " + call.method );
case Constant:
final ConstantExpression constant = (ConstantExpression) expression;
Object value = constant.value;
if ( value instanceof Number ) {
Number number = (Number) value;
if ( value instanceof Double || value instanceof Float ) {
return rexBuilder.makeApproxLiteral( BigDecimal.valueOf( number.doubleValue() ) );
} else if ( value instanceof BigDecimal ) {
return rexBuilder.makeExactLiteral( (BigDecimal) value );
} else {
return rexBuilder.makeExactLiteral( BigDecimal.valueOf( number.longValue() ) );
}
} else if ( value instanceof Boolean ) {
return rexBuilder.makeLiteral( (Boolean) value );
} else {
return rexBuilder.makeLiteral( constant.toString() );
}
default:
throw new UnsupportedOperationException( "unknown expression type " + expression.getNodeType() + " " + expression );
}
}
private RexNode binary( Expression expression, BinaryOperator op ) {
BinaryExpression call = (BinaryExpression) expression;
return rexBuilder.makeCall( type( call ), op, toRex( ImmutableList.of( call.expression0, call.expression1 ) ) );
}
private List<RexNode> toRex( List<Expression> expressions ) {
final List<RexNode> list = new ArrayList<>();
for ( Expression expression : expressions ) {
list.add( toRex( expression ) );
}
return list;
}
protected AlgDataType type( Expression expression ) {
final Type type = expression.getType();
return ((JavaTypeFactory) rexBuilder.getTypeFactory()).createType( type );
}
@Override
public ScalarTranslator bind( List<ParameterExpression> parameterList, List<RexNode> values ) {
return new LambdaScalarTranslator( rexBuilder, parameterList, values );
}
public RexNode parameter( ParameterExpression param ) {
throw new RuntimeException( "unknown parameter " + param );
}
}
/**
* Translator that looks for parameters.
*/
private static class LambdaScalarTranslator extends EmptyScalarTranslator {
private final List<ParameterExpression> parameterList;
private final List<RexNode> values;
LambdaScalarTranslator( RexBuilder rexBuilder, List<ParameterExpression> parameterList, List<RexNode> values ) {
super( rexBuilder );
this.parameterList = parameterList;
this.values = values;
}
@Override
public RexNode parameter( ParameterExpression param ) {
int i = parameterList.indexOf( param );
if ( i >= 0 ) {
return values.get( i );
}
throw new RuntimeException( "unknown parameter " + param );
}
}
}
| 40.752475 | 179 | 0.618521 |
763c306288232c5951d3594d4dbb3280cf232338 | 3,009 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.driver.internal.reactive;
import org.neo4j.driver.Query;
import org.reactivestreams.Publisher;
import java.util.concurrent.CompletableFuture;
import org.neo4j.driver.internal.async.UnmanagedTransaction;
import org.neo4j.driver.internal.cursor.RxResultCursor;
import org.neo4j.driver.internal.util.Futures;
import org.neo4j.driver.reactive.RxResult;
import org.neo4j.driver.reactive.RxTransaction;
import static org.neo4j.driver.internal.reactive.RxUtils.createEmptyPublisher;
public class InternalRxTransaction extends AbstractRxQueryRunner implements RxTransaction
{
private final UnmanagedTransaction tx;
public InternalRxTransaction( UnmanagedTransaction tx )
{
this.tx = tx;
}
@Override
public RxResult run(Query query)
{
return new InternalRxResult( () -> {
CompletableFuture<RxResultCursor> cursorFuture = new CompletableFuture<>();
tx.runRx(query).whenComplete( (cursor, completionError ) -> {
if ( cursor != null )
{
cursorFuture.complete( cursor );
}
else
{
// We failed to create a result cursor so we cannot rely on result cursor to handle failure.
// The logic here shall be the same as `TransactionPullResponseHandler#afterFailure` as that is where cursor handling failure
// This is optional as tx still holds a reference to all cursor futures and they will be clean up properly in commit
Throwable error = Futures.completionExceptionCause( completionError );
tx.markTerminated( error );
cursorFuture.completeExceptionally( error );
}
} );
return cursorFuture;
} );
}
@Override
public <T> Publisher<T> commit()
{
return close( true );
}
@Override
public <T> Publisher<T> rollback()
{
return close( false );
}
private <T> Publisher<T> close( boolean commit )
{
return createEmptyPublisher( () -> {
if ( commit )
{
return tx.commitAsync();
}
else
{
return tx.rollbackAsync();
}
} );
}
}
| 32.354839 | 145 | 0.630442 |
5df0bfd26ccddb2635ec3cb1061a7c808bf14ad3 | 1,846 | package com.nenusoftware.onlineexam.entity.user;
/**
* @Author:Liangll
* @Description: 用户的实体类
* @Date: 21:58 2019/4/28
*/
public class User {
/**
* 用户Id
*/
private Integer userId;
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String password;
private String birthday;
private String sex;
private Integer power;
private String image;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
this.power = power;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday='" + birthday + '\'' +
", sex='" + sex + '\'' +
", power=" + power +
", image='" + image + '\'' +
'}';
}
}
| 18.098039 | 50 | 0.510834 |
581eedb33f3dc64820cc534059a5d8c544cbd5cc | 1,033 | package com.revanwang.rabbitmq.util;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RevanRabbitConnection {
/**
* 建立与RabbitMQ的连接
* @return
* @throws Exception
*/
public static Connection getConnection() {
//定义连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置服务地址
factory.setHost("192.168.0.110");
//端口
factory.setPort(5672);
//设置账号信息,用户名、密码、vhost
factory.setVirtualHost("/revan");
factory.setUsername("revan");
factory.setPassword("revan");
// 通过工程获取连接
try {
Connection connection = factory.newConnection();
return connection;
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return null;
}
}
| 26.487179 | 61 | 0.585673 |
e367ad0f0a1322d3eab46d9ca85071e6bb2c7a52 | 11,788 | // $Id$
// Author: Jean-Guilhem Rouel
// (c) COPYRIGHT MIT, ERCIM and Keio, 2005.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.css.values;
import java.util.HashMap;
/**
* @spec https://www.w3.org/TR/2016/WD-css-color-4-20160705/
*/
public class CssColorCSS3 {
protected static final HashMap<String, RGB> definedRGBColorsCSS3;
private static final RGBA trans;
static final CssIdent currentColor = CssIdent.getIdent("currentColor");
public static RGB getRGB(String ident) {
return definedRGBColorsCSS3.get(ident);
}
public static RGBA getRGBA(String ident) {
if ("transparent".equalsIgnoreCase(ident)) {
return trans;
}
return null;
}
// those are the same as CSS2, let's use that
// and note that they are deprecated...
public static String getSystem(String ident) {
return CssColorCSS2.definedSystemColorsCSS2.get(ident);
}
// special case for currentColor and possible ident-only defined colors.
public static String getIdentColor(String ident) {
if ("currentColor".equalsIgnoreCase(ident)) {
return currentColor.toString();
}
return null;
}
static {
trans = new RGBA(0, 0, 0, 0.f);
// https://www.w3.org/TR/2016/WD-css-color-4-20160705/#named-colors
definedRGBColorsCSS3 = new HashMap<String, RGB>();
definedRGBColorsCSS3.put("aliceblue", new RGB(240, 248, 255));
definedRGBColorsCSS3.put("antiquewhite", new RGB(250, 235, 215));
definedRGBColorsCSS3.put("aqua", new RGB(0, 255, 255));
definedRGBColorsCSS3.put("aquamarine", new RGB(127, 255, 212));
definedRGBColorsCSS3.put("azure", new RGB(240, 255, 255));
definedRGBColorsCSS3.put("beige", new RGB(245, 245, 220));
definedRGBColorsCSS3.put("bisque", new RGB(255, 228, 196));
definedRGBColorsCSS3.put("black", new RGB(0, 0, 0));
definedRGBColorsCSS3.put("blanchedalmond", new RGB(255, 235, 205));
definedRGBColorsCSS3.put("blue", new RGB(0, 0, 255));
definedRGBColorsCSS3.put("blueviolet", new RGB(138, 43, 226));
definedRGBColorsCSS3.put("brown", new RGB(165, 42, 42));
definedRGBColorsCSS3.put("burlywood", new RGB(222, 184, 135));
definedRGBColorsCSS3.put("cadetblue", new RGB(95, 158, 160));
definedRGBColorsCSS3.put("chartreuse", new RGB(127, 255, 0));
definedRGBColorsCSS3.put("chocolate", new RGB(210, 105, 30));
definedRGBColorsCSS3.put("coral", new RGB(255, 127, 80));
definedRGBColorsCSS3.put("cornflowerblue", new RGB(100, 149, 237));
definedRGBColorsCSS3.put("cornsilk", new RGB(255, 248, 220));
definedRGBColorsCSS3.put("crimson", new RGB(220, 20, 60));
definedRGBColorsCSS3.put("cyan", new RGB(0, 255, 255));
definedRGBColorsCSS3.put("darkblue", new RGB(0, 0, 139));
definedRGBColorsCSS3.put("darkcyan", new RGB(0, 139, 139));
definedRGBColorsCSS3.put("darkgoldenrod", new RGB(184, 134, 11));
definedRGBColorsCSS3.put("darkgray", new RGB(169, 169, 169));
definedRGBColorsCSS3.put("darkgreen", new RGB(0, 100, 0));
definedRGBColorsCSS3.put("darkgrey", new RGB(169, 169, 169));
definedRGBColorsCSS3.put("darkkhaki", new RGB(189, 183, 107));
definedRGBColorsCSS3.put("darkmagenta", new RGB(139, 0, 139));
definedRGBColorsCSS3.put("darkolivegreen", new RGB(85, 107, 47));
definedRGBColorsCSS3.put("darkorange", new RGB(255, 140, 0));
definedRGBColorsCSS3.put("darkorchid", new RGB(153, 50, 204));
definedRGBColorsCSS3.put("darkred", new RGB(139, 0, 0));
definedRGBColorsCSS3.put("darksalmon", new RGB(233, 150, 122));
definedRGBColorsCSS3.put("darkseagreen", new RGB(143, 188, 143));
definedRGBColorsCSS3.put("darkslateblue", new RGB(72, 61, 139));
definedRGBColorsCSS3.put("darkslategray", new RGB(47, 79, 79));
definedRGBColorsCSS3.put("darkslategrey", new RGB(47, 79, 79));
definedRGBColorsCSS3.put("darkturquoise", new RGB(0, 206, 209));
definedRGBColorsCSS3.put("darkviolet", new RGB(148, 0, 211));
definedRGBColorsCSS3.put("deeppink", new RGB(255, 20, 147));
definedRGBColorsCSS3.put("deepskyblue", new RGB(0, 191, 255));
definedRGBColorsCSS3.put("dimgray", new RGB(105, 105, 105));
definedRGBColorsCSS3.put("dimgrey", new RGB(105, 105, 105));
definedRGBColorsCSS3.put("dodgerblue", new RGB(30, 144, 255));
definedRGBColorsCSS3.put("firebrick", new RGB(178, 34, 34));
definedRGBColorsCSS3.put("floralwhite", new RGB(255, 250, 240));
definedRGBColorsCSS3.put("forestgreen", new RGB(34, 139, 34));
definedRGBColorsCSS3.put("fuchsia", new RGB(255, 0, 255));
definedRGBColorsCSS3.put("gainsboro", new RGB(220, 220, 220));
definedRGBColorsCSS3.put("ghostwhite", new RGB(248, 248, 255));
definedRGBColorsCSS3.put("gold", new RGB(255, 215, 0));
definedRGBColorsCSS3.put("goldenrod", new RGB(218, 165, 32));
definedRGBColorsCSS3.put("gray", new RGB(128, 128, 128));
definedRGBColorsCSS3.put("green", new RGB(0, 128, 0));
definedRGBColorsCSS3.put("greenyellow", new RGB(173, 255, 47));
definedRGBColorsCSS3.put("grey", new RGB(128, 128, 128));
definedRGBColorsCSS3.put("honeydew", new RGB(240, 255, 240));
definedRGBColorsCSS3.put("hotpink", new RGB(255, 105, 180));
definedRGBColorsCSS3.put("indianred", new RGB(205, 92, 92));
definedRGBColorsCSS3.put("indigo", new RGB(75, 0, 130));
definedRGBColorsCSS3.put("ivory", new RGB(255, 255, 240));
definedRGBColorsCSS3.put("khaki", new RGB(240, 230, 140));
definedRGBColorsCSS3.put("lavender", new RGB(230, 230, 250));
definedRGBColorsCSS3.put("lavenderblush", new RGB(255, 240, 245));
definedRGBColorsCSS3.put("lawngreen", new RGB(124, 252, 0));
definedRGBColorsCSS3.put("lemonchiffon", new RGB(255, 250, 205));
definedRGBColorsCSS3.put("lightblue", new RGB(173, 216, 230));
definedRGBColorsCSS3.put("lightcoral", new RGB(240, 128, 128));
definedRGBColorsCSS3.put("lightcyan", new RGB(224, 255, 255));
definedRGBColorsCSS3.put("lightgoldenrodyellow", new RGB(250, 250, 210));
definedRGBColorsCSS3.put("lightgray", new RGB(211, 211, 211));
definedRGBColorsCSS3.put("lightgreen", new RGB(144, 238, 144));
definedRGBColorsCSS3.put("lightgrey", new RGB(211, 211, 211));
definedRGBColorsCSS3.put("lightpink", new RGB(255, 182, 193));
definedRGBColorsCSS3.put("lightsalmon", new RGB(255, 160, 122));
definedRGBColorsCSS3.put("lightseagreen", new RGB(32, 178, 170));
definedRGBColorsCSS3.put("lightskyblue", new RGB(135, 206, 250));
definedRGBColorsCSS3.put("lightslategray", new RGB(119, 136, 153));
definedRGBColorsCSS3.put("lightslategrey", new RGB(119, 136, 153));
definedRGBColorsCSS3.put("lightsteelblue", new RGB(176, 196, 222));
definedRGBColorsCSS3.put("lightyellow", new RGB(255, 255, 224));
definedRGBColorsCSS3.put("lime", new RGB(0, 255, 0));
definedRGBColorsCSS3.put("limegreen", new RGB(50, 205, 50));
definedRGBColorsCSS3.put("linen", new RGB(250, 240, 230));
definedRGBColorsCSS3.put("magenta", new RGB(255, 0, 255));
definedRGBColorsCSS3.put("maroon", new RGB(128, 0, 0));
definedRGBColorsCSS3.put("mediumaquamarine", new RGB(102, 205, 170));
definedRGBColorsCSS3.put("mediumblue", new RGB(0, 0, 205));
definedRGBColorsCSS3.put("mediumorchid", new RGB(186, 85, 211));
definedRGBColorsCSS3.put("mediumpurple", new RGB(147, 112, 219));
definedRGBColorsCSS3.put("mediumseagreen", new RGB(60, 179, 113));
definedRGBColorsCSS3.put("mediumslateblue", new RGB(123, 104, 238));
definedRGBColorsCSS3.put("mediumspringgreen", new RGB(0, 250, 154));
definedRGBColorsCSS3.put("mediumturquoise", new RGB(72, 209, 204));
definedRGBColorsCSS3.put("mediumvioletred", new RGB(199, 21, 133));
definedRGBColorsCSS3.put("midnightblue", new RGB(25, 25, 112));
definedRGBColorsCSS3.put("mintcream", new RGB(245, 255, 250));
definedRGBColorsCSS3.put("mistyrose", new RGB(255, 228, 225));
definedRGBColorsCSS3.put("moccasin", new RGB(255, 228, 181));
definedRGBColorsCSS3.put("navajowhite", new RGB(255, 222, 173));
definedRGBColorsCSS3.put("navy", new RGB(0, 0, 128));
definedRGBColorsCSS3.put("oldlace", new RGB(253, 245, 230));
definedRGBColorsCSS3.put("olive", new RGB(128, 128, 0));
definedRGBColorsCSS3.put("olivedrab", new RGB(107, 142, 35));
definedRGBColorsCSS3.put("orange", new RGB(255, 165, 0));
definedRGBColorsCSS3.put("orangered", new RGB(255, 69, 0));
definedRGBColorsCSS3.put("orchid", new RGB(218, 112, 214));
definedRGBColorsCSS3.put("palegoldenrod", new RGB(238, 232, 170));
definedRGBColorsCSS3.put("palegreen", new RGB(152, 251, 152));
definedRGBColorsCSS3.put("paleturquoise", new RGB(175, 238, 238));
definedRGBColorsCSS3.put("palevioletred", new RGB(219, 112, 147));
definedRGBColorsCSS3.put("papayawhip", new RGB(255, 239, 213));
definedRGBColorsCSS3.put("peachpuff", new RGB(255, 218, 185));
definedRGBColorsCSS3.put("peru", new RGB(205, 133, 63));
definedRGBColorsCSS3.put("pink", new RGB(255, 192, 203));
definedRGBColorsCSS3.put("plum", new RGB(221, 160, 221));
definedRGBColorsCSS3.put("powderblue", new RGB(176, 224, 230));
definedRGBColorsCSS3.put("purple", new RGB(128, 0, 128));
definedRGBColorsCSS3.put("rebeccapurple", new RGB(102, 51, 153));
definedRGBColorsCSS3.put("red", new RGB(255, 0, 0));
definedRGBColorsCSS3.put("rosybrown", new RGB(188, 143, 143));
definedRGBColorsCSS3.put("royalblue", new RGB(65, 105, 225));
definedRGBColorsCSS3.put("saddlebrown", new RGB(139, 69, 19));
definedRGBColorsCSS3.put("salmon", new RGB(250, 128, 114));
definedRGBColorsCSS3.put("sandybrown", new RGB(244, 164, 96));
definedRGBColorsCSS3.put("seagreen", new RGB(46, 139, 87));
definedRGBColorsCSS3.put("seashell", new RGB(255, 245, 238));
definedRGBColorsCSS3.put("sienna", new RGB(160, 82, 45));
definedRGBColorsCSS3.put("silver", new RGB(192, 192, 192));
definedRGBColorsCSS3.put("skyblue", new RGB(135, 206, 235));
definedRGBColorsCSS3.put("slateblue", new RGB(106, 90, 205));
definedRGBColorsCSS3.put("slategray", new RGB(112, 128, 144));
definedRGBColorsCSS3.put("slategrey", new RGB(112, 128, 144));
definedRGBColorsCSS3.put("snow", new RGB(255, 250, 250));
definedRGBColorsCSS3.put("springgreen", new RGB(0, 255, 127));
definedRGBColorsCSS3.put("steelblue", new RGB(70, 130, 180));
definedRGBColorsCSS3.put("tan", new RGB(210, 180, 140));
definedRGBColorsCSS3.put("teal", new RGB(0, 128, 128));
definedRGBColorsCSS3.put("thistle", new RGB(216, 191, 216));
definedRGBColorsCSS3.put("tomato", new RGB(255, 99, 71));
definedRGBColorsCSS3.put("turquoise", new RGB(64, 224, 208));
definedRGBColorsCSS3.put("violet", new RGB(238, 130, 238));
definedRGBColorsCSS3.put("wheat", new RGB(245, 222, 179));
definedRGBColorsCSS3.put("white", new RGB(255, 255, 255));
definedRGBColorsCSS3.put("whitesmoke", new RGB(245, 245, 245));
definedRGBColorsCSS3.put("yellow", new RGB(255, 255, 0));
definedRGBColorsCSS3.put("yellowgreen", new RGB(154, 205, 50));
}
}
| 59.535354 | 81 | 0.657024 |
577e6abd50d8787bf4ed2f1725c6facd3ecc3b61 | 594 | package org.cleanas2.util;
/**
* Holder for system constants. Gotta be a better way
*
* @author Andrew Backer {@literal [email protected] / [email protected]}
*/
public class Constants {
public static final String APP_NAME = "CleanAS2"; // app name without spaces
public static final String APP_VERSION = "0.9";
public static final String AS2_SERVER_SENDER_NAME = APP_NAME + "Server/" + APP_VERSION;
public static final String AS2_PROTOCOL_VERSION = "1.1";
public static final String MIME_VERSION_1_0 = "1.0";
public static final String CRLF = "\r\n";
}
| 37.125 | 91 | 0.718855 |
d23dd32d3e9ff194732133cc77d71a151c409e9d | 172 | package com.erc.his;
public class Application {
public static void main(String... args) {
MenuFrame menuFrame = new MenuFrame();
menuFrame.startApplication();
}
}
| 15.636364 | 42 | 0.715116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.