text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
package py.com.snowtech.patterns.behavioral; import java.util.ArrayList; import java.util.List; /** * Memento pattern is used to reduce where we want to restore state of an object * to a previous state. Memento pattern falls under behavioral pattern category. * * Memento pattern uses three actor classes. Memento contains state of an object * to be restored. Originator creates and stores states in Memento objects and * Caretaker object which is responsible to restore object state from Memento. * * We've created classes Memento, Originator and CareTaker. * MementoPatternDemo, our demo class will use CareTaker and Originator objects * to show restoration of object states. * * @author cristhian * */ class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } } class Originator { private String state; public void setState(String state) { this.state = state; } public String getState() { return state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento Memento) { state = Memento.getState(); } } class CareTaker { private List<Memento> mementoList = new ArrayList<>(); public void add(Memento state) { mementoList.add(state); } public Memento get(int index) { return mementoList.get(index); } } public class MementoPattern { public static void main(String[] args) { Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState("State #1"); originator.setState("State #2"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #3"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #4"); System.out.println("Current State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(0)); System.out.println("First saved State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(1)); System.out.println("Second saved State: " + originator.getState()); } }
Java
CL
6a15700f0a495713f8d8e833b94e6e65245f244ada4c1d3d653ec77ff7668420
/* * */ package org.xmlgen.context; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; /** * The Class FrameStack. * * @author Didier Garcin */ public class FrameStack implements Map<String, Object> { /** The stack. */ Stack<Frame> stack = new Stack<Frame>(); /** * Instantiates a new frame stack. * * @param frameName * the frame name */ public FrameStack(String frameName) { stack.push(new Frame(frameName)); pushNumbering(); } /** * Gets frames count * @return the number of frames */ public int framesCount() { return stack.size(); } /** * Gets the frame at * * @param index * @return the frame at index */ public Frame elementAt(int index) { return stack.elementAt(index); } /** * Clear top frame. */ @Override public void clear() { stack.peek().clear(); } /** * Peek. * * @return the frame */ public Frame peek() { return stack.peek(); } /** * Searchs key in all Frame Stack (not only the top frame). * * @param key * the key * @return true, if successful */ @Override public boolean containsKey(Object key) { String keyStr = (String) key; boolean found = false; int i = stack.size()-1; while (!found && i >= 0) { found = stack.elementAt(i).containsKey(keyStr); i--; } return found; } /** * Returns if stack frame contains value. * * @param value * the value * @return true, if successful */ @Override public boolean containsValue(Object value) { boolean notFound; int i = stack.size(); do { i--; notFound = stack.elementAt(i).containsValue(value); } while (notFound || i > 0); return !notFound; } /** * Apply Map<K,V>.get(Object key) on the stack beginning by the top. * * @param key * the key * @return the object */ @Override public Object get(Object key) { int i = stack.size(); Object value = null; boolean found = false; while (!found && i > 0) { i--; Frame frame = stack.elementAt(i); found = frame.containsKey(key); if (found) { value = stack.elementAt(i).get(key); } } return value; } /** * Check if frame stack is empty. Should always return false. * * @return true, if is empty */ @Override public boolean isEmpty() { return stack.isEmpty(); } /** * Returns all reference names. * * @return the sets the */ @Override public Set<String> keySet() { ; Set<String> values = new HashSet<String>(100); for (int i = stack.size() - 1; i >= 0; i--) { values.addAll(stack.elementAt(i).keySet()); } return values; } /** * Put value on top frame. * * @param key * the key * @param value * the value * @return the object */ @Override public Object put(String key, Object value) { return stack.peek().put(key, value); } /** * putAll in the top frame. * * @param m * the m */ @Override public void putAll(Map<? extends String, ? extends Object> m) { stack.peek().putAll(m); } /** * remove from the top frame. * * @param key * the key * @return the object */ @Override public Object remove(Object key) { return stack.peek().remove(key); } /* * (non-Javadoc) * * @see java.util.Map#size() */ @Override /* * Returns size of stack as a large Map */ public int size() { int size = 0; for (int i = 0; i < stack.size(); i++) { size += stack.elementAt(i).size(); } return size; } /* * (non-Javadoc) * * @see java.util.Map#values() */ @Override public Collection<Object> values() { int i = stack.size() - 1; @SuppressWarnings("unchecked") Collection<Object> values = (Collection<Object>) stack.elementAt(i); for (i--; i >= 0; i--) { @SuppressWarnings("unchecked") Collection<Object> otherValues = (Collection<Object>) stack.elementAt(i); values.addAll(otherValues); } return values; } /** * Push frame on stack. * * @param frame * the frame */ public void push(Frame frame) { Integer level = numbering.peek() + 1; numbering.set(numbering.size() - 1, level); frame.setLevel(numberingToString()); stack.push(frame); } /** * Pop frame from stack. */ public void pop() { stack.pop(); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { String string = ""; for (String key : keySet()) { string += '(' + key + ", " + get(key) + ")\n"; } return string; } /** * Returns top frame's entry set. * * @return the sets the */ @Override public Set<java.util.Map.Entry<String, Object>> entrySet() { HashMap<String, Object> identifiers = new HashMap<String, Object>(size()); ArrayList<java.util.Map.Entry<String, Object>> copy = new ArrayList<java.util.Map.Entry<String, Object>>(size()); for (int i = stack.size() - 1; i >= 0; i--) { for (Entry<String, Object> e : stack.elementAt(i).entrySet()) { String identifier = e.getKey(); if (!identifiers.containsKey(identifier)) { Object value = e.getValue(); copy.add(new MyEntry<String, Object>(identifier, value)); identifiers.put(identifier, null); } } } return new HashSet<java.util.Map.Entry<String, Object>>(copy); } /** * The Class MyEntry. * * @param <K> * the key type * @param <V> * the value type */ final class MyEntry<K, V> implements Map.Entry<K, V> { /** The key. */ private final K key; /** The value. */ private V value; /** * Instantiates a new my entry. * * @param key * the key * @param value * the value */ public MyEntry(K key, V value) { this.key = key; this.value = value; } /* * (non-Javadoc) * * @see java.util.Map.Entry#getKey() */ @Override public K getKey() { return key; } /* * (non-Javadoc) * * @see java.util.Map.Entry#getValue() */ @Override public V getValue() { return value; } /* * (non-Javadoc) * * @see java.util.Map.Entry#setValue(java.lang.Object) */ @Override public V setValue(V value) { V old = this.value; this.value = value; return old; } } public void pushNumbering() { numbering.push(0); } public void popNumbering() { numbering.pop(); } protected String numberingToString() { String numberingStr = numbering.firstElement().toString(); for (int i = 1; i < numbering.size(); i++) { numberingStr += "." + numbering.elementAt(i).toString(); } return numberingStr; } private Stack<Integer> numbering = new Stack<Integer>(); }
Java
CL
eb58ecb4a5f102e3b002785a02a5378ce6bf241a5670c20496a386851fbc54dd
package au.com.roadhouse.rxdbflow.rx1.sql.observables; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.runtime.FlowContentObserver; import com.raizlabs.android.dbflow.sql.language.SQLOperator; import com.raizlabs.android.dbflow.sql.queriable.ModelQueriable; import com.raizlabs.android.dbflow.structure.BaseModel; import com.raizlabs.android.dbflow.structure.BaseQueryModel; import com.raizlabs.android.dbflow.structure.Model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.Observable; import rx.Subscriber; /** * Given a RxSQLite query, emits the the first element from the query as a custom model. */ public class DBFlowCustomModelObservable<TQueryModel extends BaseQueryModel, TModel> extends Observable<TQueryModel> { private final Class<TQueryModel> mModelClazz; private final ModelQueriable<TModel> mBaseModelQueriable; private List<Class<? extends Model>> mSubscribedClasses; /** * Creates a new observable which runs a query and emits the first element in the result set as a CustomModel * @param clazz The table/view model in which the FlowCursorList will contain * @param baseModelQueriable The query to run */ public DBFlowCustomModelObservable(Class<TQueryModel> clazz, ModelQueriable<TModel> baseModelQueriable) { super(new OnDBFlowSubscribeWithChanges<>(clazz, baseModelQueriable)); mModelClazz = clazz; mBaseModelQueriable = baseModelQueriable; mSubscribedClasses = new ArrayList<>(); } /** * Observes changes on the current table, restarts the query on change, and emits the updated * query result to any subscribers * @param tableToListen The tables to observe for changes * @return An observable which observes any changes in the specified tables */ @SafeVarargs public final Observable<TQueryModel> restartOnChange(Class<? extends Model>... tableToListen){ Collections.addAll(mSubscribedClasses, tableToListen); return lift(new DBFlowOnChangeOperator()); } /** * Forces onComplete to be called upon returning with a result, therefore automatically * unsubscribing the subscription. This should be used when you're only interested in a * single result i.e. not using {@link #restartOnChange(Class[])}. * If this is not used, the subscriber will be responsible for unsubscribing * @return An observable which will call onComplete once the result has returned. */ public Observable<TQueryModel> completeOnResult(){ return lift(new CompleteOnResultOperator<TQueryModel>()); } private static class OnDBFlowSubscribeWithChanges<AQueryModel extends BaseQueryModel, TModel> implements OnSubscribe<AQueryModel> { private final Class<AQueryModel> mClazz; private final ModelQueriable<TModel> mBaseModelQueriable; OnDBFlowSubscribeWithChanges(Class<AQueryModel> clazz, ModelQueriable<TModel> baseModelQueriable) { mBaseModelQueriable = baseModelQueriable; mClazz = clazz; } @Override public void call(final Subscriber<? super AQueryModel> subscriber) { subscriber.onNext(mBaseModelQueriable.queryCustomSingle(mClazz)); } } private class DBFlowOnChangeOperator implements Operator<TQueryModel, TQueryModel> { private FlowContentObserver mFlowContentObserver; public DBFlowOnChangeOperator() { mFlowContentObserver = new FlowContentObserver(); } @Override public Subscriber<? super TQueryModel> call(final Subscriber<? super TQueryModel> subscriber) { return new Subscriber<TQueryModel>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(TQueryModel tModels) { for (int i = 0; i < mSubscribedClasses.size(); i++) { mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i)); } mFlowContentObserver.addModelChangeListener(new FlowContentObserver.OnModelStateChangedListener() { @Override public void onModelStateChanged(@Nullable Class<?> table, BaseModel.Action action, @NonNull SQLOperator[] primaryKeyValues) { if (subscriber.isUnsubscribed()) { mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext()); } else { subscriber.onNext(mBaseModelQueriable.queryCustomSingle(mModelClazz)); } } }); } }; } } }
Java
CL
19e9421c776fe6a1c7ef9344370805887d754867441a3be4eb0a1fbcc48c91c2
package com.eas.application; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import com.eas.client.AppClient; import com.eas.client.CallbackAdapter; import com.eas.client.GroupingHandlerRegistration; import com.eas.client.PlatypusLogFormatter; import com.eas.core.Predefine; import com.eas.core.Utils; import com.eas.ui.JsUi; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.ScriptInjector; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; import com.google.gwt.dom.client.ScriptElement; /** * * @author mg */ public class Application { protected static class LoggingLoadHandler implements Loader.LoadHandler { public LoggingLoadHandler() { super(); } @Override public void started(String anItemName) { final String message = "Loading... " + anItemName; Predefine.platypusApplicationLogger.log(Level.INFO, message); } @Override public void loaded(String anItemName) { final String message = anItemName + " - Loaded"; Predefine.platypusApplicationLogger.log(Level.INFO, message); } } protected static GroupingHandlerRegistration loaderHandlerRegistration = new GroupingHandlerRegistration(); public static void run() throws Exception { Formatter f = new PlatypusLogFormatter(true); Handler[] handlers = Logger.getLogger("").getHandlers(); for (Handler h : handlers) { h.setFormatter(f); } Predefine.init(); JsApi.init(); JsUi.init(); loaderHandlerRegistration.add(Loader.addHandler(new LoggingLoadHandler())); NodeList<Element> scriptTags = Document.get().getElementsByTagName("script"); String init = null; String entryPoint = null; String sourcePrefix = null; boolean simpleModules = false; int gwtScripts = 0; for (int s = 0; s < scriptTags.getLength() && gwtScripts < 2; s++) { ScriptElement script = scriptTags.getItem(s).cast(); if (script.getSrc().endsWith("pwc.nocache.js")) { gwtScripts++; if (script.hasAttribute("init")) { init = script.getAttribute("init"); if (!init.toLowerCase().endsWith(".js")) { init += ".js"; } } if (script.hasAttribute("entry-point")) { entryPoint = script.getAttribute("entry-point"); if (!entryPoint.toLowerCase().endsWith(".js")) { entryPoint += ".js"; } } if (script.hasAttribute("source-path")) { sourcePrefix = script.getAttribute("source-path").toLowerCase(); } simpleModules = script.hasAttribute("simple-modules"); } } AppClient.setSimpleModules(simpleModules); AppClient.setSourcePath(sourcePrefix); if (entryPoint != null && !entryPoint.isEmpty()) { if (init != null && !init.isEmpty()) { final String _entryPoint = entryPoint; ScriptInjector.fromUrl(AppClient.relativeUri() + AppClient.getSourcePath() + init).setWindow(ScriptInjector.TOP_WINDOW).setRemoveTag(true).setCallback(new Callback<Void, Exception>() { @Override public void onFailure(Exception reason) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, "Error while initializing modules loader", reason); } @Override public void onSuccess(Void result) { ScriptInjector.fromUrl(AppClient.relativeUri() + AppClient.getSourcePath() + _entryPoint).setWindow(ScriptInjector.TOP_WINDOW).setRemoveTag(true).inject(); } }).inject(); } else { ScriptInjector.fromUrl(AppClient.relativeUri() + AppClient.getSourcePath() + entryPoint).setWindow(ScriptInjector.TOP_WINDOW).setRemoveTag(true).inject(); } } else { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, "\"entry-point\" attribute missing while initializing modules loader"); } } private static JavaScriptObject lookupResolved(List<String> deps) { Map<String, JavaScriptObject> defined = Loader.getDefined(); Utils.JsObject resolved = JavaScriptObject.createArray().cast(); for (int d = 0; d < deps.size(); d++) { String mName = deps.get(d); JavaScriptObject m = defined.get(mName); resolved.setSlot(d, m != null ? m : Loader.lookupInGlobal(mName)); } return resolved; } public static JavaScriptObject require(final Utils.JsObject aDeps, final Utils.JsObject aOnSuccess, final Utils.JsObject aOnFailure) throws Exception { String calledFromDir = Utils.lookupCallerJsDir(); final List<String> deps = new ArrayList<String>(); for (int i = 0; i < aDeps.length(); i++) { String dep = aDeps.getString(i); if (calledFromDir != null && dep.startsWith("./") || dep.startsWith("../")) { dep = AppClient.toFilyAppModuleId(dep, calledFromDir); } if (dep.toLowerCase().endsWith(".js")) { dep = dep.substring(0, dep.length() - 3); } deps.add(dep); } Loader.load(deps, new CallbackAdapter<Void, String>() { @Override public void onFailure(String reason) { if (aOnFailure != null) { try { Utils.executeScriptEventString(aOnFailure, aOnFailure, reason); } catch (Exception ex) { Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex); } } else { Logger.getLogger(Application.class.getName()).log(Level.WARNING, "Require failed and callback is missing. Required modules are: " + aDeps.toString()); } } @Override protected void doWork(Void aResult) throws Exception { if (aOnSuccess != null) { JavaScriptObject resolved = lookupResolved(deps); aOnSuccess.apply(null, resolved); } else Logger.getLogger(Application.class.getName()).log(Level.WARNING, "Require succeded, but callback is missing. Required modules are: " + aDeps.toString()); } }, new HashSet<String>()); return lookupResolved(deps); } public static void define(String aModuleName, final Utils.JsObject aDeps, final Utils.JsObject aModuleDefiner) { String calledFromFile = Utils.lookupCallerJsFile(); int lastSlashIndex = calledFromFile.lastIndexOf('/'); String calledFromDir = calledFromFile.substring(0, lastSlashIndex); String calledFromFileShort = calledFromFile.substring(lastSlashIndex + 1, calledFromFile.length()); final List<String> deps = new ArrayList<String>(); for (int i = 0; i < aDeps.length(); i++) { String dep = aDeps.getString(i); if (calledFromDir != null && dep.startsWith("./") || dep.startsWith("../")) { dep = AppClient.toFilyAppModuleId(dep, calledFromDir); } if (dep.endsWith(".js")) { dep = dep.substring(0, dep.length() - 3); } deps.add(dep); } if (aModuleName == null) { aModuleName = AppClient.toFilyAppModuleId("./" + calledFromFileShort, calledFromDir); if (aModuleName.endsWith(".js")) { aModuleName = aModuleName.substring(0, aModuleName.length() - 3); } } Loader.addAmdDefine(aModuleName, deps, new Callback<String, Void>() { @Override public void onSuccess(String aModuleName) { Map<String, JavaScriptObject> defined = Loader.getDefined(); Utils.JsObject resolved = JavaScriptObject.createArray().cast(); for (int d = 0; d < deps.size(); d++) { String mName = deps.get(d); JavaScriptObject m = defined.get(mName); resolved.setSlot(d, m != null ? m : Loader.lookupInGlobal(mName)); } resolved.setSlot(deps.size(), aModuleName); JavaScriptObject module = (JavaScriptObject) aModuleDefiner.apply(null, resolved); defined.put(aModuleName, module); } @Override public void onFailure(Void reason) { // no op } }); } }
Java
CL
9bfcf4f1758af6ba91b6c4ecd275e92068d0646543bbb8db1e72afaf060788c4
// isComment package it.sasabz.android.sasabus.ui; import android.Manifest; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.SwitchPreference; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.Toast; import it.sasabz.android.sasabus.AppApplication; import it.sasabz.android.sasabus.R; import it.sasabz.android.sasabus.receiver.BluetoothReceiver; import it.sasabz.android.sasabus.receiver.LocationReceiver; import it.sasabz.android.sasabus.ui.departure.DepartureActivity; import it.sasabz.android.sasabus.ui.widget.PreferenceFragment; import it.sasabz.android.sasabus.util.AnalyticsHelper; import it.sasabz.android.sasabus.util.Settings; import it.sasabz.android.sasabus.util.Utils; import timber.log.Timber; /** * isComment */ public class isClassOrIsInterface extends AppCompatActivity { private static final String isVariable = "isStringConstant"; private final String[] isVariable = { "isStringConstant", "isStringConstant", "isStringConstant", "isStringConstant", "isStringConstant", "isStringConstant" }; private int isVariable; private static boolean isVariable; @Override protected void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isNameExpr.isMethod(this); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr); Toolbar isVariable = (Toolbar) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isMethod(isNameExpr); assert isMethod() != null; isMethod().isMethod(true); isNameExpr.isMethod(isParameter -> isMethod()); Intent isVariable = isMethod(); isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, new PreferenceMenuFragment()).isMethod(); if (isNameExpr.isMethod("isStringConstant") != null) { isMethod(true); } else { isNameExpr = true; } if (isNameExpr != null) { isNameExpr = isNameExpr.isMethod("isStringConstant"); Fragment isVariable = isMethod().isMethod(isNameExpr[isNameExpr]); if (isNameExpr == null) { isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, new PreferenceMenuFragment()).isMethod(); } else { isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isNameExpr]).isMethod(isIntegerConstant, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(); } } isNameExpr.isMethod("isStringConstant", (String) null); } @Override public void isMethod() { isMethod(); } @Override protected void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isNameExpr.isMethod("isStringConstant", isNameExpr); } /** * isComment */ private void isMethod() { FragmentManager isVariable = isMethod(); if (isNameExpr.isMethod() > isIntegerConstant) { isNameExpr.isMethod(); isNameExpr = isIntegerConstant; } else { if (isNameExpr) { Intent isVariable = new Intent(this, DepartureActivity.class); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr | isNameExpr.isFieldAccessExpr); isMethod(isNameExpr); } else { isMethod(); } } } /** * isComment */ private void isMethod(boolean isParameter) { isNameExpr = isIntegerConstant; Fragment isVariable = new AppearanceFragment(); FragmentTransaction isVariable = isMethod().isMethod(); if (isNameExpr) { isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } else { isNameExpr.isMethod(isIntegerConstant, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isIntegerConstant]).isMethod(isNameExpr[isIntegerConstant]).isMethod(); } /** * isComment */ private void isMethod() { isNameExpr = isIntegerConstant; Fragment isVariable = new MapFragment(); isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isIntegerConstant]).isMethod(isNameExpr[isIntegerConstant]).isMethod(); } /** * isComment */ private void isMethod() { isNameExpr = isIntegerConstant; Fragment isVariable = new BeaconsFragment(); isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isIntegerConstant]).isMethod(isNameExpr[isIntegerConstant]).isMethod(); } /** * isComment */ private void isMethod() { isNameExpr = isIntegerConstant; Fragment isVariable = new NotificationsFragment(); isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isIntegerConstant]).isMethod(isNameExpr[isIntegerConstant]).isMethod(); } /** * isComment */ private void isMethod() { isNameExpr = isIntegerConstant; Fragment isVariable = new AdvancedFragment(); isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isIntegerConstant, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, isNameExpr[isIntegerConstant]).isMethod(isNameExpr[isIntegerConstant]).isMethod(); } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment implements View.OnClickListener { @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr, true); RelativeLayout isVariable = (RelativeLayout) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); RelativeLayout isVariable = (RelativeLayout) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); RelativeLayout isVariable = (RelativeLayout) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); RelativeLayout isVariable = (RelativeLayout) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); RelativeLayout isVariable = (RelativeLayout) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod(this); isNameExpr.isMethod(this); isNameExpr.isMethod(this); isNameExpr.isMethod(this); isNameExpr.isMethod(this); return isNameExpr; } @Override public void isMethod(View isParameter) { switch(isNameExpr.isMethod()) { case isNameExpr.isFieldAccessExpr.isFieldAccessExpr: ((PreferenceActivity) isMethod()).isMethod(true); break; case isNameExpr.isFieldAccessExpr.isFieldAccessExpr: ((PreferenceActivity) isMethod()).isMethod(); break; case isNameExpr.isFieldAccessExpr.isFieldAccessExpr: ((PreferenceActivity) isMethod()).isMethod(); break; case isNameExpr.isFieldAccessExpr.isFieldAccessExpr: ((PreferenceActivity) isMethod()).isMethod(); break; case isNameExpr.isFieldAccessExpr.isFieldAccessExpr: ((PreferenceActivity) isMethod()).isMethod(); break; } } } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment { @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); ListPreference isVariable = (ListPreference) isMethod("isStringConstant"); isNameExpr.isMethod((isParameter, isParameter) -> { isNameExpr = true; isNameExpr.isMethod(isMethod()); Intent isVariable = isMethod().isMethod(); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod("isStringConstant", "isStringConstant"); isMethod().isMethod(); isMethod().isMethod(isIntegerConstant, isIntegerConstant); isMethod(isNameExpr); isMethod().isMethod(isIntegerConstant, isIntegerConstant); return true; }); } @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = super.isMethod(isNameExpr, isNameExpr, isNameExpr); assert isNameExpr != null; isNameExpr.isMethod(isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); return isNameExpr; } } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment { @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); SwitchPreference isVariable = (SwitchPreference) isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod((isParameter, isParameter) -> { isNameExpr = true; return true; }); ListPreference isVariable = (ListPreference) isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod((isParameter, isParameter) -> { isNameExpr = true; return true; }); } @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = super.isMethod(isNameExpr, isNameExpr, isNameExpr); assert isNameExpr != null; isNameExpr.isMethod(isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); return isNameExpr; } } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment { private static final int isVariable = isIntegerConstant; private static final int isVariable = isIntegerConstant; private SwitchPreference isVariable; @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr = (SwitchPreference) isMethod(isNameExpr.isFieldAccessExpr); isNameExpr.isMethod((isParameter, isParameter) -> { boolean isVariable = (boolean) isNameExpr; if (isNameExpr) { isMethod().isMethod().isMethod(new ComponentName(isMethod(), LocationReceiver.class), isNameExpr.isFieldAccessExpr, isIntegerConstant); isMethod().isMethod().isMethod(new ComponentName(isMethod(), BluetoothReceiver.class), isNameExpr.isFieldAccessExpr, isIntegerConstant); isNameExpr.isMethod("isStringConstant"); } else { isMethod().isMethod().isMethod(new ComponentName(isMethod(), LocationReceiver.class), isNameExpr.isFieldAccessExpr, isIntegerConstant); isMethod().isMethod().isMethod(new ComponentName(isMethod(), BluetoothReceiver.class), isNameExpr.isFieldAccessExpr, isIntegerConstant); isNameExpr.isMethod("isStringConstant"); } return !isNameExpr || isMethod(); }); if (!isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr) || isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr) != isNameExpr.isFieldAccessExpr) { isNameExpr.isMethod(true); } } @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = super.isMethod(isNameExpr, isNameExpr, isNameExpr); assert isNameExpr != null; isNameExpr.isMethod(isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); return isNameExpr; } @Override public void isMethod(int isParameter, int isParameter, Intent isParameter) { super.isMethod(isNameExpr, isNameExpr, isNameExpr); if (isNameExpr == isNameExpr) { if (isNameExpr == isNameExpr.isFieldAccessExpr) { ((AppApplication) isMethod().isMethod()).isMethod(); } else { isNameExpr.isMethod(true); } } } @Override public void isMethod(int isParameter, @NonNull String[] isParameter, @NonNull int[] isParameter) { super.isMethod(isNameExpr, isNameExpr, isNameExpr); switch(isNameExpr) { case isNameExpr: if (isNameExpr.isFieldAccessExpr > isIntegerConstant && isNameExpr[isIntegerConstant] == isNameExpr.isFieldAccessExpr) { isNameExpr.isMethod(isMethod()); } else { isNameExpr.isMethod(true); } break; } } boolean isMethod() { BluetoothAdapter isVariable = isNameExpr.isMethod(); if (isNameExpr == null || !isMethod().isMethod().isMethod(isNameExpr.isFieldAccessExpr)) { isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr.isFieldAccessExpr).isMethod(); return true; } if (isNameExpr.isFieldAccessExpr.isFieldAccessExpr >= isNameExpr.isFieldAccessExpr.isFieldAccessExpr && isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr) != isNameExpr.isFieldAccessExpr) { isMethod(new String[] { isNameExpr.isFieldAccessExpr.isFieldAccessExpr }, isNameExpr); return true; } if (!isNameExpr.isMethod()) { Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr); isMethod(isNameExpr, isNameExpr); } else { ((AppApplication) isMethod().isMethod()).isMethod(); } return true; } } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment { @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = super.isMethod(isNameExpr, isNameExpr, isNameExpr); assert isNameExpr != null; isNameExpr.isMethod(isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); return isNameExpr; } } /** * isComment */ public static class isClassOrIsInterface extends PreferenceFragment { @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } @Override public View isMethod(LayoutInflater isParameter, ViewGroup isParameter, Bundle isParameter) { View isVariable = super.isMethod(isNameExpr, isNameExpr, isNameExpr); assert isNameExpr != null; isNameExpr.isMethod(isNameExpr.isMethod(isMethod(), isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); return isNameExpr; } } }
Java
CL
e9727a324fb4afb8bc9c1cc5f6f85174275b759e48e08e647e5204f6e9c82597
package com.cg.common.config.spring; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import com.cg.common.config.date.converter.CustomDateFormat; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; /** * MVC配置 * 拦截器配置 */ @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { protected static final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class); /** * 将当前登录用户自动注入 */ // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new UserArgumentResolver()); // } /** * 为true 路径参数如果带".", 则后面的值将被忽略 默认为true */ @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(false); } /** * 配置全局日期格式转换 */ @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper(); // 请求中有多余的参数不报错 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 设置全局时间转换 DateFormat dateFormat = objectMapper.getDateFormat(); objectMapper.setDateFormat(new CustomDateFormat(dateFormat)); // 设置中文编码格式 List<MediaType> list = new ArrayList<MediaType>(); list.add(MediaType.APPLICATION_JSON_UTF8); jackson2HttpMessageConverter.setSupportedMediaTypes(list); jackson2HttpMessageConverter.setObjectMapper(objectMapper); converters.add(0, jackson2HttpMessageConverter); } }
Java
CL
787526350eab94ae06699f9a24eebc0ff6cadc0d97734db22f988a7a25da91fb
/* * 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 py.com.tesisrgb.generics; import ij.ImagePlus; import ij.io.FileSaver; import ij.process.ByteProcessor; import ij.process.ColorProcessor; import py.com.daas.imagestorage.models.RgbImage; import py.com.daas.imagestorage.utils.RgbImageJpaController; import py.com.tesisrgb.models.Pixel; import py.com.tesisrgb.models.PixelWeight; import py.com.tesisrgb.models.TesisComparator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * * @author Derlis Argüello */ public abstract class BasicFilterAbstract { //jpa components public RgbImageJpaController rgbImageJpaController; public RgbImage rgbImage; public int width; public int height; public ColorProcessor noisyColProcessor; public ColorProcessor restoredColProcessor; public String filterName; public String filter; public Pixel[] se; public String [] components = {"R", "G", "B"}; //defaultOrder public int[] componentsOrder = {0, 1, 2}; public ByteProcessor[] channels = new ByteProcessor[components.length]; public double[] decisionByComp = new double[components.length]; public long [] decisionByCompCounter = new long[components.length]; public double reducedValue = 0; public long reducedValueCounter = 0; public Weight weight; public BasicFilterAbstract(String filter, RgbImage rgbImage, Pixel[] se) { //set noisyColProcessor data rgbImage.setChannelData(); this.filter = filter; this.se = se; this.rgbImage = rgbImage; this.restoredColProcessor = new ColorProcessor(rgbImage.getWidth(), rgbImage.getHeight()); this.noisyColProcessor = rgbImage.getColorProcessor(); this.height = noisyColProcessor.getHeight(); this.width = noisyColProcessor.getWidth(); this.channels = rgbImage.getChannels(); rgbImageJpaController = new RgbImageJpaController(); } public abstract void setWindowsList() throws Exception; public int[] order(double[] weight, Pixel p) { int cLength = channels.length; int x, y; double t = 0.0; int[] rgbColor; List<PixelWeight> orderPixelWeight = new ArrayList<>(); PixelWeight pixelWeight; int[] filterP; for (Pixel sePixel : se) { x = p.getX() + sePixel.getX(); y = p.getY() + sePixel.getY(); //verificamos si esta en la ventana del elemento estructurante if (x > -1 && x < width && y > -1 && y < height) { rgbColor = new int[cLength]; for (int channel = 0; channel < cLength; channel++) { rgbColor[channel] = channels[channel].get(x, y); t = t + weight[channel] * rgbColor[channel]; } pixelWeight = new PixelWeight(rgbColor, t); orderPixelWeight.add(pixelWeight); t = 0.0; } } TesisComparator comparator = new TesisComparator(cLength); //ordenamos por peso Collections.sort(orderPixelWeight, comparator); //logger.debug("orderPixelWeight={}", orderPixelWeight.toString()); for (int i = 0; i < cLength; i++) { decisionByCompCounter[i] += comparator.chooseChannel[i]; } //los valores reducidos reducedValueCounter += comparator.valorReducido; //obtenemos el filtro filterP = getFilter(orderPixelWeight); //logger.debug("filterP={}", Arrays.toString(filterP)); return filterP; } //implementaciones de los filtros public int[] min(List<PixelWeight> orderPixelWeight) { int element = 0; return orderPixelWeight.get(element).getPixel(); } public int[] max(List<PixelWeight> orderPixelWeight) { int element = orderPixelWeight.size() - 1; return orderPixelWeight.get(element).getPixel(); } public int[] median(List<PixelWeight> orderPixelWeight) { int element = (int) Math.ceil(orderPixelWeight.size() / 2); return orderPixelWeight.get(element).getPixel(); } //solicitar tipo de filtro public int[] getFilter(List<PixelWeight> orderPixelWeight){ switch(filter){ case "Min": return min(orderPixelWeight); case "Max": return max(orderPixelWeight); case "Median": return median(orderPixelWeight); default: return null; } } public double[] calculateWeight(int[][] channelHistogram, int numPixels){ return weight.calculateWeight(channelHistogram, numPixels); } public abstract double[] getRealWeight(Pixel p); public abstract Weight getWeight(); public ColorProcessor run() throws Exception { int[] elementP; double[] realWeight; Pixel pixel; long totalDecisiones = 0; setWindowsList(); weight = getWeight(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixel = new Pixel(x, y); realWeight = getRealWeight(pixel); elementP = order(realWeight, pixel); restoredColProcessor.putPixel(x, y, elementP); } } show(); for (int channel = 0; channel < channels.length; channel++) { totalDecisiones = decisionByCompCounter[channel]; } totalDecisiones += reducedValueCounter; for (int i = 0; i < channels.length; i++) { decisionByComp[i] = (double)decisionByCompCounter[i]/(double)totalDecisiones; } reducedValue = (double)reducedValueCounter/(double)totalDecisiones; return restoredColProcessor; } /** * debug */ public void print(){ ImagePlus imgPlus = new ImagePlus(filterName + filter, restoredColProcessor); imgPlus.show(); } /** * for save restored image in disk */ public void save(){ String imgExtension = rgbImage.getExtension(); ImagePlus imgPlus = new ImagePlus(filterName, restoredColProcessor); if (imgExtension.equalsIgnoreCase("png")) { new FileSaver(imgPlus).saveAsPng(filterName + "." + imgExtension); }else if (imgExtension.equalsIgnoreCase("jpg")){ new FileSaver(imgPlus).saveAsJpeg(filterName + "." + imgExtension); } } public void show(){ //save(); }; @Override public String toString() { return "BasicFilterAbstract{" + "rgbImage=" + rgbImage.toString() + ", width=" + width + ", height=" + height + ", filterName=" + filterName + ", filter=" + filter + ", decisionByComp=" + Arrays.toString(decisionByComp) + ", reducedValue=" + reducedValue + '}'; } public void setFilterName(String filterName) { this.filterName = filterName + filter; } }
Java
CL
50fdfe84e40afda29287f4587ce3deefa3a456edb25ba649feb889b1c21741c2
/* * 工具自动生成:VIEWDAO接口 * 生成时间 : 2016/03/10 14:58:49 */ package com.icomp.dao; import com.icomp.common.dao.BaseViewDao; import com.icomp.common.entity.BaseEntity; import com.icomp.entity.base.Vworkshopsummary; import java.sql.SQLException; import java.util.List; /** * 继承父接口 * @author 工具自动生成 * 创建者 :yzq * 更新者 :taoyy * */ public interface VworkshopsummaryDao extends BaseViewDao { public List<Vworkshopsummary> searchByList1(BaseEntity entity) throws SQLException; }
Java
CL
8aa870b616f4f754ba006620e7b5268cd06f94da04622c419b5200ce042c76f3
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package josteo.model.paziente; /** * * @author cristiano */ public class ValutazioneRuleMessages extends josteo.infrastructure.DomainBase.BrokenRuleMessages { @Override protected void PopulateMessages(){ } }
Java
CL
67463aa7facf729652fabd6e7b79ff7ee13fb4006cebbd6813569def76ca7dff
package com.google.codeu.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.codeu.data.Datastore; import com.google.codeu.data.User; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; @WebServlet("/blobstore-upload-url") public class BlobstoreUploadUrlServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); String uploadUrl = blobstoreService.createUploadUrl("/my-form-handler") ; response.setContentType("text/html"); response.getOutputStream().println(uploadUrl); } }
Java
CL
91b5592a6166e1c89dd0e6bc6d0fffa648b65008c2f6097a9007b81dbfc8cba6
package it.greentone.persistence; import java.util.Collection; import javax.inject.Inject; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ca.odell.glazedlists.BasicEventList; import ca.odell.glazedlists.EventList; /** * <code> * GreenTone - gestionale per geometri italiani.<br> * Copyright (C) 2011 GreenTone Developer Team.<br> * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * </code> <br> * <br> * Classe di supporto per l'accesso e gestione di {@link Operation}. * * @author Giuseppe Caliendo */ @Service("operationService") @Transactional(propagation = Propagation.REQUIRED) public class OperationService { @Inject private OperationDAO operationDAO; private final EventList<Operation> allOperationEventList = new BasicEventList<Operation>(); /** * Aggiunge una nuova operazione. * * @param operation * operazione da aggiungere */ public void addOperation(Operation operation) { storeOperation(operation); allOperationEventList.add(operation); } /** * Rende persistente un oggetto nel database. * * @param operation * oggetto da rendere persistente */ public void storeOperation(final Operation operation) { operationDAO.storeOperation(operation); } /** * Elimina l'operazione. * * @param operation * operazione da eliminare */ public void deleteOperation(final Operation operation) { operationDAO.deleteOperation(operation); allOperationEventList.remove(operation); } /** * Restituisce la lista di tutte le operazioni. * * @return la lista di tutte le operazioni * @throws DataAccessException */ public EventList<Operation> getAllOperations() throws DataAccessException { if (allOperationEventList.isEmpty()) allOperationEventList.addAll(operationDAO.getAllOperations()); return allOperationEventList; } /** * Restituisce la lista delle operazioni dell'incarico passato in ingresso. * * @param job * incarico * @return la lista delle operazioni dell'incarico passato in ingresso */ public Collection<Operation> getOperationsJob(Job job) { return operationDAO.getOperationsJob(job); } }
Java
CL
621b9d886231681ce46e4a7ec802ec9bcdc866b377c5bcbdd8117af6fd7eccc5
package com.legstar.test.cixs.redmulti; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.legstar.test.cixs.redmulti package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _RedmultiResponse_QNAME = new QName("http://cixs.test.legstar.com/redmulti", "RedmultiResponse"); private final static QName _RedmultiFaultInfo_QNAME = new QName("http://cixs.test.legstar.com/redmulti", "RedmultiFaultInfo"); private final static QName _RedmultiRequest_QNAME = new QName("http://cixs.test.legstar.com/redmulti", "RedmultiRequest"); private final static QName _RedmultiHostHeader_QNAME = new QName("http://cixs.test.legstar.com/redmulti", "RedmultiHostHeader"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.legstar.test.cixs.redmulti * */ public ObjectFactory() { } /** * Create an instance of {@link RedmultiResponse } * */ public RedmultiResponse createRedmultiResponse() { return new RedmultiResponse(); } /** * Create an instance of {@link RedmultiFaultInfo } * */ public RedmultiFaultInfo createRedmultiFaultInfo() { return new RedmultiFaultInfo(); } /** * Create an instance of {@link RedmultiHostHeader } * */ public RedmultiHostHeader createRedmultiHostHeader() { return new RedmultiHostHeader(); } /** * Create an instance of {@link RedmultiRequest } * */ public RedmultiRequest createRedmultiRequest() { return new RedmultiRequest(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RedmultiResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://cixs.test.legstar.com/redmulti", name = "RedmultiResponse") public JAXBElement<RedmultiResponse> createRedmultiResponse(RedmultiResponse value) { return new JAXBElement<RedmultiResponse>(_RedmultiResponse_QNAME, RedmultiResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RedmultiFaultInfo }{@code >}} * */ @XmlElementDecl(namespace = "http://cixs.test.legstar.com/redmulti", name = "RedmultiFaultInfo") public JAXBElement<RedmultiFaultInfo> createRedmultiFaultInfo(RedmultiFaultInfo value) { return new JAXBElement<RedmultiFaultInfo>(_RedmultiFaultInfo_QNAME, RedmultiFaultInfo.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RedmultiRequest }{@code >}} * */ @XmlElementDecl(namespace = "http://cixs.test.legstar.com/redmulti", name = "RedmultiRequest") public JAXBElement<RedmultiRequest> createRedmultiRequest(RedmultiRequest value) { return new JAXBElement<RedmultiRequest>(_RedmultiRequest_QNAME, RedmultiRequest.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RedmultiHostHeader }{@code >}} * */ @XmlElementDecl(namespace = "http://cixs.test.legstar.com/redmulti", name = "RedmultiHostHeader") public JAXBElement<RedmultiHostHeader> createRedmultiHostHeader(RedmultiHostHeader value) { return new JAXBElement<RedmultiHostHeader>(_RedmultiHostHeader_QNAME, RedmultiHostHeader.class, null, value); } }
Java
CL
25b19ed6332ee8ddf950dde5502741793fa127ff780833ee3e9ead9228533b12
/* * The MIT License * * Copyright 2015 Tim Boudreau. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.mastfrog.giulius.mongodb.reactive; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Provider; /** * * @author Tim Boudreau */ class MongoTypedCollectionProvider<T> implements Provider<MongoCollection<T>> { private final String collectionName; private final Class<T> collectionType; private final Provider<ExistingCollections> knownProvider; private final Provider<MongoClient> client; private final AtomicBoolean initialized; MongoTypedCollectionProvider(String collectionName, Class<T> collectionType, Provider<ExistingCollections> knownProvider, Provider<MongoClient> client) { this.collectionName = collectionName; this.collectionType = collectionType; this.knownProvider = knownProvider; this.client = client; initialized = new AtomicBoolean(); } MongoTypedCollectionProvider(String collectionName, Class<T> collectionType, Provider<ExistingCollections> knownProvider, Provider<MongoClient> client, AtomicBoolean initialized) { this.collectionType = collectionType; this.collectionName = collectionName; this.knownProvider = knownProvider; this.client = client; this.initialized = initialized; } <T> MongoTypedCollectionProvider<T> withType(Class<T> type) { return new MongoTypedCollectionProvider<>(collectionName, type, knownProvider, client, initialized); } @Override public MongoCollection<T> get() { // Ensure we initialize the client outside of a call to // KnownCollections, or we risk deadlock if (initialized.compareAndSet(false, true)) { client.get(); } MongoCollection<T> result = knownProvider.get().get(collectionName).withDocumentClass(collectionType); return result; } }
Java
CL
9a3c430fe71d5246c1d2647a4bee8f557a9d53595d893a6a191529ffdd4b6af5
/** * Copyright 2011 Archfirst * * 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.archfirst.bfoms.interfaceout.exchange.trading; import javax.annotation.Resource; import javax.inject.Inject; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import org.archfirst.bfoms.domain.account.brokerage.order.Order; import org.archfirst.bfoms.domain.exchange.ExchangeMessageGenerator; import org.archfirst.bfoms.domain.exchange.ExchangeTradingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JmsExchangeTradingService * * @author Naresh Bhatia */ public class JmsExchangeTradingService implements ExchangeTradingService { private static final Logger logger = LoggerFactory.getLogger(JmsExchangeTradingService.class); @Resource(mappedName="jms/ConnectionFactory") private ConnectionFactory connectionFactory; @Resource(mappedName="jms/OmsToExchangeQueue") private Destination destination; @Inject private ExchangeMessageGenerator exchangeMessageGenerator; @Override public void placeOrder(Order order) { sendJmsMessage( exchangeMessageGenerator.generateNewOrderSingleMessage(order)); } @Override public void cancelOrder(Order order) { sendJmsMessage( exchangeMessageGenerator.generateOrderCancelRequest(order)); } private void sendJmsMessage(String messageText) { Connection connection = null; try { connection = connectionFactory.createConnection(); Session session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); producer.send(session.createTextMessage(messageText)); } catch (JMSException e) { throw new RuntimeException("Failed to send message to exchange", e); } finally { if (connection != null) try {connection.close();} catch (Exception e) {} } } }
Java
CL
9534bc59543a0bdb05757a96420fac4a99f2385a6e36194e2796d4e7064c49b7
package com.codegans.ai.cup2015.decision; import com.codegans.ai.cup2015.Navigator; import com.codegans.ai.cup2015.Priority; import com.codegans.ai.cup2015.action.Action; import com.codegans.ai.cup2015.action.MoveAction; import com.codegans.ai.cup2015.model.Marker; import com.codegans.ai.cup2015.model.Point; import model.Car; import model.Game; import model.Move; import model.World; import java.util.Collection; import java.util.Collections; /** * JavaDoc here * * @author Victor Polischuk * @since 19.11.2015 10:40 */ public class MoveDecision implements Decision { private static final int WINDOW = 2; @Override public Collection<Action<?>> decide(Car self, World world, Game game, Move move, Navigator navigator) { Collection<Marker> path = navigator.getPath(self, self.getNextWaypointIndex(), WINDOW); Point target = path.stream().map(e -> e.left.shiftTo(e.right, 0)).reduce(new Point(self.getX(), self.getY()), (a, b) -> a.shiftTo(b, 0)); return Collections.singleton(new MoveAction(Priority.NONE, self, target.x, target.y)); } }
Java
CL
9e3f94cee6bc4603fae8393eb3a949e523169b01b584d8b1700adc23ac2a59c3
package com.xuhongxu.xiaoya.Fragment; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import java.util.ArrayList; import com.xuhongxu.Assist.TableCourse; import com.xuhongxu.xiaoya.Adapter.TableCourseRecyclerViewAdapter; import com.xuhongxu.xiaoya.R; import com.xuhongxu.xiaoya.YaApplication; /** * A fragment representing a list of Items. * <p/> * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} * interface. */ public class TableCourseFragment extends Fragment { private OnListFragmentInteractionListener mListener; private YaApplication app = null; RecyclerView recyclerView; ProgressBar progressBar; ArrayList<TableCourse> courses = new ArrayList<>(); String grade = "", level = "", dept = "", spec = ""; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public TableCourseFragment() { } public static TableCourseFragment newInstance(String grade, String level, String dept, String spec) { TableCourseFragment fragment = new TableCourseFragment(); Bundle bundle = new Bundle(); bundle.putString("grade", grade); bundle.putString("level", level); bundle.putString("dept", dept); bundle.putString("spec", spec); fragment.setArguments(bundle); return fragment; } private class QueryTask extends AsyncTask<Void, Void, ArrayList<TableCourse>> { @Override protected ArrayList<TableCourse> doInBackground(Void... voids) { if (app != null) { try { return app.getAssist().getCourseDetails(grade, level, dept, spec); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(ArrayList<TableCourse> result) { progressBar.setVisibility(View.GONE); courses.clear(); if (result != null) { courses.addAll(result); } recyclerView.getAdapter().notifyDataSetChanged(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); grade = getArguments().getString("grade", ""); level = getArguments().getString("level", ""); dept = getArguments().getString("dept", ""); spec = getArguments().getString("spec", ""); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_spec_list, container, false); app = (YaApplication) getActivity().getApplication(); // Set the adapter Context context = view.getContext(); progressBar = (ProgressBar) view.findViewById(R.id.loading); recyclerView = (RecyclerView) view.findViewById(R.id.list); recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.setAdapter(new TableCourseRecyclerViewAdapter(courses, mListener)); progressBar.setVisibility(View.VISIBLE); new QueryTask().execute(); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnListFragmentInteractionListener) { mListener = (OnListFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnListFragmentInteractionListener { void onListFragmentInteraction(TableCourse item); } }
Java
CL
87fc99bae232afa05a57e5a6ee786292a37e1ce094a7d1702b12bf9d9a74e9da
/* * Copyright 2021 Arcade Data Ltd * * 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 com.arcadedb.mongodbw; import com.arcadedb.database.Database; import com.arcadedb.schema.DocumentType; import com.arcadedb.server.ArcadeDBServer; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.CollectionOptions; import de.bwaldvogel.mongo.backend.QueryResult; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.oplog.Oplog; import de.bwaldvogel.mongo.wire.message.MongoDelete; import de.bwaldvogel.mongo.wire.message.MongoInsert; import de.bwaldvogel.mongo.wire.message.MongoQuery; import de.bwaldvogel.mongo.wire.message.MongoUpdate; import io.netty.channel.Channel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; public class MongoDBDatabaseWrapper implements MongoDatabase { protected final ArcadeDBServer server; protected final Database database; protected final MongoBackend backend; protected final Map<String, MongoCollection<Long>> collections = new ConcurrentHashMap(); protected final Map<Channel, List<Document>> lastResults = new ConcurrentHashMap(); public MongoDBDatabaseWrapper(final ArcadeDBServer server, final String databaseName, final MongoBackend backend) { this.server = server; this.database = server.getDatabase(databaseName); this.backend = backend; for (DocumentType dt : database.getSchema().getTypes()) { collections.put(dt.getName(), new MongoDBCollectionWrapper(server, database, dt.getName())); } } @Override public String getDatabaseName() { return database.getName(); } @Override public void handleClose(Channel channel) { database.close(); } @Override public Document handleCommand(Channel channel, String command, Document document, final Oplog opLog) throws MongoServerException { try { if (command.equalsIgnoreCase("create")) return createCollection(document); else if (command.equalsIgnoreCase("count")) return countCollection(document); else if (command.equalsIgnoreCase("insert")) return insertDocument(channel, document); else { server.log(this, Level.SEVERE, "Received unsupported command from MongoDB client '%s', (document=%s)", command, document); throw new UnsupportedOperationException(String.format("Received unsupported command from MongoDB client '%s', (document=%s)", command, document)); } } catch (Exception e) { throw new MongoServerException("Error on executing MongoDB '" + command + "' command", e); } } @Override public QueryResult handleQuery(final MongoQuery query) throws MongoServerException { try { this.clearLastStatus(query.getChannel()); final String collectionName = query.getCollectionName(); final MongoCollection<Long> collection = collections.get(collectionName); if (collection == null) { return new QueryResult(); } else { int numSkip = query.getNumberToSkip(); int numReturn = query.getNumberToReturn(); return collection.handleQuery(query.getQuery(), numSkip, numReturn); } } catch (Exception e) { throw new MongoServerException("Error on executing MongoDB query", e); } } @Override public void handleInsert(final MongoInsert mongoInsert, final Oplog opLog) { } @Override public void handleDelete(final MongoDelete mongoDelete, final Oplog opLog) { } @Override public void handleUpdate(final MongoUpdate mongoUpdate, final Oplog opLog) { } @Override public boolean isEmpty() { return false; } @Override public MongoCollection<?> createCollectionOrThrowIfExists(String s, CollectionOptions collectionOptions) { return null; } @Override public MongoCollection<?> resolveCollection(final String collectionName, final boolean throwExceptionIfNotFound) { return null; } @Override public void drop(final Oplog opLog) { database.drop(); } @Override public void dropCollection(final String collectionName, final Oplog opLog) { database.getSchema().dropType(collectionName); } @Override public void moveCollection(MongoDatabase mongoDatabase, MongoCollection<?> mongoCollection, String s) { throw new UnsupportedOperationException(); } @Override public void unregisterCollection(final String collectionName) { } private Document createCollection(final Document document) { database.getSchema().createDocumentType((String) document.get("create"), 1); return responseOk(); } private Document countCollection(final Document document) throws MongoServerException { final String collectionName = document.get("count").toString(); database.countType(collectionName, false); final Document response = responseOk(); final MongoCollection<Long> collection = collections.get(collectionName); if (collection == null) { response.put("missing", Boolean.TRUE); response.put("n", 0); } else { Document queryObject = (Document) document.get("query"); int limit = this.getOptionalNumber(document, "limit", -1); int skip = this.getOptionalNumber(document, "skip", 0); response.put("n", collection.count(queryObject, skip, limit)); } return response; } private Document insertDocument(final Channel channel, final Document query) throws MongoServerException { String collectionName = query.get("insert").toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); List<Document> documents = (List) query.get("documents"); List<Document> writeErrors = new ArrayList(); int n = 0; try { this.clearLastStatus(channel); try { if (collectionName.startsWith("system.")) { throw new MongoServerError(16459, "attempt to insert in system namespace"); } else { MongoCollection<Long> collection = getOrCreateCollection(collectionName); n = collection.insertDocuments(documents).size(); assert n == documents.size(); Document result = new Document("n", n); this.putLastResult(channel, result); } } catch (MongoServerError var7) { this.putLastError(channel, var7); throw var7; } ++n; } catch (MongoServerError e) { Document error = new Document(); error.put("index", n); error.put("errmsg", e.getMessage()); error.put("code", e.getCode()); error.putIfNotNull("codeName", e.getCodeName()); writeErrors.add(error); } Document result = new Document(); result.put("n", n); if (!writeErrors.isEmpty()) { result.put("writeErrors", writeErrors); } Utils.markOkay(result); return result; } private MongoCollection<Long> getOrCreateCollection(final String collectionName) { MongoCollection<Long> collection = collections.get(collectionName); if (collection == null) { collection = new MongoDBCollectionWrapper(server, database, collectionName); collections.put(collectionName, collection); } return collection; } private Document responseOk() { Document response = new Document(); Utils.markOkay(response); return response; } private int getOptionalNumber(final Document query, final String fieldName, final int defaultValue) { final Number limitNumber = (Number) query.get(fieldName); return limitNumber != null ? limitNumber.intValue() : defaultValue; } private synchronized void clearLastStatus(final Channel channel) { List<Document> results = this.lastResults.get(channel); if (results == null) { results = new ArrayList<>(10); this.lastResults.put(channel, results); } results.add(null); } private synchronized void putLastResult(final Channel channel, final Document result) { final List<Document> results = this.lastResults.get(channel); final Document last = results.get(results.size() - 1); if (last != null) throw new IllegalStateException("last result already set: " + last); results.set(results.size() - 1, result); } private void putLastError(final Channel channel, final MongoServerException ex) { final Document error = new Document(); if (ex instanceof MongoServerError) { final MongoServerError err = (MongoServerError) ex; error.put("err", err.getMessage()); error.put("code", err.getCode()); error.putIfNotNull("codeName", err.getCodeName()); } else { error.put("err", ex.getMessage()); } error.put("connectionId", channel.id().asShortText()); this.putLastResult(channel, error); } }
Java
CL
61c2fe3d9de4313308abcdaab7f4396f9446ed86ba101a1fa6f38178e51a8827
package pl.shalpuk.scooterService.util; import org.springframework.data.jpa.domain.Specification; import pl.shalpuk.scooterService.dto.ScooterSpecificationDto; import pl.shalpuk.scooterService.model.Location; import pl.shalpuk.scooterService.model.Scooter; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ScooterSpecification implements Specification<Scooter> { private static final long serialVersionUID = -3396764680457245526L; private final ScooterSpecificationDto scooterSpecificationDto; public ScooterSpecification(ScooterSpecificationDto scooterSpecificationDto) { this.scooterSpecificationDto = scooterSpecificationDto; } @Override public Predicate toPredicate(Root<Scooter> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { Set<String> manufacturers = scooterSpecificationDto.getManufacturers(); Set<String> models = scooterSpecificationDto.getModels(); int batteryChargeTo = scooterSpecificationDto.getBatteryChargeTo(); Set<String> locations = scooterSpecificationDto.getLocationAddress(); boolean isActive = scooterSpecificationDto.isActive(); Join<Scooter, Location> locationJoin = root.join("currentLocation"); List<Predicate> predicates = new ArrayList<>(); predicates.add(root.get("manufacturer").in(manufacturers)); predicates.add(root.get("model").in(models)); predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("batteryCharge"), scooterSpecificationDto.getBatteryChargeFrom())); predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("batteryCharge"), batteryChargeTo)); predicates.add(locationJoin.get("street").in(locations)); if (isActive) { predicates.add(root.get("active").in(true)); } return criteriaBuilder.and(predicates.toArray(new Predicate[]{})); } }
Java
CL
081d2fba71384ac9b2666b0669e485d81ad25e4794b3cb1917bdf02b7b2b44e8
package skyglass.composer.sagas.simpledsl; import java.util.function.Function; import java.util.function.Predicate; import skyglass.composer.commands.common.Command; import skyglass.composer.commands.consumer.CommandWithDestination; public interface WithCompensationBuilder<Data> { InvokeParticipantStepBuilder<Data> withCompensation(Function<Data, CommandWithDestination> compensation); InvokeParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, Function<Data, CommandWithDestination> compensation); <C extends Command> InvokeParticipantStepBuilder<Data> withCompensation(CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider); <C extends Command> InvokeParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, CommandEndpoint<C> commandEndpoint, Function<Data, C> commandProvider); }
Java
CL
cf2ea19f4ff220966860cb323d778dfdf463fbd7cf8b65cda7329a35559ce0c1
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.function.Consumer; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.SAMLObject; import org.opensaml.saml.saml2.core.EncryptedID; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.impl.LogoutRequestUnmarshaller; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlVerificationUtils.VerifierPartial; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * A {@link Saml2LogoutRequestValidator} that authenticates a SAML 2.0 Logout Requests * received from a SAML 2.0 Asserting Party using OpenSAML. * * @author Josh Cummings * @since 5.6 */ public final class OpenSamlLogoutRequestValidator implements Saml2LogoutRequestValidator { static { OpenSamlInitializationService.initialize(); } private final ParserPool parserPool; private final LogoutRequestUnmarshaller unmarshaller; /** * Constructs a {@link OpenSamlLogoutRequestValidator} */ public OpenSamlLogoutRequestValidator() { XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); this.unmarshaller = (LogoutRequestUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() .getUnmarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); } /** * {@inheritDoc} */ @Override public Saml2LogoutValidatorResult validate(Saml2LogoutRequestValidatorParameters parameters) { Saml2LogoutRequest request = parameters.getLogoutRequest(); RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration(); Authentication authentication = parameters.getAuthentication(); byte[] b = Saml2Utils.samlDecode(request.getSamlRequest()); LogoutRequest logoutRequest = parse(inflateIfRequired(request, b)); return Saml2LogoutValidatorResult.withErrors().errors(verifySignature(request, logoutRequest, registration)) .errors(validateRequest(logoutRequest, registration, authentication)).build(); } private String inflateIfRequired(Saml2LogoutRequest request, byte[] b) { if (request.getBinding() == Saml2MessageBinding.REDIRECT) { return Saml2Utils.samlInflate(b); } return new String(b, StandardCharsets.UTF_8); } private LogoutRequest parse(String request) throws Saml2Exception { try { Document document = this.parserPool .parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutRequest) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception("Failed to deserialize LogoutRequest", ex); } } private Consumer<Collection<Saml2Error>> verifySignature(Saml2LogoutRequest request, LogoutRequest logoutRequest, RelyingPartyRegistration registration) { return (errors) -> { VerifierPartial partial = OpenSamlVerificationUtils.verifySignature(logoutRequest, registration); if (logoutRequest.isSigned()) { errors.addAll(partial.post(logoutRequest.getSignature())); } else { errors.addAll(partial.redirect(request)); } }; } private Consumer<Collection<Saml2Error>> validateRequest(LogoutRequest request, RelyingPartyRegistration registration, Authentication authentication) { return (errors) -> { validateIssuer(request, registration).accept(errors); validateDestination(request, registration).accept(errors); validateSubject(request, registration, authentication).accept(errors); }; } private Consumer<Collection<Saml2Error>> validateIssuer(LogoutRequest request, RelyingPartyRegistration registration) { return (errors) -> { if (request.getIssuer() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to find issuer in LogoutRequest")); return; } String issuer = request.getIssuer().getValue(); if (!issuer.equals(registration.getAssertingPartyDetails().getEntityId())) { errors.add( new Saml2Error(Saml2ErrorCodes.INVALID_ISSUER, "Failed to match issuer to configured issuer")); } }; } private Consumer<Collection<Saml2Error>> validateDestination(LogoutRequest request, RelyingPartyRegistration registration) { return (errors) -> { if (request.getDestination() == null) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to find destination in LogoutRequest")); return; } String destination = request.getDestination(); if (!destination.equals(registration.getSingleLogoutServiceLocation())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_DESTINATION, "Failed to match destination to configured destination")); } }; } private Consumer<Collection<Saml2Error>> validateSubject(LogoutRequest request, RelyingPartyRegistration registration, Authentication authentication) { return (errors) -> { if (authentication == null) { return; } NameID nameId = getNameId(request, registration); if (nameId == null) { errors.add( new Saml2Error(Saml2ErrorCodes.SUBJECT_NOT_FOUND, "Failed to find subject in LogoutRequest")); return; } validateNameId(nameId, authentication, errors); }; } private NameID getNameId(LogoutRequest request, RelyingPartyRegistration registration) { NameID nameId = request.getNameID(); if (nameId != null) { return nameId; } EncryptedID encryptedId = request.getEncryptedID(); if (encryptedId == null) { return null; } return decryptNameId(encryptedId, registration); } private void validateNameId(NameID nameId, Authentication authentication, Collection<Saml2Error> errors) { String name = nameId.getValue(); if (!name.equals(authentication.getName())) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_REQUEST, "Failed to match subject in LogoutRequest with currently logged in user")); } } private NameID decryptNameId(EncryptedID encryptedId, RelyingPartyRegistration registration) { final SAMLObject decryptedId = LogoutRequestEncryptedIdUtils.decryptEncryptedId(encryptedId, registration); if (decryptedId instanceof NameID) { return ((NameID) decryptedId); } return null; } }
Java
CL
3e801c0d4cb1f53bd3221f805257a4f0f2e86df72453dfda21ebf387d66814ea
package com.wat.tabularasa20.utilities; import android.os.AsyncTask; import androidx.annotation.Nullable; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * Klasa pozwalająca pobrać dokument tekstowy z internetu */ public class Downloader extends AsyncTask<Object, Void, String> { /** * Interfejs potrzebny do utworzenia akcji na zakończenie pobierania */ public interface DownloadActions { void getResult(@Nullable String result); } private DownloadActions onResultListener = null; private String response = null; /** * Setter akcji pobierania */ public void setOnResultListener (DownloadActions onResultListener) { this.onResultListener = onResultListener; } /** * Motoda wykonywana gdy na obiekcie klasy zostanie wykonane <code>execute(String url)</code> * @param params adres URL strony jako <code>String</code> */ @Override protected String doInBackground (Object... params) { try { StringBuilder sb = new StringBuilder(); URL url = new URL((String) params[0]); URLConnection urlConnection = url.openConnection(); //((HttpURLConnection) urlConnection).setRequestMethod("POST"); //urlConnection.setRequestProperty("Authorization", "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-date, Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024"); int status = ((HttpURLConnection) urlConnection).getResponseCode(); InputStream is = urlConnection.getInputStream(); //InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) sb.append(inputLine); in.close(); return sb.toString(); } catch (Exception e) { System.out.println(e.toString()); } return null; } /** * Metoda wywołująca listener na zakończenie pobierania */ @Override protected void onPostExecute (String str) { if (onResultListener != null) onResultListener.getResult(str); } /** * Getter ostatniej odpowiedzi * @return ostatnia odpowiedź jako <code>String</code> */ @Nullable public String getResponse () { return response; } }
Java
CL
15d4da91f5ffec66214af0cbd8a654d26c3eadb30f6e45a0bab1a6f9f6cc89cc
package programming.techie.springredditclone.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import programming.techie.springredditclone.model.Post; import programming.techie.springredditclone.model.User; import programming.techie.springredditclone.model.Vote; @Repository public interface VoteRepository extends JpaRepository<Vote, Long> { Optional<Vote> findByPostAndUser(Post post, User currentUser); }
Java
CL
3c3265da752a32e76d21cfcbe82b2a3be99f0be22528cf9a0852d87d9a1ca6e9
/** * Alipay.com Inc. * Copyright (c) 2004-2014 All Rights Reserved. */ package org.footoo.server.configureServerFinder; import java.util.ArrayList; import java.util.List; import org.footoo.common.http.HttpMethodEnum; import org.footoo.common.http.SimpleHttpClient; import org.footoo.common.log.Logger; import org.footoo.common.log.LoggerFactory; import org.footoo.common.tools.JsonSerializable; /** * 配置服务器发现服务提供的对外api * * @author jeff * @version $Id: ConfigureServerFinderApi.java, v 0.1 2014年4月14日 下午11:39:49 jeff Exp $ */ public abstract class ConfigureServerFinderApi { /** 日志 */ private static final Logger logger = LoggerFactory.getLogger(ConfigureServerFinderApi.class); /** * 获取配置服务器列表 * * @param host * @param timeout * @return */ @SuppressWarnings("unchecked") public static List<String> getConfigureServers(String host, int timeout) { List<String> servers = new ArrayList<>(); try { SimpleHttpClient client = new SimpleHttpClient(host, ConfigureServerFinder.DEFAULT_PORT); byte[] result = client.visit(HttpMethodEnum.GET, null, "/", null, timeout); String htmls = new String(result); int index = htmls.indexOf("\r\n\r\n"); if (index < 0) { return servers; } htmls = htmls.substring(index + 4); servers = JsonSerializable.deserialize(htmls, List.class); } catch (Exception e) { // TODO: handle exception logger.warn(e, "获取配置服务气列表发生异常"); } return servers; } }
Java
CL
372fc8046d6344125e044dafebd87a647ca98592dd3c184f608b36b0d73cf6a2
package se.citerus.cqrs.bookstore.ordercontext.infrastructure; import org.junit.Test; import se.citerus.cqrs.bookstore.ordercontext.order.OrderId; import se.citerus.cqrs.bookstore.ordercontext.query.orderlist.OrderLineProjection; import se.citerus.cqrs.bookstore.ordercontext.query.orderlist.OrderProjection; import se.citerus.cqrs.bookstore.ordercontext.query.orderlist.OrderProjectionRepository; import java.util.Collections; import java.util.Iterator; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static se.citerus.cqrs.bookstore.ordercontext.order.OrderStatus.PLACED; public class InMemOrderProjectionRepositoryTest { @Test public void sortingOfOrders() { OrderProjectionRepository repository = new InMemOrderProjectionRepository(); repository.save(new OrderProjection(OrderId.<OrderId>randomId(), 1, "Test Person", 0, Collections.<OrderLineProjection>emptyList(), PLACED)); repository.save(new OrderProjection(OrderId.<OrderId>randomId(), 3, "Test Person 2", 0, Collections.<OrderLineProjection>emptyList(), PLACED)); Iterator<OrderProjection> iterator = repository.listOrdersByTimestamp().iterator(); assertThat(iterator.next().getOrderPlacedTimestamp(), is(3L)); assertThat(iterator.next().getOrderPlacedTimestamp(), is(1L)); } }
Java
CL
76192dfc9c4a0f6ce308f74b6c845fa8baca4aacd1fa2b39c6635e3cb5141772
package com.blackey.finance.component.service; import com.blackey.finance.component.domain.UserRequireLike; import com.blackey.finance.dto.form.AddOrCancelFollowForm; import com.blackey.finance.global.constants.AddCancelEnum; import com.blackey.mybatis.service.BaseService; import com.blackey.mybatis.utils.PageUtils; import java.util.Map; /** * 用户需求点赞表 UserRequireLikeService * * @author kaven * @date 2018-12-07 09:40:20 */ public interface UserRequireLikeService extends BaseService<UserRequireLike> { /** * 分页查询 * @param params * @return */ PageUtils queryPage(Map<String, Object> params); /** * 点赞 * @param addOrCancelFollowForm * @return */ AddCancelEnum likeRequire(AddOrCancelFollowForm addOrCancelFollowForm); /** * 删除需求的关注信息 * @param requireId */ void deleteLikeByRequireId(String requireId); }
Java
CL
115a4d43d77a1814036fa80ad99294b72696d44c19c91284e97a9dc8f278514c
/* * Copyright 2019 NUROX Ltd. * * Licensed under the NUROX Ltd Software License (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.looseboxes.com/legal/licenses/software.html * * 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.looseboxes.msofficekiosk.net; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; /** * @author Chinomso Bassey Ikwuagwu on Apr 25, 2019 12:37:14 PM */ public class CookieJarInMemoryStaticCache implements CookieJar { private static final Logger LOG = Logger.getLogger(CookieJarInMemoryStaticCache.class.getName()); private static final Map<String, Set<Cookie>> cache = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { if(cookies == null || cookies.isEmpty()) { return; } final String key = getKey(url); Set<Cookie> set = cache.getOrDefault(key, null); if(set == null) { set = new HashSet<>(); cache.put(key, set); } LOG.log(Level.FINER, "Adding cookies:: {0}", cookies.stream().map((cookie) -> cookie.toString()).collect(Collectors.joining("\n"))); set.addAll(cookies); } @Override public List<Cookie> loadForRequest(HttpUrl url) { final String key = getKey(url); final Set<Cookie> set = cache.getOrDefault(key, null); final List<Cookie> cookies = set == null || set.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(set); LOG.log(Level.FINER, "Returning cookies:: {0}", cookies.stream().map((cookie) -> cookie.toString()).collect(Collectors.joining("\n"))); return cookies; } public String getKey(HttpUrl url) { return url.host(); } }
Java
CL
834594dded0d27904afae4c181d877240ca7edb061534bf73497cd4255e9cf76
package org.broadinstitute.hellbender.tools.copynumber; import htsjdk.samtools.SAMSequenceDictionary; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; import org.apache.logging.log4j.Logger; import org.apache.spark.api.java.JavaSparkContext; import org.broadinstitute.barclay.argparser.Advanced; import org.broadinstitute.barclay.argparser.Argument; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.barclay.help.DocumentedFeature; import org.broadinstitute.hdf5.HDF5Library; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.cmdline.programgroups.CopyNumberProgramGroup; import org.broadinstitute.hellbender.engine.spark.SparkCommandLineProgram; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.tools.copynumber.arguments.CopyNumberArgumentValidationUtils; import org.broadinstitute.hellbender.tools.copynumber.arguments.CopyNumberStandardArgument; import org.broadinstitute.hellbender.tools.copynumber.denoising.GCBiasCorrector; import org.broadinstitute.hellbender.tools.copynumber.denoising.HDF5SVDReadCountPanelOfNormals; import org.broadinstitute.hellbender.tools.copynumber.formats.collections.AnnotatedIntervalCollection; import org.broadinstitute.hellbender.tools.copynumber.formats.collections.SimpleCountCollection; import org.broadinstitute.hellbender.tools.copynumber.formats.records.annotation.CopyNumberAnnotations; import org.broadinstitute.hellbender.tools.copynumber.utils.HDF5Utils; import org.broadinstitute.hellbender.utils.SimpleInterval; import org.broadinstitute.hellbender.utils.Utils; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.stream.Collectors; /** * Creates a panel of normals (PoN) for read-count denoising given the read counts for samples in the panel. * The resulting PoN can be used with {@link DenoiseReadCounts} to denoise other samples. * * <p> * The input read counts are first transformed to log2 fractional coverages and preprocessed * according to specified filtering and imputation parameters. Singular value decomposition (SVD) * is then performed to find the first {@code number-of-eigensamples} principal components, * which are stored in the PoN. Some or all of these principal components can then be used for * denoising case samples with {@link DenoiseReadCounts}; it is assumed that the principal components used * represent systematic sequencing biases (rather than statistical noise). Examining the singular values, * which are also stored in the PoN, may be useful in determining the appropriate number * of principal components to use for denoising. * </p> * * <p> * If annotated intervals are provided, explicit GC-bias correction will be performed by {@link GCBiasCorrector} * before filtering and SVD. GC-content information for the intervals will be stored in the PoN * and used to perform explicit GC-bias correction identically in {@link DenoiseReadCounts}. * Note that if annotated intervals are not provided, it is still likely that GC-bias correction is * implicitly performed by the SVD denoising process (i.e., some of the principal components arise from GC bias). * </p> * * <p> * Note that such SVD denoising cannot distinguish between variance due to systematic sequencing biases and that * due to true common germline CNVs present in the panel; signal from the latter may thus be inadvertently denoised * away. Furthermore, variance arising from coverage on the sex chromosomes may also significantly contribute * to the principal components if the panel contains samples of mixed sex. Therefore, if sex chromosomes * are not excluded from coverage collection, it is strongly recommended that users avoid creating panels of * mixed sex and take care to denoise case samples only with panels containing only individuals of the same sex * as the case samples. (See {@link GermlineCNVCaller}, which avoids these issues by simultaneously learning * a probabilistic model for systematic bias and calling rare and common germline CNVs for samples in the panel.) * </p> * * <h3>Inputs</h3> * * <ul> * <li> * Counts files (TSV or HDF5 output of {@link CollectReadCounts}). * </li> * <li> * (Optional) GC-content annotated-intervals file from {@link AnnotateIntervals}. * Explicit GC-bias correction will be performed on the panel samples and identically for subsequent case samples. * </li> * </ul> * * <h3>Outputs</h3> * * <ul> * <li> * Panel-of-normals file. * This is an HDF5 file containing the panel data in the paths defined in {@link HDF5SVDReadCountPanelOfNormals}. * HDF5 files may be viewed using <a href="https://support.hdfgroup.org/products/java/hdfview/">hdfview</a> * or loaded in python using <a href="http://www.pytables.org/">PyTables</a> or <a href="http://www.h5py.org/">h5py</a>. * </li> * </ul> * * <h3>Usage examples</h3> * * <pre> * gatk CreateReadCountPanelOfNormals \ * -I sample_1.counts.hdf5 \ * -I sample_2.counts.hdf5 \ * ... \ * -O cnv.pon.hdf5 * </pre> * * <pre> * gatk CreateReadCountPanelOfNormals \ * -I sample_1.counts.hdf5 \ * -I sample_2.counts.tsv \ * ... \ * --annotated-intervals annotated_intervals.tsv \ * -O cnv.pon.hdf5 * </pre> * * @author Samuel Lee &lt;slee@broadinstitute.org&gt; */ @CommandLineProgramProperties( summary = "Creates a panel of normals for read-count denoising given the read counts for samples in the panel", oneLineSummary = "Creates a panel of normals for read-count denoising", programGroup = CopyNumberProgramGroup.class ) @DocumentedFeature public final class CreateReadCountPanelOfNormals extends SparkCommandLineProgram { private static final long serialVersionUID = 1L; //default values for filtering private static final double DEFAULT_MINIMUM_INTERVAL_MEDIAN_PERCENTILE = 10.0; private static final double DEFAULT_MAXIMUM_ZEROS_IN_SAMPLE_PERCENTAGE = 5.0; private static final double DEFAULT_MAXIMUM_ZEROS_IN_INTERVAL_PERCENTAGE = 5.0; private static final double DEFAULT_EXTREME_SAMPLE_MEDIAN_PERCENTILE = 2.5; private static final boolean DEFAULT_DO_IMPUTE_ZEROS = true; private static final double DEFAULT_EXTREME_OUTLIER_TRUNCATION_PERCENTILE = 0.1; private static final int DEFAULT_NUMBER_OF_EIGENSAMPLES = 20; private static final int DEFAULT_CHUNK_DIVISOR = 16; private static final int DEFAULT_MAXIMUM_CHUNK_SIZE = HDF5Utils.MAX_NUMBER_OF_VALUES_PER_HDF5_MATRIX / DEFAULT_CHUNK_DIVISOR; //parameter names public static final String MINIMUM_INTERVAL_MEDIAN_PERCENTILE_LONG_NAME = "minimum-interval-median-percentile"; public static final String MAXIMUM_ZEROS_IN_SAMPLE_PERCENTAGE_LONG_NAME = "maximum-zeros-in-sample-percentage"; public static final String MAXIMUM_ZEROS_IN_INTERVAL_PERCENTAGE_LONG_NAME = "maximum-zeros-in-interval-percentage"; public static final String EXTREME_SAMPLE_MEDIAN_PERCENTILE_LONG_NAME = "extreme-sample-median-percentile"; public static final String IMPUTE_ZEROS_LONG_NAME = "do-impute-zeros"; public static final String EXTREME_OUTLIER_TRUNCATION_PERCENTILE_LONG_NAME = "extreme-outlier-truncation-percentile"; public static final String MAXIMUM_CHUNK_SIZE = "maximum-chunk-size"; @Argument( doc = "Input TSV or HDF5 files containing integer read counts in genomic intervals for all samples in the panel of normals (output of CollectReadCounts). " + "Intervals must be identical and in the same order for all samples.", fullName = StandardArgumentDefinitions.INPUT_LONG_NAME, shortName = StandardArgumentDefinitions.INPUT_SHORT_NAME, minElements = 1 ) private List<File> inputReadCountFiles = new ArrayList<>(); @Argument( doc = "Input file containing annotations for GC content in genomic intervals (output of AnnotateIntervals). " + "If provided, explicit GC correction will be performed before performing SVD. " + "Intervals must be identical to and in the same order as those in the input read-counts files.", fullName = CopyNumberStandardArgument.ANNOTATED_INTERVALS_FILE_LONG_NAME, optional = true ) private File inputAnnotatedIntervalsFile = null; @Argument( doc = "Output file for the panel of normals.", fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME, shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME ) private File outputPanelOfNormalsFile; @Argument( doc = "Genomic intervals with a median (across samples) of fractional coverage (optionally corrected for GC bias) " + "less than or equal to this percentile are filtered out. " + "(This is the first filter applied.)", fullName = MINIMUM_INTERVAL_MEDIAN_PERCENTILE_LONG_NAME, minValue = 0., maxValue = 100., optional = true ) private double minimumIntervalMedianPercentile = DEFAULT_MINIMUM_INTERVAL_MEDIAN_PERCENTILE; @Argument( doc = "Samples with a fraction of zero-coverage genomic intervals greater than or equal to this percentage are filtered out. " + "(This is the second filter applied.)", fullName = MAXIMUM_ZEROS_IN_SAMPLE_PERCENTAGE_LONG_NAME, minValue = 0., maxValue = 100., optional = true ) private double maximumZerosInSamplePercentage = DEFAULT_MAXIMUM_ZEROS_IN_SAMPLE_PERCENTAGE; @Argument( doc = "Genomic intervals with a fraction of zero-coverage samples greater than or equal to this percentage are filtered out. " + "(This is the third filter applied.)", fullName = MAXIMUM_ZEROS_IN_INTERVAL_PERCENTAGE_LONG_NAME, minValue = 0., maxValue = 100., optional = true ) private double maximumZerosInIntervalPercentage = DEFAULT_MAXIMUM_ZEROS_IN_INTERVAL_PERCENTAGE; @Argument( doc = "Samples with a median (across genomic intervals) of fractional coverage normalized by genomic-interval medians " + "strictly below this percentile or strictly above the complementary percentile are filtered out. " + "(This is the fourth filter applied.)", fullName = EXTREME_SAMPLE_MEDIAN_PERCENTILE_LONG_NAME, minValue = 0., maxValue = 50., optional = true ) private double extremeSampleMedianPercentile = DEFAULT_EXTREME_SAMPLE_MEDIAN_PERCENTILE; @Argument( doc = "If true, impute zero-coverage values as the median of the non-zero values in the corresponding interval. " + "(This is applied after all filters.)", fullName = IMPUTE_ZEROS_LONG_NAME, optional = true ) private boolean doImputeZeros = DEFAULT_DO_IMPUTE_ZEROS; @Argument( doc = "Fractional coverages normalized by genomic-interval medians that are " + "strictly below this percentile or strictly above the complementary percentile are set to the corresponding percentile value. " + "(This is applied after all filters and imputation.)", fullName = EXTREME_OUTLIER_TRUNCATION_PERCENTILE_LONG_NAME, minValue = 0., maxValue = 50., optional = true ) private double extremeOutlierTruncationPercentile = DEFAULT_EXTREME_OUTLIER_TRUNCATION_PERCENTILE; @Argument( doc = "Number of eigensamples to use for truncated SVD and to store in the panel of normals. " + "The number of samples retained after filtering will be used instead if it is smaller than this.", fullName = CopyNumberStandardArgument.NUMBER_OF_EIGENSAMPLES_LONG_NAME, minValue = 0, optional = true ) private int numEigensamplesRequested = DEFAULT_NUMBER_OF_EIGENSAMPLES; @Advanced @Argument( doc = "Maximum HDF5 matrix chunk size. Large matrices written to HDF5 are chunked into equally sized " + "subsets of rows (plus a subset containing the remainder, if necessary) to avoid a hard limit in " + "Java HDF5 on the number of elements in a matrix. However, since a single row is not allowed to " + "be split across multiple chunks, the number of columns must be less than the maximum number of " + "values in each chunk. Decreasing this number will reduce heap usage when writing chunks.", fullName = MAXIMUM_CHUNK_SIZE, minValue = 1, maxValue = HDF5Utils.MAX_NUMBER_OF_VALUES_PER_HDF5_MATRIX, optional = true ) private int maximumChunkSize = DEFAULT_MAXIMUM_CHUNK_SIZE; @Override protected void runPipeline(final JavaSparkContext ctx) { if (!new HDF5Library().load(null)) { //Note: passing null means using the default temp dir. throw new UserException.HardwareFeatureException("Cannot load the required HDF5 library. " + "HDF5 is currently supported on x86-64 architecture and Linux or OSX systems."); } validateArguments(); //get sample filenames final List<String> sampleFilenames = inputReadCountFiles.stream().map(File::getAbsolutePath).collect(Collectors.toList()); //get sequence dictionary and intervals from the first read-counts file to use to validate remaining files //(this first file is read again below, which is slightly inefficient but is probably not worth the extra code) final File firstReadCountFile = inputReadCountFiles.get(0); logger.info(String.format("Retrieving intervals from first read-counts file (%s)...", firstReadCountFile)); final SimpleCountCollection firstReadCounts = SimpleCountCollection.read(firstReadCountFile); final SAMSequenceDictionary sequenceDictionary = firstReadCounts.getMetadata().getSequenceDictionary(); final List<SimpleInterval> intervals = firstReadCounts.getIntervals(); Utils.validateArg(firstReadCounts.size() <= maximumChunkSize, String.format("The number of intervals (%d) in each read-counts file cannot exceed the maximum chunk size (%d).", firstReadCounts.size(), maximumChunkSize)); //get GC content (null if not provided) final AnnotatedIntervalCollection annotatedIntervals = CopyNumberArgumentValidationUtils.validateAnnotatedIntervals( inputAnnotatedIntervalsFile, firstReadCounts, logger); final double[] intervalGCContent = annotatedIntervals == null ? null : annotatedIntervals.getRecords().stream() .mapToDouble(i -> i.getAnnotationMap().getValue(CopyNumberAnnotations.GC_CONTENT)) .toArray(); //validate input read-counts files (i.e., check intervals and that only integer counts are contained) //and aggregate as a RealMatrix with dimensions numIntervals x numSamples final RealMatrix readCountMatrix = constructReadCountMatrix(logger, inputReadCountFiles, sequenceDictionary, intervals); //create the PoN logger.info("Creating the panel of normals..."); HDF5SVDReadCountPanelOfNormals.create(outputPanelOfNormalsFile, getCommandLine(), sequenceDictionary, readCountMatrix, sampleFilenames, intervals, intervalGCContent, minimumIntervalMedianPercentile, maximumZerosInSamplePercentage, maximumZerosInIntervalPercentage, extremeSampleMedianPercentile, doImputeZeros, extremeOutlierTruncationPercentile, numEigensamplesRequested, maximumChunkSize, ctx); logger.info(String.format("%s complete.", getClass().getSimpleName())); } private void validateArguments() { if (numEigensamplesRequested > inputReadCountFiles.size()) { logger.warn(String.format("Number of eigensamples (%d) is greater than the number of input samples (%d); " + "the number of samples retained after filtering will be used instead.", numEigensamplesRequested, inputReadCountFiles.size())); } Utils.validateArg(inputReadCountFiles.size() == new HashSet<>(inputReadCountFiles).size(), "List of input read-counts files cannot contain duplicates."); inputReadCountFiles.forEach(CopyNumberArgumentValidationUtils::validateInputs); CopyNumberArgumentValidationUtils.validateInputs(inputAnnotatedIntervalsFile); CopyNumberArgumentValidationUtils.validateOutputFiles(outputPanelOfNormalsFile); } private static RealMatrix constructReadCountMatrix(final Logger logger, final List<File> inputReadCountFiles, final SAMSequenceDictionary sequenceDictionary, final List<SimpleInterval> intervals) { logger.info("Validating and aggregating input read-counts files..."); final int numSamples = inputReadCountFiles.size(); final int numIntervals = intervals.size(); final RealMatrix readCountMatrix = new Array2DRowRealMatrix(numSamples, numIntervals); final ListIterator<File> inputReadCountFilesIterator = inputReadCountFiles.listIterator(); while (inputReadCountFilesIterator.hasNext()) { final int sampleIndex = inputReadCountFilesIterator.nextIndex(); final File inputReadCountFile = inputReadCountFilesIterator.next(); logger.info(String.format("Aggregating read-counts file %s (%d / %d)", inputReadCountFile, sampleIndex + 1, numSamples)); final SimpleCountCollection readCounts = SimpleCountCollection.read(inputReadCountFile); if (!CopyNumberArgumentValidationUtils.isSameDictionary(readCounts.getMetadata().getSequenceDictionary(), sequenceDictionary)) { logger.warn(String.format("Sequence dictionary for read-counts file %s does not match those in other read-counts files.", inputReadCountFile)); } Utils.validateArg(readCounts.getIntervals().equals(intervals), String.format("Intervals for read-counts file %s do not match those in other read-counts files.", inputReadCountFile)); readCountMatrix.setRow(sampleIndex, readCounts.getCounts()); } return readCountMatrix; } }
Java
CL
7d7906040feab56ed7fdd2687a107fb0cdbdb372c4da15dabacfcbaa31a773a8
package com.zyw.horrarndoo.sdk.utils; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.view.View; /** * Created by Horrarndoo on 2017/9/1. * <p> * 资源工具类-加载资源文件 */ public class ResourcesUtils { /** * 获取strings.xml资源文件字符串 * * @param id 资源文件id * @return 资源文件对应字符串 */ public static String getString(int id) { return AppUtils.getContext().getResources().getString(id); } /** * 获取strings.xml资源文件字符串数组 * * @param id 资源文件id * @return 资源文件对应字符串数组 */ public static String[] getStringArray(int id) { return AppUtils.getContext().getResources().getStringArray(id); } /** * 获取drawable资源文件图片 * * @param id 资源文件id * @return 资源文件对应图片 */ public static Drawable getDrawable(int id) { return AppUtils.getContext().getResources().getDrawable(id); } /** * 获取colors.xml资源文件颜色 * * @param id 资源文件id * @return 资源文件对应颜色值 */ public static int getColor(int id) { return AppUtils.getContext().getResources().getColor(id); } /** * 获取颜色的状态选择器 * * @param id 资源文件id * @return 资源文件对应颜色状态 */ public static ColorStateList getColorStateList(int id) { return AppUtils.getContext().getResources().getColorStateList(id); } /** * 获取dimens资源文件中具体像素值 * * @param id 资源文件id * @return 资源文件对应像素值 */ public static int getDimen(int id) { return AppUtils.getContext().getResources().getDimensionPixelSize(id);// 返回具体像素值 } /** * 加载布局文件 * * @param id 布局文件id * @return 布局view */ public static View inflate(int id) { return View.inflate(AppUtils.getContext(), id, null); } }
Java
CL
4f2fd4d42193d88ca08e0740da27ae7fe110a4618f7f29e76e1ec04f1b451c95
package com.onboarding.abstractfactory.factory; import org.springframework.context.annotation.Description; import com.onboarding.abstractfactory.services.DatabaseService; @Description(value = "Product Factory - Creational Factory.") public interface AbstractDataBaseFactory { DatabaseService createDatabase(); }
Java
CL
c09106cb7a36b1a5c9a62e7fc596ece483638d0c213f3b68f72f2d5ebf61ccb7
package com.vungle.warren.persistence; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import android.os.FileObserver; import android.os.StatFs; import androidx.core.content.C0769b; import com.ogury.p159cm.OguryChoiceManager; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class CacheManager { private static final String COM_VUNGLE_SDK = "com.vungle.sdk"; private static final String PATH_ID = "cache_path"; private static final String PATH_IDS = "cache_paths"; private static final String VUNGLE_DIR = "vungle_cache"; private boolean changed; private final Context context; private File current; private Set<Listener> listeners = new HashSet(); private List<FileObserver> observers = new ArrayList(); private List<File> old = new ArrayList(); private final SharedPreferences prefs; public interface Listener { void onCacheChanged(); } public CacheManager(Context context2) { this.context = context2; this.prefs = context2.getSharedPreferences(COM_VUNGLE_SDK, 0); } private void check() { File file = this.current; if (file == null || !file.exists() || !this.current.isDirectory() || !this.current.canWrite()) { selectFileDest(); } } private synchronized void observeDirectory(File file) { if (file != null) { this.observers.clear(); this.observers.add(new FileObserver(file.getPath(), OguryChoiceManager.TcfV2.Purpose.DEVELOP_AND_IMPROVE_PRODUCTS) { public void onEvent(int i, String str) { stopWatching(); CacheManager.this.selectFileDest(); } }); while (file.getParent() != null) { final String name = file.getName(); this.observers.add(new FileObserver(file.getParent(), 256) { public void onEvent(int i, String str) { if (name.equals(str)) { stopWatching(); CacheManager.this.selectFileDest(); } } }); file = file.getParentFile(); } for (FileObserver startWatching : this.observers) { startWatching.startWatching(); } } } /* access modifiers changed from: private */ public synchronized void selectFileDest() { boolean z; File file = null; if (this.current == null) { String string = this.prefs.getString(PATH_ID, (String) null); this.current = string != null ? new File(string) : null; } File externalFilesDir = this.context.getExternalFilesDir((String) null); File filesDir = this.context.getFilesDir(); File[] fileArr = new File[2]; fileArr[0] = new File((Build.VERSION.SDK_INT >= 19 || C0769b.m2414a(this.context, "android.permission.WRITE_EXTERNAL_STORAGE") == 0) && Environment.getExternalStorageState().equals("mounted") && externalFilesDir != null ? externalFilesDir : filesDir, VUNGLE_DIR); fileArr[1] = new File(filesDir, VUNGLE_DIR); Iterator it = Arrays.asList(fileArr).iterator(); boolean z2 = false; while (true) { if (!it.hasNext()) { break; } File file2 = (File) it.next(); if (file2.exists() && file2.isFile() && !file2.delete()) { break; } if (!file2.exists()) { z2 = file2.mkdirs(); z = z2; continue; } else if (!file2.isDirectory() || !file2.canWrite()) { z = false; continue; } else { z = true; continue; } if (z) { file = file2; break; } } File cacheDir = this.context.getCacheDir(); Set<String> stringSet = this.prefs.getStringSet(PATH_IDS, new HashSet()); if (file != null) { stringSet.add(file.getPath()); } stringSet.add(cacheDir.getPath()); this.prefs.edit().putStringSet(PATH_IDS, stringSet).apply(); this.old.clear(); for (String next : stringSet) { if (file == null || !file.getPath().equals(next)) { this.old.add(new File(next)); } } if (z2 || ((file != null && !file.equals(this.current)) || (this.current != null && !this.current.equals(file)))) { this.current = file; if (file != null) { this.prefs.edit().putString(PATH_ID, this.current.getPath()).apply(); } for (Listener onCacheChanged : this.listeners) { onCacheChanged.onCacheChanged(); } this.changed = true; } observeDirectory(externalFilesDir); } public synchronized void addListener(Listener listener) { check(); this.listeners.add(listener); if (this.changed) { listener.onCacheChanged(); } } public long getBytesAvailable() { long j; long j2; File cache = getCache(); if (cache == null) { return -1; } StatFs statFs = new StatFs(cache.getPath()); if (Build.VERSION.SDK_INT >= 18) { j = statFs.getBlockSizeLong(); j2 = statFs.getAvailableBlocksLong(); } else { j = (long) statFs.getBlockSize(); j2 = (long) statFs.getAvailableBlocks(); } return j * j2; } public synchronized File getCache() { check(); return this.current; } public synchronized List<File> getOldCaches() { check(); return this.old; } public synchronized void removeListener(Listener listener) { this.listeners.remove(listener); } }
Java
CL
7b5d27ba6efefef3300d8c881fcbf4d24ac9fdb9e8c1c6808b4c9f633a35e8a1
package com.zzw.teacher.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.Data; import lombok.EqualsAndHashCode; /** * //功能描述: 添加类/接口功能描述 * * @author 周梓武 * @since 2020-02-07 */ @Data @TableName("teacher") @EqualsAndHashCode(callSuper = false) public class TeacherEntity extends Model<TeacherEntity> { private static final long serialVersionUID = 1L; /** *主键 */ @TableId("id") private String id; /** *all_user的外键 */ @TableId("all_user_id") private String allUserId; /** *出生年月,长度10 */ @TableField("birth") private String birth; /** *学位,长度4 */ @TableField("degree") private String degree; /** *就读最高学历所在大学,长度20 */ @TableField("university") private String university; /** *所读专业,长度20 */ @TableField("major") private String major; /** *所教科目,长度20 */ @TableField("subject") private String subject; /** *是否毕业,1为是,0为否 */ @TableField("graduate") private String graduate; /** *教授方式,长度10 */ @TableField("tutor_mode") private String tutorMode; /** *信誉分,长度3,百分制 */ @TableField("credit_score") private Integer creditScore; /** *自我评价,长度200 */ @TableField("self_assessment") private String selfAssessment; /** *教学优秀案例,长度400 */ @TableField("cases") private String cases; /** *收费标准,长度20 */ @TableField("charge") private String charge; /** * 下列属性均为all_user表中属性 */ @TableField(exist = false) private String trueName; @TableField(exist = false) private String number; @TableField(exist = false) private String certification; @TableField(exist = false) private String qq; @TableField(exist = false) private String tel; @TableField(exist = false) private String city; @TableField(exist = false) private String gender; }
Java
CL
e08fd16f13037a4906f4b6de8782a24cf501b6c95e02880379a370f0b343b236
package com.viber.voip.analytics.story.b.a; final class i implements Runnable { private final h a; private final h.a b; i(h arg1, h.a arg2) { } public void run() { } } /* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_3_dex2jar.jar * Qualified Name: com.viber.voip.analytics.story.b.a.i * JD-Core Version: 0.6.2 */
Java
CL
7bf04a256028febd388e19717c9970fabdbee27d681f0f723c42231d827d3e45
package com.hyh.fyp.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.os.Handler; import android.support.annotation.IntDef; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewTreeObserver; import com.hyh.common.utils.ViewUtil; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.ref.WeakReference; /** * @author Administrator * @description * @data 2020/7/21 */ public class DragViewHelper implements View.OnTouchListener, View.OnAttachStateChangeListener, ViewTreeObserver.OnGlobalLayoutListener { public static final int IDLE_MODE_NONE = 0; public static final int IDLE_MODE_LEFT_SIDE = 1; public static final int IDLE_MODE_RIGHT_SIDE = 2; public static final int IDLE_MODE_BOTH_SIDE = 3; @IntDef({IDLE_MODE_NONE, IDLE_MODE_LEFT_SIDE, IDLE_MODE_RIGHT_SIDE, IDLE_MODE_BOTH_SIDE}) @Retention(RetentionPolicy.SOURCE) public @interface IdleMode { } private final WeakReference<View> viewRef; private final InitialPosition mInitialPosition; private final int mIdleMode; private final boolean mHalfHidden; private final float mLeftRatio; private final int mTouchSlop; private final HalfHiddenTask mHalfHiddenTask = new HalfHiddenTask(); private float mInitialTouchX; private float mInitialTouchY; private float mLastTranslationX; private float mLastTranslationY; private boolean mInDragging; private float mMinTranslationX; private float mMaxTranslationX; private float mMinTranslationY; private float mMaxTranslationY; private boolean mPositionInitialized; private boolean mAllowHandleTouch; private ObjectAnimator mIdleAnim; private DragViewHelper(Builder builder) { this.viewRef = new WeakReference<>(builder.view); this.mInitialPosition = builder.initialPosition; this.mIdleMode = builder.idleMode; this.mHalfHidden = builder.halfHidden; this.mLeftRatio = builder.leftRatio; this.mTouchSlop = ViewConfiguration.get(builder.view.getContext()).getScaledTouchSlop(); builder.view.setOnTouchListener(this); builder.view.addOnAttachStateChangeListener(this); if (ViewUtil.isAttachedToWindow(builder.view)) { onViewAttachedToWindow(builder.view); } } @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { mHalfHiddenTask.cancel(); ObjectAnimator idleAnim = mIdleAnim; mAllowHandleTouch = idleAnim == null || !idleAnim.isStarted(); } boolean result = false; switch (action) { case MotionEvent.ACTION_DOWN: { mInitialTouchX = event.getRawX(); mInitialTouchY = event.getRawY(); float translationX = v.getTranslationX(); if (translationX < mMinTranslationX) { v.setTranslationX(mMinTranslationX); } if (translationX > mMaxTranslationX) { v.setTranslationX(mMaxTranslationX); } mLastTranslationX = v.getTranslationX(); mLastTranslationY = v.getTranslationY(); break; } case MotionEvent.ACTION_MOVE: { if (!mAllowHandleTouch) { return false; } float x = event.getRawX(); float y = event.getRawY(); float tx = x - mInitialTouchX; float ty = y - mInitialTouchY; if (Math.abs(tx) > mTouchSlop || Math.abs(ty) > mTouchSlop) { mInDragging = true; } if (mInDragging) { float translationX = mLastTranslationX + tx; float translationY = mLastTranslationY + ty; translationX = Math.max(mMinTranslationX, translationX); translationX = Math.min(mMaxTranslationX, translationX); translationY = Math.max(mMinTranslationY, translationY); translationY = Math.min(mMaxTranslationY, translationY); v.setTranslationX(translationX); v.setTranslationY(translationY); } result = mInDragging; break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { result = mInDragging; mInDragging = false; startIdleAnim(); break; } } return result; } private void startIdleAnim() { View view = viewRef.get(); if (view == null) return; float startTranslation = view.getTranslationX(); float endTranslation; switch (mIdleMode) { default: case IDLE_MODE_NONE: { endTranslation = startTranslation; break; } case IDLE_MODE_LEFT_SIDE: { endTranslation = mMinTranslationX; break; } case IDLE_MODE_RIGHT_SIDE: { endTranslation = mMaxTranslationX; break; } case IDLE_MODE_BOTH_SIDE: { if (startTranslation > (mMaxTranslationX - mMinTranslationX) * 0.5f) { endTranslation = mMaxTranslationX; } else { endTranslation = mMinTranslationX; } break; } } if (startTranslation == endTranslation) { mHalfHiddenTask.post(); return; } mIdleAnim = ObjectAnimator.ofFloat(view, "translationX", startTranslation, endTranslation) .setDuration(300); mIdleAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mIdleAnim = null; mHalfHiddenTask.post(); } }); mIdleAnim.start(); } @Override public void onViewAttachedToWindow(View v) { v.getViewTreeObserver().addOnGlobalLayoutListener(this); computeBound(); mHalfHiddenTask.post(); } @Override public void onViewDetachedFromWindow(View v) { v.getViewTreeObserver().removeOnGlobalLayoutListener(this); } @Override public void onGlobalLayout() { computeBound(); } private void computeBound() { View view = viewRef.get(); if (view == null) return; View parent = (View) view.getParent(); mMinTranslationX = -view.getLeft(); mMaxTranslationX = parent.getWidth() - view.getWidth() - view.getLeft(); mMinTranslationY = -view.getTop(); mMaxTranslationY = parent.getHeight() - view.getHeight() - view.getTop(); setInitialPosition(); } private void setInitialPosition() { if (mPositionInitialized) return; View view = viewRef.get(); if (view == null) return; if (mInitialPosition != null) { View parent = (View) view.getParent(); if (parent == null) return; int width = parent.getWidth(); int height = parent.getHeight(); if (width == 0 || height == 0) return; mPositionInitialized = true; float translationX; float translationY; int left = view.getLeft(); int top = view.getTop(); int gravity = mInitialPosition.gravity; final int layoutDirection = view.getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection); final int horizontalGravity = absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (horizontalGravity) { case Gravity.CENTER_HORIZONTAL: { translationX = -left + (parent.getWidth() - view.getWidth()) * 0.5f; break; } case Gravity.RIGHT: { translationX = -left + (parent.getWidth() - view.getWidth()); break; } case Gravity.LEFT: { translationX = -left; break; } default: { translationX = 0; break; } } switch (verticalGravity) { case Gravity.TOP: { translationY = -top; break; } case Gravity.CENTER_VERTICAL: { translationY = -top + (parent.getHeight() - view.getHeight()) * 0.5f; break; } case Gravity.BOTTOM: { translationY = -top + (parent.getHeight() - view.getHeight()); break; } default: { translationY = 0; break; } } translationX += parent.getWidth() * mInitialPosition.horizontalBias; translationY += parent.getHeight() * mInitialPosition.verticalBias; view.setTranslationX(translationX); view.setTranslationY(translationY); } } private class HalfHiddenTask implements Runnable { @Override public void run() { View view = viewRef.get(); if (view == null) return; float startTranslationX = view.getTranslationX(); float endTranslationX = startTranslationX; if (startTranslationX == mMinTranslationX) { endTranslationX = startTranslationX - view.getWidth() * mLeftRatio; } else if (startTranslationX == mMaxTranslationX) { endTranslationX = startTranslationX + view.getWidth() * (1 - mLeftRatio); } if (startTranslationX == endTranslationX) { return; } ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", startTranslationX, endTranslationX) .setDuration(300); animator.start(); } void post() { if (!mHalfHidden) return; View view = viewRef.get(); if (view == null) return; Handler handler = view.getHandler(); if (handler == null) return; handler.postDelayed(this, 3000); } void cancel() { View view = viewRef.get(); if (view == null) return; Handler handler = view.getHandler(); if (handler == null) return; handler.removeCallbacks(this); } } public static class InitialPosition { public int gravity; public float horizontalBias; public float verticalBias; public InitialPosition(int gravity, float horizontalBias, float verticalBias) { this.gravity = gravity; this.horizontalBias = horizontalBias; this.verticalBias = verticalBias; } } public static class Builder { private View view; private InitialPosition initialPosition; private int idleMode; private boolean halfHidden; private float leftRatio; public Builder(View view) { this.view = view; } public Builder initialPosition(InitialPosition initialPosition) { this.initialPosition = initialPosition; return this; } public Builder idleMode(@IdleMode int idleMode) { this.idleMode = idleMode; return this; } public Builder halfHidden(boolean halfHidden) { this.halfHidden = halfHidden; return this; } public Builder leftRatio(float leftRatio) { this.leftRatio = leftRatio; return this; } public DragViewHelper build() { return new DragViewHelper(this); } } }
Java
CL
d3b4d537d2d1ce445eb39d0f40a0017c5f92474b96e1f5fc373a6b07e0e145ce
package com.dice.stepdefs; import com.dice.serenitysteps.SleepInSerenitySteps; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import net.thucydides.core.annotations.Steps; import org.apache.log4j.Logger; public class SleepInStepDef { final static Logger logger = Logger.getLogger(SleepInStepDef.class); @Steps SleepInSerenitySteps sleepInSerenitySteps; @Given("^the user is on Dice\\.com$") public void the_user_is_on_Dice_com() throws Exception { sleepInSerenitySteps.goToHomePage(); } @And("^they log in$") public void they_log_in() throws Exception { sleepInSerenitySteps.logIn(); } @And("^go to the profile page$") public void go_to_the_profile_page() throws Exception { sleepInSerenitySteps.goToProfilePage(); } @Then("^the resume should be updated while I'm sound asleep$") public void the_resume_should_be_updated_while_I_m_sound_asleep() throws Exception { sleepInSerenitySteps.upload(); } }
Java
CL
b85f0f66384b4093342fc2df10cab7b3e4e1bbb1ab0cb6f1f0e8c0350c973061
package com.lambdaschool.orders.controllers; import com.lambdaschool.orders.models.Agent; import com.lambdaschool.orders.services.AgentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/agents") public class AgentController { // inject services into this class @Autowired private AgentService agentsService; //http://localhost:2019/agent/{agentcode} @DeleteMapping(value = "/agent/{agentcode}", produces = {"application/json"}) public ResponseEntity<?> deleteAgent(@PathVariable long agentcode) { Agent currentAgent = new Agent(); agentsService.delete(agentcode); return new ResponseEntity<>("Delete Successful", HttpStatus.OK); } }
Java
CL
55084dbc9ac2aa231e900d41979456d9a739cc56559a2f6f2a3bb990a0613212
package au.com.dius.resilience.test.unit.location; import au.com.dius.resilience.location.LocationBroadcaster; import au.com.dius.resilience.location.StopLocatingRunnable; import au.com.dius.resilience.test.unit.utils.ResilienceTestRunner; import au.com.dius.resilience.test.unit.utils.TestHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.mockito.Mockito.verify; @RunWith(ResilienceTestRunner.class) public class StopLocatingRunnableTest { private StopLocatingRunnable stopLocatingRunnable; @Mock private LocationBroadcaster locationBroadcaster; @Before public void setup() { stopLocatingRunnable = new StopLocatingRunnable(locationBroadcaster); TestHelper.setField(stopLocatingRunnable, "locationBroadcaster", locationBroadcaster); } @Test public void shouldStopPollingWhenRun() { stopLocatingRunnable.run(); verify(locationBroadcaster).stopPolling(); } }
Java
CL
1ef02eed2674445370be2adb09b6b83dfa2ae927982a2d645157e3fe540f8f3b
package per.itachi.test.gallery; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import per.itachi.test.gallery.window.MainFrame; public class MainFrameEntry { private static final Logger logger = LoggerFactory.getLogger(MainFrameEntry.class); private static final String MAIN_TITLE = "Gallery"; public static void main(String[] args) { logger.info("Starting {}", MAIN_TITLE); logger.info("Initialising UI look-and-feel... "); initialiseUILookAndFeel(); logger.info("UI look-and-feel is ready. "); logger.info("Initialising Spring Framework... "); ApplicationContext applicationContext = new FileSystemXmlApplicationContext("conf/application-context*.xml"); logger.info("Spring Framework is ready. "); logger.info("Initialising Main Frame... "); JFrame mainFrame = applicationContext.getBean(MainFrame.class); logger.info("Main Frame is ready. "); logger.info("Showing main frame... "); mainFrame.setVisible(true); mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); mainFrame.setTitle(MAIN_TITLE); logger.info("Started {}", MAIN_TITLE); } /** * UI look-and-feel is required to execute before initialising frame. * Otherwise, UI look-and-feel won't work. * * */ private static void initialiseUILookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e) { logger.error("Error occured when initialising main frame. ", e); } catch (InstantiationException e) { logger.error("Error occured when initialising main frame. ", e); } catch (IllegalAccessException e) { logger.error("Error occured when initialising main frame. ", e); } catch (UnsupportedLookAndFeelException e) { logger.error("Error occured when initialising main frame. ", e); } } }
Java
CL
96eaece878885f688e5571cc6a4da855109b636c2acf206182cad4d096d1f603
package org.azure.samplequeue; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.azure.messaging.servicebus.ServiceBusClientBuilder; import com.azure.messaging.servicebus.ServiceBusErrorContext; import com.azure.messaging.servicebus.ServiceBusException; import com.azure.messaging.servicebus.ServiceBusFailureReason; import com.azure.messaging.servicebus.ServiceBusMessage; import com.azure.messaging.servicebus.ServiceBusMessageBatch; import com.azure.messaging.servicebus.ServiceBusProcessorClient; import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.messaging.servicebus.ServiceBusReceivedMessageContext; import com.azure.messaging.servicebus.ServiceBusSenderClient; public class QueueMain { // Primary connection string for a Service Bus Namespace static String connectionString = "Endpoint=sb://service-bus-namespace-spring.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=WhZdS2PKpc9fi9Fb+J2i5RA6hrEbKPG25hziVWU4zn8="; static String queueName = "samplequeue1"; public static void main(String[] args) throws InterruptedException { sendMessage(); sendMessageBatch(); receiveMessages(); } // Send One message to the Queue static void sendMessage() { ServiceBusSenderClient senderClient = createSenderClient(); // send one message to the queue senderClient.sendMessage(new ServiceBusMessage("Hello, World!")); System.out.println("Sent a single message to the queue: " + queueName); } static List<ServiceBusMessage> createMessages() { // create a list of sample messages and return it to the caller ServiceBusMessage[] messages = { new ServiceBusMessage("First message"), new ServiceBusMessage("Second message"), new ServiceBusMessage("Third message") }; return Arrays.asList(messages); } // Invokes the createMessages method to get the list of messages, prepares one or more batches, and sends the batches to the queue. static void sendMessageBatch() { ServiceBusSenderClient senderClient = createSenderClient(); // Creates an ServiceBusMessageBatch where the ServiceBus. ServiceBusMessageBatch messageBatch = senderClient.createMessageBatch(); // create a list of messages List<ServiceBusMessage> listOfMessages = createMessages(); // We try to add as many messages as a batch can fit based on the maximum size and send to Service Bus when // the batch can hold no more messages. Create a new batch for next set of messages and repeat until all // messages are sent. for (ServiceBusMessage message : listOfMessages) { if (messageBatch.tryAddMessage(message)) { continue; } // The batch is full, so send the batch. senderClient.sendMessages(messageBatch); System.out.println("Sent a batch of messages to the queue: " + queueName); // create a new batch messageBatch = senderClient.createMessageBatch(); // Add that message that we couldn't before. if (!messageBatch.tryAddMessage(message)) { System.err.printf("Message is too large for an empty batch. Skipping. Max size: %s.", messageBatch.getMaxSizeInBytes()); } } // Send leftover messages if (messageBatch.getCount() > 0) { senderClient.sendMessages(messageBatch); System.out.println("Sent a batch of messages to the queue: " + queueName); } //close the client senderClient.close(); } static ServiceBusSenderClient createSenderClient() { // create a Service Bus Sender client for the queue return new ServiceBusClientBuilder() .connectionString(connectionString) .sender() .queueName(queueName) .buildClient(); } // Retrieve messages from the queue and handles received messages static void receiveMessages() throws InterruptedException { // Create an instance of the processor through the ServiceBusClientBuilder ServiceBusProcessorClient processorClient = createProcessorClient(); // starts the processor, waits for few seconds, prints the messages that are received, and then stops and closes the processor System.out.println("Starting the processor"); processorClient.start(); TimeUnit.SECONDS.sleep(10); System.out.println("Stopping and closing the processor"); processorClient.close(); } // process a message received from the Service Bus queue private static void processMessage(ServiceBusReceivedMessageContext context) { ServiceBusReceivedMessage message = context.getMessage(); System.out.printf("Processing message. Session: %s, Sequence #: %s. Contents: %s%n", message.getMessageId(), message.getSequenceNumber(), message.getBody()); } // method to handle error messages. private static void processError(ServiceBusErrorContext context, CountDownLatch countdownLatch) { System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n", context.getFullyQualifiedNamespace(), context.getEntityPath()); if (!(context.getException() instanceof ServiceBusException)) { System.out.printf("Non-ServiceBusException occurred: %s%n", context.getException()); return; } ServiceBusException exception = (ServiceBusException) context.getException(); ServiceBusFailureReason reason = exception.getReason(); if (reason == ServiceBusFailureReason.MESSAGING_ENTITY_DISABLED || reason == ServiceBusFailureReason.MESSAGING_ENTITY_NOT_FOUND || reason == ServiceBusFailureReason.UNAUTHORIZED) { System.out.printf("An unrecoverable error occurred. Stopping processing with reason %s: %s%n", reason, exception.getMessage()); // Decrements the count of the latch, releasing all waiting threads ifthe count reaches zero. countdownLatch.countDown(); } else if (reason == ServiceBusFailureReason.MESSAGE_LOCK_LOST) { System.out.printf("Message lock lost for message: %s%n", context.getException()); } else if (reason == ServiceBusFailureReason.SERVICE_BUSY) { try { // Choosing an arbitrary amount of time to wait until trying again. TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.err.println("Unable to sleep for period of time"); } } else { System.out.printf("Error source %s, reason %s, message: %s%n", context.getErrorSource(), reason, context.getException()); } } // Create an instance of the processor through the ServiceBusClientBuilder static ServiceBusProcessorClient createProcessorClient() { // we use a CountDownLatch in order to block a thread until other threads have finished some processing. CountDownLatch countdownLatch = new CountDownLatch(1); // creates a ServiceBusProcessorClient for the queue return new ServiceBusClientBuilder() .connectionString(connectionString) .processor() .queueName(queueName) .processMessage(QueueMain::processMessage) .processError(context -> processError(context, countdownLatch)) .buildProcessorClient(); } }
Java
CL
d3ed370ed5552f5e0893147cc5f5a2774697a20b63fa95e96bec579d547dac39
package com.spontzoug.server.controller; import com.spontzoug.server.redis.IInvitationService; import com.spontzoug.server.http.*; import com.spontzoug.server.model.Business; import com.spontzoug.server.model.PaymentMethod; import com.spontzoug.server.annotation.*; import com.spontzoug.server.redis.ISseService; import com.spontzoug.server.util.SseChannel; import com.spontzoug.server.util.SseEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.codec.ServerSentEvent; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.util.Date; @RestController @RequestMapping("/sse") public class SseController { @Autowired private ISseService sseService; /* @GetMapping(value="/gen/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Mono<Long> gensse( @PathVariable("id") String id) { return sseService.publishEnt(SseChannel.SSE_CHANNEL_ENT, new SseEvent("city",id,"","")); } */ @GetMapping(value="/ent/{region}/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<SseEvent>> entsse( @PathVariable("region") String region, @PathVariable("id") String bizid) { return sseService.entSubscribe(region,bizid) .map(ev -> ServerSentEvent.<SseEvent>builder() .id(Long.toString(new Date().getTime())) .event("sse") .data(ev) .build()); } @GetMapping(value="/cust/{region}/{uid}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<SseEvent>> custsse( @PathVariable("region") String region, @PathVariable("uid") String uid) { return sseService.custSubscribe(region, uid) .map(ev -> ServerSentEvent.<SseEvent>builder() .id(Long.toString(new Date().getTime())) .event("sse") .data(ev) .build()); } /* return Flux.interval(Duration.ofSeconds(2)) .map(seq -> ServerSentEvent.<String>builder() .id(id) .event("periodic-envent") .data("sse-"+LocalTime.now().toString()) .build()); */ }
Java
CL
9701bde194e1d2dadad22fc15da9a8831c88607f8919039795d895161cc6c8e8
package com.study.thinking.in.spring.resource; import com.study.thinking.in.spring.resource.util.ResourceUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.Resource; import javax.annotation.PostConstruct; import java.util.stream.Stream; /** * @Description: 注入 {@link Resource} 对象示例 * @Author Xiaoyaoyou * @Date: 2020/12/2 18:09 * @Version 1.0 * @see Resource * @see Value * @see AnnotationConfigApplicationContext */ public class InjectingResourceDemo { @Value("classpath:/META-INF/default.properties") private Resource resource; @Value("classpath*:/META-INF/*.properties") private Resource[] resources; @Value("${user.dir}") private String currentRootPath; @PostConstruct public void init(){ System.out.println(ResourceUtils.getContent(resource)); System.out.println("=================================="); System.out.println(currentRootPath); System.out.println("=================================="); Stream.of(resources).map(ResourceUtils::getContent).forEach(System.out::println); } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(InjectingResourceDemo.class); context.refresh(); context.close(); } }
Java
CL
3bb6e300cfefbff848e569fe792b9ed44e66d56abeddbc955a2ecf1ae683b89a
package com.project.react_spring.Repository; import com.project.react_spring.Models.Accounts; import com.project.react_spring.Models.Sample; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Component; @Component public interface SampleRepository extends MongoRepository<Accounts, String> { }
Java
CL
9758c8fe5cb18a3a849d77d07a7cbda798aaf994ed29c9755c39cd422b42c347
package mage.cards.h; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.DrawDiscardControllerEffect; import mage.abilities.effects.common.continuous.BoostEnchantedEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.AttachmentType; import mage.constants.CardType; import mage.constants.Outcome; import mage.constants.SubType; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class HardCover extends CardImpl { public HardCover(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{U}"); this.subtype.add(SubType.AURA); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); Ability ability = new EnchantAbility(auraTarget); this.addAbility(ability); // Enchanted creature gets +0/+2 and has "{T}: Draw a card, then discard a card." ability = new SimpleStaticAbility(new BoostEnchantedEffect(0, 2)); ability.addEffect(new GainAbilityAttachedEffect(new SimpleActivatedAbility( new DrawDiscardControllerEffect(1, 1), new TapSourceCost() ), AttachmentType.AURA).setText("and has \"{T}: Draw a card, then discard a card.\"")); this.addAbility(ability); } private HardCover(final HardCover card) { super(card); } @Override public HardCover copy() { return new HardCover(this); } }
Java
CL
df5573be14f3327bcfa0d4da1bba40abf8e4c1c275f55cac3c6355e3eeb8f38d
package org.lukas.javach; import org.lukas.javach.document.*; import org.lukas.javach.editor.Editor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Scanner; /** * Created by Lukas on 27.07.2019. * * @author Lukas Pecak */ class Edi { private static final Logger LOG = LoggerFactory.getLogger(Edi.class); public static void main(String[] args) throws IOException { if (args.length > 1) { LOG.error("Too many arguments. Expected : 1 but was : {}. " + "Please specify only the path to the edited file ...", args.length); } DocumentContentFactory contentFactory = new DocumentContentFactoryImpl(); Document document; if (args.length == 1) { DocumentContent content; DocumentMetadata metadata; byte[] loadedBytes = new Edi().loadBytes(args[0]); if (loadedBytes == null) { content = contentFactory.createDocumentContent(new byte[0]); metadata = DocumentMetadata.EMPTY; } else { content = contentFactory.createDocumentContent(loadedBytes); Path path = Paths.get(args[0]); BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); metadata = DocumentMetadata.createBuilder() .setFileName(path.getFileName().toString()) .setPath(path) .setCreationTime(attributes.creationTime().toInstant()) .setLastModifiedTime(attributes.lastModifiedTime().toInstant()) .setLastAccessTime(attributes.lastAccessTime().toInstant()) .setRegularFile(attributes.isRegularFile()) .setSize(attributes.size()) .build(); } document = new TextDocument(content, metadata); } else { DocumentContent content = contentFactory.createDocumentContent(new byte[0]); DocumentMetadata metadata = DocumentMetadata.EMPTY; document = new TextDocument(content, metadata); } System.out.println("[---METADATA---]"); System.out.println(document.getMetadata()); System.out.println("\n[---CONTENT----]"); Editor editor = new Editor(); editor.openContent(document.getContent()); editor.readAllLines().forEach(System.out::println); } byte[] loadBytes(String pathString) { LOG.debug("Loading file for name : {}", pathString); if (pathString == null || pathString.isEmpty()) { throw new IllegalArgumentException("Path cannot be null or empty"); } byte[] bytes; try { bytes = Files.readAllBytes(Paths.get(pathString)); } catch (IOException e) { LOG.error("Error while trying to read file"); return null; } LOG.debug("File {} loaded successfully", pathString); return bytes; } void saveBytes(byte[] bytes, String pathString) { try { Files.write(Paths.get(pathString), bytes); } catch (IOException e) { LOG.error("Error while trying to save file"); } } }
Java
CL
0c0b5d86af4642c1312c1ed4cebbc1d1f0bb3c2349e7e874b7ffb624c68aaa2a
package cn.e3mall.controller; import cn.e3mall.common.pojo.E3Result; import cn.e3mall.common.pojo.TreeNode; import cn.e3mall.content.service.ContentCatService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class ContentCatController { @Autowired private ContentCatService contentCatService; /** * 查询所有内容 * * @return */ @RequestMapping("/content/category/list") @ResponseBody public List<TreeNode> findCateList(@RequestParam(name = "id", defaultValue = "0") long parentId) { List<TreeNode> list = contentCatService.findCateList(parentId); return list; } /** * 添加新节点 */ @RequestMapping("/content/category/create") @ResponseBody public E3Result creatTreeNode(long parentId, String name) { E3Result result = contentCatService.creatTreeNode(parentId, name); return result; } /** * 修改节点 */ @RequestMapping("/content/category/update") @ResponseBody public void updateNode(long id, String name) { contentCatService.updateNode(id, name); } /** * 删除子节点 */ @RequestMapping("/content/category/delete/") @ResponseBody public E3Result deleteNode(long id) { E3Result result = contentCatService.deleteNode(id); return result; } }
Java
CL
9de9b099d3a732e6ebae716fa59e0e001be10d9855704f879de581a28f1f9b44
/* The MIT License (MIT) Copyright (c) 2013 yinzara Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.yinzara.jasperreports.fonts.maven.plugin; /** * * @author Matthew */ public class FamilyRename { /** * The font family to rename from. */ private String fromFamily; /** * The font family to rename to. */ private String toFamily; /** * Gets the family to match font family name against. * * @return The font family name */ public String getFromFamily() { return fromFamily; } /** * Sets the family to match font family name against. * * @param fromFamily Family to set */ public void setFromFamily(final String fromFamily) { this.fromFamily = fromFamily; } /** * Gets the family name to set the font family to. * * @return The font family name */ public String getToFamily() { return toFamily; } /** * Sets the family name to set the font family to. * * @param toFamily Family to set */ public void setToFamily(final String toFamily) { this.toFamily = toFamily; } }
Java
CL
f55a4b0d46111499cc205d01aa1339f3b468ef59410e0127ba1a5163b042b582
package com.anisat.authendication.jwtauth.controller; import com.anisat.authendication.jwtauth.controller.model.UserModel; import com.anisat.authendication.jwtauth.service.JwtUserDetailsService; import com.anisat.authendication.jwtauth.service.convertor.JwtServiceConvertor; import com.anisat.authendication.jwtauth.service.dto.UserDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; @RestController public class HomepageController { @Autowired JwtUserDetailsService userDetailsService; @Autowired JwtServiceConvertor jwtServiceConvertor; @GetMapping("/home") public String loadHomePage() { return "home"; } }
Java
CL
c4ae570e8373972b07a8b9e7a8e63947ce2bce3a48d1893fa5ba178ec04b5fba
package info.u_team.u_team_core.impl; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; import info.u_team.u_team_core.api.network.NetworkContext; import info.u_team.u_team_core.api.network.NetworkEnvironment; import info.u_team.u_team_core.api.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; public class ForgeNetworkHandler implements NetworkHandler { private final String protocolVersion; private Predicate<String> clientAcceptedVersions; private Predicate<String> serverAcceptedVersions; private final SimpleChannel network; ForgeNetworkHandler(String protocolVersion, ResourceLocation channel) { this.protocolVersion = protocolVersion; clientAcceptedVersions = protocolVersion::equals; serverAcceptedVersions = protocolVersion::equals; network = NetworkRegistry.newSimpleChannel(channel, () -> protocolVersion, version -> clientAcceptedVersions.test(version), version -> serverAcceptedVersions.test(version)); } @Override public <M> void registerMessage(int index, Class<M> clazz, BiConsumer<M, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, M> decoder, BiConsumer<M, NetworkContext> messageConsumer, Optional<NetworkEnvironment> handlerEnvironment) { network.registerMessage(index, clazz, encoder, decoder, (message, contextSupplier) -> { final NetworkEvent.Context context = contextSupplier.get(); messageConsumer.accept(message, new ForgeNetworkContext(context)); context.setPacketHandled(true); }, handlerEnvironment.map(environment -> { return switch (environment) { case CLIENT -> NetworkDirection.PLAY_TO_CLIENT; case SERVER -> NetworkDirection.PLAY_TO_SERVER; }; })); } @Override public <M> void sendToPlayer(ServerPlayer player, M message) { network.send(PacketDistributor.PLAYER.with(() -> player), message); } @Override public <M> void sendToServer(M message) { network.send(PacketDistributor.SERVER.noArg(), message); } @Override public String getProtocolVersion() { return protocolVersion; } @Override public void setProtocolAcceptor(Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) { this.clientAcceptedVersions = clientAcceptedVersions; this.serverAcceptedVersions = serverAcceptedVersions; } @OnlyIn(Dist.CLIENT) private class Client { @OnlyIn(Dist.CLIENT) private static Player getClientPlayer() { return Minecraft.getInstance().player; } } public static class ForgeNetworkContext implements NetworkContext { private final NetworkEvent.Context context; ForgeNetworkContext(NetworkEvent.Context context) { this.context = context; } @Override public NetworkEnvironment getEnvironment() { return switch (context.getDirection().getReceptionSide()) { case CLIENT -> NetworkEnvironment.CLIENT; case SERVER -> NetworkEnvironment.SERVER; }; } @Override public Player getPlayer() { if (context.getDirection().getReceptionSide() == LogicalSide.CLIENT) { return DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> () -> Client.getClientPlayer()); } return context.getSender(); } @Override public void executeOnMainThread(Runnable runnable) { context.enqueueWork(runnable); } } public static class Factory implements NetworkHandler.Factory { @Override public NetworkHandler create(String protocolVersion, ResourceLocation location) { return new ForgeNetworkHandler(protocolVersion, location); } } }
Java
CL
fbfdd30557203aa395c447d986b6958e1862e29fd84c52d6f2e958c22e61e35b
package com.visni.smartchannelling.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.AliasToBeanResultTransformer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.visni.smartchannelling.entity.HospitalRole; import com.visni.smartchannelling.entity.HospitalSpecialization; import com.visni.smartchannelling.entity.Specialization; import com.visni.smartchannelling.entity.UserRole; import com.visni.smartchannelling.util.ActiveStatus; @Repository("masterDataDAO") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) @SuppressWarnings("unchecked") public class MasterDataDAOImpl implements MasterDataDAO { private String SUCCESS = "success"; @Autowired private SessionFactory sessionFactory; @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String saveSpecialization(Specialization specialization) throws Exception { return (String) sessionFactory.getCurrentSession().save(specialization); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String updateSpecialization(Specialization specialization) throws Exception { sessionFactory.getCurrentSession().save(specialization); return SUCCESS; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String deleteSpecialzation(Specialization specialization) throws Exception { sessionFactory.getCurrentSession().delete(specialization); return SUCCESS; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String saveHospitalRole(HospitalRole hospitalRole) throws Exception { return (String) sessionFactory.getCurrentSession().save(hospitalRole); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String updateHospitalRole(HospitalRole hospitalRole) throws Exception { sessionFactory.getCurrentSession().update(hospitalRole); return SUCCESS ; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public String deleteHospitalRole(HospitalRole hospitalRole) throws Exception { sessionFactory.getCurrentSession().delete(hospitalRole); return SUCCESS; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public HospitalRole getHospitalRoleById(String hospitalRoleId) throws Exception{ Criteria criteria = sessionFactory.getCurrentSession().createCriteria(HospitalRole.class); criteria.add(Restrictions.eq("hospitalRoleId", hospitalRoleId)); return (HospitalRole) criteria.uniqueResult(); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public List<Specialization> getAllActiveSpecializations() throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Specialization.class, "sp"); criteria.setProjection(Projections.projectionList().add(Property.forName("sp.specializationId").as("specializationId")) .add(Property.forName("sp.activeStatus").as("activeStatus")).add(Property.forName("sp.name").as("name")) .add(Property.forName("sp.description").as("description")).add(Property.forName("sp.area").as("area")) .add(Property.forName("sp.versionId").as("versionId")) ); criteria.add(Restrictions.eq("sp.activeStatus", ActiveStatus.ACTIVE)); criteria.addOrder(Order.asc("specializationId")); List<Specialization> specializations = criteria.setResultTransformer(new AliasToBeanResultTransformer(Specialization.class)).list(); return specializations; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public List<HospitalRole> getAllActiveHospitalRole() throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(HospitalRole.class, "hr"); criteria.setProjection(Projections.projectionList().add(Property.forName("hr.hospitalRoleId").as("hospitalRoleId")) .add(Property.forName("hr.activeStatus").as("activeStatus")).add(Property.forName("hr.name").as("name")) .add(Property.forName("hr.description").as("description")).add(Property.forName("hr.versionId").as("versionId"))); criteria.add(Restrictions.eq("hr.activeStatus", ActiveStatus.ACTIVE)); criteria.addOrder(Order.asc("hospitalRoleId")); List<HospitalRole> hospitalRoles = criteria.setResultTransformer(new AliasToBeanResultTransformer(HospitalRole.class)).list(); return hospitalRoles; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public List<UserRole> getAllUserRoles() throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(UserRole.class, "ur"); return criteria.list(); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public Specialization getSpecializationById(String id) throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Specialization.class, "sp"); // criteria.setProjection(Projections.projectionList() // .add(Property.forName("sp.specializationId").as("specializationId")) // .add(Property.forName("sp.name").as("name")) // .add(Property.forName("sp.versionId").as("versionId"))); criteria.add(Restrictions.conjunction().add(Restrictions.eq("sp.specializationId", id)) .add(Restrictions.eq("sp.activeStatus", ActiveStatus.ACTIVE))); return (Specialization) criteria.uniqueResult(); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public HospitalSpecialization getHospitalSpecializationById(String id) throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(HospitalSpecialization.class, "hs"); criteria.setProjection(Projections.projectionList().add(Property.forName("hs.hospitalSpecializationId").as("hospitalSpecializationId")) .add(Property.forName("hs.versionId").as("versionId"))); criteria.add(Restrictions.conjunction().add(Restrictions.eq("hs.specializationId", id)) .add(Restrictions.eq("hs.activeStatus", ActiveStatus.ACTIVE))); HospitalSpecialization hospitalSpecialization = (HospitalSpecialization) criteria.setResultTransformer( new AliasToBeanResultTransformer(HospitalSpecialization.class)).uniqueResult(); return hospitalSpecialization; } }
Java
CL
0ad611c05634a623c08418abf823b2f260e2c4aa55d181ca4fab7b1e8853c358
/* * Copyright (C) 2018. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at support@openlattice.com * */ package com.openlattice.mail; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; public class EmailRequest { protected static final String FROM_FIELD = "from"; protected static final String TO_FIELD = "to"; protected static final String CC_FIELD = "cc"; protected static final String BCC_FIELD = "bcc"; private final Optional<String> from; private final String[] to; private final Optional<String[]> cc; private final Optional<String[]> bcc; public EmailRequest( Optional<String> from, String[] to, Optional<String[]> cc, Optional<String[]> bcc ) { this.from = Preconditions.checkNotNull( from ); this.to = ImmutableList.copyOf( Arrays.asList( Preconditions.checkNotNull( to ) ).stream() .filter( input -> StringUtils.isNotBlank( input ) ).collect( Collectors.toList() ) ).toArray( new String[ 0 ] ); this.cc = Preconditions.checkNotNull( cc ); this.bcc = Preconditions.checkNotNull( bcc ); Preconditions.checkState( this.to.length > 0 ); } @JsonProperty( FROM_FIELD ) public Optional<String> getFrom() { return from; } @SuppressFBWarnings(value="EI_EXPOSE_REP",justification = "Only used internally hopefully not abused.") @JsonProperty( TO_FIELD ) public String[] getTo() { return to; } @JsonProperty( CC_FIELD ) public Optional<String[]> getCc() { return cc; } @JsonProperty( BCC_FIELD ) public Optional<String[]> getBcc() { return bcc; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( bcc == null ) ? 0 : bcc.hashCode() ); result = prime * result + ( ( cc == null ) ? 0 : cc.hashCode() ); result = prime * result + ( ( from == null ) ? 0 : from.hashCode() ); result = prime * result + Arrays.hashCode( to ); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; EmailRequest other = (EmailRequest) obj; if ( bcc == null ) { if ( other.bcc != null ) return false; } else if ( !bcc.equals( other.bcc ) ) return false; if ( cc == null ) { if ( other.cc != null ) return false; } else if ( !cc.equals( other.cc ) ) return false; if ( from == null ) { if ( other.from != null ) return false; } else if ( !from.equals( other.from ) ) return false; if ( !Arrays.equals( to, other.to ) ) return false; return true; } }
Java
CL
378b579a85d5911c6e9b4339b032805c63e974db3048c42b62a1682325a805fc
/* * Copyright 2021 Red Hat, 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 loginmodules; import org.wildfly.security.auth.principal.NamePrincipal; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import java.io.IOException; import java.security.Principal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * A {@link LoginModule} implementation used in the JAAS security realm tests. It uses a static * map of username -> password to determine if a login is successful or not. */ public class CustomLoginModule implements LoginModule { private final Map<String, char[]> usersMap = new HashMap<String, char[]>(); private Principal principal; private Subject subject; private CallbackHandler handler; @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { this.subject = subject; this.handler = callbackHandler; this.usersMap.put("user1", "password1".toCharArray()); this.usersMap.put("user2", "password2".toCharArray()); } @Override public boolean login() throws LoginException { // obtain the incoming username and password from the callback handler NameCallback nameCallback = new NameCallback("Username"); PasswordCallback passwordCallback = new PasswordCallback("Password", false); Callback[] callbacks = new Callback[]{nameCallback, passwordCallback}; try { this.handler.handle(callbacks); } catch (UnsupportedCallbackException | IOException e) { throw new LoginException("Error handling callback: " + e.getMessage()); } final String username = nameCallback.getName(); this.principal = new NamePrincipal(username); final char[] password = passwordCallback.getPassword(); char[] storedPassword = this.usersMap.get(username); if (!Arrays.equals(storedPassword, password)) { throw new LoginException("Invalid password"); } else { return true; } } @Override public boolean commit() throws LoginException { if (this.principal.getName().equals("user1") || this.principal.getName().equals("user2")) { this.subject.getPrincipals().add(new Roles("Admin")); this.subject.getPrincipals().add(new Roles("User")); this.subject.getPrincipals().add(new Roles("Guest")); } return true; } @Override public boolean abort() throws LoginException { return true; } @Override public boolean logout() throws LoginException { this.subject.getPrincipals().clear(); return true; } private static class Roles implements Principal { private final String name; Roles(final String name) { this.name = name; } public String getName() { return this.name; } } }
Java
CL
6e38401032bf080a2b55c468399df4527269c08a1a1d80bcd9b4a7bc82e4ccd6
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.communication.phonenumbers.siprouting; import com.azure.communication.phonenumbers.siprouting.models.SipTrunk; import com.azure.communication.phonenumbers.siprouting.models.SipTrunkRoute; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.*; @Execution(value = ExecutionMode.SAME_THREAD) public class SipRoutingClientIntegrationTest extends SipRoutingIntegrationTestBase { // get trunk @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void getTrunkNotExisting(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "getTrunkNotExistingSync"); SipTrunk trunk = client.getTrunk(NOT_EXISTING_FQDN); assertNull(trunk); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void getTrunkNotExistingWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "getTrunkNotExistingWithResponseSync"); Response<SipTrunk> response = client.getTrunkWithResponse(NOT_EXISTING_FQDN, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertNull(response.getValue()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void getTrunkExisting(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "getTrunkExistingSync"); client.setTrunk(SET_TRUNK); SipTrunk trunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(trunk); assertEquals(SET_TRUNK_PORT, trunk.getSipSignalingPort()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void getTrunkExistingWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "getTrunkExistingWithResponseSync"); client.setTrunk(SET_TRUNK); Response<SipTrunk> response = client.getTrunkWithResponse(SET_TRUNK_FQDN, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); SipTrunk trunk = response.getValue(); assertNotNull(trunk); assertEquals(SET_TRUNK_PORT, trunk.getSipSignalingPort()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void getTrunkExistingWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "getTrunkExistingWithAADSync"); client.setTrunk(SET_TRUNK); SipTrunk trunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(trunk); assertEquals(SET_TRUNK_PORT, trunk.getSipSignalingPort()); } // list trunks @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listTrunksEmpty(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "listTrunksEmptySync"); client.setTrunks(new ArrayList<>()); PagedIterable<SipTrunk> trunks = client.listTrunks(); assertNotNull(trunks); assertTrue(getAsList(trunks).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listTrunksNotEmpty(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "listTrunksNotEmptySync"); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listTrunksNotEmptyWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "listTrunksNotEmptyWithAADSync"); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } // list routes @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listRoutesEmpty(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "listRoutesEmptySync"); client.setRoutes(new ArrayList<>()); PagedIterable<SipTrunkRoute> routes = client.listRoutes(); assertNotNull(routes); assertTrue(getAsList(routes).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listRoutesNotEmpty(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "listRoutesNotEmptySync"); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void listRoutesNotEmptyWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "listRoutesNotEmptyWithAADSync"); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); } // set trunk @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunkNotExistingEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunkNotExistingEmptyBeforeSync"); client.setTrunks(new ArrayList<>()); List<SipTrunk> trunksAsList = getAsList(client.listTrunks()); assertTrue(trunksAsList.size() == 0); client.setTrunk(SET_TRUNK); SipTrunk storedTrunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(storedTrunk); assertEquals(SET_TRUNK_PORT, storedTrunk.getSipSignalingPort()); assertEquals(1, getAsList(client.listTrunks()).size()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunkNotExistingNotEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunkNotExistingNotEmptyBeforeSync"); List<SipTrunk> initialTrunks = EXPECTED_TRUNKS; client.setTrunks(initialTrunks); validateTrunks(initialTrunks, client.listTrunks()); client.setTrunk(SET_TRUNK); SipTrunk storedTrunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(storedTrunk); assertEquals(SET_TRUNK_PORT, storedTrunk.getSipSignalingPort()); ArrayList<SipTrunk> expectedTrunks = new ArrayList<>(initialTrunks); expectedTrunks.add(SET_TRUNK); validateTrunks(expectedTrunks, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunkExisting(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunkExistingSync"); List<SipTrunk> expectedTrunks = new ArrayList<>(EXPECTED_TRUNKS); expectedTrunks.add(SET_TRUNK); client.setTrunks(expectedTrunks); validateTrunks(expectedTrunks, client.listTrunks()); client.setTrunk(SET_UPDATED_TRUNK); SipTrunk storedTrunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(storedTrunk); assertEquals(SET_TRUNK_UPDATED_PORT, storedTrunk.getSipSignalingPort()); expectedTrunks = new ArrayList<>(EXPECTED_TRUNKS); expectedTrunks.add(SET_UPDATED_TRUNK); validateTrunks(expectedTrunks, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunkExistingWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "setTrunkExistingWithAADSync"); List<SipTrunk> expectedTrunks = new ArrayList<>(EXPECTED_TRUNKS); expectedTrunks.add(SET_TRUNK); client.setTrunks(expectedTrunks); validateTrunks(expectedTrunks, client.listTrunks()); client.setTrunk(SET_UPDATED_TRUNK); SipTrunk storedTrunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(storedTrunk); assertEquals(SET_TRUNK_UPDATED_PORT, storedTrunk.getSipSignalingPort()); expectedTrunks = new ArrayList<>(EXPECTED_TRUNKS); expectedTrunks.add(SET_UPDATED_TRUNK); validateTrunks(expectedTrunks, client.listTrunks()); } // set trunks @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksEmptyBeforeSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksEmptyBeforeWithResponseSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); Response<Void> response = client.setTrunksWithResponse(EXPECTED_TRUNKS, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksEmptyBeforeWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksEmptyBeforeWithAADSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksNotEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksNotEmptyBeforeSync"); client.setTrunks(UPDATED_TRUNKS); List<SipTrunk> trunksAsList = getAsList(client.listTrunks()); assertEquals(UPDATED_TRUNKS.size(), trunksAsList.size()); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksNotEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksNotEmptyBeforeWithResponseSync"); client.setTrunks(UPDATED_TRUNKS); List<SipTrunk> trunksAsList = getAsList(client.listTrunks()); assertEquals(UPDATED_TRUNKS.size(), trunksAsList.size()); Response<Void> response = client.setTrunksWithResponse(EXPECTED_TRUNKS, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksWithoutAffectingRoutes(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksWithoutAffectingRoutesSync"); client.setRoutes(EXPECTED_ROUTES); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksWithoutAffectingRoutesWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksWithoutAffectingRoutesWithResponseSync"); client.setRoutes(EXPECTED_ROUTES); Response<Void> response = client.setTrunksWithResponse(EXPECTED_TRUNKS, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyTrunksNotEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyTrunksNotEmptyBeforeSync"); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyTrunksNotEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyTrunksNotEmptyBeforeWithResponseSync"); client.setTrunks(EXPECTED_TRUNKS); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); Response<Void> response = client.setTrunksWithResponse(new ArrayList<>(), Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertTrue(getAsList(client.listTrunks()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyTrunksEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyTrunksEmptyBeforeSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyTrunksEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyTrunksEmptyBeforeWithResponseSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); Response<Void> response = client.setTrunksWithResponse(new ArrayList<>(), Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertTrue(getAsList(client.listTrunks()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksInvalidFqdn(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksInvalidFqdnSync"); SipTrunk invalidTrunk = new SipTrunk(SET_TRUNK_INVALID_FQDN, SET_TRUNK_PORT); assertThrows(HttpResponseException.class, () -> client.setTrunk(invalidTrunk)); assertThrows(HttpResponseException.class, () -> client.setTrunks(asList(invalidTrunk))); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksInvalidPort(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksInvalidPortSync"); client.setTrunk(SET_TRUNK); SipTrunk invalidTrunk = new SipTrunk(SET_TRUNK_FQDN, SET_TRUNK_INVALID_PORT); assertThrows(HttpResponseException.class, () -> client.setTrunk(invalidTrunk)); assertThrows(HttpResponseException.class, () -> client.setTrunks(asList(invalidTrunk))); SipTrunk storedTrunk = client.getTrunk(SET_TRUNK_FQDN); assertNotNull(storedTrunk); assertEquals(SET_TRUNK_PORT, storedTrunk.getSipSignalingPort()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksRemoveRequiredTrunk(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksRemoveRequiredTrunkSync"); client.setTrunk(SET_TRUNK); client.setRoutes(EXPECTED_ROUTES_WITH_REFERENCED_TRUNK); assertThrows(HttpResponseException.class, () -> client.setTrunks(EXPECTED_TRUNKS)); assertThrows(HttpResponseException.class, () -> client.deleteTrunk(SET_TRUNK_FQDN)); client.setRoutes(new ArrayList<>()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setTrunksRemoveRequiredTrunkWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setTrunksRemoveRequiredTrunkWithResponseSync"); client.setTrunk(SET_TRUNK); client.setRoutes(EXPECTED_ROUTES_WITH_REFERENCED_TRUNK); assertThrows(HttpResponseException.class, () -> client.setTrunksWithResponse(EXPECTED_TRUNKS, Context.NONE)); assertThrows(HttpResponseException.class, () -> client.deleteTrunkWithResponse(SET_TRUNK_FQDN, Context.NONE)); client.setRoutes(new ArrayList<>()); } // set routes @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesEmptyBeforeSync"); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesEmptyBeforeWithResponseSync"); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); Response<Void> response = client.setRoutesWithResponse(EXPECTED_ROUTES, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesEmptyBeforeWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "setRoutesEmptyBeforeWithAADSync"); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesNotEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesNotEmptyBeforeSync"); client.setRoutes(UPDATED_ROUTES); List<SipTrunkRoute> routesAsList = getAsList(client.listRoutes()); assertEquals(UPDATED_ROUTES.size(), routesAsList.size()); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesNotEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesNotEmptyBeforeWithResponseSync"); client.setRoutes(UPDATED_ROUTES); List<SipTrunkRoute> routesAsList = getAsList(client.listRoutes()); assertEquals(UPDATED_ROUTES.size(), routesAsList.size()); Response<Void> response = client.setRoutesWithResponse(EXPECTED_ROUTES, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateExpectedRoutes(client.listRoutes()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesWithoutAffectingTrunks(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesWithoutAffectingTrunksSync"); client.setTrunks(EXPECTED_TRUNKS); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesWithoutAffectingTrunksWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesWithoutAffectingTrunksWithResponseSync"); client.setTrunks(EXPECTED_TRUNKS); Response<Void> response = client.setRoutesWithResponse(EXPECTED_ROUTES, Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); validateExpectedRoutes(client.listRoutes()); validateTrunks(EXPECTED_TRUNKS, client.listTrunks()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyRoutesNotEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyRoutesNotEmptyBeforeSync"); client.setRoutes(EXPECTED_ROUTES); validateExpectedRoutes(client.listRoutes()); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyRoutesNotEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyRoutesNotEmptyBeforeWithResponseSync"); client.setRoutes(EXPECTED_ROUTES); PagedIterable<SipTrunkRoute> iter = client.listRoutes(); validateExpectedRoutes(iter); Response<Void> response = client.setRoutesWithResponse(new ArrayList<>(), Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertTrue(getAsList(client.listRoutes()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyRoutesEmptyBefore(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyRoutesEmptyBeforeSync"); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setEmptyRoutesEmptyBeforeWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setEmptyRoutesEmptyBeforeWithResponseSync"); client.setRoutes(new ArrayList<>()); assertTrue(getAsList(client.listRoutes()).size() == 0); Response<Void> response = client.setRoutesWithResponse(new ArrayList<>(), Context.NONE); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertTrue(getAsList(client.listRoutes()).size() == 0); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesInvalidName(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesInvalidNameSync"); SipTrunkRoute invalidRoute = new SipTrunkRoute(null, SET_TRUNK_ROUTE_NUMBER_PATTERN); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutes(asList(invalidRoute))); assertEquals(MESSAGE_INVALID_ROUTE_NAME, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesInvalidNameWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesInvalidNameWithResponseSync"); SipTrunkRoute invalidRoute = new SipTrunkRoute(null, SET_TRUNK_ROUTE_NUMBER_PATTERN); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutesWithResponse(asList(invalidRoute), Context.NONE)); assertEquals(MESSAGE_INVALID_ROUTE_NAME, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesInvalidNumberPattern(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesInvalidNumberPatternSync"); SipTrunkRoute invalidRoute = new SipTrunkRoute(SET_TRUNK_ROUTE_NAME, null); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutes(asList(invalidRoute))); assertEquals(MESSAGE_INVALID_NUMBER_PATTERN, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesInvalidNumberPatternWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesInvalidNumberPatternWithResponseSync"); SipTrunkRoute invalidRoute = new SipTrunkRoute(SET_TRUNK_ROUTE_NAME, null); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutesWithResponse(asList(invalidRoute), Context.NONE)); assertEquals(MESSAGE_INVALID_NUMBER_PATTERN, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesDuplicatedRoutes(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesDuplicatedRoutesSync"); List<SipTrunkRoute> invalidRoutes = asList(SET_TRUNK_ROUTE, SET_TRUNK_ROUTE); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutes(invalidRoutes)); assertEquals(MESSAGE_DUPLICATE_ROUTES, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesDuplicatedRoutesWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesDuplicatedRoutesWithResponseSync"); List<SipTrunkRoute> invalidRoutes = asList(SET_TRUNK_ROUTE, SET_TRUNK_ROUTE); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutesWithResponse(invalidRoutes, Context.NONE)); assertEquals(MESSAGE_DUPLICATE_ROUTES, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesDuplicatedRoutingTrunks(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesDuplicatedRoutingTrunksSync"); client.setTrunk(SET_TRUNK); SipTrunkRoute routeWithDuplicatedTrunks = new SipTrunkRoute(SET_TRUNK_ROUTE_NAME, SET_TRUNK_ROUTE_NUMBER_PATTERN) .setTrunks(asList(SET_TRUNK_FQDN, SET_TRUNK_FQDN)); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutes(asList(routeWithDuplicatedTrunks))); assertEquals(MESSAGE_DUPLICATE_TRUNKS, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesDuplicatedRoutingTrunksWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesDuplicatedRoutingTrunksWithResponseSync"); client.setTrunk(SET_TRUNK); SipTrunkRoute routeWithDuplicatedTrunks = new SipTrunkRoute(SET_TRUNK_ROUTE_NAME, SET_TRUNK_ROUTE_NUMBER_PATTERN) .setTrunks(asList(SET_TRUNK_FQDN, SET_TRUNK_FQDN)); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutesWithResponse(asList(routeWithDuplicatedTrunks), Context.NONE)); assertEquals(MESSAGE_DUPLICATE_TRUNKS, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesMissingTrunk(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesMissingTrunkSync"); client.setTrunks(new ArrayList<>()); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutes(EXPECTED_ROUTES_WITH_REFERENCED_TRUNK)); assertEquals(MESSAGE_MISSING_TRUNK, exception.getMessage()); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void setRoutesMissingTrunkWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "setRoutesMissingTrunkWithResponseSync"); client.setTrunks(new ArrayList<>()); Throwable exception = assertThrows(HttpResponseException.class, () -> client.setRoutesWithResponse(EXPECTED_ROUTES_WITH_REFERENCED_TRUNK, Context.NONE)); assertEquals(MESSAGE_MISSING_TRUNK, exception.getMessage()); } // delete trunk @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void deleteTrunkExisting(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "deleteTrunkExistingSync"); client.setTrunk(DELETE_TRUNK); assertNotNull(client.getTrunk(DELETE_FQDN)); client.deleteTrunk(DELETE_FQDN); assertNull(client.getTrunk(DELETE_FQDN)); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void deleteTrunkExistingWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "deleteTrunkExistingWithResponseSync"); client.setTrunk(DELETE_TRUNK); assertNotNull(client.getTrunk(DELETE_FQDN)); Response<Void> response = client.deleteTrunkWithResponse(DELETE_FQDN, Context.NONE); assertNotNull(response); assertNull(response.getValue()); assertEquals(200, response.getStatusCode()); assertNull(client.getTrunk(DELETE_FQDN)); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void deleteTrunkExistingWithAAD(HttpClient httpClient) { SipRoutingClient client = getClientWithManagedIdentity(httpClient, "deleteTrunkExistingWithAADSync"); client.setTrunk(DELETE_TRUNK); assertNotNull(client.getTrunk(DELETE_FQDN)); client.deleteTrunk(DELETE_FQDN); assertNull(client.getTrunk(DELETE_FQDN)); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void deleteTrunkNotExisting(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "deleteTrunkNotExistingSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); assertNull(client.getTrunk(DELETE_FQDN)); client.deleteTrunk(DELETE_FQDN); assertNull(client.getTrunk(DELETE_FQDN)); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable(named = "SKIP_SIP_ROUTING_LIVE_TESTS", matches = "(?i)(true)") public void deleteTrunkNotExistingWithResponse(HttpClient httpClient) { SipRoutingClient client = getClientWithConnectionString(httpClient, "deleteTrunkNotExistingWithResponseSync"); client.setTrunks(new ArrayList<>()); assertTrue(getAsList(client.listTrunks()).size() == 0); assertNull(client.getTrunk(DELETE_FQDN)); Response<Void> response = client.deleteTrunkWithResponse(DELETE_FQDN, Context.NONE); assertNotNull(response); assertNull(response.getValue()); assertEquals(200, response.getStatusCode()); assertNull(client.getTrunk(DELETE_FQDN)); } private void validateTrunks(List<SipTrunk> expected, PagedIterable<SipTrunk> actual) { assertNotNull(actual); List<SipTrunk> trunksList = getAsList(actual); assertEquals(expected.size(), trunksList.size()); for (SipTrunk expectedTrunk : expected) { Optional<SipTrunk> actualTrunk = trunksList.stream() .filter(value -> Objects.equals(expectedTrunk.getFqdn(), value.getFqdn())).findAny(); assertTrue(actualTrunk.isPresent()); assertEquals(expectedTrunk.getSipSignalingPort(), actualTrunk.get().getSipSignalingPort()); } } private void validateExpectedRoutes(PagedIterable<SipTrunkRoute> routes) { assertNotNull(routes); List<SipTrunkRoute> routesList = getAsList(routes); assertEquals(3, routesList.size()); for (int i = 0; i < routesList.size(); i++) { SipTrunkRoute route = routesList.get(i); assertEquals("route" + i, route.getName()); assertEquals(i + ".*", route.getNumberPattern()); assertEquals("desc" + i, route.getDescription()); assertTrue(route.getTrunks().isEmpty()); } } private SipRoutingClient getClientWithConnectionString(HttpClient httpClient, String testName) { SipRoutingClientBuilder builder = super.getClientBuilderWithConnectionString(httpClient); return addLoggingPolicy(builder, testName).buildClient(); } private SipRoutingClient getClientWithManagedIdentity(HttpClient httpClient, String testName) { SipRoutingClientBuilder builder = super.getClientBuilderUsingManagedIdentity(httpClient); return addLoggingPolicy(builder, testName).buildClient(); } private <T> List<T> getAsList(PagedIterable<T> listIterable) { List<T> list = new ArrayList<T>(); listIterable.streamByPage().forEach(resp -> { resp.getElements().forEach(value -> list.add(value)); }); return list; } }
Java
CL
be443782d80b06f2e49362e7107df36e59773581d6de93ddc74040017e49ac0a
/* * #%L * share-po * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.po.share.dashlet; import org.alfresco.po.RenderTime; import org.alfresco.po.RenderWebElement; import org.openqa.selenium.WebDriver; import org.alfresco.po.exception.PageOperationException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebElement; /** * This page object is to set the image into site notice dashlet. This Page holds all the required element finding methods. * * @author cbairaajoni */ public class InsertOrEditImagePage extends BaseAdvancedTinyMceOptionsPage { private static Log logger = LogFactory.getLog(InsertOrEditImagePage.class); @RenderWebElement private static By IMAGE_URL_CSS = By.xpath("//div[starts-with(@class, 'mce-container-body')]/label[contains(text(), 'Source')]/following-sibling::div/input[starts-with(@class, 'mce-textbox')]"); @RenderWebElement private static By IMAGE_DESC_CSS = By.xpath("//div[starts-with(@class, 'mce-container-body')]/label[contains(text(), 'description')]/following-sibling::input[starts-with(@class, 'mce-textbox')]"); @RenderWebElement private static By DIMENSIONS_HEIGHT_CSS2 = By.xpath("//input[starts-with(@class, 'mce-textbox') and @aria-label='Height']"); @RenderWebElement private static By DIMENSIONS_WIDTH_CSS1 = By.xpath("//input[starts-with(@class, 'mce-textbox') and @aria-label='Width']"); /** * Constructor. * * @param drone WebDrone * @param element WebElement */ public InsertOrEditImagePage(WebDriver driver, WebElement element) { super(driver, element); } /** * This enum is used to describe the target items present on alignment dropdown. */ public enum ImageAlignment { NOT_SET("-- Not Set --"), BASE_LINE("Baseline"), TOP("Top"), MIDDLE("Middle"), BOTTOM("Bottom"), TEXT_TOP("Text Top"), TEXT_BOTTOM("Text Bottom"), LEFT("Left"), RIGHT("Right"); private String itemName; private ImageAlignment(String name) { itemName = name; } public String getItemName() { return itemName; } } @SuppressWarnings("unchecked") @Override public InsertOrEditImagePage render(RenderTime timer) { webElementRender(timer); return this; } @SuppressWarnings("unchecked") @Override public InsertOrEditImagePage render() { return render(new RenderTime(maxPageLoadingTime)); } /** * This method sets the given text into Link Url. * * @param url String */ public void setImageUrl(String url) { if (StringUtils.isEmpty(url)) { throw new IllegalArgumentException("Link url value is required"); } try { WebElement imageUrlField = findAndWait(IMAGE_URL_CSS); imageUrlField.clear(); imageUrlField.sendKeys(url); } catch (TimeoutException te) { logger.info("Unable to find the image Url field.", te); throw new PageOperationException("Unable to find image Url field.", te); } } /** * This method sets the given description into image description field. * * @param desc String */ public void setDescription(String desc) { if (desc == null) { throw new IllegalArgumentException("Description should not be null"); } try { WebElement descriptionField = findAndWait(IMAGE_DESC_CSS); descriptionField.clear(); descriptionField.sendKeys(desc); } catch (TimeoutException te) { logger.info("Unable to find the image descrption field.", te); throw new PageOperationException("Unable to find image descrption field."); } } // /** // * This method sets the given Target item from the Target dropdown values. // * // * @param target // */ // public void setAlignment(ImageAlignment target) // { // if (target == null) // { // throw new IllegalArgumentException("Alignment value is required"); // } // // try // { // selectOption(ALIGNMENT_CSS, target.getItemName()); // } // catch (TimeoutException te) // { // logger.info("Unable to find the Alignment Item field.", te); // throw new PageOperationException("Unable to find Alignment Item field."); // } // } /** * This method sets the given description into image description field. * * @param width long * @param height long */ public void setDimensions(long width, long height) { if (width < 0 || height < 0) { throw new IllegalArgumentException("Width or Height of Image values should not be less than 0"); } try { WebElement widthElement = findAndWait(DIMENSIONS_WIDTH_CSS1); widthElement.clear(); widthElement.sendKeys(Long.valueOf(width).toString()); WebElement heightElement = findAndWait(DIMENSIONS_HEIGHT_CSS2); heightElement.clear(); heightElement.sendKeys(Long.valueOf(height).toString()); } catch (TimeoutException te) { logger.info("Unable to find the image dimensions field.", te); throw new PageOperationException("Unable to find image dimensions field.", te); } } }
Java
CL
8ead57c70dde107da9d1fca67ac113b51ab974b87f26b5ba5ddbf262a0437229
package com.example.android.myexpensemanager; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; public class VRExpense extends AppCompatActivity { static String TAG = VRExpense.class.getName(); SpeechRecognizer mRecognizer = null; public static final String PRICE_KEY_CODE = "price_key_code"; public static final String DATE_KEY_CODE = "date_key_code"; private static final int RECORD_PERMISSION_CODE = 101; private boolean mFoundDate = false; private String[] mDate = {"", "", ""}; private boolean mFoundPrice = false; private double mPrice = 0; private boolean mFoundOperation = false; final RecognitionListener listener = new RecognitionListener() { @Override public void onResults(Bundle results) { Log.i(TAG, "onResult()"); final ArrayList<String> voiceResults = results .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); final float[] confidenceScore = results .getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES); Log.i(TAG, "Obtaining matches: "); Runnable tokenizeRunnable = new Runnable() { @Override public void run() { Log.d(TAG, "Thread in action " + Thread.currentThread().getName()); int index = 0; try { if (voiceResults != null) { assert confidenceScore != null; for(String res : voiceResults) { Log.i(TAG, "result = " + res + " score = " + confidenceScore[index]); if (!mFoundDate || !mFoundOperation || !mFoundPrice) { analyzeRecord(res); } } } else { Log.i(TAG, "voice result is null"); } } catch (Exception e) { e.printStackTrace(); } } }; mFoundDate = false; mFoundOperation = false; mFoundPrice = false; mDate[0] = mDate[1] = mDate[2] = ""; mPrice = 0; // Thread tokenThread = new Thread(tokenizeRunnable, "tokenThread"); // tokenThread.start(); Handler handler = new Handler(); handler.post(tokenizeRunnable); } @Override public void onReadyForSpeech(Bundle params) { Log.i(TAG, "onReadyForSpeech()"); } /** * ERROR_NETWORK_TIMEOUT = 1; * ERROR_NETWORK = 2; * ERROR_AUDIO = 3; * ERROR_SERVER = 4; * ERROR_CLIENT = 5; * ERROR_SPEECH_TIMEOUT = 6; * ERROR_NO_MATCH = 7; * ERROR_RECOGNIZER_BUSY = 8; * ERROR_INSUFFICIENT_PERMISSIONS = 9; * * @param error code is defined in SpeechRecognizer */ @Override public void onError(int error) { Log.i(TAG, "onError" + error); } @Override public void onBeginningOfSpeech() { Log.i(TAG, "onBeginningOfSpeech"); } @Override public void onBufferReceived(byte[] buffer) { Log.i(TAG, "onBufferReceived"); } @Override public void onEndOfSpeech() { Log.i(TAG, "onEndOfSpeech"); } @Override public void onEvent(int eventType, Bundle params) { Log.i(TAG, "onEvent"); } @Override public void onPartialResults(Bundle partialResults) { Log.i(TAG, "onPartialResults"); } @Override public void onRmsChanged(float rmsdB) { // Log.i(TAG, "onRmsChanged" + rmsdB); } }; private boolean recognizeAdd(String str) { Log.d(TAG, "In recognizeAdd"); return str.equalsIgnoreCase("add") || str.equalsIgnoreCase("spend") || str.equalsIgnoreCase("spent") || str.equalsIgnoreCase("expense") || str.equalsIgnoreCase("expenditure") || str.equalsIgnoreCase("expend") || str.equalsIgnoreCase("expended") || str.equalsIgnoreCase("cost") || str.equalsIgnoreCase("costed") || str.equalsIgnoreCase("bought") || str.equalsIgnoreCase("buy"); } private boolean recognizeQuery(String str) { Log.d(TAG, "In recognizeQuery"); return str.equalsIgnoreCase("find") || str.equalsIgnoreCase("search") || str.equalsIgnoreCase("query"); } private String[] recognizeDate(String str) { Log.d(TAG, "In recognize date "+str); String[] months = {"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"}; String[] splitStr = str.split(" "); String[] date = {"", "", ""}; for (int i=0;i<splitStr.length;i++) { for (int j=0;j<months.length;j++) { String month = months[j]; try { if (splitStr[i].toLowerCase().contains(month)) { mFoundDate =true; date[1] = Integer.valueOf(j + 1).toString(); Integer left = Integer.parseInt(splitStr[i - 1] .toLowerCase() .split("th")[0] .split("st")[0] .split("nd")[0]); Integer right = Integer.parseInt(splitStr[i + 1] .toLowerCase() .split("th")[0] .split("st")[0] .split("nd")[0]); Log.d(TAG, "Left = " + left); Log.d(TAG, "Right = " + right); if (left < 31) { date[0] = left.toString(); date[2] = right.toString(); } else { date[2] = left.toString(); date[0] = right.toString(); } break; } else if (Integer.parseInt(splitStr[i]) > 0) { mFoundDate = true; if (i + 1 < splitStr.length && Integer.parseInt(splitStr[i + 1]) > 0) { if (i + 2 < splitStr.length && Integer.parseInt(splitStr[i + 2]) > 0) { if (AddExpense.checkDate(splitStr[i] + "/" + splitStr[i + 1] + "/" + splitStr[i + 2])) { date[0] = splitStr[i]; date[1] = splitStr[i + 1]; date[2] = splitStr[i + 2]; } else { date[2] = splitStr[i]; date[1] = splitStr[i + 1]; date[0] = splitStr[i + 2]; } } } break; } } catch (NumberFormatException e) { // pass } catch (Exception e) { e.printStackTrace(); } } } return date; } private double recognizePrice(String str, String[] date) { double price = 0; for (String s : str.split(" ")) { try { if (Double.parseDouble(s) > 0) { boolean isPrice = true; for (String d : date) { if (s.equals(d)) { isPrice = false; break; } } if (isPrice) { mFoundPrice = true; price = Double.parseDouble(s); break; } } } catch (NumberFormatException e) { // pass } catch (Exception e) { e.printStackTrace(); } } return price; } public void analyzeRecord(String result) { Log.d(TAG, "In analyzeRecord"); /* check the date */ if (!mFoundDate) { mDate = recognizeDate(result); } Log.i(TAG, "Date = "+mDate[0]+"/"+mDate[1]+"/"+mDate[2]); /* check the price */ if (!mFoundPrice) { mPrice = recognizePrice(result, mDate); } Log.i(TAG, "Price = "+mPrice); /* check the operation */ for (String str : result.split(" ")) { Log.d(TAG, str); if (!mFoundOperation && recognizeAdd(str)) { mFoundOperation = true; Log.i(TAG, "Add found"); Intent addIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putDouble(PRICE_KEY_CODE, mPrice); bundle.putString(DATE_KEY_CODE, mDate[0]+"/"+mDate[1]+"/"+mDate[2]); addIntent.setClass(VRExpense.this, AddExpense.class); addIntent.putExtras(bundle); Log.i(TAG, "AddExpense Activity Launched"); startActivity(addIntent); break; } else if (recognizeQuery(str)) { Log.i(TAG, "Search found"); break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vr_expense); androidx.appcompat.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO}, RECORD_PERMISSION_CODE); } mRecognizer = SpeechRecognizer.createSpeechRecognizer(this.getApplicationContext()); Button startVR = findViewById(R.id.test_start); startVR.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.com.example.android.myexpensemanager"); mRecognizer.setRecognitionListener(listener); mRecognizer.startListening(intent); } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (RECORD_PERMISSION_CODE == requestCode) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "Permission for record granted"); } else { onBackPressed(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); mRecognizer.stopListening(); mRecognizer = null; } }
Java
CL
ae95606b1155919884590bfa350da1d3073e9f990a85b01dba9de551844e2eec
/* * Copyright 2021 - 2022 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.session.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; import org.traccar.helper.BitUtil; import org.traccar.helper.UnitsConverter; import org.traccar.model.Position; import java.net.SocketAddress; import java.util.Date; import java.util.LinkedList; import java.util.List; public class Dsf22ProtocolDecoder extends BaseProtocolDecoder { public Dsf22ProtocolDecoder(Protocol protocol) { super(protocol); } @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; buf.skipBytes(2); // header String id = String.valueOf(buf.readUnsignedShortLE()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); if (deviceSession == null) { return null; } List<Position> positions = new LinkedList<>(); int count = buf.readUnsignedByte(); for (int i = 0; i < count; i++) { Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.setValid(true); position.setLatitude(buf.readIntLE() / 10000000.0); position.setLongitude(buf.readIntLE() / 10000000.0); position.setTime(new Date(buf.readUnsignedIntLE() * 1000)); position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte())); position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShortLE() * 0.001); int status = buf.readUnsignedByte(); position.set(Position.KEY_IGNITION, BitUtil.check(status, 0)); position.set(Position.PREFIX_IN + 1, BitUtil.check(status, 1)); position.set(Position.PREFIX_OUT + 1, BitUtil.check(status, 4)); position.set(Position.KEY_ALARM, BitUtil.check(status, 6) ? Position.ALARM_JAMMING : null); position.set(Position.KEY_STATUS, status); positions.add(position); } if (channel != null) { byte[] response = {0x01}; channel.writeAndFlush(new NetworkMessage(Unpooled.wrappedBuffer(response), remoteAddress)); } return positions; } }
Java
CL
b12301b8d0312fef316a27f82a2b2d3f6dca85d7b71aedfa0966b31554ecd01d
package sa.elm.ob.scm.event; import javax.enterprise.event.Observes; import org.apache.log4j.Logger; import org.openbravo.base.exception.OBException; import org.openbravo.base.model.Entity; import org.openbravo.base.model.ModelProvider; import org.openbravo.base.model.Property; import org.openbravo.base.provider.OBProvider; import org.openbravo.client.kernel.event.EntityDeleteEvent; import org.openbravo.client.kernel.event.EntityNewEvent; import org.openbravo.client.kernel.event.EntityPersistenceEventObserver; import org.openbravo.client.kernel.event.EntityUpdateEvent; import org.openbravo.dal.core.OBContext; import org.openbravo.dal.service.OBDal; import org.openbravo.dal.service.OBQuery; import org.openbravo.erpCommon.utility.OBMessageUtils; import org.openbravo.model.common.plm.Product; import org.openbravo.model.common.plm.ProductCharacteristic; import sa.elm.ob.scm.ESCMCharactTempltLine; /** * @author Priyanka Ranjan on 03/03/2017 */ public class ESCMCharacteristicsTemplateLineEvent extends EntityPersistenceEventObserver { private static Entity[] entities = { ModelProvider.getInstance().getEntity(ESCMCharactTempltLine.ENTITY_NAME) }; @Override protected Entity[] getObservedEntities() { return entities; } private Logger log = Logger.getLogger(this.getClass()); public void onUpdate(@Observes EntityUpdateEvent event) { if (!isValidEvent(event)) { return; } try { OBContext.setAdminMode(); ESCMCharactTempltLine Check = (ESCMCharactTempltLine) event.getTargetInstance(); // update product window - characteristic tab if template is associated with some product final Property characteristic = entities[0] .getProperty(ESCMCharactTempltLine.PROPERTY_CHARACTERISTIC); if (!event.getCurrentState(characteristic).equals(event.getPreviousState(characteristic))) { OBQuery<Product> template = OBDal.getInstance().createQuery(Product.class, "as e where e.escmCharacTemplate.id=:tempId and e.client.id=:clientID"); template.setNamedParameter("tempId", Check.getEscmCharactTemplt().getId()); template.setNamedParameter("clientID", Check.getClient().getId()); if (template.list().size() > 0) { for (Product prod : template.list()) { for (ProductCharacteristic character : prod.getProductCharacteristicList()) { Object oldcharact = event.getPreviousState( entities[0].getProperty(ESCMCharactTempltLine.PROPERTY_CHARACTERISTIC)); if (oldcharact.equals(character.getCharacteristic())) { character.setCharacteristic(Check.getCharacteristic()); OBDal.getInstance().save(character); break; } } } } } } catch (Exception e) { log.error(" Exception while updating Characteristic Template Line : ", e); throw new OBException(OBMessageUtils.messageBD("HB_INTERNAL_ERROR")); } finally { OBContext.restorePreviousMode(); } } public void onSave(@Observes EntityNewEvent event) { if (!isValidEvent(event)) { return; } try { OBContext.setAdminMode(); ESCMCharactTempltLine Check = (ESCMCharactTempltLine) event.getTargetInstance(); // Insert records in product window - characteristic tab if template is associated with some // product OBQuery<Product> template = OBDal.getInstance().createQuery(Product.class, "as e where e.escmCharacTemplate.id=:tempId and e.client.id=:clientID "); template.setNamedParameter("tempId", Check.getEscmCharactTemplt().getId()); template.setNamedParameter("clientID", Check.getClient().getId()); if (template.list().size() > 0) { for (Product prod : template.list()) { ProductCharacteristic line = OBProvider.getInstance().get(ProductCharacteristic.class); line.setSequenceNumber(Check.getLineNo()); line.setCharacteristic(Check.getCharacteristic()); line.setProduct(prod); OBDal.getInstance().save(line); } } } catch (Exception e) { log.error(" Exception while Saving Characteristic Template Line : ", e); throw new OBException(OBMessageUtils.messageBD("HB_INTERNAL_ERROR")); } finally { OBContext.restorePreviousMode(); } } public void onDelete(@Observes EntityDeleteEvent event) { if (!isValidEvent(event)) { return; } try { OBContext.setAdminMode(); ESCMCharactTempltLine Check = (ESCMCharactTempltLine) event.getTargetInstance(); // restric to delete the line if its associated with some product OBQuery<Product> template = OBDal.getInstance().createQuery(Product.class, "as e where e.escmCharacTemplate.id=:tempId and e.client.id=:clientID "); template.setNamedParameter("tempId", Check.getEscmCharactTemplt().getId()); template.setNamedParameter("clientID", Check.getClient().getId()); if (template.list().size() > 0) { throw new OBException(OBMessageUtils.messageBD("ESCM_Charateristic_delete")); } } catch (OBException e) { log.error(" Exception while Deleting Characteristic Template Line : ", e); throw new OBException(e.getMessage()); } catch (Exception e) { log.error(" Exception while Deleting Characteristic Template Line : ", e); throw new OBException(OBMessageUtils.messageBD("HB_INTERNAL_ERROR")); } finally { OBContext.restorePreviousMode(); } } }
Java
CL
e5393448666ccd05b5152eb08a970f94830bf92aec741ce10d37ab3d0cf6ed42
package com.argo.bukkit.util; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.sk89q.wepif.PermissionsResolverManager; /** Permission abstraction class, use Vault, WEPIF, Perm2 or superperms, depending on what's available. * * Dependencies: (to be handled through maven when I setup a repository some day..) * Vault 1.x: http://dev.bukkit.org/server-mods/vault/ * WorldEdit 5.x: http://build.sk89q.com/ * PermissionsEx: http://goo.gl/jthCz * Permissions 2.7 or 3.x: http://goo.gl/liHFt (2.7) or http://goo.gl/rn4LP (3.x) * * Author's note: The "ideal" design would be to setup an interface class and let each permission * type implement that interface and use polymorphism. In fact, that's how Vault and WEPIF work. * However, the design goal for this class is to have a single class I can use between projects * that implements permissions abstraction, thus the less-than-great C-style integer values, * switch statements and if/else ladders. * * @author morganm * */ public class PermissionSystem { // class version: 14 public enum Type { SUPERPERMS, VAULT, WEPIF, OPS } /** For use by pure superperms systems that have no notion of group, the * convention is that groups are permissions that start with "group." * */ private static final String GROUP_PREFIX = "group."; /** Singleton instance. * */ private static PermissionSystem instance; private final JavaPlugin plugin; private final Logger log; private final String logPrefix; private Type systemInUse; private net.milkbowl.vault.permission.Permission vaultPermission = null; private PermissionsResolverManager wepifPerms = null; public PermissionSystem(JavaPlugin plugin, Logger log, String logPrefix) { this.plugin = plugin; if( log != null ) this.log = log; else this.log = Logger.getLogger(PermissionSystem.class.toString()); if( logPrefix != null ) { if( logPrefix.endsWith(" ") ) this.logPrefix = logPrefix; else this.logPrefix = logPrefix + " "; } else this.logPrefix = "["+plugin.getDescription().getName()+"] "; instance = this; } /** **WARNING** Not your typical singleton pattern, this CAN BE NULL. An instance * must be created by the plugin before this will return a value. This simply * points to the most recent object that was instantiated. * * @return */ public static PermissionSystem getInstance() { return instance; } public Type getSystemInUse() { return systemInUse; } public String getSystemInUseString() { switch(systemInUse) { case VAULT: final String permName = Bukkit.getServer().getServicesManager().getRegistration(Permission.class).getProvider().getName(); return "VAULT:"+permName; case WEPIF: String wepifPermInUse = ""; try { Class<?> clazz = wepifPerms.getClass(); Field field = clazz.getDeclaredField("permissionResolver"); field.setAccessible(true); Object o = field.get(wepifPerms); String className = o.getClass().getSimpleName(); wepifPermInUse = ":"+className.replace("Resolver", ""); } // catch both normal and runtime exceptions catch(Throwable t) { // we don't care, it's just extra information if we can get it } return "WEPIF" + wepifPermInUse; case OPS: return "OPS"; case SUPERPERMS: default: return "SUPERPERMS"; } } public void setupPermissions() { setupPermissions(true); } public void setupPermissions(final boolean verbose) { List<String> permPrefs = null; if( plugin.getConfig().get("permissions") != null ) { permPrefs = plugin.getConfig().getStringList("permissions"); } else { permPrefs = new ArrayList<String>(5); permPrefs.add("vault"); permPrefs.add("wepif"); permPrefs.add("superperms"); permPrefs.add("ops"); } for(String system : permPrefs) { if( "vault".equalsIgnoreCase(system) ) { if( setupVaultPermissions() ) { systemInUse = Type.VAULT; // if( verbose ) // log.info(logPrefix+"using Vault permissions"); break; } } else if( "wepif".equalsIgnoreCase(system) ) { if( setupWEPIFPermissions() ) { systemInUse = Type.WEPIF; // if( verbose ) // log.info(logPrefix+"using WEPIF permissions"); break; } } else if( "superperms".equalsIgnoreCase(system) ) { systemInUse = Type.SUPERPERMS; // if( verbose ) // log.info(logPrefix+"using Superperms permissions"); break; } else if( "ops".equalsIgnoreCase(system) ) { systemInUse = Type.OPS; // if( verbose ) // log.info(logPrefix+"using basic Op check for permissions"); break; } } if( verbose ) log.info(logPrefix+"using "+getSystemInUseString()+" for permissions"); } /** Check to see if player has a given permission. * * @param p The player * @param permission the permission to be checked * @return true if the player has the permission, false if not */ public boolean has(CommandSender sender, String permission) { Player p = null; // console always has access if( sender instanceof ConsoleCommandSender ) return true; if( sender instanceof Player ) p = (Player) sender; if( p == null ) return false; boolean permAllowed = false; switch(systemInUse) { case VAULT: permAllowed = vaultPermission.has(p, permission); break; case WEPIF: permAllowed = wepifPerms.hasPermission(p.getName(), permission); break; case SUPERPERMS: permAllowed = p.hasPermission(permission); break; case OPS: permAllowed = p.isOp(); break; } return permAllowed; } public boolean has(String world, String player, String permission) { boolean permAllowed = false; switch(systemInUse) { case VAULT: permAllowed = vaultPermission.has(world, player, permission); break; case WEPIF: permAllowed = wepifPerms.hasPermission(player, permission); break; case SUPERPERMS: { Player p = plugin.getServer().getPlayer(player); // technically this is not guaranteed to be accurate since superperms // doesn't support checking cross-world perms. Upgrade to a better // perm system if you care about this. if( p != null ) permAllowed = p.hasPermission(permission); break; } case OPS: { Player p = plugin.getServer().getPlayer(player); if( p != null ) permAllowed = p.isOp(); break; } } return permAllowed; } public boolean has(String player, String permission) { return has("world", player, permission); } public String getPlayerGroup(String world, String playerName) { String group = null; switch(systemInUse) { case VAULT: group = vaultPermission.getPrimaryGroup(world, playerName); break; case WEPIF: { String[] groups = wepifPerms.getGroups(playerName); if( groups != null && groups.length > 0 ) group = groups[0]; break; } case SUPERPERMS: { Player player = plugin.getServer().getPlayer(playerName); group = getSuperpermsGroup(player); break; } // OPS has no group support case OPS: break; } return group; } /** Superperms has no group support, but we fake it (this is slow and stupid since * it has to iterate through ALL permissions a player has). But if you're * attached to superperms and not using a nice plugin like bPerms and Vault * then this is as good as it gets. * * @param player * @return the group name or null */ private String getSuperpermsGroup(Player player) { if( player == null ) return null; String group = null; // this code shamelessly adapted from WorldEdit's WEPIF support for superperms Permissible perms = getPermissible(player); if (perms != null) { for (PermissionAttachmentInfo permAttach : perms.getEffectivePermissions()) { String perm = permAttach.getPermission(); if (!(perm.startsWith(GROUP_PREFIX) && permAttach.getValue())) { continue; } // we just grab the first "group.XXX" permission we can find group = perm.substring(GROUP_PREFIX.length(), perm.length()); break; } } return group; } /** This code shamelessly stolen from WEPIF in order to support a fake "group" * notion for Superperms. * * @param offline * @return */ private Permissible getPermissible(OfflinePlayer offline) { if (offline == null) return null; Permissible perm = null; if (offline instanceof Permissible) { perm = (Permissible) offline; } else { Player player = offline.getPlayer(); if (player != null) perm = player; } return perm; } private boolean setupVaultPermissions() { Plugin vault = plugin.getServer().getPluginManager().getPlugin("Vault"); if( vault != null ) { RegisteredServiceProvider<net.milkbowl.vault.permission.Permission> permissionProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { vaultPermission = permissionProvider.getProvider(); } } return (vaultPermission != null); } private boolean setupWEPIFPermissions() { try { Plugin worldEdit = plugin.getServer().getPluginManager().getPlugin("WorldEdit"); String version = null; int versionNumber = 840; // assume compliance unless we find otherwise try { version = worldEdit.getDescription().getVersion(); // version "4.7" is equivalent to build #379 if( "4.7".equals(version) ) versionNumber = 379; // version "5.0" is equivalent to build #670 else if( "5.0".equals(version) ) versionNumber = 670; else if( version.startsWith("5.") ) // 5.x series versionNumber = 840; else { int index = version.indexOf('-'); versionNumber = Integer.parseInt(version.substring(0, index)); } } catch(Exception e) {} // catch any NumberFormatException or anything else // System.out.println("WorldEdit version: "+version+", number="+versionNumber); if( versionNumber < 660 ) { log.info(logPrefix + "You are currently running version "+version+" of WorldEdit. WEPIF was changed in #660, please update to latest WorldEdit. (skipping WEPIF for permissions)"); return false; } if( worldEdit != null ) { wepifPerms = PermissionsResolverManager.getInstance(); // wepifPerms.initialize(plugin); // wepifPerms = new PermissionsResolverManager(this, "LoginLimiter", log); // (new PermissionsResolverServerListener(wepifPerms, this)).register(this); } } catch(Exception e) { log.info(logPrefix + " Unexpected error trying to setup WEPIF permissions hooks (this message can be ignored): "+e.getMessage()); } return wepifPerms != null; } }
Java
CL
61a1800d8bb57dfc1ffe1f28f60b83939c020bdf806d01ac59badae51149b148
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nanoframework.spi.support; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import java.util.jar.JarFile; import org.nanoframework.spi.exception.SPIException; import org.nanoframework.toolkit.lang.ArrayUtils; import org.nanoframework.toolkit.lang.CollectionUtils; import org.nanoframework.toolkit.lang.ResourceUtils; import org.nanoframework.toolkit.lang.StringUtils; import org.nanoframework.toolkit.properties.PropertiesLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * @author yanghe * @since 1.4.8 */ public class SPILoader { private static Logger LOGGER = LoggerFactory.getLogger(SPILoader.class); private static String SPI_DIR = "META-INF/nano/spi"; private static Map<Class<?>, List<SPIMapper>> SPI_MAPPERS = Maps.newHashMap(); private static AtomicBoolean LOADED = new AtomicBoolean(false); private static ReentrantLock LOCK = new ReentrantLock(); private static Set<JarFile> JAR_FILES = Sets.newHashSet(); /** */ protected SPILoader() { } private static void loading() { var lock = LOCK; SPILoader loader = null; Map<String, List<InputStream>> streams = null; try { lock.lock(); loader = new SPILoader(); Enumeration<URL> resources; try { resources = loader.getResources(); } catch (Throwable e) { throw new SPIException("加载资源异常: " + e.getMessage(), e); } SPIResource spiResource; try { spiResource = loader.getSPIResource(resources); } catch (Throwable e) { throw new SPIException("获取SPI资源文件异常: " + e.getMessage(), e); } var spiMappers = new HashMap<Class<?>, List<SPIMapper>>(); loader.getSPIMapper(spiResource.getFiles(), spiMappers); streams = spiResource.getStreams(); loader.getSPIMapperWithStream(streams, spiMappers); loader.sortSPIMapper(spiMappers); clear(); SPI_MAPPERS.putAll(spiMappers); LOADED.set(true); } finally { if (loader != null) { if (streams != null) { loader.closeStream(streams.values()); } loader.closeJarFile(); } lock.unlock(); } } /** * @return 获取所有已被加载的SPI配置关系 */ public static Map<Class<?>, List<SPIMapper>> spis() { if (!LOADED.get()) { loading(); } return Collections.unmodifiableMap(SPI_MAPPERS); } /** * @param cls Class * @return 获取指定Class对应的所有已被加载的SPI配置信息 */ public static List<SPIMapper> spis(Class<?> cls) { var mappers = spis().get(cls); if (CollectionUtils.isEmpty(mappers)) { return Collections.emptyList(); } return Collections.unmodifiableList(mappers); } /** * @param spiCls Class * @return 获取指定Class对应的所有的已被加载的SPI类名信息 */ public static Set<String> spiNames(Class<?> spiCls) { if (!LOADED.get()) { loading(); } var spiMappers = SPI_MAPPERS.get(spiCls); if (!CollectionUtils.isEmpty(spiMappers)) { var spiNames = new LinkedHashSet<String>(); spiMappers.forEach(spiMapper -> spiNames.add(spiMapper.getName())); return Collections.unmodifiableSet(spiNames); } return Collections.emptySet(); } /** * @return 获取SPI资源配置文件信息 * @throws IOException 读取SPI资源异常 */ protected Enumeration<URL> getResources() throws IOException { var loader = SPILoader.class.getClassLoader(); if (loader != null) { return loader.getResources(SPI_DIR); } else { return ClassLoader.getSystemResources(SPI_DIR); } } /** * @param resources SPI资源配置文件信息 * @return SPI资源 * @throws URISyntaxException URI格式异常 * @throws MalformedURLException URL格式异常 * @throws IOException SPI信息读取异常 */ protected SPIResource getSPIResource(Enumeration<URL> resources) throws URISyntaxException, MalformedURLException, IOException { if (resources != null) { var files = new ArrayList<File>(); var streams = new HashMap<String, List<InputStream>>(); while (resources.hasMoreElements()) { var url = resources.nextElement(); if (!ResourceUtils.isJarURL(url)) { findSPIFiles(url, files); } else { findSPIFilesWithJar(url, streams); } } return SPIResource.create(files, streams); } return SPIResource.EMPTY; } private void findSPIFiles(URL url, List<File> files) throws URISyntaxException { var uri = url.toURI(); File file; try { file = new File(uri); } catch (Throwable e) { LOGGER.error("无效的文件路径: {}", uri); return; } if (file.exists()) { var spiFiles = file.listFiles(f -> !f.isDirectory()); if (ArrayUtils.isNotEmpty(spiFiles)) { Arrays.stream(spiFiles).forEach(files::add); } } } private void findSPIFilesWithJar(URL url, Map<String, List<InputStream>> streams) throws FileNotFoundException, MalformedURLException, IOException { var jarFile = new JarFile(ResourceUtils.getFile(ResourceUtils.extractJarFileURL(url))); JAR_FILES.add(jarFile); var entries = jarFile.entries(); while (entries.hasMoreElements()) { var entry = entries.nextElement(); var fileName = entry.getName().replace('\\', '/'); if (StringUtils.startsWith(fileName, SPI_DIR) && !entry.isDirectory()) { var fileNameSection = fileName.split("/"); var spiFileName = fileNameSection[fileNameSection.length - 1]; if (!streams.containsKey(spiFileName)) { streams.put(spiFileName, Lists.newArrayList(jarFile.getInputStream(entry))); } else { streams.get(spiFileName).add(jarFile.getInputStream(entry)); } } } } private void getSPIMapper(List<File> spiFiles, Map<Class<?>, List<SPIMapper>> spiMappers) { if (!CollectionUtils.isEmpty(spiFiles)) { spiFiles.forEach(file -> { Properties define = PropertiesLoader.load(file.getAbsolutePath()); bindSPI(define, file.getName(), spiMappers); }); } } private void getSPIMapperWithStream(Map<String, List<InputStream>> stream, Map<Class<?>, List<SPIMapper>> spiMappers) { stream.entrySet().forEach(entry -> { var spiClsName = entry.getKey(); var spiStreams = entry.getValue(); if (!CollectionUtils.isEmpty(spiStreams)) { spiStreams.forEach(spiStream -> { Properties define = PropertiesLoader.load(spiStream); bindSPI(define, spiClsName, spiMappers); }); } }); } private void bindSPI(Properties define, String spiClsName, Map<Class<?>, List<SPIMapper>> spiMappers) { var spiCls = getSPIClass(spiClsName); if (spiCls == null) { return; } define.keySet().forEach(name -> { var spiName = (String) name; var instanceClsName = define.getProperty(spiName); try { Class<?> instanceCls; if (StringUtils.isNotBlank(instanceClsName)) { instanceCls = Class.forName(instanceClsName); } else { instanceCls = Class.forName(spiName); spiName = instanceCls.getSimpleName(); LOGGER.debug("默认SPI定义: {} = {}", spiName, instanceCls.getName()); } if (spiCls.isAssignableFrom(instanceCls)) { var spiMapper = SPIMapper.create(spiCls, spiName, instanceCls); if (!spiMappers.containsKey(spiCls)) { spiMappers.put(spiCls, Lists.newArrayList(spiMapper)); } else { spiMappers.get(spiCls).add(spiMapper); } } else { LOGGER.warn("无法加载类: {}, 未实现接口 {}", instanceClsName, spiClsName); } } catch (ClassNotFoundException e) { LOGGER.warn("未定义SPI实现类: {} = {}", name, instanceClsName); } }); } private Class<?> getSPIClass(String spiClsName) { try { return Class.forName(spiClsName); } catch (ClassNotFoundException e) { return null; } } private void sortSPIMapper(Map<Class<?>, List<SPIMapper>> spiMappers) { spiMappers.forEach((spiCls, spis) -> { Collections.sort(spis, (before, after) -> { var beforeOrder = before.getOrder(); var afterOrder = after.getOrder(); if (beforeOrder > afterOrder) { return 1; } else if (beforeOrder < afterOrder) { return -1; } return 0; }); }); } private void closeStream(Collection<List<InputStream>> streams) { if (!CollectionUtils.isEmpty(streams)) { streams.forEach(spiStream -> { spiStream.forEach(stream -> { try { stream.close(); } catch (IOException e) { LOGGER.warn("关闭JarEntry资源异常: {}", e.getMessage()); } }); }); } } private void closeJarFile() { if (!CollectionUtils.isEmpty(JAR_FILES)) { JAR_FILES.forEach(jarFile -> { try { jarFile.close(); } catch (IOException e) { LOGGER.warn("关闭JarFile资源异常: {}", e.getMessage()); } }); JAR_FILES.clear(); } } public static void clear() { SPI_MAPPERS.values().forEach(mappers -> { mappers.clear(); }); SPI_MAPPERS.clear(); } }
Java
CL
1d7e94c434c9901200f58117953654a9249d3fba6c73ec4d54dd63a3a87c8e2a
package com.github.animelist.animelist.controller; import com.github.animelist.animelist.model.JwtUserDetails; import com.github.animelist.animelist.model.input.ContinuousRatingSystemInput; import com.github.animelist.animelist.model.input.DiscreteRatingSystemInput; import com.github.animelist.animelist.model.input.RatingSystemInput; import com.github.animelist.animelist.model.input.RatingSystemType; import com.github.animelist.animelist.model.ratingsystem.ContinuousRatingSystem; import com.github.animelist.animelist.model.ratingsystem.DiscreteRatingSystem; import com.github.animelist.animelist.model.ratingsystem.RatingSystem; import com.github.animelist.animelist.model.ratingsystem.SubRating; import com.github.animelist.animelist.service.RatingSystemService; import org.bson.types.ObjectId; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import java.util.Arrays; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.github.animelist.animelist.util.TestUtil.TEST_USERNAME; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class RatingSystemControllerTest { private ObjectId expectedObjectID = new ObjectId(); @Mock private RatingSystemService ratingSystemService; @InjectMocks private RatingSystemController ratingSystemController; @Test void getRatingSystem_happy() { ObjectId testID = new ObjectId(); final RatingSystem expected = ContinuousRatingSystem.builder() .id(testID.toString()) .name("Test") .ownerId(new ObjectId()) .size(10) .offset(1) .subRatings(Collections.singletonList(SubRating.builder().id(0).name("score").weight(1f).build())) .build(); when(ratingSystemService.getRatingSystem(testID.toString())).thenReturn(Optional.of(expected)); final RatingSystem actual = ratingSystemController.getRatingSystem(testID.toString()); assertThat(actual,is(expected)); } @Test void createDiscreteRatingSystem_happy() { mockAuthenticationPrincipal(); final DiscreteRatingSystemInput discreteInput = new DiscreteRatingSystemInput(Arrays.asList("one","two","three")); final RatingSystemInput input = new RatingSystemInput( "Test", 3, Collections.singletonList(SubRating.builder().id(0).name("score").weight(1f).build()), RatingSystemType.DISCRETE, discreteInput, null); final RatingSystem expected = DiscreteRatingSystem.builder() .id(new ObjectId().toString()) .name("Test") .ownerId(new ObjectId()) .size(3) .subRatings(Collections.singletonList(SubRating.builder().id(0).name("score").weight(1f).build())) .labels(IntStream.range(1, 4).mapToObj(String::valueOf).collect(Collectors.toList())) .build(); when(ratingSystemService.createRatingSystem(any())).thenReturn(expected); final RatingSystem actual = ratingSystemController.createRatingSystem(input); assertThat(actual,is(expected)); } @Test void createContinuousRatingSystem_happy() { mockAuthenticationPrincipal(); final ContinuousRatingSystemInput continuousInput = new ContinuousRatingSystemInput(1); final RatingSystemInput input = new RatingSystemInput("Test",10,Collections.singletonList(SubRating.builder().id(0).name("score").weight(1f).build()), RatingSystemType.CONTINUOUS,null,continuousInput); final RatingSystem expected = DiscreteRatingSystem.builder() .id(new ObjectId().toString()) .name("Test") .ownerId(new ObjectId()) .size(10) .subRatings(Collections.singletonList(SubRating.builder().id(0).name("score").weight(1f).build())) .labels(IntStream.range(1, 11).mapToObj(String::valueOf).collect(Collectors.toList())) .build(); when(ratingSystemService.createRatingSystem(any())).thenReturn(expected); final RatingSystem actual = ratingSystemController.createRatingSystem(input); assertThat(actual,is(expected)); } private void mockAuthenticationPrincipal() { final JwtUserDetails mockJwtUserDetails = JwtUserDetails.builder() .username(TEST_USERNAME) .id(expectedObjectID.toString()) .build(); final Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn(mockJwtUserDetails); final SecurityContext secCtx = mock(SecurityContext.class); when(secCtx.getAuthentication()).thenReturn(auth); SecurityContextHolder.setContext(secCtx); } }
Java
CL
c1c1059162f11e6bddbc6f9e3364f5fa4125c3b4a0403b2a62c914a1f57e5ff3
package com.cmall.groupcenter.job; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.quartz.JobExecutionContext; import com.srnpr.xmassystem.helper.PlusHelperNotice; import com.srnpr.xmassystem.load.LoadSkuInfo; import com.srnpr.xmassystem.load.LoadSkuItem; import com.srnpr.zapcom.basehelper.FormatHelper; import com.srnpr.zapcom.basemodel.MDataMap; import com.srnpr.zapdata.dbdo.DbUp; import com.srnpr.zapweb.rootweb.RootJob; /** * 每天下午7点定时排查直播品 */ public class JobForEventExcludeTv extends RootJob { LoadSkuInfo loadSkuInfo = new LoadSkuInfo(); LoadSkuItem loadSkuItem = new LoadSkuItem(); public void doExecute(JobExecutionContext context) { disable(); } /** * 作废当天活动的直播品 */ private void disable() { // 查询第二天的直播品,只查询1台 List<String> tvProductList = getTvProductList(); if(tvProductList.isEmpty()) { return; } // 查询已经发布的活动中包含了直播品的数据 String codes = "'" + StringUtils.join(tvProductList,"','") + "'"; String tomorrow = FormatHelper.upDateTime(DateUtils.addDays(new Date(), 1),"yyyy-MM-dd"); // 查询明天参与活动的商品 String sql = "SELECT p.event_code, p.item_code, p.product_code, p.sku_code FROM systemcenter.sc_event_info e,systemcenter.sc_event_item_product p" + " WHERE e.event_status = '4497472700020002' AND p.event_code = e.event_code AND p.flag_enable = 1 AND e.exclude_tv_flag = '449748600002'" + " AND e.event_type_code IN('4497472600010001','4497472600010002','4497472600010005','4497472600010024','4497472600010030')" + " AND ((e.begin_time <= :tomorrow AND e.end_time > :tomorrow) OR e.begin_time LIKE '"+tomorrow+"%')" + " AND p.product_code IN(" + codes + ")"; List<Map<String, Object>> itemMapList = DbUp.upTable("sc_event_info").dataSqlList(sql, new MDataMap("tomorrow", tomorrow)); String skuCode,productCode,eventCode,itemCode,time; for(Map<String, Object> itemMap : itemMapList) { eventCode = itemMap.get("event_code").toString(); itemCode = itemMap.get("item_code").toString(); productCode = itemMap.get("product_code").toString(); skuCode = itemMap.get("sku_code").toString(); // 作废商品 DbUp.upTable("sc_event_item_product").dataUpdate(new MDataMap("flag_enable","0","item_code",itemCode), "flag_enable", "item_code"); // 清理缓存 loadSkuInfo.deleteInfoByCode(skuCode); loadSkuItem.deleteInfoByCode(itemCode); // 兼容折扣没有SKU的情况 if(StringUtils.isBlank(skuCode)) { PlusHelperNotice.onChangeProductInfo(productCode); } // 记录作废的商品明细 time = FormatHelper.upDateTime(); DbUp.upTable("sc_event_tv_disabled").dataInsert(new MDataMap( "event_code", eventCode, "item_code", itemCode, "product_code", productCode, "sku_code", skuCode, "flag", "0", "create_time", time, "update_time", time )); } } private List<String> getTvProductList() { // 查询第二天的节目品 String today = FormatHelper.upDateTime(DateUtils.addDays(new Date(), 1),"yyyy-MM-dd"); String sql = "SELECT DISTINCT good_id FROM productcenter.pc_tv WHERE form_fr_date LIKE '"+today+"%' and so_id = '1000001'"; List<Map<String, Object>> tvList = DbUp.upTable("pc_tv").dataSqlList(sql, new MDataMap()); List<String> tvProductList = new ArrayList<String>(); for(Map<String, Object> m : tvList) { tvProductList.add((String)m.get("good_id")); } return tvProductList; } }
Java
CL
c5dde79b42b546c275cceab71eb11dba35272c008cf45ba46a974f2942c0b561
package com.spc.schedule.storage.ctr; import com.spc.common.CountProxyHelper; import com.spc.common.LoggerCountRecoverManager; import com.spc.common.LoggerRecoverManager; import com.spc.schedule.storage.bean.HandleResult; import com.spc.schedule.storage.bean.LogCountInfo; import com.spc.schedule.storage.bean.LogInfo; import com.spc.schedule.storage.repo.LogCountInfoRepository; import com.spc.schedule.storage.repo.LogInfoRepository; import com.spc.schedule.storage.service.LogInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.SimpleTimeZone; @Controller public class LogRecoverController { @Autowired LogInfoRepository logInfoRepository; @Autowired LogCountInfoRepository countRepository; @Autowired LogInfoService logInfoService; @PostMapping("/spc/log/getAll") @ResponseBody public List<LogInfo> getAll(@RequestBody Map map) { return logInfoService.getAll(map); } @PostMapping("/spc/log/edit") @ResponseBody public HandleResult add(@RequestBody LogInfo info) { return HandleResult.of(logInfoService.add(info),null); } @PostMapping("/spc/log/delete") @ResponseBody public HandleResult delete(@RequestBody LogInfo info) { return HandleResult.of(logInfoService.delete(info),null); } @PostMapping("/spc/log/exec") @ResponseBody public HandleResult exec(@RequestBody LogInfo info) { LoggerRecoverManager.execute(info); return HandleResult.of(true,null); } @PostMapping("/spc/logCount/getAll") @ResponseBody public List<LogCountInfo> getLogCountAll() { return countRepository.findAll(); } @PostMapping("/spc/logCount/edit") @ResponseBody public HandleResult addLogCount(@RequestBody LogCountInfo info) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); countRepository.save(info); return HandleResult.of(true,null); } @PostMapping("/spc/logCount/delete") @ResponseBody public HandleResult deleteLogCount(@RequestBody LogCountInfo info) { countRepository.delete(info); return HandleResult.of(true,null); } @PostMapping("/spc/logCount/exec") @ResponseBody public HandleResult logCountExec(@RequestBody LogCountInfo info) { LoggerCountRecoverManager.execute(info); return HandleResult.of(true,null); } @PostMapping("/spc/logCount/getExecClass") @ResponseBody public List<String> getExecClass() throws Exception{ return CountProxyHelper.getAllCountMgrNames(); } }
Java
CL
a399d9bcfa146e393844c28ae735cbd68b6aff564209dfec42d577de3a1bc1b3
package org.csstudio.utility.toolbox.view; import org.csstudio.utility.toolbox.actions.OpenStoreEditorAction; import org.csstudio.utility.toolbox.entities.Lager; import org.csstudio.utility.toolbox.framework.controller.CrudController; import org.csstudio.utility.toolbox.framework.template.AbstractCrudEditorPartTemplate; import org.csstudio.utility.toolbox.func.Func1Void; import org.csstudio.utility.toolbox.view.forms.StoreGuiForm; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import com.google.inject.Inject; public class StoreEditorPart extends AbstractCrudEditorPartTemplate<Lager> implements CrudController<Lager> { public static final String ID = "org.csstudio.utility.toolbox.view.StoreEditorPart"; @Inject private StoreGuiForm storeGuiForm; @Inject private OpenStoreEditorAction openStoreEditorAction; @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { super.init(site, input, storeGuiForm); setEditorPartName("name"); } @Override public void createPartControl(Composite composite) { storeGuiForm.createEditPart(composite, getEditorInput(), this); setFocusWidget(storeGuiForm.getFocusWidget()); } @Override public void create() { openStoreEditorAction.runWith(new Lager()); } @Override public void copy() { if (!getEditorInput().hasData()) { throw new IllegalStateException("Data expected"); } getEditorInput().processData(new Func1Void<Lager>() { @Override public void apply(Lager lager) { Lager clone = lager.deepClone(); openStoreEditorAction.runWith(clone); } }); } }
Java
CL
0116d92355d682f26b64dae5f034822455368e8a360c1f902825a1ea78014057
package com.wmd.kroplayer.mvp.ui.activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder; import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer; import com.wmd.kroplayer.R; import com.wmd.kroplayer.base.BaseKroGSYVideoActivity; import com.wmd.kroplayer.bean.VideoInfoBean; import com.wmd.kroplayer.bean.VideoPlayHistoryBean; import com.wmd.kroplayer.mvp.ui.view.KroGsyVideoPlayer; import com.wmd.kroplayer.utils.AppUtils; import com.wmd.kroplayer.utils.FileSizeUtil; import com.wmd.kroplayer.utils.FileUtils; import com.wmd.kroplayer.utils.TimeUtils; import butterknife.BindView; import static com.wmd.kroplayer.utils.ContractUtils.LOCAL_VIDEO_INFO; /** * Author: Edwardwmd * E-mail: 1732141816wmd @ gmail.com * Link: https://github.com/Edwardwmd * Data: 2020/2/2121 * Version: 1.0.0 * Desc: VideoPlayActivity */ public class VideoPlayActivity extends BaseKroGSYVideoActivity<StandardGSYVideoPlayer> { @BindView(R.id.kro_gsyplayer) KroGsyVideoPlayer kroGsyplayer; @BindView(R.id.tv_play_video_name) TextView tvPlayVideoName; @BindView(R.id.tv_video_size) TextView tvVideoSize; @BindView(R.id.tv_create_video_date) TextView tvCreateVideoDate; @BindView(R.id.tv_video_formality) TextView tvVideoFormality; @BindView(R.id.tv_video_highwidth) TextView tvVideoHighwidth; @BindView(R.id.cv_video_info) CardView cvVideoInfo; private ImageView thum; private VideoInfoBean videoInfoBean; private VideoPlayHistoryBean videoPlayHistoryBean; @Override public StandardGSYVideoPlayer getGSYVideoPlayer() { return kroGsyplayer; } @Override public GSYVideoOptionBuilder getGSYVideoOptionBuilder() { return new GSYVideoOptionBuilder() .setThumbImageView(thum) .setUrl(videoInfoBean.getPath()) .setCacheWithPlay(true) .setVideoTitle(videoInfoBean.getVideoName()) .setIsTouchWiget(true) .setRotateViewAuto(false) .setLockLand(true) .setShowFullAnimation(true) .setNeedLockFull(true) .setDismissControlTime(4000) .setSeekRatio(10.0f); } @Override public void clickForFullScreen() { } @Override public boolean getDetailOrientationRotateAuto() { return false; } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.activity_videoplay; } @Override public void initData(@Nullable Bundle savedInstanceState) { loadView(); loadCover(); initVideoBuilderMode(); } private void loadView() { Intent intent = getIntent(); if (intent != null) { videoInfoBean = intent.getParcelableExtra(LOCAL_VIDEO_INFO); } tvPlayVideoName.setText(videoInfoBean.getVideoName()); tvVideoHighwidth.setText(videoInfoBean.getVideoWidth()+"X"+videoInfoBean.getVideoHigh()); tvVideoSize.setText(FileSizeUtil.FormetFileSize(videoInfoBean.getVideoSize())); tvCreateVideoDate.setText(TimeUtils.getFormatedDateTime("yyyy-MM-dd", videoInfoBean.getTime())); tvVideoFormality.setText(FileUtils.checkVideoType(videoInfoBean.getPath())); videoPlayHistoryBean=new VideoPlayHistoryBean(); } private void loadCover() { thum = new ImageView(this); //SDK>=21(Android 5.0)时实现元素共享转场 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { thum.setTransitionName(getString(R.string.text_transition_share_image)); } thum.setScaleType(ImageView.ScaleType.CENTER_CROP); AppUtils.loadVideoScreenshot(this, videoInfoBean.getThumbPath(), thum, 350000000); } @Override public void initVideo() { super.initVideo(); //重载后实现点击,不横屏 if (getGSYVideoPlayer().getFullscreenButton() != null) { getGSYVideoPlayer().getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //第一个true是否需要隐藏actionbar,第二个true是否需要隐藏statusbar getGSYVideoPlayer().startWindowFullscreen(VideoPlayActivity.this, true, true); } }); } } @Override public void onClickStop(String url, Object... objects) { super.onClickStop(url, objects); //保存播放进度 } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); orientationUtils.setEnable(false); } //重载后不做任何事情,实现竖屏全屏 @Override public void onQuitFullscreen(String url, Object... objects) { super.onQuitFullscreen(url, objects); } @Override protected void onDestroy() { super.onDestroy(); if (kroGsyplayer != null) { kroGsyplayer.release(); kroGsyplayer = null; } } @Override public boolean isBaseOnWidth() { return false; } @Override public float getSizeInDp() { return 720; } }
Java
CL
3589e8f651ea46cf94239e25f584845afc684d439992b145f990f0064c84f370
package eu.opertusmundi.web.controller.action; import java.time.ZonedDateTime; import java.util.UUID; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import eu.opertusmundi.common.model.BaseResponse; import eu.opertusmundi.common.model.RestResponse; import eu.opertusmundi.web.model.message.client.ClientMessageCollectionResponse; import eu.opertusmundi.web.model.message.client.ClientMessageCommandDto; import eu.opertusmundi.web.model.openapi.schema.MessageEndpointTypes; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; /** * Endpoint messages and notifications */ @Tag( name = "Message", description = "The message and notification API" ) @RequestMapping(path = "/action", produces = MediaType.APPLICATION_JSON_VALUE) public interface MessageController { /** * Find messages * * @param pageIndex * @param pageSize * @param userKey * @param dateFrom * @param dateTo * @param read * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-01", summary = "Find messages", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ClientMessageCollectionResponse.class) ) ) @GetMapping(value = "/messages") @Secured({"ROLE_USER", "ROLE_HELPDESK"}) RestResponse<?> findMessages( @Parameter( in = ParameterIn.QUERY, required = false, description = "Page index", schema = @Schema(type = "integer", defaultValue = "0") ) @RequestParam(name = "page", required = false) Integer pageIndex, @Parameter( in = ParameterIn.QUERY, required = false, description = "Page size", schema = @Schema(type = "integer", defaultValue = "10") ) @RequestParam(name = "size", required = false) Integer pageSize, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter user by key" ) @RequestParam(name = "user", required = false) UUID userKey, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter messages after date" ) @RequestParam(name = "date-from", required = false) ZonedDateTime dateFrom, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter messages before date" ) @RequestParam(name = "date-to", required = false) ZonedDateTime dateTo, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter read messages" ) @RequestParam(name = "read", required = false) Boolean read ); /** * Find notifications * * @param pageIndex * @param pageSize * @param userKey * @param dateFrom * @param dateTo * @param read * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "notification-01", summary = "Find notifications", tags = { "Notification" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = MessageEndpointTypes.NotificationListResponseDto.class) ) ) @GetMapping(value = "/notifications") @Secured({"ROLE_USER"}) RestResponse<?> findNotifications( @Parameter( in = ParameterIn.QUERY, required = false, description = "Page index", schema = @Schema(type = "integer", defaultValue = "0") ) @RequestParam(name = "page", required = false) Integer pageIndex, @Parameter( in = ParameterIn.QUERY, required = false, description = "Page size", schema = @Schema(type = "integer", defaultValue = "10") ) @RequestParam(name = "size", required = false) Integer pageSize, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter user by key" ) @RequestParam(name = "user", required = false) UUID userKey, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter notifications after date" ) @RequestParam(name = "date-from", required = false) ZonedDateTime dateFrom, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter notifications before date" ) @RequestParam(name = "date-to", required = false) ZonedDateTime dateTo, @Parameter( in = ParameterIn.QUERY, required = false, description = "Filter read notifications" ) @RequestParam(name = "read", required = false) Boolean read ); /** * Send a message to the platform user with the specified key * * @param key Recipient user unique key * @param message Message command object * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-04", summary = "Send a message to a platform user", description = "Sends a message to the specified user from a Helpdesk account", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = MessageEndpointTypes.MessageReceiptDto.class) ) ) @PostMapping(value = "/message/user/{key}") @Secured({"ROLE_HELPDESK"}) BaseResponse sendToUser( @Parameter( in = ParameterIn.PATH, required = true, description = "User unique key" ) @PathVariable(name = "key", required = true) UUID key, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Message", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ClientMessageCommandDto.class) ), required = true ) @RequestBody(required = true) ClientMessageCommandDto message ); /** * Send a message to the provider with the specified key * * @param key Recipient provider unique key * @param message Message command object * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-05", summary = "Send a message to a provider", description = "Sends a message to the specified provider from the authenticated user", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = MessageEndpointTypes.MessageReceiptDto.class) ) ) @PostMapping(value = "/message/provider/{key}") @Secured({"ROLE_USER", "ROLE_HELPDESK"}) BaseResponse sendToProvider( @Parameter( in = ParameterIn.PATH, required = true, description = "Provider unique id" ) @PathVariable(name = "key", required = true) UUID key, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Message", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ClientMessageCommandDto.class)), required = true ) @RequestBody(required = true) ClientMessageCommandDto message ); /** * Send message to Helpdesk * * @param message Message configuration object * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-06", summary = "Send a message to Helpdesk", description = "Sends a message to Helpdesk from the authenticated user", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = MessageEndpointTypes.MessageReceiptDto.class)) ) @PostMapping(value = "/message/helpdesk") @Secured({"ROLE_USER", "ROLE_PROVIDER"}) BaseResponse sendToHelpdesk( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Message", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ClientMessageCommandDto.class)), required = true ) @RequestBody(required = true) ClientMessageCommandDto message ); /** * Reply to message * * @param key Reply to message with the specified key * @param message Message command object * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-03", summary = "Reply to a message", description = "Reply to a message accessible to the authenticated user", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = MessageEndpointTypes.MessageReceiptDto.class)) ) @PostMapping(value = "/message/{key}") @Secured({"ROLE_USER", "ROLE_PROVIDER", "ROLE_HELPDESK"}) BaseResponse replyToMessage( @Parameter( in = ParameterIn.PATH, required = true, description = "Message unique key" ) @PathVariable(name = "key", required = true) UUID key, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Message", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ClientMessageCommandDto.class)), required = true ) @RequestBody(required = true) ClientMessageCommandDto message ); /** * Mark message as read * * @param key The message to mark as read * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "message-02", summary = "Read message", description = "Marks a message as read", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = BaseResponse.class)) ) @PutMapping(value = "/message/{key}") @Secured({"ROLE_USER", "ROLE_PROVIDER", "ROLE_HELPDESK"}) BaseResponse readMessage( @Parameter( in = ParameterIn.PATH, required = true, description = "Message unique key" ) @PathVariable(name = "key", required = true) UUID key ); /** * Mark notification as read * * @param key The notification to mark as read * * @return An instance of {@link BaseResponse} */ @Operation( operationId = "notification-02", summary = "Read notification", description = "Marks a notification as read", tags = { "Message" } ) @ApiResponse( responseCode = "200", description = "successful operation", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = BaseResponse.class)) ) @PutMapping(value = "/notification/{key}") @Secured({"ROLE_USER", "ROLE_PROVIDER", "ROLE_HELPDESK"}) BaseResponse readNotification( @Parameter( in = ParameterIn.PATH, required = true, description = "Notification unique key" ) @PathVariable(name = "key", required = true) UUID key ); }
Java
CL
b3e449ebe8b9317c1cdc48077e64f305cd3f511a50a27b26618ce83cf1ebb042
package org.neatutils.collections.immutable; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.stream.Stream; import java.util.stream.StreamSupport; public interface ImmutableMap<K, V> extends Iterable<Entry<K, V>> { public V get(K key); public boolean containsKey(K key); public ImmutableMap<K, V> put(K key, V value); public ImmutableMap<K, V> putAll(Map<K, V> map); public ImmutableMap<K, V> putAll(ImmutableMap<K, V> map); public ImmutableMap<K, V> remove(K key); public ImmutableMap<K, V> remove(K key, V value); public ImmutableMap<K, V> remove(Entry<K, V> entry); public ImmutableMap<K, V> removeAll(Map<K, V> map); public ImmutableMap<K, V> removeAll(ImmutableMap<K, V> map); public ImmutableMap<K, V> removeAll(Collection<K> keys); public int size(); public Set<K> keySet(); public Collection<V> values(); public boolean isEmpty(); public default Set<Entry<K, V>> entrySet() { return this.asUnmodifiableMap().entrySet(); } public default boolean containsEntry(final K key, final V value) { if (key == null) { throw new NullPointerException("Precondition violation - argument 'key' must not be NULL!"); } V containedValue = this.get(key); if (containedValue == null) { // not contained (NULL values are not allowed) return false; } return Objects.equals(containedValue, value); } public default boolean containsEntry(final Entry<K, V> entry) { if (entry == null) { throw new NullPointerException("Precondition violation - argument 'entry' must not be NULL!"); } return this.containsEntry(entry.getKey(), entry.getValue()); } public default boolean containsValue(final V value) { return this.values().contains(value); } public default Map<K, V> asUnmodifiableMap() { return ImmutableMaps.asUnmodifiableMap(this); } public default Stream<Entry<K, V>> stream() { return StreamSupport.stream(this.spliterator(), false); } public default Stream<Entry<K, V>> parallelStream() { return StreamSupport.stream(this.spliterator(), true); } }
Java
CL
3c1c889f826f944a1ae57797dbb0da77fe6ce6bd16a60d9f335141d73fb8dc4e
/* * Copyright (c) 2017-present, CV4J Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cv4j.core.filters; import com.cv4j.core.datamodel.ImageProcessor; import com.cv4j.image.util.Tools; public class GlowFilter extends GaussianBlurFilter{ private float amount = 0.2f; private int radius; public void setAmount( float amount ) { this.amount = amount; } public float getAmount() { return amount; } @Override public ImageProcessor doFilter(ImageProcessor src){ int total = width*height; byte[] R1 = new byte[total]; byte[] G1 = new byte[total]; byte[] B1 = new byte[total]; System.arraycopy(R, 0, R1, 0, total); System.arraycopy(G, 0, G1, 0, total); System.arraycopy(B, 0, B1, 0, total); // 高斯模糊 super.doFilter(src); float a = 4*amount; int index = 0; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++ ) { int r1 = R[index] & 0xff; int g1 = G[index] & 0xff; int b1 = B[index] & 0xff; int r2 = R1[index] & 0xff; int g2 = G1[index] & 0xff; int b2 = B1[index] & 0xff; R[index] = (byte)Tools.clamp( (int)(r1 + a * r2) ); G[index] = (byte)Tools.clamp( (int)(g1 + a * g2) ); B[index] = (byte)Tools.clamp( (int)(b1 + a * b2) ); index++; } } return src; } }
Java
CL
aeab085145d083854c4b42f87444859aaeed8f71afcd005a3f4d9c69b83c10cc
// Copyright (c) 2000, 2001, 2006 Per M.A. Bothner and Brainfood Inc. // This is free software; for terms and warranty disclaimer see ./COPYING. package gnu.lists; /** A Consumer is something that will accept data (output), * and do something with it. * A consumer is like a SAX DocumentHandler or a PrintWriter, * but more abstract. If a Sequence class impleemnts Consumer, * then data "written" to the sequence will be inserted in the sequence. * <p> * <em>Note:</em> This interface is not quite final. For example it is * probable we will add methods for comments, processing instructions, etc. */ public interface Consumer extends Appendable /* #ifdef JAVA8 */ // , java.util.function.Consumer<Object>, // java.util.function.IntConsumer, // java.util.function.LongConsumer, // java.util.function.DoubleConsumer /* #endif */ { public void writeBoolean(boolean v); public void writeFloat(float v); public void writeDouble(double v); public void writeInt(int v); public void writeLong(long v); public void startDocument(); public void endDocument(); public void startElement(Object type); public void endElement(); /** Write a attribute for the current element. * This is only allowed immediately after a startElement. */ public void startAttribute(Object attrType); /** End of an attribute or end of an actual parameter. * The former use matches a startAttribute; the latter may not, * and can be used to separate parameters in a parameter list. * This double duty suggsts the method should at least be re-named. */ public void endAttribute(); public void writeObject(Object v); /** True if consumer is ignoring rest of element. * The producer can use this information to skip ahead. */ public boolean ignoring(); public void write(int ch); public void write(String string); public void write(CharSequence string, int start, int length); public void write(char[] buf, int start, int length); public Consumer append (char c); public Consumer append (CharSequence csq); public Consumer append (CharSequence csq, int start, int end); /* #ifdef JAVA8 */ // default public void accept(Object t) { writeObject(t); } // default public void accept(int t) { writeInt(t); } // default public void accept(long t) { writeLong(t); } // default public void accept(double t) { writeDouble(t); } /* #endif */ }
Java
CL
5158d3f137c847f01236df97ff29121fdcacea454e77dbea12bf2f4a4f0f8376
package P1_iud.model; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; import javax.xml.bind.DatatypeConverter; public class GlobalService { public static final int RECORDS_PER_PAGE = 3; public static final String host = "127.0.0.1"; public static final String USERID = "sa"; public static final String PASSWORD = "sa123456"; public static final String SYSTEM_NAME = "書豪網路購物商城"; public static final String JNDI_DB_NAME = "java:comp/env/jdbc/BookDataSQLver"; public static final int IMAGE_FILENAME_LENGTH = 20; public static final String DB_URL = "jdbc:sqlserver://" + GlobalService.host + ":1433;databaseName=JSPDB" ; public static final String KEY = "KittySnoopyMicky"; public static final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; public String getSystemName() { return SYSTEM_NAME; } /** * 依MD5演算法將參數字串message轉換為128位元(16個位元組)的資料。 * * @param message : 要加密的字串 * @return : 128位元資料的16進位表示法所構成的字串 */ public static String getMD5Endocing(String message) { final StringBuffer buffer = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(message.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } return buffer.toString(); } /** * 依MD5演算法將檔案file轉換為128位元(16個位元組)的資料。 * * @param message : 要加密的字串 * @return : 128位元資料的16進位表示法所構成的字串 */ public static String getMD5Endocing(File file) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream(file); byte[] ba = new byte[1024]; int len = 0; while ((len = fis.read(ba)) != -1) { md.update(ba, 0, len); } byte[] digest = md.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { byte b = digest[i]; int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } return buffer.toString(); } public static void main(String[] args) throws Exception { File file = new File("d:\\apache-tomcat-6.0.35-windows-x64.zip"); // 842de0a085372bcd8c85457635ccb3e4 System.out.println(getMD5Endocing(file)); file = new File("d:\\apache-tomcat-6.0.18.exe"); // fb827381b1eca44bf32273db548157d3 System.out.println(getMD5Endocing(file)); } // 本方法調整fileName的長度小於或等於maxLength。 // 如果fileName的長度小於或等於maxLength,直接傳回fileName // 否則保留最後一個句點與其後的附檔名,縮短主檔名使得fileName的總長度 // 等於maxLength。 public static String adjustFileName(String fileName, int maxLength) { int length = fileName.length(); if ( length <= maxLength ) { return fileName ; } int n = fileName.lastIndexOf("."); int sub = fileName.length() - n - 1; fileName = fileName.substring(0, maxLength-1-sub) + "." + fileName.substring(n+1); return fileName; } public static String getFileName(final Part part) { for (String content : part.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) { return content.substring(content.indexOf('=') + 1).trim() .replace("\"", ""); } } return null; } // 此方法可檢視上傳資料的每個欄位與每個檔案, public static void exploreParts(Collection<Part> parts, HttpServletRequest req){ imginfoVO imgVO = new imginfoVO(); viewnameVO viewVO = new viewnameVO(); int imgCount = 0; int viewCount = 0; try { for (Part part: parts){ String name = part.getName(); String contentType = part.getContentType(); String value = ""; long size = part.getSize(); // 上傳資料的大小,即上傳資料的位元組數 InputStream is =part.getInputStream(); if (contentType != null) { // 表示該part為檔案 // 取出上傳檔案的檔名 String filename = GlobalService.getFileName(part); // 將上傳的檔案寫入到location屬性所指定的資料夾 if (filename != null && filename.trim().length() > 0) { part.write(filename); } value = filename; imgCount++; if(imgCount == 1){ imgVO.setPic1(value); imgVO.setIs1(is); imgVO.setSize1(size); } if(imgCount == 2){ imgVO.setPic2(value); imgVO.setIs2(is); imgVO.setSize2(size); } if(imgCount == 3){ imgVO.setPic3(value); imgVO.setIs3(is); imgVO.setSize3(size); } } else { // 表示該part為一般的欄位 // 將上傳的欄位資料寫入到location屬性所指定的資料夾,檔名為"part_"+ name part.write("part_"+ name); value = req.getParameter(name); viewCount++; if(viewCount == 1){ viewVO.setViewID(value); } if(viewCount == 2){ viewVO.setViewname(value); } if(viewCount == 3){ viewVO.setViewArea(value); } if(viewCount == 4){ viewVO.setViewAddr(value); } if(viewCount == 5){ viewVO.setViewlng(value); } if(viewCount == 6){ viewVO.setViewlat(value); } if(viewCount == 7){ imgVO.setImgDescript1(value); } if(viewCount == 8){ imgVO.setImgDescript2(value); } if(viewCount == 9){ imgVO.setImgDescript3(value); } } System.out.printf("%-15s %-15s %8d %-20s \n", name, contentType, size, value); } String viewIdPK = (viewVO.getViewID()).substring(2,(viewVO.getViewID()).lastIndexOf("_")); String imgPK1 =imgVO.getPic1().substring(0,imgVO.getPic1().lastIndexOf(".")); String imgPK2 =imgVO.getPic2().substring(0,imgVO.getPic2().lastIndexOf(".")); String imgPK3 =imgVO.getPic3().substring(0,imgVO.getPic3().lastIndexOf(".")); viewnameService vnSvc = new viewnameService(); String successMsg = vnSvc.insert(viewIdPK,viewVO.getViewname(),viewVO.getViewArea() ,viewVO.getViewAddr(),viewVO.getViewlng(),viewVO.getViewlat()); System.out.println("successMsg = " + successMsg); System.out.println("pic1ImagesPK= "+imgVO.getPic1()); imginfoDAO imgDAO = new imginfoDAO(); String successImagesMsg = imgDAO.insertImg(imgPK1,viewIdPK,imgVO.getImgDescript1(),imgVO.getIs1(),imgVO.getSize1(),"jpg"); System.out.println("pic1 = "+ successImagesMsg); System.out.println("pic2ImagesPK= "+imgVO.getPic2()); successImagesMsg = imgDAO.insertImg(imgPK2,viewIdPK,imgVO.getImgDescript2(),imgVO.getIs2(),imgVO.getSize2(),"jpg"); System.out.println("pic2 = "+ successImagesMsg); System.out.println("pic3ImagesPK= "+imgVO.getPic3()); successImagesMsg = imgDAO.insertImg(imgPK3,viewIdPK,imgVO.getImgDescript3(),imgVO.getIs3(),imgVO.getSize3(),"jpg"); System.out.println("pic3 = "+ successImagesMsg); } catch (IOException e) { e.printStackTrace(); } } /** * 本方法可對字串message(Plaintext, 明文)加密,然後將加密後的字串 * (Ciphertext, 密文)傳回。 * * @param key : 加密金鑰 * @param message : 明文,即要加密的字串 * @return 加密後的 * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws Throwable */ public static String encryptString(String message) { // DES : Data Encryption Standard, 一種對稱式加密演算法。 // 美國聯邦政府於1976年定為聯邦資料處理標準(FIPS),它的 // 金鑰則必須是7個位元組、加密區塊(Cipher Block)固定為8個位元組。 // DES目前已被視為是一種不安全的演算法。 // AES : Advanced Encryption Standard, 一種對稱式加密演算法。 // (美國聯邦政府於2001年納入FIPS 140-2標準),此種演算法 // 的Cipher Block固定為16個位元組。金鑰則必須是16個位元組、 // 24個位元組或32個位元組(即128個位元、192個位元或256個位元)。 // ECB : Electronic CookBook, 一種資料的加密方式,這種加密方式採取 // 每個區塊(如8個或16個位元組)獨立加密,即加密任ㄧ區塊時與其它區塊 // 無關。獨立壓縮有優點也有缺點。 // 優點為可以由多個處理器來平行處理ㄧ個很大的資料。缺點為如果資料 // 的內容有重複出現的部分,而且重複資料的長度剛好與加密區塊等長, // 則這些重複出現的部分經過加密後會出現相同的結果。 // PKCS5Padding: 如果要加密的資料不是8個(如DES加密演算法)或 // 16個(如AES加密演算法)位元組的整數倍,則必須在欲加密資料的 // 尾端加入若干個位元組來湊成整數倍。PKCS5Padding是一種 // 補足不足位元組的方法。 String encryptedString = ""; try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); encryptedString = DatatypeConverter.printBase64Binary(cipher.doFinal(message.getBytes())); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return encryptedString; } /** * 本方法可對加密之字串(Ciphertext)解密,key為當初加密時的金鑰 * 傳回值為解密後的字串(Plaintext) * */ public static String decryptString(String key, String stringToDecrypt) { String decryptedString = ""; try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] b = DatatypeConverter.parseBase64Binary(stringToDecrypt); decryptedString = new String(cipher.doFinal(b)); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return decryptedString; } public static void close(Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e) { System.err.println("關閉Connection物件時發生例外: " + e); } } } public static void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { System.err.println("關閉ResultSet物件時發生例外: " + e); } } } public static void close(PreparedStatement pStmt) { if (pStmt != null) { try { pStmt.close(); } catch (SQLException e) { System.err.println("關閉PreparedStatement物件時發生例外: " + e); } } } }
Java
CL
91bf0f729d3283146386183bc8c38b14b77049f5550e9b64307ba51045ac3703
package com.shi.utils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.sql.SQLException; /** * @author 千文sea * @create 2020-09-18 10:33 * * 事务管理相关的工具类,它包含了: 开启事务,提交事务,回滚事务和释放连接 */ @Component("transactionManager") @Aspect public class TransactionManager { @Autowired private ConnectionUtils connectionUtils; @Pointcut("execution(* com.shi.service.impl.*.*(..))") private void pt1(){}; /** * 开启事务 */ public void beginTransaction(){ try { connectionUtils.getThreadLocalConnection().setAutoCommit(false); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * 提交事务 */ public void commitTransaction(){ try { connectionUtils.getThreadLocalConnection().commit(); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * 回滚事务 */ public void rollbackTransaction(){ try { connectionUtils.getThreadLocalConnection().rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * 释放连接 */ public void releaseTransaction(){ try { connectionUtils.getThreadLocalConnection().close(); //还回连接池中 connectionUtils.removeConnection(); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * 环绕通知 * @param pjp * @return */ @Around("pt1()") public Object aroundAdvice(ProceedingJoinPoint pjp){ Object rtValue = null; try { //1.获取 参数 Object[] args = pjp.getArgs(); //2.开启事务 this.beginTransaction(); //3.执行方法 rtValue = pjp.proceed(args); //4.提交事务 this.commitTransaction(); //返回结果 return rtValue; } catch (Throwable e) { //5.回滚事务 this.rollbackTransaction(); throw new RuntimeException(e); } finally { //6.释放资源 this.releaseTransaction(); } } }
Java
CL
fdf356bdc8e94ec806a2aa8ee08608f89fc83ec55dbdb782c0047d4f0a2a83c9
package com.example.apppcmarcet.repository; import com.example.apppcmarcet.entity.Property; import com.example.apppcmarcet.projection.PropertyProjection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(path = "property", itemResourceRel = "list", excerptProjection = PropertyProjection.class) public interface PropertyRepository extends JpaRepository<Property, Integer> { }
Java
CL
0f6dfaddc8ae7e5f9d89b5b4c20f9c5a7909f8b532ffe9fa8060ba2bd629f7ea
/* * This file is generated by jOOQ. */ package generated.db.tables; import generated.db.Code4good; import generated.db.Keys; import generated.db.tables.records.QuizParticipantsRecord; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.1" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class QuizParticipants extends TableImpl<QuizParticipantsRecord> { private static final long serialVersionUID = 1868744005; /** * The reference instance of <code>code4good.quiz_participants</code> */ public static final QuizParticipants QUIZ_PARTICIPANTS = new QuizParticipants(); /** * The class holding records for this type */ @Override public Class<QuizParticipantsRecord> getRecordType() { return QuizParticipantsRecord.class; } /** * The column <code>code4good.quiz_participants.id</code>. */ public final TableField<QuizParticipantsRecord, Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.age</code>. */ public final TableField<QuizParticipantsRecord, Integer> AGE = createField("age", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.sex</code>. */ public final TableField<QuizParticipantsRecord, String> SEX = createField("sex", org.jooq.impl.SQLDataType.VARCHAR.length(45).nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.ip</code>. */ public final TableField<QuizParticipantsRecord, String> IP = createField("ip", org.jooq.impl.SQLDataType.VARCHAR.length(45).nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.country</code>. */ public final TableField<QuizParticipantsRecord, String> COUNTRY = createField("country", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.quiz_answers</code>. */ public final TableField<QuizParticipantsRecord, String> QUIZ_ANSWERS = createField("quiz_answers", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); /** * The column <code>code4good.quiz_participants.percent_correct_answers</code>. */ public final TableField<QuizParticipantsRecord, Integer> PERCENT_CORRECT_ANSWERS = createField("percent_correct_answers", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * Create a <code>code4good.quiz_participants</code> table reference */ public QuizParticipants() { this("quiz_participants", null); } /** * Create an aliased <code>code4good.quiz_participants</code> table reference */ public QuizParticipants(String alias) { this(alias, QUIZ_PARTICIPANTS); } private QuizParticipants(String alias, Table<QuizParticipantsRecord> aliased) { this(alias, aliased, null); } private QuizParticipants(String alias, Table<QuizParticipantsRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Code4good.CODE4GOOD; } /** * {@inheritDoc} */ @Override public Identity<QuizParticipantsRecord, Long> getIdentity() { return Keys.IDENTITY_QUIZ_PARTICIPANTS; } /** * {@inheritDoc} */ @Override public UniqueKey<QuizParticipantsRecord> getPrimaryKey() { return Keys.KEY_QUIZ_PARTICIPANTS_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<QuizParticipantsRecord>> getKeys() { return Arrays.<UniqueKey<QuizParticipantsRecord>>asList(Keys.KEY_QUIZ_PARTICIPANTS_PRIMARY); } /** * {@inheritDoc} */ @Override public QuizParticipants as(String alias) { return new QuizParticipants(alias, this); } /** * Rename this table */ @Override public QuizParticipants rename(String name) { return new QuizParticipants(name, null); } }
Java
CL
c8e0c7b1643bac0e483a171f0164a39bf345375aa473e9fb82b04b9bbf39c67d
package org.limewire.core.impl.mojito; import org.limewire.core.api.mojito.MojitoManager; import com.google.inject.AbstractModule; /** * Guice module to configure Mojito API for the mock core. */ public class MockMojitoModule extends AbstractModule { /** * Configures Mojito API for the mock core. */ @Override protected void configure() { bind(MojitoManager.class).to(MockMojitoManager.class); } }
Java
CL
46799ebe962864420958880e669d413a71361bffcc83555cba7f56a234b03c76
/* * Copyright 2007-2010 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.impalaframework.config; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.impalaframework.exception.ConfigurationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * State holder for injectible, dynamically modifiable {@link Date} value. * * @author Phil Zoio */ public class DatePropertyValue extends BasePropertyValue implements InitializingBean { private static final Log logger = LogFactory.getLog(DatePropertyValue.class); private String defaultValueString; private Date defaultValue; private String rawValue; private String pattern; private Date value; public DatePropertyValue() { super(); } public DatePropertyValue(PropertySource propertySource, String name, String pattern, Date defaultValue) { super(propertySource, name, defaultValue); Assert.notNull(pattern); this.pattern = pattern; this.defaultValue = defaultValue; } public void init() { Assert.notNull(pattern, "Pattern cannot be null"); if (defaultValueString != null && defaultValue == null) { try { defaultValue = new SimpleDateFormat(pattern).parse(defaultValueString); } catch (ParseException e) { throw new ConfigurationException("Default value '" + defaultValueString + "' does not convert to a date using pattern: " + pattern, e); } } } public void afterPropertiesSet() throws Exception { init(); } public synchronized Date getValue() { String rawValue = super.getRawValue(); if (rawValue == null) { value = defaultValue; } else if (!rawValue.equals(this.rawValue)) { try { this.value = new SimpleDateFormat(pattern).parse(rawValue); this.rawValue = rawValue; } catch (ParseException e) { logger.error("Property " + rawValue + " is not a valid date"); } } return value; } public void setDefaultValueString(String defaultValue) { this.defaultValueString = defaultValue; } public void setDefaultValue(Date defaultValue) { this.defaultValue = defaultValue; } public void setPattern(String pattern) { this.pattern = pattern; } }
Java
CL
7f7a380384985ad350c87d281f7d7f17d1ef10f6fd6b7c7c734824f1d6e98e09
/* * The Fascinator - Plugin - Harvester - SKOS * Copyright (C) 2010-2011 University of Southern Queensland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package au.edu.usq.fascinator.harvester.skos; import java.io.File; import java.util.Set; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.edu.usq.fascinator.api.PluginManager; import au.edu.usq.fascinator.api.harvester.Harvester; import au.edu.usq.fascinator.api.storage.Storage; /** * Unit tests for the SKOS harvester plugin * * @author Linda Octalina */ public class SkosHarvesterTest { /** logging */ private Logger log = LoggerFactory.getLogger(SkosHarvesterTest.class); private Storage ram; /** * Sets the "test.dir" and "test.cache.dir" system property for use in the * JSON configuration * * @throws Exception if any error occurs */ @Before public void setup() throws Exception { File baseDir = new File(SkosHarvesterTest.class.getResource("/") .toURI()); System.setProperty("test.dir", baseDir.getAbsolutePath()); ram = PluginManager.getStorage("ram"); ram.init("{}"); } /** * Test on getting concept scheme uri * * @throws Exception if any error occurs */ @Test public void getConceptScheme() throws Exception { SkosHarvester skosHarvester = getHarvester("/for-subset.json"); Assert.assertEquals(skosHarvester.getConceptScheme().toString(), "http://purl.org/anzsrc/for/#for"); } @Test public void getConceptScheme2() throws Exception { SkosHarvester skosHarvester = getHarvester("/for08-subset.json"); Assert.assertEquals(skosHarvester.getConceptScheme().toString(), "http://purl.org/asc/1297.0/2008/for/"); } /** * Test on getting object list * * @throws Exception if any error occurs */ @Test public void getObjectIdList() throws Exception { SkosHarvester skosHarvester = getHarvester("/for-subset.json"); Set<String> concepts = skosHarvester.getObjectIdList(); Assert.assertEquals(15, concepts.size()); } @Test public void getObjectIdList2() throws Exception { SkosHarvester skosHarvester = getHarvester("/for08-subset.json"); Set<String> concepts = skosHarvester.getObjectIdList(); Assert.assertEquals(99, concepts.size()); } private SkosHarvester getHarvester(String filename) throws Exception { Harvester skos = PluginManager.getHarvester("skos", ram); File f = new File(getClass().getResource(filename).toURI()); skos.init(f); return (SkosHarvester) skos; } }
Java
CL
2de4984a1ded639e9bfb82170207445497e656bf0f1aa3516ec0a9da904f7151
package br.com.auster.vivo.billcheckout.cache; import java.util.List; /** * An interface for DataBarn service methods * * @author etirelli */ public interface DataBarnInterestFeeServices { /*** * Retunrs a List of InterestFeePenalty objects representing each * occurrency of late payment fees from data barn, for a given account * Concrete implementations MUST return an empty list instead of Null for the cases * where there are not late payment fee, interest penalties. * * @param acctNumber * @return */ public List getInterestRecordsFor (String queryName, Object[] parametersString); }
Java
CL
c83f8bdf92eb829d8caa5da3f53cdc9ac6caed864ac7d26804f1942edc94e9e0
package hu.webuni.totinistvan.logistics.security; import hu.webuni.totinistvan.logistics.model.dto.LoginDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class JwtLoginController { @Autowired AuthenticationManager authenticationManager; @Autowired JwtService jwtService; @PostMapping("/api/login") public String login(@RequestBody LoginDto loginDto) { Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword())); return jwtService.createJwtToken((UserDetails) authentication.getPrincipal()); } }
Java
CL
81c4e6ab617f2b9de5bc8d02f519a1a29b96b22b0ecfa72f5f73a747d4005725
package com.openkm.frontend.client.service; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.user.client.rpc.impl.TypeHandler; import java.util.HashMap; import java.util.Map; public class OKMNoteService_TypeSerializer extends com.google.gwt.user.client.rpc.impl.SerializerBase { private static final Map<String, TypeHandler> methodMapJava; private static final MethodMap methodMapNative; private static final Map<Class<?>, String> signatureMapJava; private static final JsArrayString signatureMapNative; static { if (GWT.isScript()) { methodMapJava = null; methodMapNative = loadMethodsNative(); signatureMapJava = null; signatureMapNative = loadSignaturesNative(); } else { methodMapJava = loadMethodsJava(); methodMapNative = null; signatureMapJava = loadSignaturesJava(); signatureMapNative = null; } } @SuppressWarnings("deprecation") private static Map<String, TypeHandler> loadMethodsJava() { Map<String, TypeHandler> result = new HashMap<String, TypeHandler>(); result.put("com.google.gwt.i18n.client.impl.DateRecord/112389920", new com.google.gwt.i18n.client.impl.DateRecord_FieldSerializer.Handler()); result.put("com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException/3936916533", new com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException_FieldSerializer.Handler()); result.put("com.openkm.frontend.client.OKMException/1351513842", new com.openkm.frontend.client.OKMException_FieldSerializer.Handler()); result.put("com.openkm.frontend.client.bean.GWTNote/2046630910", new com.openkm.frontend.client.bean.GWTNote_FieldSerializer.Handler()); result.put("java.lang.String/2004016611", new com.google.gwt.user.client.rpc.core.java.lang.String_FieldSerializer.Handler()); result.put("java.sql.Date/3996530531", new com.google.gwt.user.client.rpc.core.java.sql.Date_FieldSerializer.Handler()); result.put("java.sql.Time/831929183", new com.google.gwt.user.client.rpc.core.java.sql.Time_FieldSerializer.Handler()); result.put("java.sql.Timestamp/1769758459", new com.google.gwt.user.client.rpc.core.java.sql.Timestamp_FieldSerializer.Handler()); result.put("java.util.Date/1659716317", new com.google.gwt.user.client.rpc.core.java.util.Date_FieldSerializer.Handler()); return result; } @SuppressWarnings("deprecation") private static native MethodMap loadMethodsNative() /*-{ var result = {}; result["com.google.gwt.i18n.client.impl.DateRecord/112389920"] = [ @com.google.gwt.i18n.client.impl.DateRecord_FieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.i18n.client.impl.DateRecord_FieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Lcom/google/gwt/i18n/client/impl/DateRecord;), ]; result["com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException/3936916533"] = [ @com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException_FieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException_FieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Lcom/google/gwt/user/client/rpc/IncompatibleRemoteServiceException;), @com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException_FieldSerializer::serialize(Lcom/google/gwt/user/client/rpc/SerializationStreamWriter;Lcom/google/gwt/user/client/rpc/IncompatibleRemoteServiceException;) ]; result["com.openkm.frontend.client.OKMException/1351513842"] = [ @com.openkm.frontend.client.OKMException_FieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.openkm.frontend.client.OKMException_FieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Lcom/openkm/frontend/client/OKMException;), ]; result["com.openkm.frontend.client.bean.GWTNote/2046630910"] = [ @com.openkm.frontend.client.bean.GWTNote_FieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.openkm.frontend.client.bean.GWTNote_FieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Lcom/openkm/frontend/client/bean/GWTNote;), ]; result["java.lang.String/2004016611"] = [ @com.google.gwt.user.client.rpc.core.java.lang.String_CustomFieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.core.java.lang.String_CustomFieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Ljava/lang/String;), @com.google.gwt.user.client.rpc.core.java.lang.String_CustomFieldSerializer::serialize(Lcom/google/gwt/user/client/rpc/SerializationStreamWriter;Ljava/lang/String;) ]; result["java.sql.Date/3996530531"] = [ @com.google.gwt.user.client.rpc.core.java.sql.Date_CustomFieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.core.java.sql.Date_CustomFieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Ljava/sql/Date;), ]; result["java.sql.Time/831929183"] = [ @com.google.gwt.user.client.rpc.core.java.sql.Time_CustomFieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.core.java.sql.Time_CustomFieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Ljava/sql/Time;), ]; result["java.sql.Timestamp/1769758459"] = [ @com.google.gwt.user.client.rpc.core.java.sql.Timestamp_CustomFieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.core.java.sql.Timestamp_CustomFieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Ljava/sql/Timestamp;), ]; result["java.util.Date/1659716317"] = [ @com.google.gwt.user.client.rpc.core.java.util.Date_CustomFieldSerializer::instantiate(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;), @com.google.gwt.user.client.rpc.core.java.util.Date_CustomFieldSerializer::deserialize(Lcom/google/gwt/user/client/rpc/SerializationStreamReader;Ljava/util/Date;), ]; return result; }-*/; @SuppressWarnings("deprecation") private static Map<Class<?>, String> loadSignaturesJava() { Map<Class<?>, String> result = new HashMap<Class<?>, String>(); result.put(com.google.gwt.i18n.client.impl.DateRecord_FieldSerializer.concreteType(), "com.google.gwt.i18n.client.impl.DateRecord/112389920"); result.put(com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException_FieldSerializer.concreteType(), "com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException/3936916533"); result.put(com.openkm.frontend.client.OKMException_FieldSerializer.concreteType(), "com.openkm.frontend.client.OKMException/1351513842"); result.put(com.openkm.frontend.client.bean.GWTNote_FieldSerializer.concreteType(), "com.openkm.frontend.client.bean.GWTNote/2046630910"); result.put(com.google.gwt.user.client.rpc.core.java.lang.String_FieldSerializer.concreteType(), "java.lang.String/2004016611"); result.put(com.google.gwt.user.client.rpc.core.java.sql.Date_FieldSerializer.concreteType(), "java.sql.Date/3996530531"); result.put(com.google.gwt.user.client.rpc.core.java.sql.Time_FieldSerializer.concreteType(), "java.sql.Time/831929183"); result.put(com.google.gwt.user.client.rpc.core.java.sql.Timestamp_FieldSerializer.concreteType(), "java.sql.Timestamp/1769758459"); result.put(com.google.gwt.user.client.rpc.core.java.util.Date_FieldSerializer.concreteType(), "java.util.Date/1659716317"); return result; } @SuppressWarnings("deprecation") private static native JsArrayString loadSignaturesNative() /*-{ var result = []; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@com.google.gwt.i18n.client.impl.DateRecord::class)] = "com.google.gwt.i18n.client.impl.DateRecord/112389920"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException::class)] = "com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException/3936916533"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@com.openkm.frontend.client.OKMException::class)] = "com.openkm.frontend.client.OKMException/1351513842"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@com.openkm.frontend.client.bean.GWTNote::class)] = "com.openkm.frontend.client.bean.GWTNote/2046630910"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@java.lang.String::class)] = "java.lang.String/2004016611"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@java.sql.Date::class)] = "java.sql.Date/3996530531"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@java.sql.Time::class)] = "java.sql.Time/831929183"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@java.sql.Timestamp::class)] = "java.sql.Timestamp/1769758459"; result[@com.google.gwt.core.client.impl.Impl::getHashCode(Ljava/lang/Object;)(@java.util.Date::class)] = "java.util.Date/1659716317"; return result; }-*/; public OKMNoteService_TypeSerializer() { super(methodMapJava, methodMapNative, signatureMapJava, signatureMapNative); } }
Java
CL
4cda179782559366189b62db5c5a8b5eb5f27ce457fd94c01d6e4140e4d8491d
package com.evolveum.midpoint.studio.action; import com.evolveum.midpoint.studio.action.task.DiffLocalTask; import com.evolveum.midpoint.studio.impl.Environment; import com.evolveum.midpoint.studio.util.MidPointUtils; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import java.util.List; /** * Created by Viliam Repan (lazyman). */ public class DiffLocalAction extends AsyncAction<DiffLocalTask> { public static final String ACTION_NAME = "Diff local"; public DiffLocalAction() { super(ACTION_NAME, AllIcons.Actions.Diff); } @Override public void update(@NotNull AnActionEvent evt) { super.update(evt); Presentation presentation = evt.getPresentation(); boolean enabled = MidPointUtils.shouldEnableAction(evt); if (!enabled) { presentation.setEnabled(false); return; } VirtualFile[] selectedFiles = ApplicationManager.getApplication().runReadAction( (Computable<VirtualFile[]>) () -> evt.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY)); List<VirtualFile> toProcess = MidPointUtils.filterXmlFiles(selectedFiles); if (toProcess.size() != 2) { presentation.setEnabled(false); return; } presentation.setEnabled(enabled); } @Override protected DiffLocalTask createTask(AnActionEvent e, Environment env) { DiffLocalTask task = new DiffLocalTask(e); task.setEnvironment(env); return task; } }
Java
CL
5a3580c87dbe1750eb334ab8ef57c069e5c97e55984783f3a21b75f79609a50c
package com.arithmetic.features.datastructure.sort; import org.junit.Test; import java.util.Arrays; /** * 基数排序 * * 以空间换时间,稳定排序算法,这个实现不能排序负数,需要改进才可以 * * @author alan.chen * @date 2020/5/27 11:30 PM */ public class RadixSort { private static int[] arr = {50, 3, 22, 99, 90, 567, 999, 66, 123, 9}; @Test public void test() { radixSort(arr); print(); } private void radixSort(int[] arr) { // 创建二维数组,表示桶,用来保存每次排序的数据 int[][] bucket = new int[10][arr.length]; // 行表示0-9的每位数保存的桶位置,arr.length表示该桶保存的最大数据,可能会有浪费,不过这样不会溢出 // 该数组用来记录每个桶中的有几个数 int[] countOfElement = new int[10]; int maxNum = arr[0]; for (int i = 1; i < arr.length; i++) { if(maxNum < arr[i]) { maxNum = arr[i]; } } // 数字的最大位数 int maxNumLength = String.valueOf(maxNum).length(); // 数据的位数决定了循环多少次,可以完成排序 for (int i = 0, n = 1; i < maxNumLength; i++, n*=10) { // 循环数据,保存到指定的桶 for (int j = 0; j < arr.length; j++) { // 计算当前位数的桶是多少 int digitOfElement = arr[j] / n % 10; // 将数据保存到对应的桶, 并保存到第几个桶的第几个位置,这个位置用另一个数组记录 bucket[digitOfElement][countOfElement[digitOfElement]] = arr[j]; // 记录指定桶保存的数据量 countOfElement[digitOfElement]++; } // 定义原数组中的填充索引 int index = 0; // 每次将数据保存一次到桶中,然后顺序的开始将数据从桶中填充到原数组 for (int k = 0; k < countOfElement.length; k++) { if(countOfElement[k] != 0) { // 如果记录的指定的桶中有数据,则从桶中取数据并填充到原数组 for (int l = 0; l < countOfElement[k]; l++) { arr[index++] = bucket[k][l]; } } // 将记录数组中的桶的数据个数清空,为了下一次大循环可以继续使用 countOfElement[k] = 0; } } } public static void print() { Arrays.stream(arr).forEach(System.out::println); } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
Java
CL
e537f19da93dec5e029c7b9b1e8e968131dd5ea51e432706416ec307367bd8d6
package net.neiquan.okhttp; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.util.Pair; import com.alibaba.fastjson.JSON; import net.neiquan.okhttp.body.BodyWrapper; import net.neiquan.okhttp.builder.UploadRequestBuilder; import net.neiquan.okhttp.listener.DownloadListener; import net.neiquan.okhttp.listener.UploadListener; import org.haitao.common.utils.AppLog; import org.haitao.common.utils.ToastUtil; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Description * Author by wangHaitao(a758277560@gmail.com) * Created on 2016/5/31 * Version 1.0 */ public class OkHttpUtils { private static Handler mHandler = new Handler(Looper.getMainLooper()); private static OkHttpClient mHttpClient ; private static OkHttpUtils okHttpUtils ; /** * 是否已经在主界面了 登录的时候要重置为 false */ public static boolean alreadyInHome; private static Context context; public static void init(Context _context){ context=_context; } public static void init(Context _context,Class<?> skpCls){ context=_context; cls=skpCls; } private static Class<?> cls; public static void SetSessionOutCls(Class<?> _cls){ cls=_cls; } // 上面的代码主要是为了 过期跳转主页 private static OkHttpUtils init() { synchronized (OkHttpUtils.class) { if (mHttpClient == null) { mHttpClient = new OkHttpClient(); okHttpUtils =new OkHttpUtils(); } } return okHttpUtils; } public static OkHttpUtils getInstance() { return mHttpClient == null ? init() : okHttpUtils; } /** * get 同步 * @param url * @param netCallBack * @param type */ public void get(String url, final NetCallBack netCallBack, final Class type){ get(url,null,netCallBack,type); } /** * get 同步 * @param url * @param map * @param netCallBack * @param type */ public void get(String url, Map<String, String> map, final NetCallBack netCallBack, final Class type){ url= appendGetParams(url,map); Request request = new Request.Builder() .url(url) .build(); sync(map,request,netCallBack,type); } /** * get异步 * @param url * @param netCallBack * @param type */ public void getAnsy(String url, final NetCallBack netCallBack, final Class type){ getAnsy(url,null,netCallBack,type); } /** * get异步 * @param url * @param map 请求参数 * @param netCallBack * @param type */ public void getAnsy(String url, Map<String, String> map, final NetCallBack netCallBack, final Class type){ url= appendGetParams(url,map); Request request = new Request.Builder() .url(url) .build(); async(map,request,netCallBack,type); } /** * post 同步 * @param url * @param netCallBack * @param type */ public void post(String url, final NetCallBack netCallBack, final Class type){ post(url,null,netCallBack,type); } /** * post 同步 * @param url * @param map 请求参数 * @param netCallBack * @param type */ public void post(String url, Map<String, Object> map, final NetCallBack netCallBack, final Class type){ RequestBody body = appendPostParams(map); Request request = new Request.Builder() .url(url) .post(body) .build(); sync(map,request,netCallBack,type); } /** * 异步post * @param url * @param netCallBack * @param type */ public void postAnsy(String url, final NetCallBack netCallBack, final Class type){ postAnsy(url,null,netCallBack,type); } /** * 异步post * @param url * @param map 请求参数 * @param netCallBack * @param type */ public void postAnsy(String url, Map<String, Object> map, final NetCallBack netCallBack, final Class type){ RequestBody body = appendPostParams(map); Request request = new Request.Builder() .url(url) .post(body) .build(); async(map,request,netCallBack,type); } /** * 异步post json * @param url * @param map 请求参数 * @param netCallBack * @param type */ public void postJsonAnsy(String url, Map<String, Object> map, final NetCallBack netCallBack, final Class type){ postJsonAnsy(url, JSON.toJSONString(map),netCallBack,type); } /** * 异步post json * @param url * @param json 请求参数 * @param netCallBack * @param type */ public void postJsonAnsy(String url, String json, final NetCallBack netCallBack, final Class type){ MediaType JSON = MediaType.parse("application/json; charset=utf-8"); // MediaType JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); async(json,request,netCallBack,type); } /** * 同步 * @param request * @param netCallBack * @param type */ private void sync(Object requstPram,final Request request, final NetCallBack netCallBack, final Class type){ AppLog.e("url "+request.url()+" "+requstPram); Response response = null; try { response = mHttpClient.newCall(request).execute(); // 网络请求成功 if (response.isSuccessful()) { paserResponse (requstPram,response,netCallBack,type); }else{ paserFail(requstPram,request,response.code(),netCallBack); } } catch (IOException e) { e.printStackTrace(); } } /** * 异步 * @param request * @param netCallBack * @param type */ private void async(final Object requstPram,final Request request, final NetCallBack netCallBack, final Class type){ AppLog.e("url "+request.url()+" "+requstPram); mHttpClient.newCall(request).enqueue(new Callback(){ @Override public void onFailure(Request request, IOException e) { paserFail(requstPram,request,404,netCallBack); } @Override public void onResponse(Response response) throws IOException { paserResponse (requstPram,response,netCallBack,type); } }); } /** * 下载文件 有进度显示 * @param url * @param downloadListener * @return */ public Call download(String url, DownloadListener downloadListener) { Request request = new Request.Builder().url(url).build(); Call call = BodyWrapper.addProgressResponseListener(mHttpClient, downloadListener).newCall(request); call.enqueue(downloadListener); return call; } /** * 异步post 上传文件 * @param url * @param file * @param map * @param uploadListener */ public void postFile(String url, Pair<String, File> file,Map<String, String> map, UploadListener uploadListener){ new UploadRequestBuilder() .url(url) .file(file) .setParams(map) .setWriteTimeOut(20) .start(mHttpClient ,uploadListener); } /** * 创建 get 参数 * @param url * @param params * @return */ protected String appendGetParams(String url, Map<String, String> params) { StringBuilder sb = new StringBuilder(); sb.append(url + "?"); if (params != null && !params.isEmpty()) { for (String key : params.keySet()) { sb.append(key).append("=").append(params.get(key)).append("&"); } } sb = sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * 创建 post参数 * @param map * @return */ private RequestBody appendPostParams(Map<String, Object> map){ // 创建请求的参数body FormBody.Builder builder = new FormBody.Builder(); /** * 遍历key */ if (null != map) { for (Map.Entry<String, Object> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue().toString()); } } RequestBody body = builder.build(); return body; } /** * @param requstPram * @param request * @param code * @param netCallBack */ private void paserFail(Object requstPram,Request request,final int code, final NetCallBack netCallBack){ AppLog.e("fail url "+request.url()+" code "+code+" " +requstPram); if (netCallBack!=null){ mHandler.post(new Runnable() { @Override public void run() { // onFailure(e); if ( netCallBack!=null){ netCallBack.onFail(true,code,""); } } }); } } /** * 处理成功结果 * @param response * @param netCallBack */ private void paserResponse (Object requstPram,final Response response, final NetCallBack netCallBack, final Class type){ String res=""; try { res =response.body().string(); } catch (IOException e) { e.printStackTrace(); mHandler.post(new Runnable() { @Override public void run() { netCallBack.onFail(true,0,"服务器没有数据..."); } }); } AppLog.jsonAppend("========= url ========"+response.request().url().toString()+"\nrquestbody "+requstPram+"\n" + "code:"+response.code()+"\nresult:",res); if (response.isSuccessful()){ if (netCallBack!=null){ final Result result = JSON.parseObject(res, Result.class); if(result.getCode()==0){ //服务器逻辑成功 //判断 是否有对象 final ResultModel body = new ResultModel(); if(null!=type){ // 判断是jsonObject 还是 jsonArray if (result.getResponse()!=null){ if (isJsonArray(result.getResponse())){ List<?> ls = JSON.parseArray(result.getResponse(), type); body.setModelList(ls); }else{ body.setModel(JSON.parseObject(result.getResponse(), type)); } mHandler.post(new Runnable() { @Override public void run() { netCallBack.onSuccess(result.getResponse(),result.getErrorMessage(),body); } }); }else{ // 服务器没有返回对象 mHandler.post(new Runnable() { @Override public void run() { netCallBack.onFail(true,0,"服务器没有数据..."); } }); } }else{ mHandler.post(new Runnable() { @Override public void run() { AppLog.e("=============返回体==============="+result.getResponse()); netCallBack.onSuccess(result.getResponse(),result.getErrorMessage(),null); } }); } }else{ mHandler.post(new Runnable() { @Override public void run() { netCallBack.onFail(false,result.getCode(),result.getErrorMessage()); // } }); if (result.getCode()==50||result.getCode()==51){ // 登录 if (!alreadyInHome && context!=null && cls!=null) { alreadyInHome=true; // 防止多次跳转 Intent intent = new Intent(context,cls); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("sessionOut", true); context.startActivity(intent); ToastUtil.shortShowToast(result.getErrorMessage()); } } } } }else{ if (netCallBack!=null){ mHandler.post(new Runnable() { @Override public void run() { netCallBack.onFail(false,response.code(),"服务器异常..."); } }); } } } /** * 判断是否是json数组 * @param str * @return */ public boolean isJsonArray(String str){ final char[] strChar = str.substring(0, 1).toCharArray(); final char firstChar = strChar[0]; return firstChar == '[' ; } }
Java
CL
59c5687dbd093c0a247678eca7e4dff5f661d7378218406acb2e8ef3f4f59ae8
package com.mygame.android.net; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import android.os.Message; import com.mygame.android.json.util.JsonFormatFactory; import com.mygame.android.net.NetPostAsynTask.NetPostTask; import com.mygame.android.net.handle.INetResponseDataParse; public class NetGetAsynTask { /** * post 请求方式 * * @param url * @param params * @return */ protected static NetPostHandler handler = new NetPostHandler(); protected static void sendMessage(int code, NetPostTask task) { Message msg = Message.obtain(handler); msg.what = code; msg.obj = task; msg.sendToTarget(); } private static String Get(String url, List<NameValuePair> params) { HttpGet httpPost = new HttpGet(url); String result = null; HttpResponse httpResponse = null; try { //httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpResponse = new DefaultHttpClient().execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(httpResponse.getEntity()); System.out.println("result:" + result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } public static void doNetGet(String url, NetRequest request, Class<? extends NetResponse> responseClass) { if (null == request || null == url || "".equals(url.trim())) { return; } NetPostTask task = new NetPostTask(); task.url = url; task.request = request; task.responseClass = responseClass; sendMessage(NetConst.HANDLE_MESSAGE_FLAG_START_TASK, task); NetPostThread thread = new NetPostThread(task); thread.start(); } public static void doNetGet(String url, NetRequest request,String responseKeyName, Class<? extends NetResponse> responseClass) { if (null == request || null == responseClass || null == url || "".equals(url.trim())) { return; } NetPostTask task = new NetPostTask(); task.url = url; task.responseKeyName = responseKeyName; task.request = request; task.responseClass = responseClass; sendMessage(NetConst.HANDLE_MESSAGE_FLAG_START_TASK, task); NetPostThread thread = new NetPostThread(task); thread.start(); } private static class NetPostThread extends Thread { protected NetPostTask task; public NetPostThread(NetPostTask task) { super(); this.task = task; } public void run() { String result = null; HttpResponse httpResponse = null; String httpparams = task.request.complieGet(); if(!"".equals(httpparams.trim())){ task.url += "?"; task.url += httpparams; } HttpGet httpPost = new HttpGet(task.url); try { /* httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); */ HttpParams httpGetParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpGetParams, 10000); HttpConnectionParams.setSoTimeout(httpGetParams, 10000); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpGetParams); httpResponse = defaultHttpClient.execute(httpPost); int responseStatusCode = httpResponse.getStatusLine() .getStatusCode(); if (responseStatusCode == 200) { result = EntityUtils.toString(httpResponse.getEntity()); System.out.println("URL:"+task.url); System.out.println("result:" + result); try { INetResponseDataParse dataParse = task.request.dataParseHandle.newInstance(); task.response = dataParse.responseDataParse(task.request, result, task.responseClass); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); sendMessage(NetConst.HANDLE_MESSAGE_FLAG_ERROR, task); } sendMessage(NetConst.HANDLE_MESSAGE_FLAG_200, task); } else if (responseStatusCode == 500) { sendMessage(NetConst.HANDLE_MESSAGE_FLAG_500, task); } else if (responseStatusCode == 400 || responseStatusCode == 404) { sendMessage(NetConst.HANDLE_MESSAGE_FLAG_400, task); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); sendMessage(NetConst.HANDLE_MESSAGE_FLAG_ERROR, task); } catch (ClientProtocolException e) { e.printStackTrace(); sendMessage(NetConst.HANDLE_MESSAGE_FLAG_URL_ERROR, task); } catch (ParseException e) { e.printStackTrace(); sendMessage(NetConst.HANDLE_MESSAGE_FLAG_URL_ERROR, task); } catch (IOException e) { e.printStackTrace(); sendMessage(NetConst.HANDLE_MESSAGE_FLAG_NETWORK_ERROR, task); } } } }
Java
CL
f87e40e270f39b8d6b30a8126d15c90a8d7238c0c341b7da6670510d20be6ed8
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.io; import com.intellij.util.io.FileChannelInterruptsRetryer.FileChannelIdempotentOperation; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.file.OpenOption; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Class implements most of {@link FileChannel} operations so that each operation is either completed * successfully, or not started -- but operation (e.g. read or write) couldn't be partially applied. * Basically, it just reopens the underlying FileChannel, and repeats each operation on it until the * operation succeeds. Implementation mostly relies on already existing {@link FileChannelInterruptsRetryer} * machinery for that -- read {@link FileChannelInterruptsRetryer} description for implementation details * and discussions. * <p/> * This class could be seen as a counterpart for {@link FileChannelInterruptsRetryer} in following sense: * {@link FileChannelInterruptsRetryer} implements 'atomicity' (all-or-nothing) for logical unit of work * ({@link FileChannelIdempotentOperation}), while this class implements same 'atomicity' in relation to * elementary operations like read and write. * <p/> * All relative-positioned methods are guarded by 'this' lock -- this means that they are not concurrent * even if underlying FileChannel implementation and hardware allow parallel access. Use absolute * positioned methods if you're sure underlying impl support parallel access, and you want piggyback * on it. */ @ApiStatus.Internal public final class ResilientFileChannel extends FileChannel { private final FileChannelInterruptsRetryer fileChannelHandle; /** * Keep position for relative-positioned operations -- reopened FileChannel lose its position, * so better have our own. * Position access/modification is protected by 'this' lock. */ //@GuardedBy("this") private long position = 0; public ResilientFileChannel(final @NotNull Path path, final OpenOption @NotNull ... openOptions) throws IOException { Set<OpenOption> openOptionsSet; if (openOptions.length == 0) { openOptionsSet = Collections.emptySet(); } else { openOptionsSet = new HashSet<>(); Collections.addAll(openOptionsSet, openOptions); } fileChannelHandle = new FileChannelInterruptsRetryer(path, openOptionsSet); } public ResilientFileChannel(final @NotNull Path path, final Set<? extends @NotNull OpenOption> openOptions) throws IOException { fileChannelHandle = new FileChannelInterruptsRetryer(path, openOptions); } public <T> T executeOperation(final @NotNull FileChannelIdempotentOperation<T> operation) throws IOException { return fileChannelHandle.retryIfInterrupted(operation); } //FileChannelInterruptsRetryer requires idempotent operation -- so the operation could be repeated // multiple times without corrupting the data structure in the underlying file. // 1. Some operations are naturally idempotent (i.e. size) // 2. Absolute-position methods of FileChannel are also naturally idempotent // 3. All relative-position methods themselves are not idempotent -> to circumvent it, we keep .position // in a local field (i.e. it is _detached_ from underlying FileChannel.position), and call apt absolute // -positioned method instead @Override public long size() throws IOException { return fileChannelHandle.retryIfInterrupted(ch -> ch.size()); } @Override public FileChannel truncate(final long size) throws IOException { synchronized (this) { this.position = Math.min(position, size); } return fileChannelHandle.retryIfInterrupted(ch -> ch.truncate(size)); } @Override public void force(final boolean metaData) throws IOException { fileChannelHandle.retryIfInterrupted(ch -> { ch.force(metaData); return null; }); } //RC: Could buffer.position/limit be 'corrupted' if operation is interrupted? It seems they could: // i.e. it seems FileChannel operation interrupted in the middle could actually read all bytes // in the buffer, and update position, but throw exception on the exit path (and tests seem to // confirm such a behavior). This means we must store buffer.position before each .retryIfInterrupted() // call and restore it inside lambda. @Override public int read(final ByteBuffer target, final long offset) throws IOException { final int bufferPos = target.position(); return fileChannelHandle.retryIfInterrupted(ch -> { target.position(bufferPos); return ch.read(target, offset); }); } @Override public int write(final ByteBuffer source, final long offset) throws IOException { final int bufferPos = source.position(); return fileChannelHandle.retryIfInterrupted(ch -> { source.position(bufferPos); return ch.write(source, offset); }); } @Override public MappedByteBuffer map(final MapMode mapMode, final long mapRegionOffset, final long mapRegionSize) throws IOException { return fileChannelHandle.retryIfInterrupted(ch -> ch.map(mapMode, mapRegionOffset, mapRegionSize)); } @Override protected void implCloseChannel() throws IOException { fileChannelHandle.close(); } //================================================================================================== //Relative-position methods: themselves not idempotent, implemented via absolute-positioned // methods, keeping .position in a local field (i.e. it is _detached_ from underlying FileChannel.position) //Relative-positioned methods are all synchronized(this) -- file position modification must be guarded // by lock. //================================================================================================== @Override public synchronized FileChannel position(final long newPosition) throws IOException { this.position = newPosition; return this; } @Override public synchronized int read(final ByteBuffer target) throws IOException { final int bytesRead = read(target, position); position += Math.max(0, bytesRead); return bytesRead; } @Override public synchronized int write(final ByteBuffer src) throws IOException { final int bytesWritten = write(src, position); position += Math.max(0, bytesWritten); return bytesWritten; } @Override public synchronized long position() { return position; } //================================================================================================== //Some methods could be implemented, but are not used, so implementation efforts not pay off now, //================================================================================================== //MAYBE RC: replace @Deprecated annotation with something more explicitly stating '@DoNotCall'? /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public long read(ByteBuffer[] targets, int offset, int length) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public long transferTo(long position, long count, WritableByteChannel target) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public FileLock lock(long position, long size, boolean shared) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } /** @deprecated method is not implemented due to constructive laziness */ @Override @Deprecated @Contract("_, _, _ -> fail") public FileLock tryLock(long position, long size, boolean shared) throws IOException { throw new UnsupportedOperationException("Method not implemented yet: no use"); } }
Java
CL
915fcff3917eb2beb82d669e352133e21a0cf97aefc727cd7ac05e8f787078c6
package com.springboot.edgeserver.filters; import java.util.Comparator; import java.util.Optional; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import static org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME; /** * Filter for /admin/** to check if user is authenticated and has role ADMIN. */ @Slf4j @Component @AllArgsConstructor public class AdminResourcesFilter implements GatewayFilter { private final TokenStore tokenStore; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return exchange.getSession() .flatMap(session -> { log.debug("Trying to validate path: {}", exchange.getRequest().getPath()); log.debug("Trying first to get securityContext by session:size: {}", session.getAttributes().size()); return Mono.justOrEmpty((SecurityContext) session.getAttribute(DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME)); }) .switchIfEmpty(ReactiveSecurityContextHolder.getContext()) .switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not authenticated"))) .flatMap(s -> { Authentication authentication = s.getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { log.debug("User is not authenticated: {}", (authentication != null ? authentication.getName() : "")); String message = String.format("To access this resource(%s) user must be authenticated!", exchange.getRequest().getURI()); return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, message)); } else if (authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).anyMatch("ROLE_ADMIN"::equals)) { log.debug("User has admin role: {}", authentication.getAuthorities()); if (!exchange.getRequest().getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { Optional<OAuth2AccessToken> oAuth2AccessToken = tokenStore.findTokensByClientId(authentication.getName()) .stream() .filter(a -> !a.isExpired()) .max(Comparator.comparing(OAuth2AccessToken::getExpiration)); if (oAuth2AccessToken.isPresent()) { log.info("adminResourcesFilter:Set authorization header from redis session"); OAuth2AccessToken oAuth2AccessTokenValue = oAuth2AccessToken.get(); ServerHttpRequest builder = exchange.getRequest().mutate() .header("X-WEBAUTH-USER", "admin") .header(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", oAuth2AccessTokenValue.getValue())) .build(); return chain.filter(exchange.mutate().request(builder).build()); } } return chain.filter(exchange); } else { String message = String.format("User has not ROLE_ADMIN: %s", authentication.getName()); return Mono.error(new ResponseStatusException(HttpStatus.FORBIDDEN, message)); } }); } }
Java
CL
30eed46944a556a354a4969692f1be604b691d2d53424b75a460c0405133417e
package com.playtika.janusgraph.aerospike.operations; import com.playtika.janusgraph.aerospike.transaction.TransactionalOperations; import com.playtika.janusgraph.aerospike.transaction.WriteAheadLogCompleter; public interface Operations { AerospikeOperations getAerospikeOperations(); TransactionalOperations getTransactionalOperations(); WriteAheadLogCompleter getWriteAheadLogCompleter(); ReadOperations getReadOperations(); ScanOperations getScanOperations(); void close(); }
Java
CL
2e9035f46caa6b8d0e9a7d76b168b92d7c13b25b2d381dd73988cf6918bef193
import java.util.ArrayList; /** * Class to represent Naive Bayes * * @author Prakhar * @date 11/22/2013 * @hw 3 */ public class NaiveBayes extends Learner { NaiveBayes(DataSet trainSet) { super(trainSet); } /** * Method to print the model parameters. */ void printBasicModelParams() { int i = 0; if(Utility.IS_VERBOSE) { for(ArrayList<Integer[]> featureArray : mBasicModelParams) { System.out.println("Feature[" + i++ + "]\n-----------------"); int j = 0; for(Integer[] values : featureArray) System.out.println("FeatureValue[" + j++ + "] = " + values[0] + " | " + values[1]); System.out.println(); } } i = 0; for(; i < mNumSoleFeatures; i++) System.out.println(mFeatures.get(i).getName() + " class"); System.out.println(); } /** * Method to test the accuracy of the model generated. * * @param testSet Test data set * @return Accuracy of the generated model over the given test set. */ public double testNaiveBayesModel(DataSet testSet, boolean prob1) { int correctPredictionCount = 0; ArrayList<String> classValues = mTrainSet.getOutputFeature().getValues(); // Run through the examples now. for(Example e : testSet) { Double numerator = (double)(mOutputValueCount[0] + 1);//(mExamplesWithFIRSTLabelCount + 1); Double denominator = (double)(mOutputValueCount[1] + 1); //(mExamplesWithSECONDLabelCount + 1); for(int i = 0; i < mNumSoleFeatures; i++) { String featureValueInExample = e.get(i); DiscreteFeature f = (DiscreteFeature) mFeatures.get(i); int featureValueIndex = f.valueIndexMap.get(featureValueInExample); // Locate the feature value ArrayList<Integer[]> featureArray = mBasicModelParams.get(i); int numFeatureValues = f.getNumValues(); // Number of values for current feature, used for ensuring Laplace Estimates. numerator *= ((double)(featureArray.get(featureValueIndex)[0] + 1)/(mOutputValueCount[0] + numFeatureValues)); //(mExamplesWithFIRSTLabelCount + numFeatureValues)); denominator *= ((double)(featureArray.get(featureValueIndex)[1] + 1)/(mOutputValueCount[1] + numFeatureValues)); } // Predict the label of this test set example String predictedLabel = ""; double posteriorProb = 0.0; if(numerator.compareTo(denominator) > 0) // Predicted Label = FirstLabel { predictedLabel = classValues.get(0); posteriorProb = numerator / (numerator + denominator); } else { predictedLabel = classValues.get(1); posteriorProb = denominator / (numerator + denominator); } String actualLabel = e.get(mNumFeatures - 1); if(Utility.IS_VERBOSE) System.out.println("e[" + e.getName() + "] :\t" + predictedLabel + " " + actualLabel); else if (prob1) System.out.println(predictedLabel + " " + actualLabel + " " + posteriorProb); if(predictedLabel.equals(actualLabel)) correctPredictionCount++; } if(Utility.IS_VERBOSE) System.out.println("\nNumber of Correct Predictions = " + correctPredictionCount); else if (prob1) System.out.println("\n" + correctPredictionCount); return ((double)correctPredictionCount * 100/testSet.size()); } }
Java
CL
99fe008c5bd0400844b06e68c2d0e7bf04f4076560fad3b7e9c017f3a8118953
package com.dropbox.core.v2.sharing; import com.dropbox.core.stone.CompositeSerializer; import com.dropbox.core.stone.StoneSerializer; import com.dropbox.core.stone.StoneSerializers; import com.dropbox.core.stone.UnionSerializer; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import in.sinew.enpass.IRemoteStorage; import java.io.IOException; import java.util.Arrays; import java.util.regex.Pattern; import net.sqlcipher.database.SQLiteDatabase; public final class AddMemberSelectorError { public static final AddMemberSelectorError AUTOMATIC_GROUP = new AddMemberSelectorError(Tag.AUTOMATIC_GROUP, null, null, null); public static final AddMemberSelectorError GROUP_DELETED = new AddMemberSelectorError(Tag.GROUP_DELETED, null, null, null); public static final AddMemberSelectorError GROUP_NOT_ON_TEAM = new AddMemberSelectorError(Tag.GROUP_NOT_ON_TEAM, null, null, null); public static final AddMemberSelectorError OTHER = new AddMemberSelectorError(Tag.OTHER, null, null, null); private final Tag _tag; private final String invalidDropboxIdValue; private final String invalidEmailValue; private final String unverifiedDropboxIdValue; static /* synthetic */ class AnonymousClass1 { static final /* synthetic */ int[] $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag = new int[Tag.values().length]; static { try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.AUTOMATIC_GROUP.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.INVALID_DROPBOX_ID.ordinal()] = 2; } catch (NoSuchFieldError e2) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.INVALID_EMAIL.ordinal()] = 3; } catch (NoSuchFieldError e3) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.UNVERIFIED_DROPBOX_ID.ordinal()] = 4; } catch (NoSuchFieldError e4) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.GROUP_DELETED.ordinal()] = 5; } catch (NoSuchFieldError e5) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.GROUP_NOT_ON_TEAM.ordinal()] = 6; } catch (NoSuchFieldError e6) { } try { $SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[Tag.OTHER.ordinal()] = 7; } catch (NoSuchFieldError e7) { } } } static class Serializer extends UnionSerializer<AddMemberSelectorError> { public static final Serializer INSTANCE = new Serializer(); Serializer() { } public void serialize(AddMemberSelectorError value, JsonGenerator g) throws IOException, JsonGenerationException { switch (AnonymousClass1.$SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[value.tag().ordinal()]) { case SQLiteDatabase.OPEN_READONLY /*1*/: g.writeString("automatic_group"); return; case SQLiteDatabase.CONFLICT_ABORT /*2*/: g.writeStartObject(); writeTag("invalid_dropbox_id", g); g.writeFieldName("invalid_dropbox_id"); StoneSerializers.string().serialize(value.invalidDropboxIdValue, g); g.writeEndObject(); return; case SQLiteDatabase.CONFLICT_FAIL /*3*/: g.writeStartObject(); writeTag("invalid_email", g); g.writeFieldName("invalid_email"); StoneSerializers.string().serialize(value.invalidEmailValue, g); g.writeEndObject(); return; case SQLiteDatabase.CONFLICT_IGNORE /*4*/: g.writeStartObject(); writeTag("unverified_dropbox_id", g); g.writeFieldName("unverified_dropbox_id"); StoneSerializers.string().serialize(value.unverifiedDropboxIdValue, g); g.writeEndObject(); return; case SQLiteDatabase.CONFLICT_REPLACE /*5*/: g.writeString("group_deleted"); return; case IRemoteStorage.BOX_REMOTE /*6*/: g.writeString("group_not_on_team"); return; default: g.writeString("other"); return; } } public AddMemberSelectorError deserialize(JsonParser p) throws IOException, JsonParseException { boolean collapsed; String tag; if (p.getCurrentToken() == JsonToken.VALUE_STRING) { collapsed = true; tag = StoneSerializer.getStringValue(p); p.nextToken(); } else { collapsed = false; StoneSerializer.expectStartObject(p); tag = CompositeSerializer.readTag(p); } if (tag == null) { throw new JsonParseException(p, "Required field missing: .tag"); } AddMemberSelectorError value; if ("automatic_group".equals(tag)) { value = AddMemberSelectorError.AUTOMATIC_GROUP; } else if ("invalid_dropbox_id".equals(tag)) { StoneSerializer.expectField("invalid_dropbox_id", p); value = AddMemberSelectorError.invalidDropboxId((String) StoneSerializers.string().deserialize(p)); } else if ("invalid_email".equals(tag)) { StoneSerializer.expectField("invalid_email", p); value = AddMemberSelectorError.invalidEmail((String) StoneSerializers.string().deserialize(p)); } else if ("unverified_dropbox_id".equals(tag)) { StoneSerializer.expectField("unverified_dropbox_id", p); value = AddMemberSelectorError.unverifiedDropboxId((String) StoneSerializers.string().deserialize(p)); } else if ("group_deleted".equals(tag)) { value = AddMemberSelectorError.GROUP_DELETED; } else if ("group_not_on_team".equals(tag)) { value = AddMemberSelectorError.GROUP_NOT_ON_TEAM; } else { value = AddMemberSelectorError.OTHER; } if (!collapsed) { StoneSerializer.skipFields(p); StoneSerializer.expectEndObject(p); } return value; } } public enum Tag { AUTOMATIC_GROUP, INVALID_DROPBOX_ID, INVALID_EMAIL, UNVERIFIED_DROPBOX_ID, GROUP_DELETED, GROUP_NOT_ON_TEAM, OTHER } private AddMemberSelectorError(Tag _tag, String invalidDropboxIdValue, String invalidEmailValue, String unverifiedDropboxIdValue) { this._tag = _tag; this.invalidDropboxIdValue = invalidDropboxIdValue; this.invalidEmailValue = invalidEmailValue; this.unverifiedDropboxIdValue = unverifiedDropboxIdValue; } public Tag tag() { return this._tag; } public boolean isAutomaticGroup() { return this._tag == Tag.AUTOMATIC_GROUP; } public boolean isInvalidDropboxId() { return this._tag == Tag.INVALID_DROPBOX_ID; } public static AddMemberSelectorError invalidDropboxId(String value) { if (value == null) { throw new IllegalArgumentException("Value is null"); } else if (value.length() >= 1) { return new AddMemberSelectorError(Tag.INVALID_DROPBOX_ID, value, null, null); } else { throw new IllegalArgumentException("String is shorter than 1"); } } public String getInvalidDropboxIdValue() { if (this._tag == Tag.INVALID_DROPBOX_ID) { return this.invalidDropboxIdValue; } throw new IllegalStateException("Invalid tag: required Tag.INVALID_DROPBOX_ID, but was Tag." + this._tag.name()); } public boolean isInvalidEmail() { return this._tag == Tag.INVALID_EMAIL; } public static AddMemberSelectorError invalidEmail(String value) { if (value == null) { throw new IllegalArgumentException("Value is null"); } else if (value.length() > 255) { throw new IllegalArgumentException("String is longer than 255"); } else if (Pattern.matches("^['&A-Za-z0-9._%+-]+@[A-Za-z0-9-][A-Za-z0-9.-]*.[A-Za-z]{2,15}$", value)) { return new AddMemberSelectorError(Tag.INVALID_EMAIL, null, value, null); } else { throw new IllegalArgumentException("String does not match pattern"); } } public String getInvalidEmailValue() { if (this._tag == Tag.INVALID_EMAIL) { return this.invalidEmailValue; } throw new IllegalStateException("Invalid tag: required Tag.INVALID_EMAIL, but was Tag." + this._tag.name()); } public boolean isUnverifiedDropboxId() { return this._tag == Tag.UNVERIFIED_DROPBOX_ID; } public static AddMemberSelectorError unverifiedDropboxId(String value) { if (value == null) { throw new IllegalArgumentException("Value is null"); } else if (value.length() >= 1) { return new AddMemberSelectorError(Tag.UNVERIFIED_DROPBOX_ID, null, null, value); } else { throw new IllegalArgumentException("String is shorter than 1"); } } public String getUnverifiedDropboxIdValue() { if (this._tag == Tag.UNVERIFIED_DROPBOX_ID) { return this.unverifiedDropboxIdValue; } throw new IllegalStateException("Invalid tag: required Tag.UNVERIFIED_DROPBOX_ID, but was Tag." + this._tag.name()); } public boolean isGroupDeleted() { return this._tag == Tag.GROUP_DELETED; } public boolean isGroupNotOnTeam() { return this._tag == Tag.GROUP_NOT_ON_TEAM; } public boolean isOther() { return this._tag == Tag.OTHER; } public int hashCode() { return Arrays.hashCode(new Object[]{this._tag, this.invalidDropboxIdValue, this.invalidEmailValue, this.unverifiedDropboxIdValue}); } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AddMemberSelectorError)) { return false; } AddMemberSelectorError other = (AddMemberSelectorError) obj; if (this._tag != other._tag) { return false; } switch (AnonymousClass1.$SwitchMap$com$dropbox$core$v2$sharing$AddMemberSelectorError$Tag[this._tag.ordinal()]) { case SQLiteDatabase.OPEN_READONLY /*1*/: return true; case SQLiteDatabase.CONFLICT_ABORT /*2*/: if (this.invalidDropboxIdValue == other.invalidDropboxIdValue || this.invalidDropboxIdValue.equals(other.invalidDropboxIdValue)) { return true; } return false; case SQLiteDatabase.CONFLICT_FAIL /*3*/: if (this.invalidEmailValue == other.invalidEmailValue || this.invalidEmailValue.equals(other.invalidEmailValue)) { return true; } return false; case SQLiteDatabase.CONFLICT_IGNORE /*4*/: if (this.unverifiedDropboxIdValue == other.unverifiedDropboxIdValue || this.unverifiedDropboxIdValue.equals(other.unverifiedDropboxIdValue)) { return true; } return false; case SQLiteDatabase.CONFLICT_REPLACE /*5*/: return true; case IRemoteStorage.BOX_REMOTE /*6*/: return true; case IRemoteStorage.PIN /*7*/: return true; default: return false; } } public String toString() { return Serializer.INSTANCE.serialize((Object) this, false); } public String toStringMultiline() { return Serializer.INSTANCE.serialize((Object) this, true); } }
Java
CL
2f8c0a0deb1f190a48db7e22cefd94151110f25927accde90a137ae3a6871271
package com.beer.game.vainner.dao; import com.beer.common.utility.BaseHibernateDAO; import com.beer.game.vainner.model.GameProducerRecord; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Example; import org.springframework.stereotype.Component; @Component("gameProducerRecordDAO") public class GameProducerRecordDAO extends BaseHibernateDAO { private static final Logger log = Logger .getLogger(GameProducerRecordDAO.class); // property constants public static final String THIS_TIME_BUY = "thisTimeBuy"; public static final String ALL_NEED = "allNeed"; public static final String ACTUAL_SALE = "actualSale"; public static final String ALL_OWE = "allOwe"; public static final String DELAY_COST = "delayCost"; public static final String BEGIN_GOODS = "beginGoods"; public static final String RECEIVE_GOODS = "receiveGoods"; public static final String END_GOODS = "endGoods"; public static final String STORAGE_COST = "storageCost"; public static final String ORDER_GOODS = "orderGoods"; public static final String THIS_TIME_PROFIT = "thisTimeProfit"; public static final String GAME_ID = "gameId"; public static final String TIMES = "times"; public static final String USER_ID = "userId"; public void save(GameProducerRecord transientInstance) { log.debug("saving GameProducerRecord instance"); Session session = this.getSession(); try { session.save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(GameProducerRecord persistentInstance) { log.debug("deleting GameProducerRecord instance"); Session session = this.getSession(); try { session.beginTransaction(); session.delete(persistentInstance); session.getTransaction().commit(); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public GameProducerRecord findById(java.lang.Integer id) { log.debug("getting GameProducerRecord instance with id: " + id); try { GameProducerRecord instance = (GameProducerRecord) getSession() .get("com.vainner.game1.GameProducerRecord", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List<?> findByExample(GameProducerRecord instance) { log.debug("finding GameProducerRecord instance by example"); try { List<?> results = getSession() .createCriteria("com.vainner.game1.GameProducerRecord") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List<?> findByProperty(String propertyName, Object value) { log.debug("finding GameProducerRecord instance with property: " + propertyName + ", value: " + value); try { String queryString = "from GameProducerRecord as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List<?> findByThisTimeBuy(Object thisTimeBuy) { return findByProperty(THIS_TIME_BUY, thisTimeBuy); } public List<?> findByAllNeed(Object allNeed) { return findByProperty(ALL_NEED, allNeed); } public List<?> findByActualSale(Object actualSale) { return findByProperty(ACTUAL_SALE, actualSale); } public List<?> findByAllOwe(Object allOwe) { return findByProperty(ALL_OWE, allOwe); } public List<?> findByDelayCost(Object delayCost) { return findByProperty(DELAY_COST, delayCost); } public List<?> findByBeginGoods(Object beginGoods) { return findByProperty(BEGIN_GOODS, beginGoods); } public List<?> findByReceiveGoods(Object receiveGoods) { return findByProperty(RECEIVE_GOODS, receiveGoods); } public List<?> findByEndGoods(Object endGoods) { return findByProperty(END_GOODS, endGoods); } public List<?> findByStorageCost(Object storageCost) { return findByProperty(STORAGE_COST, storageCost); } public List<?> findByOrderGoods(Object orderGoods) { return findByProperty(ORDER_GOODS, orderGoods); } public List<?> findByThisTimeProfit(Object thisTimeProfit) { return findByProperty(THIS_TIME_PROFIT, thisTimeProfit); } public List<?> findByGameId(Object gameId) { return findByProperty(GAME_ID, gameId); } public List<?> findByTimes(Object times) { return findByProperty(TIMES, times); } public List<?> findByUserId(Object userId) { return findByProperty(USER_ID, userId); } public List<?> findAll() { log.debug("finding all GameProducerRecord instances"); try { String queryString = "from GameProducerRecord"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public GameProducerRecord merge(GameProducerRecord detachedInstance) { log.debug("merging GameProducerRecord instance"); try { GameProducerRecord result = (GameProducerRecord) getSession() .merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(GameProducerRecord instance) { log.debug("attaching dirty GameProducerRecord instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }
Java
CL
7dd1b7224837fbaa255fe632bff97f22a840fbcfa2a6c8d3fc2e17c1aaebacf1
package org.editorconfig.settings; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CustomCodeStyleSettings; import com.intellij.util.messages.Topic; /** * @author Dennis.Ushakov */ public class EditorConfigSettings extends CustomCodeStyleSettings { public static final Topic<EditorConfigListener> EDITOR_CONFIG_ENABLED_TOPIC = Topic.create("editor config changed", EditorConfigListener.class, Topic.BroadcastDirection.TO_CHILDREN); public boolean ENABLED = true; protected EditorConfigSettings(CodeStyleSettings container) { super("editorconfig", container); } }
Java
CL
78ed468e0c7ad96a7dadf93431dabc4a6cdd521c4f9116d475637b1213864ae3
package com.elm.shypr.service; import com.elm.shypr.domain.ShippingRate; import com.elm.shypr.domain.enumeration.DeliveryLocation; import com.elm.shypr.dto.ParcelDetailsDto; import com.elm.shypr.dto.ShippingRateDto; import com.elm.shypr.repository.ShippingRateRepository; import net.sf.jasperreports.engine.*; import org.modelmapper.ModelMapper; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.io.InputStream; import java.text.ParseException; import java.util.HashMap; import java.util.Set; import java.util.stream.Collectors; @Service @Transactional public class ShippingRateService { private ModelMapper modelMapper = new ModelMapper(); private ShippingRateRepository shippingRateRepository; public ShippingRateService(ShippingRateRepository shippingRateRepository) { this.shippingRateRepository = shippingRateRepository; } public Set<ShippingRateDto> getShippingRatesByCriteria(ParcelDetailsDto parcelDetailsDto) { DeliveryLocation deliveryLocation = DeliveryLocation.OUTSIDE_CITY; if(parcelDetailsDto.getFromCityId().equals(parcelDetailsDto.getToCityId())) { deliveryLocation = DeliveryLocation.INSIDE_CITY; } Set<ShippingRate> shippingRates = shippingRateRepository.getShippingRatesByCriteria(deliveryLocation, parcelDetailsDto.getWeightCategory(), parcelDetailsDto.getCashOnDelivery() ); Set<ShippingRateDto> result = shippingRates.stream().map(e -> modelMapper.map(e, ShippingRateDto.class)).collect(Collectors.toSet()); return result; } public ResponseEntity<byte[]> generateBarcode(String awbNumber) throws JRException, ParseException { InputStream template = getClass().getResourceAsStream("/templates/reports/airWaybillbarcode.jrxml"); JasperReport report = JasperCompileManager.compileReport(template); HashMap<String, Object> map = new HashMap<>(); map.put("barcode", "123-11111111"); map.put("MasterAWBBarcode", "123-11111111"); map.put("number", "pkg Numer"); map.put("ImagesDir", this.getClass().getResource("/templates/reports/images/").toString()); map.put("destnation", "dest"); map.put("AirportName", "airport"); map.put("Origin", "origin"); map.put("IssuedBy", "issuedby"); map.put("Packages", "noOfpkgs"); map.put("Total", "total"); map.put("Weight", 5.0); map.put("PkgWeight", 0.0); map.put("Chargeable", 2.0); map.put("Description", "desc"); map.put("Dimension", "dimen"); map.put("Note", "note"); map.put("From", "from"); map.put("TO","to"); JasperPrint jasperPrint = JasperFillManager.fillReport(report, map, new JREmptyDataSource()); HttpHeaders headers = new HttpHeaders(); headers.add("content-disposition", "attachment; filename=" + "ShipmentBarcode.pdf"); return new ResponseEntity<byte[]> (JasperExportManager.exportReportToPdf(jasperPrint), headers, HttpStatus.OK); // return ResponseEntity.ok().headers(headers).body(JasperExportManager.exportReportToPdf(jasperPrint)); } }
Java
CL
57075d22fd20dc5f72b3ffa17e9d865d5c9d14237e923d5c7cebddaa22edf81a
package com.tencent.mm.plugin.appbrand.ipc; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.Parcel; import com.tencent.mm.sdk.platformtools.aa; import com.tencent.mm.sdk.platformtools.v; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class AppBrandMainProcessService extends Service { private static c dEf; private static ServiceConnection dEg; private static Map<String, WeakReference<MainProcessTask>> dEj = new ConcurrentHashMap(); private static Handler dEk = new Handler() { public final void handleMessage(Message message) { MainProcessTask b = AppBrandMainProcessService.a(message.getData(), false); MainProcessTask Rf = AppBrandMainProcessService.Rf(b.lpS); if (Rf == null) { v.e("MicroMsg.AppBrandMainProcessService", "receive client msg, get null task by id %s", new Object[]{b.lpS}); return; } AppBrandMainProcessService.a(b, Rf); Rf.OM(); } }; private static Messenger dEl = new Messenger(dEk); private static final LinkedList<Parcel> dWI = new LinkedList(); private static Set<a> hvQ = new HashSet(); private final Messenger dEd = new Messenger(this.mHandler); private final com.tencent.mm.plugin.appbrand.ipc.c.a dEe = new com.tencent.mm.plugin.appbrand.ipc.c.a(this) { final /* synthetic */ AppBrandMainProcessService dEm; { this.dEm = r1; } public final void p(Bundle bundle) { Message obtain = Message.obtain(); obtain.setData(bundle); this.dEm.dEd.send(obtain); } public final void q(Bundle bundle) { AppBrandMainProcessService.a(bundle, false).OL(); } }; private final Handler mHandler = new Handler(this, com.tencent.mm.plugin.appbrand.k.a.vA().htb.getLooper()) { final /* synthetic */ AppBrandMainProcessService dEm; public final void handleMessage(Message message) { AppBrandMainProcessService.a(message.getData(), true).OL(); } }; public static class a { public void onServiceConnected() { } public void Rh() { } } static /* synthetic */ void Iq() { for (a onServiceConnected : hvQ) { onServiceConnected.onServiceConnected(); } } static /* synthetic */ void PI() { if (dEf != null) { synchronized (dWI) { Iterator it = dWI.iterator(); while (it.hasNext()) { Parcel parcel = (Parcel) it.next(); Bundle bundle = new Bundle(); bundle.setClassLoader(MainProcessTask.class.getClassLoader()); parcel.setDataPosition(0); bundle.readFromParcel(parcel); o(bundle); parcel.recycle(); } dWI.clear(); } } } static /* synthetic */ void QA() { for (a Rh : hvQ) { Rh.Rh(); } } static /* synthetic */ MainProcessTask Rf(String str) { if (dEj.containsKey(str)) { return ((WeakReference) dEj.get(str)).get() == null ? null : (MainProcessTask) ((WeakReference) dEj.get(str)).get(); } else { return null; } } public IBinder onBind(Intent intent) { return this.dEe; } public static void a(MainProcessTask mainProcessTask) { dEj.put(mainProcessTask.lpS, new WeakReference(mainProcessTask)); o(a(mainProcessTask, true)); } public static boolean b(MainProcessTask mainProcessTask) { Bundle a = a(mainProcessTask, false); if (!n(a)) { return false; } a(a(a, false), mainProcessTask); mainProcessTask.OM(); return true; } private static boolean n(Bundle bundle) { try { dEf.q(bundle); return true; } catch (Exception e) { v.e("MicroMsg.AppBrandMainProcessService", e.getMessage()); return false; } } private static void o(Bundle bundle) { if (dEf == null) { PH(); synchronized (dWI) { LinkedList linkedList = dWI; Parcel obtain = Parcel.obtain(); bundle.writeToParcel(obtain, 0); linkedList.add(obtain); } return; } try { dEf.p(bundle); } catch (Exception e) { v.e("MicroMsg.AppBrandMainProcessService", e.getMessage()); } } private static void PH() { if (dEg == null) { dEg = new ServiceConnection() { public final void onServiceConnected(ComponentName componentName, IBinder iBinder) { AppBrandMainProcessService.dEf = com.tencent.mm.plugin.appbrand.ipc.c.a.F(iBinder); AppBrandMainProcessService.PI(); AppBrandMainProcessService.Iq(); v.i("MicroMsg.AppBrandMainProcessService", "onServiceConnected(%s)", new Object[]{aa.getProcessName()}); } public final void onServiceDisconnected(ComponentName componentName) { AppBrandMainProcessService.dEf = null; AppBrandMainProcessService.QA(); AppBrandMainProcessService.PH(); v.i("MicroMsg.AppBrandMainProcessService", "onServiceDisconnected(%s)", new Object[]{aa.getProcessName()}); } }; } v.i("MicroMsg.AppBrandMainProcessService", "tryBindService"); Context context = aa.getContext(); context.bindService(new Intent(context, AppBrandMainProcessService.class), dEg, 1); } public static void a(a aVar) { hvQ.add(aVar); } public static void b(a aVar) { hvQ.remove(aVar); } private static void a(MainProcessTask mainProcessTask, MainProcessTask mainProcessTask2) { Parcel obtain = Parcel.obtain(); mainProcessTask.writeToParcel(obtain, 0); obtain.setDataPosition(0); mainProcessTask2.f(obtain); obtain.recycle(); } static Bundle a(MainProcessTask mainProcessTask, boolean z) { Bundle bundle = new Bundle(3); bundle.putParcelable("task_object", mainProcessTask); if (z) { bundle.putParcelable("task_client", dEl); } bundle.putString("task_id", mainProcessTask.lpS); return bundle; } private static MainProcessTask a(Bundle bundle, boolean z) { bundle.setClassLoader(MainProcessTask.class.getClassLoader()); MainProcessTask mainProcessTask = (MainProcessTask) bundle.getParcelable("task_object"); if (z) { mainProcessTask.dEH = (Messenger) bundle.getParcelable("task_client"); } mainProcessTask.lpS = bundle.getString("task_id"); return mainProcessTask; } }
Java
CL
910bfec8baf1a76e4ff66cfaeaf835470dfab9e3731d30101b74c9478cdbd55f
package ir.atsignsina.bookshelf.app.category; import com.fasterxml.jackson.annotation.JsonIgnore; import ir.atsignsina.bookshelf.app.book.Book; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Set; @Entity @NoArgsConstructor @Getter @Setter public class Category { @Id @GeneratedValue private Long id; private String name; @JsonIgnore @ManyToOne private Category parent; @JsonIgnore @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<Category> children; @JsonIgnore @ManyToMany @JoinTable( name = "BOOK_CATEGORIES", joinColumns = {@JoinColumn(name = "CATEGORIES_ID")}, inverseJoinColumns = {@JoinColumn(name = "BOOK_ID")}) Set<Book> books; }
Java
CL
05421f94a21fc6a6cf0b34c06751cbbd3eef3a72eac7b40b41d94728deea0dd8
/******************************************************************************* * @author Reika Kalseki * * Copyright 2015 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.DragonAPI.Instantiable.IO; import java.util.Collection; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import Reika.DragonAPI.IO.ReikaXMLBase; import Reika.DragonAPI.Instantiable.Data.Maps.MultiMap; public class XMLInterface { private Document doc; private final Class rootClass; private final String filepath; private final boolean requireFile; private final HashMap<String, String> data = new HashMap(); private final MultiMap<String, String> tree = new MultiMap(); public static final String NULL_VALUE = "#NULL!"; public XMLInterface(Class root, String path) { this(root, path, false); } public XMLInterface(Class root, String path, boolean crashIfNull) { rootClass = root; filepath = path; requireFile = crashIfNull; try { doc = ReikaXMLBase.getXMLDocument(root, path); } catch (RuntimeException e) { if (requireFile) throw new RuntimeException(e); } this.readFileToMap(); } public void reread() { try { doc = ReikaXMLBase.getXMLDocument(rootClass, filepath); this.readFileToMap(); } catch (RuntimeException e) { if (requireFile) throw new RuntimeException(e); } } private void readFileToMap() { this.recursiveRead("$TOP$", doc); } private void recursiveRead(String parent, Node n) { if (n == null) return; NodeList li = n.getChildNodes(); int len = li.getLength(); for (int i = 0; i < len; i++) { Node ch = li.item(i); String key = ReikaXMLBase.getNodeNameTree(ch); tree.addValue(parent, key); if (ch.getNodeType() == Node.ELEMENT_NODE) { //ReikaJavaLibrary.pConsole(ch.getNodeName()); this.recursiveRead(key, ch); } else if (ch.getNodeType() == Node.TEXT_NODE) { String val = ch.getNodeValue(); if (val != null) { if (val.equals("\n")) val = null; else { if (val.startsWith("\n")) val = val.substring(1); if (val.endsWith("\n")) val = val.substring(0, val.length()-1); } if (val != null && val.equals("\n")) val = null; } if (val != null) { val = val.replace("\t", ""); //ReikaJavaLibrary.pConsole("TREE: "+ReikaXMLBase.getNodeNameTree(ch)); if (data.containsKey(key)) ;//throw new RuntimeException("Your input XML has multiple node trees with the EXACT same names! Resolve this!"); data.put(key, val); } } } } public String getValueAtNode(String name) { String dat = data.get(name); if (dat == null) dat = NULL_VALUE; return dat; } public boolean nodeExists(String name) { return data.containsKey(name); } /** Only returns "tree" nodes, not text ones. */ public Collection<String> getNodesWithin(String name) { return name == null ? this.getTopNodes() : tree.get(name); } public Collection<String> getTopNodes() { return tree.get("$TOP$"); } @Override public String toString() { return data.toString(); } }
Java
CL
22a3eacfc0856f87bfbafbb159436efd948cfa8b50ca03bf092e4bf4c2a23af3
/** * Copyright (c) 2014 SAP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the SAP nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SAP BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sopeco.service.execute; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sopeco.config.Configuration; import org.sopeco.config.IConfiguration; import org.sopeco.engine.status.ErrorInfo; import org.sopeco.engine.status.EventType; import org.sopeco.engine.status.IStatusListener; import org.sopeco.engine.status.ProgressInfo; import org.sopeco.engine.status.StatusBroker; import org.sopeco.engine.status.StatusMessage; import org.sopeco.runner.SoPeCoRunner; import org.sopeco.service.persistence.ServicePersistenceProvider; import org.sopeco.service.persistence.entities.ExecutedExperimentDetails; import org.sopeco.service.persistence.entities.MECLog; import org.sopeco.service.persistence.entities.ScheduledExperiment; import org.sopeco.service.rest.exchange.ExperimentStatus; /** * @author Marius Oehler * @author Peter Merkert */ public class ExecutionQueue implements IStatusListener { private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionQueue.class); /** * Handles all the thread of SoPeCo Runner executions. */ private ExecutorService threadPool; /** * Queue of waiting experiments. */ private List<QueuedExperiment> experimentQueue; /** * The experiment which is performed at the moment. */ private QueuedExperiment runningExperiment; /** * If this object is not <code>null</code>, then an experiment is running. */ private Future<?> executeStatus; /** * The URL for this execution queue. All experiment run on the controller connected to this URL. */ private String controllerURL; /** * Stores the current hashcode of the running experiment (actually the {@link ScheduledExperiment} hashcode). * This hashcode enables to have a unique identifier for the {@link Configuration}. * * This hashcode is always refreshed with the current hashcode of the running {@link QueuedExperiment} and * it's {@link ScheduledExperiment} hashcode. */ private String experimentHashCode; /** * Constructor creates a new empty {@link QueuedExperiment} list. * Stores the given controller URL. <br /> * Adds itself to the {@link StatusManager} to receive updates about * the running experiments.<br /> * Initializes the threadpool via initThreadPool(). * * @param controllerURL the URL to the controller this queue correpsonds to */ public ExecutionQueue(String controllerURL) { this.experimentQueue = new ArrayList<QueuedExperiment>(); this.controllerURL = controllerURL; // register to the StatusManager and recevie updates from SoPeCo about this controller StatusBroker.getManager(controllerURL).addStatusListener(this); initThreadPool(); } /** * Returns whether the active experiment is executed by a thread. * * @return true, if this queue has currently an experiment running */ public boolean isExecuting() { if (executeStatus != null) { synchronized (executeStatus) { if (executeStatus.isDone() || executeStatus.isCancelled()) { return false; } return true; } } return false; } /** * Returns the {@link ExperimentStatus} of the {@link QueuedExperiment} with the * given experiment key. * * @param experimentKey the unique key to the experiment, which is returned when adding * it to the {@link ExecutionScheduler}. * @return the {@link ExperimentStatus} of the {@link QueuedExperiment} */ public ExperimentStatus getExperimentStatus(long experimentKey) { QueuedExperiment experiment = null; LOGGER.info("In this queue (URL = " + this.controllerURL + "), the current running experiment hashcode is: " + experimentHashCode + "."); if (experimentHashCode.equals(String.valueOf(experimentKey))) { // the current running experiment is requested experiment = runningExperiment; } else { // check if another experiment in the queue was requested for (QueuedExperiment exp : experimentQueue) { if (String.valueOf(exp.getScheduledExperiment().getExperimentKey()).equals(experimentKey)) { experiment = exp; // found the searched experiment break; } } } if (experiment != null) { return createExperimentStatusPackage(experiment); } return null; } /** * Adds an experiment to this {@link ExecutionQueue}. If no experiment is executed * yet, a new one will be executed. * * @param experiment the {@link QueuedExperiment} to add to the queue. */ public void addExperiment(QueuedExperiment experiment) { LOGGER.info("Adding experiment id:" + experiment.getScheduledExperiment().getId() + " to queue."); experiment.setTimeQueued(System.currentTimeMillis()); experimentQueue.add(experiment); checkToExecuteNext(); } /** * Abots the current experiment in execution. */ public void abortExperiment(long experimentKey) { if (isExecuting()) { Configuration.getSessionSingleton(String.valueOf(experimentKey)) .setProperty(IConfiguration.EXPERIMENT_RUN_ABORT, new Boolean(true)); } } /** * Checks if the controller is ready and a experiment is waiting in the * queue. If so, the next experiment is started. */ private void checkToExecuteNext() { synchronized (experimentQueue) { LOGGER.debug("Checking the current execution of the ExecutionQueue corresponding to Controller URL '{}'", controllerURL); if (isExecuting()) { LOGGER.info("Experiment is currently already running."); } else if (isLoaded()) { LOGGER.info("Experiment is already loaded, but it is not running yet."); } else if (experimentQueue.isEmpty()) { LOGGER.info("Queue is empty. There is no experiment in execution."); } else { // now the queue is not empty and it the next experimetn can be executed runningExperiment = experimentQueue.get(0); experimentQueue.remove(0); execute(runningExperiment); } } } /** * Adds the given {@link StatusMessage} to the currently running experiment. * If this queue has no active experiment, then the message is discarded. * * @param statusMessage the message which should be added to the experiment */ public void addStatusMessageToExperiment(StatusMessage statusMessage) { if (runningExperiment == null) { return; } runningExperiment.getStatusMessageList().add(statusMessage); if (statusMessage.getStatusInfo() != null && statusMessage.getStatusInfo() instanceof ProgressInfo) { runningExperiment.setLastProgressInfo((ProgressInfo) statusMessage.getStatusInfo()); } storeMECLog(runningExperiment); } /** * Checks for failed adding of {@link EventType.MEASUREMENT_FINISHED}. Fires this * event manually with a {@link StatusMessage}. */ public void check() { if (!isExecuting() && runningExperiment != null) { LOGGER.debug("Thread finished but experiment was not completed. Adding MEASUREMENT_FINISHED event."); StatusMessage sm = new StatusMessage(); sm.setEventType(EventType.MEASUREMENT_FINISHED); onNewStatus(sm); } } /** * The method for the {@link IStatusListener} which is called by the {@link StatusManager} * to fire status messages for the executed controllers. * * @param statusMessage the status message to proceed */ @Override public void onNewStatus(StatusMessage statusMessage) { LOGGER.info("New Status on '" + this.controllerURL + "': " + statusMessage.getEventType()); addStatusMessageToExperiment(statusMessage); if (statusMessage.getEventType() == EventType.EXECUTION_FAILED) { LOGGER.warn("Experiment could not be executed succesfully. Status: Execution failed"); } if (statusMessage.getEventType() == EventType.MEASUREMENT_FINISHED) { processFinishedExperiment(); } } /** * Ends the execution of the current experiment and stores information about * it in the database.<br /> * Afterwards it's tried to execute the next experiment. */ private synchronized void processFinishedExperiment() { LOGGER.info("Experiment id:" + runningExperiment.getScheduledExperiment().getId() + " finished on: " + runningExperiment.getScheduledExperiment().getControllerUrl()); runningExperiment.setTimeEnded(System.currentTimeMillis()); storeDurationInExperiment(); storeExecutedExperimentDetails(runningExperiment); storeMECLog(runningExperiment); Configuration.removeConfiguration(experimentHashCode); executeStatus = null; runningExperiment = null; experimentHashCode = ""; // now the next experiment can be executed checkToExecuteNext(); } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// HELPER /////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /** * Creates the {@link ExperimentStatus} object, that contains all * necessary information about the current controller state. * * @param experiment the experiment, whose details are requested * @return a status package with all informatio about the currently running experiment */ private ExperimentStatus createExperimentStatusPackage(QueuedExperiment experiment) { if (experiment == null) { return null; } ExperimentStatus cce = new ExperimentStatus(); cce.setAccountId(runningExperiment.getScheduledExperiment().getAccountId()); cce.setScenarioName(runningExperiment.getScheduledExperiment().getScenarioDefinition().getScenarioName()); cce.setTimeStart(runningExperiment.getTimeStarted()); cce.setLabel(runningExperiment.getScheduledExperiment().getLabel()); cce.setEventLogList(runningExperiment.getEventLogLiteList()); if (runningExperiment.getStatusMessageList().get(runningExperiment.getStatusMessageList().size() - 1) .getEventType() == EventType.MEASUREMENT_FINISHED) { cce.setFinished(true); } else { cce.setFinished(false); } if (runningExperiment.getLastProgressInfo() != null) { ProgressInfo info = runningExperiment.getLastProgressInfo(); final float maxPercentage = 100F; float progress = maxPercentage / info.getNumberOfRepetition() * info.getRepetition(); cce.setProgress(progress); } else { // then the experiment has not started yet cce.setProgress(0.0f); } if (runningExperiment.getScheduledExperiment().getDurations().size() > 2) { long sum = 0; for (long l : runningExperiment.getScheduledExperiment().getDurations()) { sum += l; } long estiamtedDuration = sum / runningExperiment.getScheduledExperiment().getDurations().size(); cce.setTimeRemaining(estiamtedDuration); } return cce; } /** * Creates an threadpool, which is responsible for the SoPeCo Runners. This is a singleton method * for the threadpool and currently a cached thread pool is created, which has a varying numbers * of thread in it. * * @return the new created {@link ExecutorService} */ private ExecutorService initThreadPool() { if (threadPool == null) { threadPool = Executors.newCachedThreadPool(); } return threadPool; } /** * Returns whether an experiment is loaded. This means, thaht an experiment has been * submitted to the threadpool to be executed in a {@link SoPeCoRunner}.<br /> * <br /> * This method does <b>not</b> query, if an experiment is currently really executed! * * @return true, if an experiment is loaded */ private boolean isLoaded() { if (runningExperiment != null) { return true; } return false; } /** * Start the next execution. Only called by <code>checkToExecuteNext()</code>! * * @param experiment the experiment to execute next */ private void execute(QueuedExperiment experiment) { LOGGER.info("Start experiment id:" + experiment.getScheduledExperiment().getId() + " on: " + experiment.getScheduledExperiment().getControllerUrl()); // prepare execution properties Map<String, Object> executionProperties = new HashMap<String, Object>(); try { // copy all the current experiment properties executionProperties.putAll(experiment.getScheduledExperiment().getProperties()); LOGGER.debug("Experiement settings controller URL: '{}'", experiment.getScheduledExperiment().getControllerUrl()); executionProperties.put(IConfiguration.CONF_MEASUREMENT_CONTROLLER_URI, new URI(experiment.getScheduledExperiment().getControllerUrl())); executionProperties.put(IConfiguration.CONF_MEASUREMENT_CONTROLLER_CLASS_NAME, null); // only if class name is null, URI is searched executionProperties.put(IConfiguration.CONF_SCENARIO_DESCRIPTION, experiment.getScheduledExperiment().getScenarioDefinition()); } catch (URISyntaxException e) { LOGGER.error("Invalid controller URL '{}'.", experiment.getScheduledExperiment().getControllerUrl()); } experimentHashCode = String.valueOf(experiment.getScheduledExperiment().getExperimentKey()); SoPeCoRunner runner = new SoPeCoRunner(experimentHashCode, executionProperties, experiment.getScheduledExperiment().getSelectedExperiments()); executeStatus = threadPool.submit(runner); experiment.setTimeStarted(System.currentTimeMillis()); } /** * Stores the duration of this execution in the list, which is stored in the * ScheduledExperiment. */ private void storeDurationInExperiment() { ScheduledExperiment exp = ServicePersistenceProvider.getInstance() .loadScheduledExperiment(runningExperiment.getScheduledExperiment().getId()); if (exp != null) { if (exp.getDurations() == null) { exp.setDurations(new ArrayList<Long>()); } long duration = runningExperiment.getTimeEnded() - runningExperiment.getTimeStarted(); exp.getDurations().add(duration); ServicePersistenceProvider.getInstance().storeScheduledExperiment(exp); } } /** * Stores the final results for the exectured experiment in the database as * an {@link ExecutedExperimentDetails} object. */ private void storeExecutedExperimentDetails(QueuedExperiment experiment) { boolean hasError = false; // check for errors in the experiment for (StatusMessage sm : experiment.getStatusMessageList()) { if (sm.getStatusInfo() != null && sm.getStatusInfo() instanceof ErrorInfo) { hasError = true; break; } } ExecutedExperimentDetails eed = new ExecutedExperimentDetails(); eed.setSuccessful(!hasError); eed.setTimeFinished(experiment.getTimeEnded()); eed.setTimeStarted(experiment.getTimeStarted()); eed.setName(experiment.getScheduledExperiment().getLabel()); eed.setControllerURL(experiment.getScheduledExperiment().getControllerUrl()); eed.setExperimentKey(experiment.getScheduledExperiment().getExperimentKey()); eed.setAccountId(experiment.getScheduledExperiment().getAccountId()); eed.setScenarioName(experiment.getScheduledExperiment().getScenarioDefinition().getScenarioName()); ServicePersistenceProvider.getInstance().storeExecutedExperimentDetails(eed); } /** * Stores the {@link MECLog} for the the given {@link QueuedExperiment}. When A MECLog with the * experiment hashcode has already existed, then it's updated. * * @param experiment the experiment to store the {@link MECLog} to */ private void storeMECLog(QueuedExperiment experiment) { long hashcode = experiment.getScheduledExperiment().getExperimentKey(); MECLog log = ServicePersistenceProvider.getInstance().loadMECLog(hashcode); if (log == null) { log = new MECLog(); log.setId(hashcode); } log.setEntries(experiment.getEventLogLiteList()); ServicePersistenceProvider.getInstance().storeMECLog(log); } }
Java
CL
4af90b48393954564a452155d2075e53aaf862c08e38db4834a7804ec5fb0c90
package com.zh.android.eggrollalarmclock.service; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.IBinder; import android.os.Vibrator; import android.text.TextUtils; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import com.zh.android.eggrollalarmclock.R; import com.zh.android.eggrollalarmclock.activity.AlarmShowActivity; import com.zh.android.eggrollalarmclock.util.MusicPlayer; import java.text.SimpleDateFormat; /** * 闹铃 */ public class AlarmRingService extends Service { private static final String STARTUP_ACTION = "startup_action"; private static final String STOP_ACTION = "stop_action"; private static final String CHANNEL_ID = "Alarm"; private static final String CHANNEL_NAME = "闹钟通知"; private static final int NOTIFICATION_ID = 10; private Vibrator mVibrator; public static Intent getStartIntent(Context context) { Intent intent = new Intent(context, AlarmRingService.class); intent.setAction(AlarmRingService.STARTUP_ACTION); return intent; } public static Intent getStopIntent(Context context) { Intent intent = new Intent(context, AlarmRingService.class); intent.setAction(AlarmRingService.STOP_ACTION); return intent; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && !TextUtils.isEmpty(intent.getAction())) { if (STARTUP_ACTION.equals(intent.getAction())) { //到达闹钟时间 Intent jumpIntent = new Intent(this, AlarmShowActivity.class); jumpIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //跳转闹钟页面 startActivity(jumpIntent); //显示通知 showHighNotification(new Intent(jumpIntent), this); //播放闹铃 playMusic(); //开始振动 startVibrate(); } else if (STOP_ACTION.equals(intent.getAction())) { //取消通知 cancelNotification(); //停止播放 stopMusic(); //取消振动 cancelVibrate(); } } return super.onStartCommand(intent, flags, startId); } /** * 播放闹铃 */ private void playMusic() { MusicPlayer.getInstance().play( getApplicationContext(), "radar.mp3", true ); } /** * 停止播放闹铃 */ private void stopMusic() { MusicPlayer.getInstance().stop(); } /** * 显示通知栏的通知 */ private void showHighNotification(Intent intent, Context context) { NotificationChannel channel = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); channel.enableVibration(false); channel.setSound(null, null); } @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ); String title = getCurrentHourMinuteTimeFormatStr() + ",闹钟时间到"; String content = "点我前往关闭闹钟"; Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(content) .setPriority(NotificationCompat.PRIORITY_MAX) .setCategory(NotificationCompat.CATEGORY_CALL) .setContentIntent(pendingIntent) .setFullScreenIntent(pendingIntent, true).build(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.createNotificationChannel(channel); } startForeground(NOTIFICATION_ID, notification); } /** * 取消通知栏 */ private void cancelNotification() { NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(NOTIFICATION_ID); stopForeground(true); } /** * 开始振动 */ protected void startVibrate() { if (mVibrator == null) { mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); } //振动时间,奇数位为振动时间,偶数为暂停时间,单位为毫秒 long[] pattern = {100, 2000, 1000, 1000, 3000}; //0为重复振动,-1为只振动一遍 mVibrator.vibrate(pattern, 0); } /** * 取消振动 */ protected void cancelVibrate() { if (mVibrator != null) { mVibrator.cancel(); } } /** * 获取(小时:分钟)格式化后的时间文本 */ @SuppressLint("SimpleDateFormat") protected String getCurrentHourMinuteTimeFormatStr() { long currentTimeMillis = System.currentTimeMillis(); SimpleDateFormat format = new SimpleDateFormat("HH:mm"); return format.format(currentTimeMillis); } }
Java
CL
dbaaba7b3cb5775f66af2049278ef838478caf1b63165a82898374dd1c9f36ba
/** * 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.lucene.spatial.strategy.jts; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.spatial.base.io.sample.SampleData; import org.apache.lucene.spatial.base.io.sample.SampleDataReader; import org.apache.lucene.spatial.base.shape.Shape; import org.apache.lucene.spatial.base.shape.jts.JtsShapeIO; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.SpatialTestCase; import org.junit.Before; import org.junit.Test; import com.vividsolutions.jts.geom.GeometryFactory; public class TestStrategyJts extends SpatialTestCase { JtsShapeIO shapeIO; JtsGeoStrategy strategy; @Before public void setUp() throws Exception { super.setUp(); shapeIO = new JtsShapeIO( new GeometryFactory() ); strategy = new JtsGeoStrategy( shapeIO.factory ); } @Override protected List<Document> getDocuments() throws IOException { File file = new File( "../data/us-states.txt" ); System.out.println( file.getAbsolutePath() ); ArrayList<Document> docs = new ArrayList<Document>(); SampleDataReader reader = new SampleDataReader(file); while( reader.hasNext() ) { SampleData data = reader.next(); Document doc = new Document(); doc.add( new Field( "name", data.name, Store.YES, Index.ANALYZED ) ); doc.add( new Field( "id", "state-"+data.fips, Store.YES, Index.ANALYZED ) ); Shape shape = shapeIO.readShape( data.shape ); SimpleSpatialFieldInfo info = new SimpleSpatialFieldInfo( "shape" ); for( Fieldable f : strategy.createFields(info, shape, true, true) ) { doc.add( f ); } docs.add( doc ); } return docs; } @Test public void testSearch() throws IOException { System.out.println( "running simple query..." ); SearchResults got = executeQuery(new MatchAllDocsQuery(), 5 ); System.out.println( "got: "+got.numFound ); } }
Java
CL
fbd55dce7a93fb8ccd2d4cc6fa80185e728d1bd8c557d66273a440312821be00
package arouter.dawn.zju.edu.module_goods.ui.search; import android.graphics.Color; import android.os.Bundle; import androidx.core.view.MenuItemCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.alibaba.android.arouter.facade.annotation.Route; import com.alibaba.android.arouter.launcher.ARouter; import java.util.ArrayList; import java.util.List; import arouter.dawn.zju.edu.module_nearby.R; import arouter.dawn.zju.edu.module_goods.adapter.GoodsListAdapter; import baselib.base.BaseActivity; import arouter.dawn.zju.edu.lib_net.bean.goods.Goods; import baselib.constants.RouteConstants; /** * @Auther: Dawn * @Date: 2018/11/22 22:01 * @Description: * 搜索商品页面 */ @Route(path = RouteConstants.AROUTER_GOODS_SEARCH) public class GoodsSearchActivity extends BaseActivity<GoodsSearchContract.Presenter> implements GoodsSearchContract.View, GoodsListAdapter.OnGoodsClickListener { RecyclerView searchResultRv; GoodsListAdapter adapter; @Override protected void initView() { searchResultRv = findViewById(R.id.search_result_list); searchResultRv.setLayoutManager(new LinearLayoutManager(this)); adapter = new GoodsListAdapter(new ArrayList<Goods>(), this); adapter.setOnGoodsClickListener(this); searchResultRv.setAdapter(adapter); } @Override protected boolean showHomeAsUp() { return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu, menu); MenuItem item = menu.findItem(R.id.search_menu_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); //进去打开搜索栏 searchView.setIconified(false); //设置输入文本的EditText SearchView.SearchAutoComplete et = searchView.findViewById(R.id.search_src_text); //设置搜索栏的默认提示,作用和setQueryHint相同 et.setHint("输入商品名或首字母"); //设置提示文本的颜色 et.setHintTextColor(Color.WHITE); //设置输入文本的颜色 et.setTextColor(Color.WHITE); //设置提交按钮是否可见 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { mPresenter.search(query); return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; } @Override protected int getLayoutId() { return R.layout.activity_goods_search; } @Override protected void bindPresenter() { mPresenter = new GoodsSearchPresenter(); } @Override public void refresh(List<Goods> goodsList) { adapter.refresh(goodsList); } @Override public void onGoodsClick(View v, Goods goods) { Bundle bundle = new Bundle(); bundle.putParcelable(RouteConstants.GOODS_DETAIL_GOODS, goods); ARouter.getInstance().build(RouteConstants.AROUTER_GOODS_DETAIL) .withBundle(RouteConstants.GOODS_DETAIL_BUNDLE, bundle).navigation(); } }
Java
CL
e10a643f1b0933fd956caf035bbb384c640b1c6a04c8645f55c18ca2cb6d7f50
package io.jshift.buildah.core.commands; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class GlobalParametersSupport { private static final String ALSOLOGTOSTDERR = "--alsologtostderr"; private static final String LOGBACKTRACEAT = "--log_backtrace_at"; private static final String LOGDIR = "--log_dir"; private static final String LOGTOSTDERR = "--logtostderr"; private static final String SKIPCONNECTIONCHECK = "--skip-connection-check"; private static final String STDERRTHRESHOLD = "--stderrthreshold"; private static final String V = "--v"; private static final String VMODULE = "--vmodule"; private Boolean alsologtostderr; private Integer log_backtrace_at; private String log_dir; private Boolean logtostderr; private Boolean skipconnectioncheck; private Integer stderrthreshold; private Integer v; private List<String> vmodule; private List<String> extraCommands; public List<String> getCliCommand() { final List<String> arguments = new ArrayList<>(); if (alsologtostderr != null && alsologtostderr.booleanValue()) { arguments.add(ALSOLOGTOSTDERR); } if (log_backtrace_at != null) { arguments.add(LOGBACKTRACEAT); arguments.add(Integer.toString(log_backtrace_at)); } if (log_dir != null) { arguments.add(LOGDIR); arguments.add(log_dir); } if (logtostderr != null && logtostderr.booleanValue()) { arguments.add(LOGTOSTDERR); } if (skipconnectioncheck != null && skipconnectioncheck.booleanValue()) { arguments.add(SKIPCONNECTIONCHECK); } if (stderrthreshold != null) { arguments.add(STDERRTHRESHOLD); arguments.add(Integer.toString(stderrthreshold)); } if (v != null) { arguments.add(V); arguments.add(Integer.toString(v)); } if (vmodule != null && vmodule.size() > 0) { arguments.add(VMODULE); arguments.add(toCsv(vmodule)); } if (extraCommands != null) { arguments.addAll(extraCommands); } return arguments; } private String toCsv(List<String> args) { return args.stream() .collect(Collectors.joining(", ")); } public static abstract class Builder<T> { private GlobalParametersSupport globalParametersSupport; private Class<T> typeOfT; public Builder() { this.globalParametersSupport = new GlobalParametersSupport(); this.typeOfT = (Class<T>) ((ParameterizedType)getClass() .getGenericSuperclass()) .getActualTypeArguments()[0]; } public T withAlsoLogToStderr() { this.globalParametersSupport.alsologtostderr = true; final Type type = ((ParameterizedType) this.getClass().getGenericInterfaces()[0]) .getActualTypeArguments()[0]; return typeOfT.cast(this); } public T withLogBacktraceAt(Integer logBacktraceAt) { this.globalParametersSupport.log_backtrace_at = logBacktraceAt; return typeOfT.cast(this); } public T withLogDir(String log_dir) { this.globalParametersSupport.log_dir = log_dir; return typeOfT.cast(this); } public T withLogToStderr() { this.globalParametersSupport.logtostderr = true; return typeOfT.cast(this); } public T withSkipConnectionCheck() { this.globalParametersSupport.skipconnectioncheck = true; return typeOfT.cast(this); } public T withStderrThreshold(Integer threshold) { this.globalParametersSupport.stderrthreshold = threshold; return typeOfT.cast(this); } public T withV(Integer v) { this.globalParametersSupport.v = v; return typeOfT.cast(this); } public T withVModule(List<String> vmodule) { this.globalParametersSupport.vmodule = vmodule; return typeOfT.cast(this); } public T withExtraArguments(List<String> extraArguments) { this.globalParametersSupport.extraCommands = extraArguments; return typeOfT.cast(this); } protected GlobalParametersSupport buildGlobalParameters() { return this.globalParametersSupport; } } }
Java
CL
5096ff08d2dab2e5d54683fecf0c37ac898d8f228564e3779a4a6ebc7305d2a4
package com.ssm.demo.controller; import com.google.common.io.ByteStreams; import com.ssm.demo.common.MessageCode; import com.ssm.demo.common.ResultObject; import com.ssm.demo.common.Util; import com.ssm.demo.service.AttachmentService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Paths; /** * @Description * @Author Roge * @Version V1.0.0 * @Since 1.0 * @Date 2019/5/6 */ @Controller @RequestMapping(value = "/commons/attachments") @Api(tags = {"共通-附件"}) public class AttachmentController { @Autowired private AttachmentService attachmentService; @Value("${config.attachFolder}") private String attachFolder; @ApiOperation(value = "上传附件") @RequestMapping(value = "/upload", method = RequestMethod.POST) public void upload(HttpServletResponse response , @ApiParam(value = "附件") @RequestPart MultipartFile multipartFile) throws IOException { response.setContentType("text/html"); String filename = attachmentService.txUpload(multipartFile); response.getWriter().println(JSONObject.fromObject(new ResultObject<>(MessageCode.CODE_SUCCESS, filename)).toString()); } @ApiOperation(value = "附件下载") @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(@ApiParam(value = "附件名称") @RequestParam String filename , @ApiParam(value = "保存文件名") @RequestParam(required = false) String saveName , HttpServletResponse response) throws IOException { saveName = Util.encodeUriParam(saveName); String mime = Files.probeContentType(Paths.get(attachFolder + filename)); saveName = StringUtils.isEmpty(saveName) ? filename : saveName; response.setContentType(mime); response.setHeader("Content-Dispositon", "attachment;filename=" + URLEncoder.encode(saveName, "UTF-8")); ByteStreams.copy(new FileInputStream(attachFolder + filename), response.getOutputStream()); } }
Java
CL
d4aae47e231d3fa3e6e59ea0212a507cd45fb438b0d7f7bcdd1d43349d4b5433
package com.katruk.web.controller.commands; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import com.katruk.entity.Period; import com.katruk.entity.Student; import com.katruk.entity.Teacher; import com.katruk.entity.User; import com.katruk.exception.ServiceException; import com.katruk.service.PeriodService; import com.katruk.service.StudentService; import com.katruk.service.TeacherService; import com.katruk.service.UserService; import com.katruk.service.impl.PeriodServiceImpl; import com.katruk.service.impl.StudentServiceImpl; import com.katruk.service.impl.TeacherServiceImpl; import com.katruk.service.impl.UserServiceImpl; import com.katruk.util.PageConfig; import com.katruk.web.PageAttribute; import com.katruk.web.controller.Command; import org.apache.commons.codec.digest.DigestUtils; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public final class Login implements Command, PageAttribute { private final static String ERROR_LOGIN_EMPTY = "Username or password is empty"; private final static String ERROR_LOGIN_WRONG = "Wrong username or password"; private final static int MAX_INACTIVE_INTERVAL = 60 * 60 * 24; private final Logger logger; private final PeriodService periodService; private final UserService userService; private final StudentService studentService; private final TeacherService teacherService; public Login() { this.periodService = new PeriodServiceImpl(); this.userService = new UserServiceImpl(); this.studentService = new StudentServiceImpl(); this.teacherService = new TeacherServiceImpl(); this.logger = Logger.getLogger(Login.class); } @Override public String execute(final HttpServletRequest request, final HttpServletResponse response) { final String username = request.getParameter(USERNAME); final String password = request.getParameter(PASSWORD); final HttpSession session = request.getSession(); String page = PageConfig.getInstance().getValue(PageConfig.INDEX); if (isNull(username) || isNull(password)) { request.setAttribute(ERROR, ERROR_LOGIN_EMPTY); this.logger.error(ERROR_LOGIN_EMPTY); } else { try { final User user = this.userService.getUserByUsername(username); if (user.getPassword().equals(DigestUtils.sha1Hex(password))) { page = getPage(request, session, user); } } catch (ServiceException e) { request.getSession().setAttribute(ERROR, ERROR_LOGIN_WRONG); logger.error(ERROR_LOGIN_WRONG, e); page = PageConfig.getInstance().getValue(PageConfig.ERROR_PAGE); } } return page; } private String getPage(HttpServletRequest request, HttpSession session, User user) throws ServiceException { String page; setAttribute(session, user); page = PageConfig.getInstance().getValue(PageConfig.PROFILE); if (nonNull(user.getRole())) { switch (user.getRole()) { case STUDENT: { setAttributeForStudent(session, user); break; } case TEACHER: { setAttributeForTeacher(session, user); break; } case ADMIN: { page = setAttributeForAdmin(request); break; } } } return page; } private String setAttributeForAdmin(HttpServletRequest request) throws ServiceException { String page; page = PageConfig.getInstance().getValue(PageConfig.ADMIN_PROFILE); Period period = this.periodService.getLastPeriod(); request.setAttribute(PERIOD_STATUS, period.getStatus()); request.setAttribute(PERIOD_DATE, period.getDate()); return page; } private void setAttributeForTeacher(HttpSession session, User user) throws ServiceException { final Teacher teacher = this.teacherService.getTeacherById(user.getId()); session.setAttribute(POSITION, teacher.getPosition()); } private void setAttributeForStudent(HttpSession session, User user) throws ServiceException { final Student student = this.studentService.getStudentById(user.getId()); session.setAttribute(CONTRACT, student.getContract()); session.setAttribute(FORM, student.getForm()); } private void setAttribute(HttpSession session, User user) { session.setAttribute(LAST_NAME, user.getPerson().getLastName()); session.setAttribute(NAME, user.getPerson().getName()); session.setAttribute(USERNAME, user.getUsername()); session.setAttribute(ROLE, user.getRole()); session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); } }
Java
CL
d7c2f86c53d1508f848031b4f41990addf864f323396264d5e18fa962d137354
package com.indeed.util.mmap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** @author jplaisance */ public final class DirectMemory extends AbstractMemory { private static final Logger log = LoggerFactory.getLogger(DirectMemory.class); private static final boolean debug = true; private final ByteOrder order; private final DirectDataAccess directDataAccess; private final long address; private final long length; DirectMemory(long address, long length, ByteOrder order) { this.address = address; this.length = length; this.order = order; directDataAccess = order.equals(ByteOrder.nativeOrder()) ? NativeEndianDirectDataAccess.getInstance() : ReverseEndianDirectDataAccess.getInstance(); } private void checkBounds(long l, long length) { if (debug) { if (l < 0 || l > this.length - length) throw new IndexOutOfBoundsException("l: " + l + " length: " + length); } } private void checkArrayBounds(final byte[] bytes, final int start, final int length) { if (debug) { if (bytes == null) throw new IllegalArgumentException("byte[] bytes cannot be null"); if (start < 0) throw new IndexOutOfBoundsException("start cannot be less than zero"); if (length < 0) throw new IllegalArgumentException("length cannot be less than zero"); if (start + length > bytes.length) throw new IndexOutOfBoundsException( "start plus length cannot be greater than length of byte[] bytes"); if (start + length < 0) throw new IndexOutOfBoundsException( "start plus length cannot be greater than Integer.MAX_VALUE"); } } @Override public byte getByte(final long l) { checkBounds(l, 1); return directDataAccess.getByte(address + l); } @Override public void putByte(final long l, final byte b) { checkBounds(l, 1); directDataAccess.putByte(address + l, b); } @Override public short getShort(final long l) { checkBounds(l, 2); return directDataAccess.getShort(address + l); } @Override public void putShort(final long l, final short i) { checkBounds(l, 2); directDataAccess.putShort(address + l, i); } @Override public char getChar(final long l) { checkBounds(l, 2); return directDataAccess.getChar(address + l); } @Override public void putChar(final long l, final char c) { checkBounds(l, 2); directDataAccess.putChar(address + l, c); } @Override public int getInt(final long l) { checkBounds(l, 4); return directDataAccess.getInt(address + l); } @Override public void putInt(final long l, final int i) { checkBounds(l, 4); directDataAccess.putInt(address + l, i); } @Override public long getLong(final long l) { checkBounds(l, 8); return directDataAccess.getLong(address + l); } @Override public void putLong(final long l, final long l1) { checkBounds(l, 8); directDataAccess.putLong(address + l, l1); } @Override public float getFloat(final long l) { checkBounds(l, 4); return directDataAccess.getFloat(address + l); } @Override public void putFloat(final long l, final float v) { checkBounds(l, 4); directDataAccess.putFloat(address + l, v); } @Override public double getDouble(final long l) { checkBounds(l, 8); return directDataAccess.getDouble(address + l); } @Override public void putDouble(final long l, final double v) { checkBounds(l, 8); directDataAccess.putDouble(address + l, v); } @Override public void putBytes(final long l, final byte[] bytes) { putBytes(l, bytes, 0, bytes.length); } @Override public void putBytes(final long l, final byte[] bytes, final int start, final int length) { checkBounds(l, length); checkArrayBounds(bytes, start, length); NativeMemoryUtils.copyFromArray(bytes, start, address + l, length); } public void putBytes(long l, DirectMemory source) { putBytes(l, source, 0, source.length()); } public void putBytes(long l, DirectMemory source, long start, long length) { checkBounds(l, length); source.checkBounds(start, length); directDataAccess.copyMemory(source.address + start, address + l, length); } @Override public void putBytes(long l, Memory source) { putBytes(l, source, 0, source.length()); } @Override public void putBytes(long l, Memory source, long start, long length) { if (source.isDirect()) { putBytes(l, (DirectMemory) source, start, length); } else { source.getBytes(start, this, l, length); } } @Override public void putBytes(long l, ByteBuffer source) { final int length = source.remaining(); checkBounds(l, length); if (source.isDirect()) { NativeMemoryUtils.copyFromDirectBuffer(source, source.position(), address + l, length); source.position(source.position() + length); } else if (source.hasArray()) { final byte[] array = source.array(); final int offset = source.arrayOffset(); putBytes(l, array, offset + source.position(), length); source.position(source.position() + length); } else { final byte[] copyBuffer = new byte[Math.min(length, 4096)]; long destAddr = l; while (source.remaining() > 0) { final int copySize = Math.min(copyBuffer.length, source.remaining()); source.get(copyBuffer, 0, copySize); putBytes(destAddr, copyBuffer, 0, copySize); destAddr += copySize; } } } @Override public void getBytes(final long l, final byte[] bytes) { getBytes(l, bytes, 0, bytes.length); } @Override public void getBytes(final long l, final byte[] bytes, final int start, final int length) { checkBounds(l, length); checkArrayBounds(bytes, start, length); NativeMemoryUtils.copyToArray(address + l, bytes, start, length); } public void getBytes(long l, DirectMemory dest) { getBytes(l, dest, 0, dest.length()); } public void getBytes(long l, DirectMemory dest, long start, long length) { checkBounds(l, length); dest.checkBounds(start, length); directDataAccess.copyMemory(address + l, dest.address + start, length); } @Override public void getBytes(long l, Memory dest) { getBytes(l, dest, 0, dest.length()); } @Override public void getBytes(long l, Memory dest, long start, long length) { if (dest.isDirect()) { getBytes(l, (DirectMemory) dest, start, length); } else { dest.putBytes(start, this, l, length); } } @Override public void getBytes(long l, ByteBuffer dest) { final int length = dest.remaining(); checkBounds(l, length); if (dest.isDirect()) { NativeMemoryUtils.copyToDirectBuffer(address + l, dest, dest.position(), length); dest.position(dest.position() + length); } else if (dest.hasArray()) { final byte[] array = dest.array(); final int offset = dest.arrayOffset(); getBytes(l, array, offset + dest.position(), length); dest.position(dest.position() + length); } else { final byte[] copyBuffer = new byte[Math.min(length, 4096)]; long sourceAddr = l; while (dest.remaining() > 0) { final int copySize = Math.min(copyBuffer.length, dest.remaining()); getBytes(sourceAddr, copyBuffer, 0, copySize); dest.put(copyBuffer, 0, copySize); sourceAddr += copySize; } } } @Override public DirectMemory slice(long startAddress, long sliceLength) { if (startAddress < 0) throw new IllegalArgumentException("startAddress must be >= 0"); if (sliceLength < 0) throw new IllegalArgumentException("sliceLength must be >= 0"); if (startAddress + sliceLength > length) throw new IllegalArgumentException("startAddress+sliceLength must be <= length"); return new DirectMemory(address + startAddress, sliceLength, order); } @Override public long length() { return length; } @Override public boolean isDirect() { return true; } @Override public ByteOrder getOrder() { return order; } /** * this is really only here for passing to jni calls. don't use it for anything else. deprecated * to make your code ugly if you use it. * * @return address */ @Deprecated public long getAddress() { return address; } }
Java
CL
3c1603bc8d38cd26412d2f0a0b20f9c6cf96cc0ab99f10c189ebc99bdd2c2e00
package com.example.localstack.consumer; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.kinesis.exceptions.InvalidStateException; import software.amazon.kinesis.exceptions.ShutdownException; import software.amazon.kinesis.lifecycle.events.InitializationInput; import software.amazon.kinesis.lifecycle.events.LeaseLostInput; import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput; import software.amazon.kinesis.lifecycle.events.ShardEndedInput; import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput; import software.amazon.kinesis.processor.ShardRecordProcessor; import software.amazon.kinesis.retrieval.KinesisClientRecord; public class EventProcessor implements ShardRecordProcessor { private static final Logger LOG = LoggerFactory.getLogger(EventProcessor.class); @Override public void initialize(InitializationInput initializationInput) { // TODO Auto-generated method stub LOG.info("Entrando en initialize"); } @Override public void processRecords(ProcessRecordsInput processRecordsInput) { LOG.info(processRecordsInput.toString()); for (KinesisClientRecord record : processRecordsInput.records()) { LOG.info("Processing Record For Partition Key : {}", record.partitionKey()); String originalData = ""; try { byte[] b = new byte[record.data().remaining()]; ByteBuffer byteBuf = record.data().get(b); originalData = new String(byteBuf.array(), "UTF-8"); LOG.info("Processing record pk: {} -- Seq: {}", record.partitionKey(), record.sequenceNumber()); } catch (Exception e) { LOG.error("Error parsing record {}", e); e.printStackTrace(); System.exit(1); } } try { /* * KCL assumes that the call to checkpoint means that all records have been * processed, records which are passed to the record processor. */ processRecordsInput.checkpointer().checkpoint(); } catch (Exception e) { LOG.error("Error during Processing of records", e); } } @Override public void leaseLost(LeaseLostInput leaseLostInput) { LOG.info("Entrando en leaseLost"); } @Override public void shardEnded(ShardEndedInput shardEndedInput) { LOG.info("Entrando en shardEnded"); try { shardEndedInput.checkpointer().checkpoint(); } catch (ShutdownException | InvalidStateException e) { e.printStackTrace(); } } @Override public void shutdownRequested(ShutdownRequestedInput shutdownRequestedInput) { LOG.info("Entrando en shutdownRequested"); try { shutdownRequestedInput.checkpointer().checkpoint(); } catch (ShutdownException | InvalidStateException e) { e.printStackTrace(); } } }
Java
CL
1deaaa7cae87a856a64b9cf5a41fd9442872f658022a3a279e16a299a46b90e6