hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
f92d55ee20e6a3b7db989936b6a4fd43fa2874d1 | 440 | package util;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Security;
import type.Sessao;
import controllers.routes;
public class ActionAuthenticator extends Security.Authenticator {
@Override
public String getUsername(Http.Context ctx) {
return ctx.session().get(Sessao.usuario.name());
}
@Override
public Result onUnauthorized(Http.Context context) {
return redirect(routes.Application.authenticate());
}
}
| 20 | 65 | 0.775 |
e9ce0e1bbac48f907dc6586f7b48738f52e5c8e9 | 3,019 | package com.zondy.mapgis.mobile.react;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.zondy.mapgis.android.model.Model;
import com.zondy.mapgis.android.model.SimpleModelLayerUtil;
import com.zondy.mapgis.core.map.SimpleModelLayer;
/**
* 模型层工具类Native功能组件
* Created by xiaoying on 2019/9/10.
*/
public class JSSimpleModelLayerUtil extends ReactContextBaseJavaModule {
private static final String REACT_CLASS = "JSSimpleModelLayerUtil";
public JSSimpleModelLayerUtil(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return REACT_CLASS;
}
@ReactMethod
public void createModelStorageFileIfNotExists(String strURL, Promise promise){
try {
boolean result = SimpleModelLayerUtil.createModelStorageFileIfNotExists(strURL);
promise.resolve(result);
}catch (Exception e){
promise.reject(e);
}
}
@ReactMethod
public void addModel(String modelLayerId, String modelId, Promise promise){
try {
SimpleModelLayer simpleModelLayer = (SimpleModelLayer) JSSimpleModelLayer.getObjFromList(modelLayerId);
Model model = JSModel.getObjFromList(modelId);
int id = SimpleModelLayerUtil.addModel(simpleModelLayer, model);
promise.resolve(id);
}catch (Exception e){
promise.reject(e);
}
}
@ReactMethod
public void updateModel(String modelLayerId, int id, String modelId, Promise promise)
{
try {
SimpleModelLayer simpleModelLayer = (SimpleModelLayer) JSSimpleModelLayer.getObjFromList(modelLayerId);
Model model = JSModel.getObjFromList(modelId);
int result = SimpleModelLayerUtil.updateModel(simpleModelLayer, id, model);
promise.resolve(result);
} catch (Exception e) {
promise.reject(e);
}
}
@ReactMethod
public void removeModel(String modelLayerId, int id, Promise promise){
try {
SimpleModelLayer simpleModelLayer = (SimpleModelLayer) JSSimpleModelLayer.getObjFromList(modelLayerId);
int result = SimpleModelLayerUtil.removeModel(simpleModelLayer, id);
promise.resolve(result);
}catch (Exception e){
promise.reject(e);
}
}
@ReactMethod
public void clearModels(String modelLayerId, Promise promise){
try {
SimpleModelLayer simpleModelLayer = (SimpleModelLayer) JSSimpleModelLayer.getObjFromList(modelLayerId);
int result = SimpleModelLayerUtil.clearModels(simpleModelLayer);
promise.resolve(result);
}catch (Exception e){
promise.reject(e);
}
}
} | 35.104651 | 116 | 0.663796 |
d92c205be4909c9502ccf2536038c761dce483ba | 1,693 | package io.quarkus.it.hibernate.search.elasticsearch.aws;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import java.util.Map;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.quarkus.test.common.QuarkusTestResourceLifecycleManager;
public class WireMockElasticsearchProxyTestResource implements QuarkusTestResourceLifecycleManager {
WireMockServer wireMockServer;
@Override
public Map<String, String> start() {
wireMockServer = new WireMockServer(8090);
wireMockServer.start();
// See surefire/failsafe configuration in pom.xml
String elasticsearchProtocol = System.getProperty("elasticsearch.protocol");
String elasticsearchHosts = System.getProperty("elasticsearch.hosts");
String elasticsearchFirstHost = elasticsearchHosts.split(",")[0];
wireMockServer.stubFor(any(anyUrl())
.willReturn(aResponse().proxiedFrom(elasticsearchProtocol + "://" + elasticsearchFirstHost)));
return Map.of(
"quarkus.hibernate-search-orm.elasticsearch.hosts", "localhost:" + wireMockServer.port());
}
@Override
public void inject(TestInjector testInjector) {
testInjector.injectIntoFields(wireMockServer,
new TestInjector.AnnotatedAndMatchesType(InjectWireMock.class, WireMockServer.class));
}
@Override
public synchronized void stop() {
if (wireMockServer != null) {
wireMockServer.stop();
wireMockServer = null;
}
}
}
| 35.270833 | 110 | 0.720614 |
3d0557b5c017e5b18de56900e822a654dd2f478c | 18,747 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin.dicttool;
import com.android.inputmethod.latin.makedict.BinaryDictDecoderUtils;
import com.android.inputmethod.latin.makedict.BinaryDictIOUtils;
import com.android.inputmethod.latin.makedict.DictDecoder;
import com.android.inputmethod.latin.makedict.DictEncoder;
import com.android.inputmethod.latin.makedict.FormatSpec;
import com.android.inputmethod.latin.makedict.FusionDictionary;
import com.android.inputmethod.latin.makedict.MakedictLog;
import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
import com.android.inputmethod.latin.makedict.Ver2DictEncoder;
import com.android.inputmethod.latin.makedict.Ver4DictEncoder;
import org.xml.sax.SAXException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import javax.xml.parsers.ParserConfigurationException;
/**
* Main class/method for DictionaryMaker.
*/
public class DictionaryMaker {
static class Arguments {
private static final String OPTION_VERSION_2 = "-2";
private static final String OPTION_VERSION_4 = "-4";
private static final String OPTION_INPUT_SOURCE = "-s";
private static final String OPTION_INPUT_BIGRAM_XML = "-b";
private static final String OPTION_INPUT_SHORTCUT_XML = "-c";
private static final String OPTION_OUTPUT_BINARY = "-d";
private static final String OPTION_OUTPUT_XML = "-x";
private static final String OPTION_OUTPUT_COMBINED = "-o";
private static final String OPTION_HELP = "-h";
public final String mInputBinary;
public final String mInputCombined;
public final String mInputUnigramXml;
public final String mInputShortcutXml;
public final String mInputBigramXml;
public final String mOutputBinary;
public final String mOutputXml;
public final String mOutputCombined;
public final int mOutputBinaryFormatVersion;
private void checkIntegrity() throws IOException {
checkHasExactlyOneInput();
checkHasAtLeastOneOutput();
checkNotSameFile(mInputBinary, mOutputBinary);
checkNotSameFile(mInputBinary, mOutputXml);
checkNotSameFile(mInputCombined, mOutputBinary);
checkNotSameFile(mInputCombined, mOutputXml);
checkNotSameFile(mInputUnigramXml, mOutputBinary);
checkNotSameFile(mInputUnigramXml, mOutputXml);
checkNotSameFile(mInputUnigramXml, mOutputCombined);
checkNotSameFile(mInputShortcutXml, mOutputBinary);
checkNotSameFile(mInputShortcutXml, mOutputXml);
checkNotSameFile(mInputShortcutXml, mOutputCombined);
checkNotSameFile(mInputBigramXml, mOutputBinary);
checkNotSameFile(mInputBigramXml, mOutputXml);
checkNotSameFile(mInputBigramXml, mOutputCombined);
checkNotSameFile(mOutputBinary, mOutputXml);
checkNotSameFile(mOutputBinary, mOutputCombined);
checkNotSameFile(mOutputXml, mOutputCombined);
}
private void checkHasExactlyOneInput() {
if (null == mInputUnigramXml && null == mInputBinary && null == mInputCombined) {
throw new RuntimeException("No input file specified");
} else if ((null != mInputUnigramXml && null != mInputBinary)
|| (null != mInputUnigramXml && null != mInputCombined)
|| (null != mInputBinary && null != mInputCombined)) {
throw new RuntimeException("Several input files specified");
} else if ((null != mInputBinary || null != mInputCombined)
&& (null != mInputBigramXml || null != mInputShortcutXml)) {
throw new RuntimeException("Separate bigrams/shortcut files are only supported"
+ " with XML input (other formats include bigrams and shortcuts already)");
}
}
private void checkHasAtLeastOneOutput() {
if (null == mOutputBinary && null == mOutputXml && null == mOutputCombined) {
throw new RuntimeException("No output specified");
}
}
/**
* Utility method that throws an exception if path1 and path2 point to the same file.
*/
private static void checkNotSameFile(final String path1, final String path2)
throws IOException {
if (null == path1 || null == path2) return;
if (new File(path1).getCanonicalPath().equals(new File(path2).getCanonicalPath())) {
throw new RuntimeException(path1 + " and " + path2 + " are the same file: "
+ " refusing to process.");
}
}
private void displayHelp() {
MakedictLog.i(getHelp());
}
public static String getHelp() {
return "Usage: makedict "
+ "[-s <unigrams.xml> [-b <bigrams.xml>] [-c <shortcuts_and_whitelist.xml>] "
+ "| [-s <combined format input]"
+ "| [-s <binary input>] [-d <binary output>] [-x <xml output>] "
+ " [-o <combined output>]"
+ "[-2] [-3] [-4]\n"
+ "\n"
+ " Converts a source dictionary file to one or several outputs.\n"
+ " Source can be an XML file, with an optional XML bigrams file, or a\n"
+ " binary dictionary file.\n"
+ " Binary version 2 (Jelly Bean), 3, 4, XML and\n"
+ " combined format outputs are supported.";
}
public Arguments(String[] argsArray) throws IOException {
final LinkedList<String> args = new LinkedList<>(Arrays.asList(argsArray));
if (args.isEmpty()) {
displayHelp();
}
String inputBinary = null;
String inputCombined = null;
String inputUnigramXml = null;
String inputShortcutXml = null;
String inputBigramXml = null;
String outputBinary = null;
String outputXml = null;
String outputCombined = null;
int outputBinaryFormatVersion = 2; // the default version is 2.
while (!args.isEmpty()) {
final String arg = args.get(0);
args.remove(0);
if (arg.charAt(0) == '-') {
if (OPTION_VERSION_2.equals(arg)) {
// Do nothing, this is the default
} else if (OPTION_VERSION_4.equals(arg)) {
outputBinaryFormatVersion = FormatSpec.VERSION4;
} else if (OPTION_HELP.equals(arg)) {
displayHelp();
} else {
// All these options need an argument
if (args.isEmpty()) {
throw new IllegalArgumentException("Option " + arg + " is unknown or "
+ "requires an argument");
}
String filename = args.get(0);
args.remove(0);
if (OPTION_INPUT_SOURCE.equals(arg)) {
if (XmlDictInputOutput.isXmlUnigramDictionary(filename)) {
inputUnigramXml = filename;
} else if (CombinedInputOutput.isCombinedDictionary(filename)) {
inputCombined = filename;
} else if (BinaryDictDecoderUtils.isBinaryDictionary(filename)) {
inputBinary = filename;
} else {
throw new IllegalArgumentException(
"Unknown format for file " + filename);
}
} else if (OPTION_INPUT_SHORTCUT_XML.equals(arg)) {
inputShortcutXml = filename;
} else if (OPTION_INPUT_BIGRAM_XML.equals(arg)) {
inputBigramXml = filename;
} else if (OPTION_OUTPUT_BINARY.equals(arg)) {
outputBinary = filename;
} else if (OPTION_OUTPUT_XML.equals(arg)) {
outputXml = filename;
} else if (OPTION_OUTPUT_COMBINED.equals(arg)) {
outputCombined = filename;
} else {
throw new IllegalArgumentException("Unknown option : " + arg);
}
}
} else {
if (null == inputBinary && null == inputUnigramXml) {
if (BinaryDictDecoderUtils.isBinaryDictionary(arg)) {
inputBinary = arg;
} else if (CombinedInputOutput.isCombinedDictionary(arg)) {
inputCombined = arg;
} else {
inputUnigramXml = arg;
}
} else if (null == outputBinary) {
outputBinary = arg;
} else {
throw new IllegalArgumentException("Several output binary files specified");
}
}
}
mInputBinary = inputBinary;
mInputCombined = inputCombined;
mInputUnigramXml = inputUnigramXml;
mInputShortcutXml = inputShortcutXml;
mInputBigramXml = inputBigramXml;
mOutputBinary = outputBinary;
mOutputXml = outputXml;
mOutputCombined = outputCombined;
mOutputBinaryFormatVersion = outputBinaryFormatVersion;
checkIntegrity();
}
}
public static void main(String[] args)
throws FileNotFoundException, ParserConfigurationException, SAXException, IOException,
UnsupportedFormatException {
final Arguments parsedArgs = new Arguments(args);
FusionDictionary dictionary = readInputFromParsedArgs(parsedArgs);
writeOutputToParsedArgs(parsedArgs, dictionary);
}
/**
* Invoke the right input method according to args.
*
* @param args the parsed command line arguments.
* @return the read dictionary.
*/
private static FusionDictionary readInputFromParsedArgs(final Arguments args)
throws IOException, UnsupportedFormatException, ParserConfigurationException,
SAXException, FileNotFoundException {
if (null != args.mInputBinary) {
return readBinaryFile(args.mInputBinary);
} else if (null != args.mInputCombined) {
return readCombinedFile(args.mInputCombined);
} else if (null != args.mInputUnigramXml) {
return readXmlFile(args.mInputUnigramXml, args.mInputShortcutXml, args.mInputBigramXml);
} else {
throw new RuntimeException("No input file specified");
}
}
/**
* Read a dictionary from the name of a binary file.
*
* @param binaryFilename the name of the file in the binary dictionary format.
* @return the read dictionary.
* @throws FileNotFoundException if the file can't be found
* @throws IOException if the input file can't be read
* @throws UnsupportedFormatException if the binary file is not in the expected format
*/
private static FusionDictionary readBinaryFile(final String binaryFilename)
throws FileNotFoundException, IOException, UnsupportedFormatException {
final File file = new File(binaryFilename);
final DictDecoder dictDecoder = BinaryDictIOUtils.getDictDecoder(file, 0, file.length());
return dictDecoder.readDictionaryBinary(false /* deleteDictIfBroken */);
}
/**
* Read a dictionary from the name of a combined file.
*
* @param combinedFilename the name of the file in the combined format.
* @return the read dictionary.
* @throws FileNotFoundException if the file can't be found
* @throws IOException if the input file can't be read
*/
private static FusionDictionary readCombinedFile(final String combinedFilename)
throws FileNotFoundException, IOException {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(combinedFilename), "UTF-8"))
) {
return CombinedInputOutput.readDictionaryCombined(reader);
}
}
private static BufferedInputStream getBufferedFileInputStream(final String filename)
throws FileNotFoundException {
if (filename == null) {
return null;
}
return new BufferedInputStream(new FileInputStream(filename));
}
/**
* Read a dictionary from a unigram XML file, and optionally a bigram XML file.
*
* @param unigramXmlFilename the name of the unigram XML file. May not be null.
* @param shortcutXmlFilename the name of the shortcut/whitelist XML file, or null if none.
* @param bigramXmlFilename the name of the bigram XML file. Pass null if there are no bigrams.
* @return the read dictionary.
* @throws FileNotFoundException if one of the files can't be found
* @throws SAXException if one or more of the XML files is not well-formed
* @throws IOException if one the input files can't be read
* @throws ParserConfigurationException if the system can't create a SAX parser
*/
private static FusionDictionary readXmlFile(final String unigramXmlFilename,
final String shortcutXmlFilename, final String bigramXmlFilename)
throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
try (
final BufferedInputStream unigrams = getBufferedFileInputStream(unigramXmlFilename);
final BufferedInputStream shortcuts = getBufferedFileInputStream(shortcutXmlFilename);
final BufferedInputStream bigrams = getBufferedFileInputStream(bigramXmlFilename);
) {
return XmlDictInputOutput.readDictionaryXml(unigrams, shortcuts, bigrams);
}
}
/**
* Invoke the right output method according to args.
*
* This will write the passed dictionary to the file(s) passed in the command line arguments.
* @param args the parsed arguments.
* @param dict the file to output.
* @throws FileNotFoundException if one of the output files can't be created.
* @throws IOException if one of the output files can't be written to.
*/
private static void writeOutputToParsedArgs(final Arguments args, final FusionDictionary dict)
throws FileNotFoundException, IOException, UnsupportedFormatException,
IllegalArgumentException {
if (null != args.mOutputBinary) {
writeBinaryDictionary(args.mOutputBinary, dict, args.mOutputBinaryFormatVersion);
}
if (null != args.mOutputXml) {
writeXmlDictionary(args.mOutputXml, dict);
}
if (null != args.mOutputCombined) {
writeCombinedDictionary(args.mOutputCombined, dict);
}
}
/**
* Write the dictionary in binary format to the specified filename.
*
* @param outputFilename the name of the file to write to.
* @param dict the dictionary to write.
* @param version the binary format version to use.
* @throws FileNotFoundException if the output file can't be created.
* @throws IOException if the output file can't be written to.
*/
private static void writeBinaryDictionary(final String outputFilename,
final FusionDictionary dict, final int version)
throws FileNotFoundException, IOException, UnsupportedFormatException {
final File outputFile = new File(outputFilename);
final FormatSpec.FormatOptions formatOptions = new FormatSpec.FormatOptions(version);
final DictEncoder dictEncoder;
if (version == FormatSpec.VERSION4) {
dictEncoder = new Ver4DictEncoder(outputFile);
} else {
dictEncoder = new Ver2DictEncoder(outputFile);
}
dictEncoder.writeDictionary(dict, formatOptions);
}
/**
* Write the dictionary in XML format to the specified filename.
*
* @param outputFilename the name of the file to write to.
* @param dict the dictionary to write.
* @throws FileNotFoundException if the output file can't be created.
* @throws IOException if the output file can't be written to.
*/
private static void writeXmlDictionary(final String outputFilename,
final FusionDictionary dict) throws FileNotFoundException, IOException {
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilename))) {
XmlDictInputOutput.writeDictionaryXml(writer, dict);
}
}
/**
* Write the dictionary in the combined format to the specified filename.
*
* @param outputFilename the name of the file to write to.
* @param dict the dictionary to write.
* @throws FileNotFoundException if the output file can't be created.
* @throws IOException if the output file can't be written to.
*/
private static void writeCombinedDictionary(final String outputFilename,
final FusionDictionary dict) throws FileNotFoundException, IOException {
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilename))) {
CombinedInputOutput.writeDictionaryCombined(writer, dict);
}
}
}
| 46.750623 | 100 | 0.624047 |
21d99ea30ca8770b7096f438dcb6a3bef83eafae | 1,530 | package com.xinra.nucleus.interfacegenerator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Generates an interface that contains all public member methods of the annotated class.
* Can only be used on top-level classes.
* See <a href="https://github.com/xinra-nucleus/interface-generator/blob/master/README.md">
* online documentation</a>.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
@Inherited
@Documented
public @interface GenerateInterface {
/**
* Name of the generated interface. If this is not specified, the {@link #namingStrategy()}
* is used to retrieve the interface name.
* If the name is not fully qualified, the interface will be placed in the same package
* as the annotated class.
*/
String value() default "";
/**
* A closure that returns the name of the generated interface as a {@link String}.
* Parameter is a {@link TypeElement} of the annotated type.
*
* @implSpec The default implementation will create the interface {@code IFoo} for the
* annotated class {@code Foo}.
*/
String namingStrategy() default InterfaceNamingStrategy.PREFIX_I;
/**
* If true, for every property {@code fooBar} a constant
* <pre>public static String FooBar = "fooBar";</pre> is generated.
*/
boolean propertyConstants() default false;
}
| 33.26087 | 93 | 0.73268 |
cdeeda0ccb7776f154dbab43eead800c92fb88d6 | 29,084 | /***********************************************************************
* Copyright (c) 2000-2004 The Apache Software Foundation. *
* All rights reserved. *
* ------------------------------------------------------------------- *
* Licensed under the Apache License, Version 2.0 (the "License"); you *
* may not use this file except in compliance with the License. You *
* may obtain a copy of the License at: *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. See the License for the specific language governing *
* permissions and limitations under the License. *
***********************************************************************/
package org.apache.james.smtpserver;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.cornerstone.services.scheduler.PeriodicTimeTrigger;
import org.apache.avalon.cornerstone.services.scheduler.Target;
import org.apache.avalon.cornerstone.services.scheduler.TimeScheduler;
import org.apache.james.*;
import org.apache.james.core.*;
import org.apache.james.services.MailServer;
import org.apache.james.services.UsersRepository;
import org.apache.james.services.UsersStore;
import org.apache.james.util.*;
import org.apache.mailet.*;
import javax.security.sasl.*;
/**
* This handles an individual incoming message. It handles regular SMTP
* commands, and when it receives a message, adds it to the spool.
*
* This is $Revision: 1.1.2.3 $
* Committed on $Date: 2004/03/15 03:54:14 $ by: $Author: noel $
*/
public class SMTPHandler
extends BaseConnectionHandler
implements ConnectionHandler, Composable, Configurable, Target {
public final static String SERVER_NAME = "SERVER_NAME";
public final static String SERVER_TYPE = "SERVER_TYPE";
public final static String REMOTE_NAME = "REMOTE_NAME";
public final static String REMOTE_IP = "REMOTE_IP";
public final static String NAME_GIVEN = "NAME_GIVEN";
public final static String CURRENT_HELO_MODE = "CURRENT_HELO_MODE";
public final static String SENDER = "SENDER_ADDRESS";
public final static String MESG_FAILED = "MESG_FAILED";
public final static String RCPT_VECTOR = "RCPT_VECTOR";
public final static String SMTP_ID = "SMTP_ID";
public final static String AUTH = "AUTHENTICATED";
public final static char[] SMTPTerminator = {'\r','\n','.','\r','\n'};
private final static boolean DEEP_DEBUG = true;
private Socket socket;
private DataInputStream in;
private PrintWriter out;
private String remoteHost;
private String remoteHostGiven;
private String remoteIP;
private String messageID;
private String smtpID;
private boolean authRequired = false;
private boolean verifyIdentity = false;
private TimeScheduler scheduler;
private UsersRepository users;
private MailServer mailServer;
private String softwaretype = "JAMES SMTP Server "
+ Constants.SOFTWARE_VERSION;
private static long count;
private HashMap state = new HashMap();
private Random random = new Random();
private long maxmessagesize = 0;
private static SaslServerFactory serverFactory = new cryptix.sasl.ServerFactory();
public void configure ( Configuration configuration )
throws ConfigurationException {
super.configure(configuration);
authRequired
= configuration.getChild("authRequired").getValueAsBoolean(true);
verifyIdentity
= configuration.getChild("verifyIdentity").getValueAsBoolean(false);
// get the message size limit from the conf file and multiply
// by 1024, to put it in bytes
maxmessagesize =
configuration.getChild( "maxmessagesize" ).getValueAsLong( 0 ) * 1024;
if (DEEP_DEBUG) {
getLogger().debug("Max message size is: " + maxmessagesize);
}
Sasl.setSaslServerFactory(serverFactory);
}
public void compose( final ComponentManager componentManager )
throws ComponentException {
mailServer = (MailServer)componentManager.lookup(
"org.apache.james.services.MailServer");
scheduler = (TimeScheduler)componentManager.lookup(
"org.apache.avalon.cornerstone.services.scheduler.TimeScheduler");
UsersStore usersStore = (UsersStore)componentManager.lookup(
"org.apache.james.services.UsersStore" );
users = usersStore.getRepository("LocalUsers");
}
/**
* Handle a connection.
* This handler is responsible for processing connections as they occur.
*
* @param connection the connection
* @exception IOException if an error reading from socket occurs
* @exception ProtocolException if an error handling connection occurs
*/
public void handleConnection( Socket connection )
throws IOException {
try {
this.socket = connection;
final InputStream bufferedInput =
new BufferedInputStream( socket.getInputStream(), 1024 );
in = new DataInputStream( bufferedInput );
out = new InternetPrintWriter(socket.getOutputStream(), true);
remoteHost = socket.getInetAddress ().getHostName ();
remoteIP = socket.getInetAddress ().getHostAddress ();
smtpID = Math.abs(random.nextInt() % 1024) + "";
resetState();
} catch (Exception e) {
getLogger().error("Cannot open connection from " + remoteHost
+ " (" + remoteIP + "): " + e.getMessage(), e );
throw new RuntimeException("Cannot open connection from "
+ remoteHost + " (" + remoteIP + "): " + e.getMessage());
}
getLogger().info("Connection from " + remoteHost + " ("
+ remoteIP + ")");
try {
// Initially greet the connector
// Format is: Sat, 24 Jan 1998 13:16:09 -0500
final PeriodicTimeTrigger trigger
= new PeriodicTimeTrigger( timeout, -1 );
scheduler.addTrigger( this.toString(), trigger, this );
out.println("220 " + this.helloName + " SMTP Server ("
+ softwaretype + ") ready "
+ RFC822DateFormat.toString(new Date()));
while (parseCommand(in.readLine())) {
scheduler.resetTrigger(this.toString());
}
socket.close();
scheduler.removeTrigger(this.toString());
} catch (SocketException se) {
getLogger().debug("Socket to " + remoteHost
+ " closed remotely.", se );
} catch ( InterruptedIOException iioe ) {
getLogger().debug( "Socket to " + remoteHost + " timeout.", iioe );
} catch ( IOException ioe ) {
getLogger().debug( "Exception handling socket to " + remoteHost
+ ":" + ioe.getMessage(), ioe );
} catch (Exception e) {
getLogger().debug( "Exception opening socket: "
+ e.getMessage(), e );
} finally {
try {
socket.close();
} catch (IOException e) {
getLogger().error("Exception closing socket: "
+ e.getMessage());
}
}
}
public void targetTriggered( final String triggerName ) {
getLogger().error("Connection timeout on socket");
try {
out.println("Connection timeout. Closing connection");
socket.close();
} catch (IOException e) {
}
}
private void resetState() {
state.clear();
state.put(SERVER_NAME, this.helloName );
state.put(SERVER_TYPE, this.softwaretype );
state.put(REMOTE_NAME, remoteHost);
state.put(REMOTE_IP, remoteIP);
state.put(SMTP_ID, smtpID);
}
private boolean parseCommand(String command)
throws Exception {
if (command == null) return false;
if (state.get(MESG_FAILED) == null) {
getLogger().info("Command received: " + command);
}
StringTokenizer commandLine
= new StringTokenizer(command.trim(), " :");
int arguments = commandLine.countTokens();
if (arguments == 0) {
return true;
} else if(arguments > 0) {
command = commandLine.nextToken();
}
String argument = (String) null;
if(arguments > 1) {
argument = commandLine.nextToken();
}
String argument1 = (String) null;
if(arguments > 2) {
argument1 = commandLine.nextToken();
}
if (command.equalsIgnoreCase("HELO"))
doHELO(command,argument,argument1);
else if (command.equalsIgnoreCase("EHLO"))
doEHLO(command,argument,argument1);
else if (command.equalsIgnoreCase("AUTH"))
doAUTH(command,argument,argument1);
else if (command.equalsIgnoreCase("MAIL"))
doMAIL(command,argument,argument1);
else if (command.equalsIgnoreCase("RCPT"))
doRCPT(command,argument,argument1);
else if (command.equalsIgnoreCase("NOOP"))
doNOOP(command,argument,argument1);
else if (command.equalsIgnoreCase("RSET"))
doRSET(command,argument,argument1);
else if (command.equalsIgnoreCase("DATA"))
doDATA(command,argument,argument1);
else if (command.equalsIgnoreCase("QUIT"))
doQUIT(command,argument,argument1);
else
doUnknownCmd(command,argument,argument1);
return (command.equalsIgnoreCase("QUIT") == false);
}
private void doHELO(String command,String argument,String argument1) {
if (state.containsKey(CURRENT_HELO_MODE)) {
out.println("250 " + state.get(SERVER_NAME)
+ " Duplicate HELO");
} else if (argument == null) {
out.println("501 domain address required: " + command);
} else {
state.put(CURRENT_HELO_MODE, command);
state.put(NAME_GIVEN, argument);
out.println( "250 " + state.get(SERVER_NAME) + " Hello "
+ argument + " (" + state.get(REMOTE_NAME)
+ " [" + state.get(REMOTE_IP) + "])");
}
}
private void doEHLO(String command,String argument,String argument1) {
if (state.containsKey(CURRENT_HELO_MODE)) {
out.println("250 " + state.get(SERVER_NAME)
+ " Duplicate EHLO");
} else if (argument == null) {
out.println("501 domain address required: " + command);
} else {
state.put(CURRENT_HELO_MODE, command);
state.put(NAME_GIVEN, argument);
if (authRequired) {
out.println("250-AUTH "+getAuthString());
}
if (maxmessagesize > 0) {
out.println("250-SIZE " + maxmessagesize);
}
out.println( "250 " + state.get(SERVER_NAME) + " Hello "
+ argument + " (" + state.get(REMOTE_NAME)
+ " [" + state.get(REMOTE_IP) + "])");
}
}
private String getAuthString() {
StringBuffer authString = new StringBuffer("LOGIN ");
String[] mechanisms = serverFactory.getMechanismNames(null);
if (mechanisms.length > 0) {
authString.append(mechanisms[0]);
for (int i=1;i<mechanisms.length;i++) {
authString.append(" "+mechanisms[i]);
}
}
return authString.toString();
}
private void doAUTH(String command,String argument,String argument1)
throws Exception {
String[] mechanisms = serverFactory.getMechanismNames(null);
if (state.containsKey(AUTH)) {
out.println("503 User has previously authenticated."
+ " Further authentication is not required!");
return;
} else if (argument == null) {
out.println("501 Usage: AUTH <"+getAuthString()+
"> [<initial response>]");
return;
// } else if (argument.equalsIgnoreCase("PLAIN")) {
// String userpass, user, pass;
// StringTokenizer authTokenizer;
// if (argument1 == null) {
// out.println("334 OK. Continue authentication");
// userpass = in.readLine().trim();
// } else
// userpass = argument1.trim();
// authTokenizer = new StringTokenizer(
// Base64.decodeAsString(userpass), "\0");
// user = authTokenizer.nextToken();
// pass = authTokenizer.nextToken();
// // Authenticate user
// if (users.test(user, pass)) {
// state.put(AUTH, user);
// out.println("235 Authentication Successful");
// getLogger().info("AUTH method PLAIN succeeded");
// } else {
// out.println("535 Authentication Failed");
// getLogger().error("AUTH method PLAIN failed");
// }
// return;
} else if (argument.equalsIgnoreCase("LOGIN")) {
String user, pass;
if (argument1 == null) {
out.println("334 VXNlcm5hbWU6"); // base64 encoded "Username:"
user = in.readLine().trim();
} else
user = argument1.trim();
user = Base64.decodeAsString(user);
out.println("334 UGFzc3dvcmQ6"); // base64 encoded "Password:"
pass = Base64.decodeAsString(in.readLine().trim());
//Authenticate user
if (users.test(user, pass)) {
state.put(AUTH, user);
out.println("235 Authentication Successful");
getLogger().info("AUTH method LOGIN succeeded");
} else {
out.println("535 Authentication Failed");
getLogger().error("AUTH method LOGIN failed");
}
return;
}
for (int i=0;i<mechanisms.length;i++) {
if (argument.equalsIgnoreCase(mechanisms[i])) {
java.util.Hashtable properties = new java.util.Hashtable();
properties.put("cryptix.sasl.srp.password.file","/tmp/cryptix-sasl/etc/tpasswd");
properties.put("cryptix.sasl.plain.password.file","/tmp/cryptix-sasl/etc/passwd");
SaslServer server =
Sasl.createSaslServer(mechanisms[i],
"SMTP",
(String)state.get(SERVER_NAME),
properties,
null);
SaslProfile profile = new SaslProfile(server, in, out);
if (profile.doAUTH(argument1)) {
state.put(AUTH, server.getAuthorizationID());
out.println("235 Authentication Successful");
getLogger().info("AUTH method "+mechanisms[i]+" succeeded");
} else {
out.println("535 Authentication Failed");
getLogger().error("AUTH method "+mechanisms[i]+" failed");
}
return;
}
}
out.println("504 Unrecognized Authentication Type");
getLogger().error("AUTH method " + argument
+ " is an unrecognized authentication type");
return;
}
private void doMAIL(String command,String argument,String argument1) {
if (state.containsKey(SENDER)) {
out.println("503 Sender already specified");
} else if (argument == null || !argument.equalsIgnoreCase("FROM")
|| argument1 == null) {
out.println("501 Usage: MAIL FROM:<sender>");
} else {
String sender = argument1.trim();
if (!sender.startsWith("<") || !sender.endsWith(">")) {
out.println("501 Syntax error in parameters or arguments");
getLogger().error("Error parsing sender address: " + sender
+ ": did not start and end with < >");
return;
}
MailAddress senderAddress = null;
//Remove < and >
sender = sender.substring(1, sender.length() - 1);
if (sender.length() == 0) {
//This is the <> case. Let senderAddress == null
} else {
try {
senderAddress = new MailAddress(sender);
} catch (Exception pe) {
out.println("501 Syntax error in parameters or arguments");
getLogger().error("Error parsing sender address: " + sender
+ ": " + pe.getMessage());
return;
}
}
state.put(SENDER, senderAddress);
out.println("250 Sender <" + sender + "> OK");
}
}
private void doRCPT(String command,String argument,String argument1) {
if (!state.containsKey(SENDER)) {
out.println("503 Need MAIL before RCPT");
} else if (argument == null || !argument.equalsIgnoreCase("TO")
|| argument1 == null) {
out.println("501 Usage: RCPT TO:<recipient>");
} else {
Collection rcptColl = (Collection) state.get(RCPT_VECTOR);
if (rcptColl == null) {
rcptColl = new Vector();
}
String recipient = argument1.trim();
if (!recipient.startsWith("<") || !recipient.endsWith(">")) {
out.println("Syntax error in parameters or arguments");
getLogger().error("Error parsing recipient address: "
+ recipient
+ ": did not start and end with < >");
return;
}
MailAddress recipientAddress = null;
//Remove < and >
recipient = recipient.substring(1, recipient.length() - 1);
try {
recipientAddress = new MailAddress(recipient);
} catch (Exception pe) {
out.println("501 Syntax error in parameters or arguments");
getLogger().error("Error parsing recipient address: "
+ recipient + ": " + pe.getMessage());
return;
}
// If this is a delivery failure notification (MAIL FROM: <>)
// we don't enforce authentication
if (authRequired && state.get(SENDER) != null) {
// Make sure the mail is being sent locally if not
// authenticated else reject.
if (!state.containsKey(AUTH)) {
String toDomain = recipientAddress.getHost();
if (!mailServer.isLocalServer(toDomain)) {
out.println("530 Authentication Required");
getLogger().error(
"Authentication is required for mail request");
return;
}
} else {
// Identity verification checking
if (verifyIdentity) {
String authUser = (String)state.get(AUTH);
MailAddress senderAddress
= (MailAddress)state.get(SENDER);
boolean domainExists = false;
if (!authUser.equalsIgnoreCase(
senderAddress.getUser())) {
out.println("503 Incorrect Authentication for Specified Email Address");
getLogger().error("User " + authUser
+ " authenticated, however tried sending email as "
+ senderAddress);
return;
}
if (!mailServer.isLocalServer(
senderAddress.getHost())) {
out.println("503 Incorrect Authentication for Specified Email Address");
getLogger().error("User " + authUser
+ " authenticated, however tried sending email as "
+ senderAddress);
return;
}
}
}
}
rcptColl.add(recipientAddress);
state.put(RCPT_VECTOR, rcptColl);
out.println("250 Recipient <" + recipient + "> OK");
}
}
private void doNOOP(String command,String argument,String argument1) {
out.println("250 OK");
}
private void doRSET(String command,String argument,String argument1) {
resetState();
out.println("250 OK");
}
private void doDATA(String command,String argument,String argument1) {
if (!state.containsKey(SENDER)) {
out.println("503 No sender specified");
} else if (!state.containsKey(RCPT_VECTOR)) {
out.println("503 No recipients specified");
} else {
out.println("354 Ok Send data ending with <CRLF>.<CRLF>");
try {
// parse headers
InputStream msgIn
= new CharTerminatedInputStream(in, SMTPTerminator);
// if the message size limit has been set, we'll
// wrap msgIn with a SizeLimitedInputStream
if (maxmessagesize > 0) {
if (DEEP_DEBUG) {
getLogger().debug("Using SizeLimitedInputStream "
+ " with max message size: "
+ maxmessagesize);
}
msgIn = new SizeLimitedInputStream(msgIn, maxmessagesize);
}
//Removes the dot stuffing
msgIn = new SMTPInputStream(msgIn);
//Parse out the message headers
MailHeaders headers = new MailHeaders(msgIn);
// if headers do not contains minimum REQUIRED headers fields,
// add them
if (!headers.isSet("Date")) {
headers.setHeader("Date",
RFC822DateFormat.toString(new Date()));
}
if (!headers.isSet("From") && state.get(SENDER) != null) {
headers.setHeader("From", state.get(SENDER).toString());
}
//Determine the Return-Path
String returnPath = headers.getHeader("Return-Path", "\r\n");
headers.removeHeader("Return-Path");
if (returnPath == null) {
if (state.get(SENDER) == null) {
returnPath = "<>";
} else {
returnPath = "<" + state.get(SENDER) + ">";
}
}
//We will rebuild the header object to put Return-Path and our
// Received message at the top
Enumeration headerLines = headers.getAllHeaderLines();
headers = new MailHeaders();
//Put the Return-Path first
headers.addHeaderLine("Return-Path: " + returnPath);
//Put our Received header next
headers.addHeaderLine("Received: from " + state.get(REMOTE_NAME)
+ " ([" + state.get(REMOTE_IP) + "])");
String temp = " by " + this.helloName + " ("
+ softwaretype + ") with SMTP ID " + state.get(SMTP_ID);
if (((Collection)state.get(RCPT_VECTOR)).size() == 1) {
//Only indicate a recipient if they're the only recipient
//(prevents email address harvesting and large headers in
// bulk email)
headers.addHeaderLine(temp);
headers.addHeaderLine(" for <"
+ ((Vector)state.get(RCPT_VECTOR)).get(0).toString()
+ ">;");
} else {
//Put the ; on the end of the 'by' line
headers.addHeaderLine(temp + ";");
}
headers.addHeaderLine(" "
+ RFC822DateFormat.toString(new Date()));
//Add all the original message headers back in next
while (headerLines.hasMoreElements()) {
headers.addHeaderLine((String)headerLines.nextElement());
}
ByteArrayInputStream headersIn
= new ByteArrayInputStream(headers.toByteArray());
MailImpl mail = new MailImpl(mailServer.getId(),
(MailAddress)state.get(SENDER),
(Vector)state.get(RCPT_VECTOR),
new SequenceInputStream(headersIn, msgIn));
// if the message size limit has been set, we'll
// call mail.getSize() to force the message to be
// loaded. Need to do this to limit the size
if (maxmessagesize > 0) {
mail.getSize();
}
mail.setRemoteHost((String)state.get(REMOTE_NAME));
mail.setRemoteAddr((String)state.get(REMOTE_IP));
mailServer.sendMail(mail);
} catch (MessagingException me) {
//Grab any exception attached to this one.
Exception e = me.getNextException();
//If there was an attached exception, and it's a
//MessageSizeException
if (e != null && e instanceof MessageSizeException) {
getLogger().error("552 Error processing message: "
+ e.getMessage());
// Add an item to the state to suppress
// logging of extra lines of data
// that are sent after the size limit has
// been hit.
state.put(MESG_FAILED, Boolean.TRUE);
//then let the client know that the size
//limit has been hit.
out.println("552 Error processing message: "
+ e.getMessage());
} else {
out.println("451 Error processing message: "
+ me.getMessage());
getLogger().error("Error processing message: "
+ me.getMessage());
me.printStackTrace();
}
return;
}
getLogger().info("Mail sent to Mail Server");
resetState();
out.println("250 Message received");
}
}
private void doQUIT(String command,String argument,String argument1) {
out.println("221 " + state.get(SERVER_NAME)
+ " Service closing transmission channel");
}
private void doUnknownCmd(String command,String argument,
String argument1) {
if (state.get(MESG_FAILED) == null) {
out.println("500 " + state.get(SERVER_NAME)
+ " Syntax error, command unrecognized: " + command);
}
}
}
| 43.933535 | 98 | 0.532423 |
676f77f9c927634cbbbcf86d8ce1e7d398af2cd6 | 1,045 | package org.openapitools.api;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import io.swagger.annotations.*;
import java.io.InputStream;
import java.util.Map;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;
@Path("/.cqactions.html")
@Api(description = "the .cqactions.html API")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2021-09-03T15:26:06.461+10:00[Australia/Melbourne]")public class CqactionsHtmlApi {
@POST
@ApiOperation(value = "", notes = "", response = Void.class, authorizations = {
@Authorization(value = "aemAuth")
}, tags={ "cq" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Default response", response = Void.class)
})
public Response postCqActions(@QueryParam("authorizableId") @NotNull String authorizableId,@QueryParam("changelog") @NotNull String changelog) {
return Response.ok().entity("magic!").build();
}
}
| 33.709677 | 192 | 0.697608 |
2fa633374595cd44d96d3fed3c0eca9a01dff166 | 31,569 | /*
* Copyright (c) 2008-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cometd.server;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Promise;
import org.cometd.bayeux.Session;
import org.cometd.bayeux.server.LocalSession;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.bayeux.server.ServerTransport;
import org.cometd.common.AsyncFoldLeft;
import org.cometd.common.HashMapMessage;
import org.cometd.server.AbstractServerTransport.Scheduler;
import org.cometd.server.transport.AbstractHttpTransport;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServerSessionImpl implements ServerSession, Dumpable {
private static final AtomicLong _idCount = new AtomicLong();
private static final Logger _logger = LoggerFactory.getLogger(ServerSession.class);
private final BayeuxServerImpl _bayeux;
private final String _id;
private final List<ServerSessionListener> _listeners = new CopyOnWriteArrayList<>();
private final List<Extension> _extensions = new CopyOnWriteArrayList<>();
private final Queue<ServerMessage> _queue = new ArrayDeque<>();
private final LocalSessionImpl _localSession;
private final AttributesMap _attributes = new AttributesMap();
private final Set<ServerChannelImpl> subscriptions = Collections.newSetFromMap(new ConcurrentHashMap<>());
private final LazyTask _lazyTask = new LazyTask();
private AbstractServerTransport.Scheduler _scheduler;
private ServerTransport _transport;
private ServerTransport _advisedTransport;
private State _state = State.NEW;
private int _maxQueue = -1;
private long _transientTimeout = -1;
private long _transientInterval = -1;
private long _timeout = -1;
private long _interval = -1;
private long _maxInterval = -1;
private long _maxProcessing = -1;
private long _maxLazy = -1;
private boolean _metaConnectDelivery;
private int _batch;
private String _userAgent;
private long _messageTime;
private long _scheduleTime;
private long _expireTime;
private boolean _nonLazyMessages;
private boolean _broadcastToPublisher;
private boolean _allowMessageDeliveryDuringHandshake;
private String _browserId;
public ServerSessionImpl(BayeuxServerImpl bayeux) {
this(bayeux, null, null);
}
public ServerSessionImpl(BayeuxServerImpl bayeux, LocalSessionImpl localSession, String idHint) {
_bayeux = bayeux;
_localSession = localSession;
StringBuilder id = new StringBuilder(30);
int len = 20;
if (idHint != null) {
len += idHint.length() + 1;
id.append(idHint);
id.append('_');
}
int index = id.length();
while (id.length() < len) {
id.append(Long.toString(_bayeux.randomLong(), 36));
}
id.insert(index, Long.toString(_idCount.incrementAndGet(), 36));
_id = id.toString();
_broadcastToPublisher = _bayeux.isBroadcastToPublisher();
}
public BayeuxServerImpl getBayeuxServer() {
return _bayeux;
}
/**
* @return the remote user agent
*/
@Override
public String getUserAgent() {
return _userAgent;
}
/**
* @param userAgent the remote user agent
*/
public void setUserAgent(String userAgent) {
_userAgent = userAgent;
}
/**
* @return the remote client identifier
*/
public String getBrowserId() {
return _browserId;
}
/**
* <p>Sets a remote client identifier, typically a browser.</p>
*
* @param browserId the remote client identifier
*/
public void setBrowserId(String browserId) {
_browserId = browserId;
}
protected void sweep(long now) {
if (isLocalSession()) {
return;
}
boolean remove = false;
Scheduler scheduler = null;
synchronized (getLock()) {
if (_expireTime == 0) {
if (_maxProcessing > 0 && now > _messageTime + _maxProcessing) {
_logger.info("Sweeping session during processing {}", this);
remove = true;
}
} else {
if (now > _expireTime) {
if (_logger.isDebugEnabled()) {
_logger.debug("Sweeping session {}", this);
}
remove = true;
}
}
if (remove) {
scheduler = _scheduler;
}
}
if (remove) {
if (scheduler != null) {
scheduler.destroy();
}
_bayeux.removeServerSession(this, true);
}
}
@Override
public Set<ServerChannel> getSubscriptions() {
return Collections.unmodifiableSet(subscriptions);
}
@Override
public void addExtension(Extension extension) {
_extensions.add(extension);
}
@Override
public void removeExtension(Extension extension) {
_extensions.remove(extension);
}
@Override
public List<Extension> getExtensions() {
return Collections.unmodifiableList(_extensions);
}
@Override
public void batch(Runnable batch) {
startBatch();
try {
batch.run();
} finally {
endBatch();
}
}
@Override
public void deliver(Session sender, ServerMessage.Mutable message, Promise<Boolean> promise) {
ServerSession session = null;
if (sender instanceof ServerSession) {
session = (ServerSession)sender;
} else if (sender instanceof LocalSession) {
session = ((LocalSession)sender).getServerSession();
}
ServerSession serverSession = session;
_bayeux.extendOutgoing(session, this, message, Promise.from(b -> {
if (b) {
deliver1(serverSession, message, promise);
} else {
promise.succeed(false);
}
}, promise::fail));
}
@Override
public void deliver(Session sender, String channelId, Object data, Promise<Boolean> promise) {
ServerMessage.Mutable message = _bayeux.newMessage();
message.setChannel(channelId);
message.setData(data);
deliver(sender, message, promise);
}
protected void deliver1(ServerSession sender, ServerMessage.Mutable mutable, Promise<Boolean> promise) {
if (sender == this && !isBroadcastToPublisher()) {
promise.succeed(false);
} else {
extendOutgoing(mutable, Promise.from(message -> {
if (message == null) {
promise.succeed(false);
} else {
_bayeux.freeze(message);
AsyncFoldLeft.run(_listeners, true, (result, listener, loop) -> {
if (listener instanceof MessageListener) {
notifyOnMessage((MessageListener)listener, sender, message, _bayeux.resolveLoop(loop));
} else {
loop.proceed(result);
}
}, Promise.from(b -> {
if (b) {
deliver2(sender, message, promise);
} else {
promise.succeed(false);
}
}, promise::fail));
}
}, promise::fail));
}
}
private void deliver2(ServerSession sender, ServerMessage.Mutable message, Promise<Boolean> promise) {
Boolean wakeup = enqueueMessage(sender, message);
if (wakeup == null) {
promise.succeed(false);
} else {
if (wakeup) {
if (message.isLazy()) {
flushLazy(message);
} else {
flush();
}
}
promise.succeed(true);
}
}
private Boolean enqueueMessage(ServerSession sender, ServerMessage.Mutable message) {
synchronized (getLock()) {
for (ServerSessionListener listener : _listeners) {
if (listener instanceof MaxQueueListener) {
final int maxQueueSize = _maxQueue;
if (maxQueueSize > 0 && _queue.size() >= maxQueueSize) {
if (!notifyQueueMaxed((MaxQueueListener)listener, this, _queue, sender, message)) {
return null;
}
}
}
}
addMessage(message);
for (ServerSessionListener listener : _listeners) {
if (listener instanceof QueueListener) {
notifyQueued((QueueListener)listener, sender, message);
}
}
return _batch == 0;
}
}
protected void extendOutgoing(ServerMessage.Mutable message, Promise<ServerMessage.Mutable> promise) {
List<Extension> extensions = new ArrayList<>(_extensions);
Collections.reverse(extensions);
AsyncFoldLeft.run(extensions, message, (result, extension, loop) -> {
try {
extension.outgoing(this, result, Promise.from(m -> {
if (m != null) {
loop.proceed(m);
} else {
loop.leave(null);
}
}, failure -> {
_logger.info("Exception reported by extension " + extension, failure);
loop.proceed(result);
}));
} catch (Exception x) {
_logger.info("Exception thrown by extension " + extension, x);
loop.proceed(result);
}
}, promise);
}
private boolean notifyQueueMaxed(MaxQueueListener listener, ServerSession session, Queue<ServerMessage> queue, ServerSession sender, ServerMessage message) {
try {
return listener.queueMaxed(session, queue, sender, message);
} catch (Throwable x) {
_logger.info("Exception while invoking listener " + listener, x);
return true;
}
}
private void notifyOnMessage(MessageListener listener, ServerSession sender, ServerMessage message, Promise<Boolean> promise) {
try {
listener.onMessage(this, sender, message, Promise.from(promise::succeed, failure -> {
_logger.info("Exception reported by listener " + listener, failure);
promise.succeed(true);
}));
} catch (Throwable x) {
_logger.info("Exception thrown by listener " + listener, x);
promise.succeed(true);
}
}
private void notifyQueued(QueueListener listener, ServerSession session, ServerMessage message) {
try {
listener.queued(session, message);
} catch (Throwable x) {
_logger.info("Exception while invoking listener " + listener, x);
}
}
protected boolean handshake(ServerMessage.Mutable message) {
AbstractServerTransport transport = message == null ? null : (AbstractServerTransport)message.getServerTransport();
if (transport != null) {
_maxQueue = transport.getOption(AbstractServerTransport.MAX_QUEUE_OPTION, -1);
_maxInterval = transport.getMaxInterval();
_maxProcessing = transport.getOption(AbstractServerTransport.MAX_PROCESSING_OPTION, -1);
_maxLazy = transport.getMaxLazyTimeout();
}
synchronized (getLock()) {
if (_state == State.NEW) {
_state = State.HANDSHAKEN;
return true;
}
return false;
}
}
protected boolean connected() {
synchronized (getLock()) {
if (_state == State.HANDSHAKEN || _state == State.CONNECTED) {
_state = State.CONNECTED;
return true;
}
return false;
}
}
@Override
public void disconnect() {
boolean connected = _bayeux.removeServerSession(this, false);
if (connected) {
ServerMessage.Mutable message = _bayeux.newMessage();
message.setSuccessful(true);
message.setChannel(Channel.META_DISCONNECT);
deliver(this, message, new Promise<Boolean>() {
@Override
public void succeed(Boolean result) {
flush();
}
});
}
}
@Override
public void startBatch() {
synchronized (getLock()) {
++_batch;
}
}
@Override
public boolean endBatch() {
boolean result = false;
synchronized (getLock()) {
if (--_batch == 0 && _nonLazyMessages) {
result = true;
}
}
if (result) {
flush();
}
return result;
}
@Override
public LocalSession getLocalSession() {
return _localSession;
}
@Override
public boolean isLocalSession() {
return _localSession != null;
}
@Override
public void addListener(ServerSessionListener listener) {
_listeners.add(listener);
}
@Override
public String getId() {
return _id;
}
public Object getLock() {
return this;
}
public Queue<ServerMessage> getQueue() {
return _queue;
}
public boolean hasNonLazyMessages() {
synchronized (getLock()) {
return _nonLazyMessages;
}
}
protected void addMessage(ServerMessage message) {
synchronized (getLock()) {
_queue.add(message);
_nonLazyMessages |= !message.isLazy();
}
}
public List<ServerMessage> takeQueue(List<ServerMessage.Mutable> replies) {
List<ServerMessage> copy = Collections.emptyList();
synchronized (getLock()) {
// Always call listeners, even if the queue is
// empty since they may add messages to the queue.
for (ServerSessionListener listener : _listeners) {
if (listener instanceof DeQueueListener) {
notifyDeQueue((DeQueueListener)listener, this, _queue, replies);
}
}
int size = _queue.size();
if (size > 0) {
copy = new ArrayList<>(size);
copy.addAll(_queue);
_queue.clear();
}
_nonLazyMessages = false;
}
return copy;
}
private void notifyDeQueue(DeQueueListener listener, ServerSession serverSession, Queue<ServerMessage> queue, List<ServerMessage.Mutable> replies) {
try {
listener.deQueue(serverSession, queue, replies);
} catch (Throwable x) {
_logger.info("Exception while invoking listener " + listener, x);
}
}
public void notifySuspended(ServerMessage message, long timeout) {
for (ServerSessionListener listener : _listeners) {
if (listener instanceof ServerSession.HeartBeatListener) {
((HeartBeatListener)listener).onSuspended(this, message, timeout);
}
}
}
public void notifyResumed(ServerMessage message, boolean timeout) {
for (ServerSessionListener listener : _listeners) {
if (listener instanceof ServerSession.HeartBeatListener) {
((HeartBeatListener)listener).onResumed(this, message, timeout);
}
}
}
@Override
public void removeListener(ServerSessionListener listener) {
_listeners.remove(listener);
}
public List<ServerSessionListener> getListeners() {
return Collections.unmodifiableList(_listeners);
}
public void setScheduler(AbstractServerTransport.Scheduler newScheduler) {
if (newScheduler == null) {
Scheduler oldScheduler;
synchronized (getLock()) {
oldScheduler = _scheduler;
if (oldScheduler != null) {
_scheduler = null;
}
}
if (oldScheduler != null) {
oldScheduler.cancel();
}
} else {
Scheduler oldScheduler;
boolean schedule = false;
synchronized (getLock()) {
oldScheduler = _scheduler;
_scheduler = newScheduler;
if (shouldSchedule()) {
schedule = true;
if (newScheduler instanceof AbstractHttpTransport.HttpScheduler) {
_scheduler = null;
}
}
}
if (oldScheduler != null && oldScheduler != newScheduler) {
oldScheduler.cancel();
}
if (schedule) {
newScheduler.schedule();
}
}
}
public boolean shouldSchedule() {
synchronized (getLock()) {
return hasNonLazyMessages() && _batch == 0;
}
}
public void flush() {
Scheduler scheduler;
synchronized (getLock()) {
_lazyTask.cancel();
scheduler = _scheduler;
if (scheduler != null) {
if (scheduler instanceof AbstractHttpTransport.HttpScheduler) {
_scheduler = null;
}
}
}
if (scheduler != null) {
scheduler.schedule();
// If there is a scheduler, then it's a remote session
// and we should not do local delivery, so we return.
return;
}
// Local delivery.
if (_localSession != null && hasNonLazyMessages()) {
for (ServerMessage msg : takeQueue(Collections.emptyList())) {
_localSession.receive(new HashMapMessage(msg), Promise.noop());
}
}
}
private void flushLazy(ServerMessage message) {
synchronized (getLock()) {
ServerChannel channel = _bayeux.getChannel(message.getChannel());
long lazyTimeout = -1;
if (channel != null) {
lazyTimeout = channel.getLazyTimeout();
}
if (lazyTimeout <= 0) {
lazyTimeout = _maxLazy;
}
if (lazyTimeout <= 0) {
flush();
} else {
_lazyTask.schedule(lazyTimeout);
}
}
}
public void destroyScheduler() {
Scheduler scheduler;
synchronized (getLock()) {
scheduler = _scheduler;
if (scheduler != null) {
_scheduler = null;
}
}
if (scheduler != null) {
scheduler.destroy();
}
}
public void cancelExpiration(boolean metaConnect) {
long now = System.currentTimeMillis();
synchronized (getLock()) {
_messageTime = now;
if (metaConnect) {
_expireTime = 0;
} else if (_expireTime != 0) {
_expireTime += now - _scheduleTime;
}
}
if (_logger.isDebugEnabled()) {
_logger.debug("{} expiration for {}", metaConnect ? "Cancelling" : "Delaying", this);
}
}
public void scheduleExpiration(long defaultInterval) {
long interval = calculateInterval(defaultInterval);
long now = System.currentTimeMillis();
synchronized (getLock()) {
_scheduleTime = now;
_expireTime = now + interval + _maxInterval;
}
if (_logger.isDebugEnabled()) {
_logger.debug("Scheduled expiration for {}", this);
}
}
protected long getMaxInterval() {
return _maxInterval;
}
long getIntervalTimestamp() {
return _expireTime;
}
@Override
public Object getAttribute(String name) {
return _attributes.getAttribute(name);
}
@Override
public Set<String> getAttributeNames() {
return _attributes.getAttributeNameSet();
}
@Override
public Object removeAttribute(String name) {
Object old = getAttribute(name);
_attributes.removeAttribute(name);
return old;
}
@Override
public void setAttribute(String name, Object value) {
_attributes.setAttribute(name, value);
}
@Override
public boolean isHandshook() {
synchronized (getLock()) {
return _state == State.HANDSHAKEN || _state == State.CONNECTED;
}
}
@Override
public boolean isConnected() {
synchronized (getLock()) {
return _state == State.CONNECTED;
}
}
public boolean isDisconnected() {
synchronized (getLock()) {
return _state == State.DISCONNECTED;
}
}
public boolean isTerminated() {
synchronized (getLock()) {
return _state == State.DISCONNECTED || _state == State.EXPIRED;
}
}
protected void extendIncoming(ServerMessage.Mutable message, Promise<Boolean> promise) {
AsyncFoldLeft.run(_extensions, true, (result, extension, loop) -> {
if (result) {
try {
extension.incoming(this, message, Promise.from(loop::proceed, failure -> {
_logger.info("Exception reported by extension " + extension, failure);
loop.proceed(true);
}));
} catch (Throwable x) {
_logger.info("Exception thrown by extension " + extension, x);
loop.proceed(true);
}
} else {
loop.leave(result);
}
}, promise);
}
public void reAdvise() {
_advisedTransport = null;
}
public Map<String, Object> takeAdvice(ServerTransport transport) {
if (transport != null && transport != _advisedTransport) {
_advisedTransport = transport;
// The timeout is calculated based on the values of the session/transport
// because we want to send to the client the *next* timeout
long timeout = getTimeout() < 0 ? transport.getTimeout() : getTimeout();
// The interval is calculated using also the transient value
// because we want to send to the client the *current* interval
long interval = calculateInterval(transport.getInterval());
Map<String, Object> advice = new HashMap<>(3);
advice.put(Message.RECONNECT_FIELD, Message.RECONNECT_RETRY_VALUE);
advice.put(Message.INTERVAL_FIELD, interval);
advice.put(Message.TIMEOUT_FIELD, timeout);
if (transport instanceof AbstractServerTransport) {
if (((AbstractServerTransport)transport).isHandshakeReconnect()) {
advice.put(Message.MAX_INTERVAL_FIELD, getMaxInterval());
}
}
return advice;
}
// advice has not changed, so return null.
return null;
}
@Override
public ServerTransport getServerTransport() {
return _transport;
}
public void setServerTransport(ServerTransport transport) {
_transport = transport;
}
@Override
public long getTimeout() {
return _timeout;
}
@Override
public long getInterval() {
return _interval;
}
@Override
public void setTimeout(long timeoutMS) {
_timeout = timeoutMS;
_advisedTransport = null;
}
@Override
public void setInterval(long intervalMS) {
_interval = intervalMS;
_advisedTransport = null;
}
public boolean isBroadcastToPublisher() {
return _broadcastToPublisher;
}
public void setBroadcastToPublisher(boolean value) {
_broadcastToPublisher = value;
}
protected void added() {
for (ServerSessionListener listener : _listeners) {
if (listener instanceof AddListener) {
notifyAdded((AddListener)listener, this);
}
}
}
/**
* @param timedOut whether the session has been timed out
* @return True if the session was connected.
*/
protected boolean removed(boolean timedOut) {
boolean result;
synchronized (this) {
result = isHandshook();
_state = timedOut ? State.EXPIRED : State.DISCONNECTED;
}
if (result) {
for (ServerChannelImpl channel : subscriptions) {
channel.unsubscribe(this);
}
for (ServerSessionListener listener : _listeners) {
if (listener instanceof ServerSession.RemoveListener) {
notifyRemoved((RemoveListener)listener, this, timedOut);
}
}
}
return result;
}
private void notifyAdded(AddListener listener, ServerSession serverSession) {
try {
listener.added(serverSession);
} catch (Exception x) {
_logger.info("Exception while invoking listener " + listener, x);
}
}
private void notifyRemoved(RemoveListener listener, ServerSession serverSession, boolean timedout) {
try {
listener.removed(serverSession, timedout);
} catch (Throwable x) {
_logger.info("Exception while invoking listener " + listener, x);
}
}
public void setMetaConnectDeliveryOnly(boolean meta) {
_metaConnectDelivery = meta;
}
public boolean isMetaConnectDeliveryOnly() {
return _metaConnectDelivery;
}
public boolean isAllowMessageDeliveryDuringHandshake() {
return _allowMessageDeliveryDuringHandshake;
}
public void setAllowMessageDeliveryDuringHandshake(boolean allow) {
_allowMessageDeliveryDuringHandshake = allow;
}
protected boolean subscribe(ServerChannelImpl channel) {
synchronized (getLock()) {
if (isTerminated()) {
return false;
} else {
subscriptions.add(channel);
return true;
}
}
}
protected void unsubscribedFrom(ServerChannelImpl channel) {
subscriptions.remove(channel);
}
public long calculateTimeout(long defaultTimeout) {
if (_transientTimeout >= 0) {
return _transientTimeout;
}
if (_timeout >= 0) {
return _timeout;
}
return defaultTimeout;
}
public long calculateInterval(long defaultInterval) {
if (_transientInterval >= 0) {
return _transientInterval;
}
if (_interval >= 0) {
return _interval;
}
return defaultInterval;
}
/**
* Updates the transient timeout with the given value.
* The transient timeout is the one sent by the client, that should
* temporarily override the session/transport timeout, for example
* when the client sends {timeout:0}
*
* @param timeout the value to update the timeout to
* @see #updateTransientInterval(long)
*/
public void updateTransientTimeout(long timeout) {
_transientTimeout = timeout;
}
/**
* Updates the transient interval with the given value.
* The transient interval is the one sent by the client, that should
* temporarily override the session/transport interval, for example
* when the client sends {timeout:0,interval:60000}
*
* @param interval the value to update the interval to
* @see #updateTransientTimeout(long)
*/
public void updateTransientInterval(long interval) {
_transientInterval = interval;
}
@Override
public String dump() {
return ContainerLifeCycle.dump(this);
}
@Override
public void dump(Appendable out, String indent) throws IOException {
ContainerLifeCycle.dumpObject(out, this);
List<Object> children = new ArrayList<>();
children.add(new Dumpable() {
@Override
public String dump() {
return null;
}
@Override
public void dump(Appendable out, String indent) throws IOException {
List<ServerSessionListener> listeners = getListeners();
ContainerLifeCycle.dumpObject(out, "listeners: " + listeners.size());
if (_bayeux.isDetailedDump()) {
ContainerLifeCycle.dump(out, indent, listeners);
}
}
});
ContainerLifeCycle.dump(out, indent, children);
}
@Override
public String toString() {
long last;
long expire;
State state;
long now = System.currentTimeMillis();
synchronized (getLock()) {
last = now - _messageTime;
expire = _expireTime == 0 ? 0 : _expireTime - now;
state = _state;
}
return String.format("%s,%s,last=%d,expire=%d", _id, state, last, expire);
}
private class LazyTask implements Runnable {
private long _execution;
private volatile org.eclipse.jetty.util.thread.Scheduler.Task _task;
@Override
public void run() {
flush();
_execution = 0;
_task = null;
}
public boolean cancel() {
org.eclipse.jetty.util.thread.Scheduler.Task task = _task;
return task != null && task.cancel();
}
public boolean schedule(long lazyTimeout) {
long execution = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(lazyTimeout);
if (_task == null || execution < _execution) {
cancel();
_execution = execution;
_task = _bayeux.schedule(this, lazyTimeout);
return true;
}
return false;
}
}
private enum State {
NEW, HANDSHAKEN, CONNECTED, DISCONNECTED, EXPIRED
}
}
| 31.695783 | 161 | 0.576927 |
af75314e1e9d3a0c7366ba550eafe7131211ab48 | 10,953 | package com.weaver.emobile.gateway.filter;
import static java.util.function.Function.identity;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.filter.factory.rewrite.MessageBodyDecoder;
import org.springframework.cloud.gateway.filter.factory.rewrite.MessageBodyEncoder;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.server.ServerWebExchange;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weaver.emobile.gateway.global.BodyEncryptException;
import com.weaver.emobile.gateway.util.Consts;
import com.weaver.emobile.gateway.util.EncodeUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
@Component
public class ResponseEncryptFilter implements GlobalFilter, Ordered {
private static Logger logger = LoggerFactory.getLogger(ResponseEncryptFilter.class);
private final Map<String, MessageBodyDecoder> messageBodyDecoders;
private final Map<String, MessageBodyEncoder> messageBodyEncoders;
public ResponseEncryptFilter(Set<MessageBodyDecoder> messageBodyDecoders,
Set<MessageBodyEncoder> messageBodyEncoders) {
this.messageBodyDecoders = messageBodyDecoders.stream()
.collect(Collectors.toMap(MessageBodyDecoder::encodingType, identity()));
this.messageBodyEncoders = messageBodyEncoders.stream()
.collect(Collectors.toMap(MessageBodyEncoder::encodingType, identity()));
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange.mutate().response(decorate(exchange)).build());
}
ServerHttpResponse decorate(ServerWebExchange exchange) {
return new ServerHttpResponseDecorator(exchange.getResponse()) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
String originalResponseContentType = exchange
.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
if (StringUtils.isNotBlank(originalResponseContentType) &&
originalResponseContentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, originalResponseContentType);
ClientResponse clientResponse = prepareClientResponse(body, httpHeaders);
Mono modifiedBody = extractBody(exchange, clientResponse, String.class)
.flatMap(originalBody -> {
String newBody = null;
String path = exchange.getRequest().getPath().toString();
if ("/emp/passport/getsetting".equalsIgnoreCase(path)) {
try {
Map<String, Object> encryptOption = new HashMap<String, Object>();
encryptOption.put("keyEncryptType", "RSA");
encryptOption.put("keyEncryptKey", Consts.PUBLIC_KEY);
encryptOption.put("dataEncryptType", "AES");
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> returnValue = mapper.readValue(originalBody, Map.class);
returnValue.put("encryptOption", encryptOption);
newBody = mapper.writeValueAsString(returnValue);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} else {
String dataEncryptDecryptKey = exchange.getAttribute("Decrypted-Data-Encrypt-Key");
if (StringUtils.isNotBlank(dataEncryptDecryptKey) && StringUtils.isNotBlank(originalBody)) {
try {
newBody = EncodeUtils.aesEncrypt(originalBody, dataEncryptDecryptKey);
} catch (Exception e) {
throw new BodyEncryptException(e);
}
} else{
newBody = originalBody;
}
}
return Mono.just(newBody);
});
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody,
String.class);
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange,
exchange.getResponse().getHeaders());
return bodyInserter.insert(outputMessage, new BodyInserterContext())
.then(Mono.defer(() -> {
Mono<DataBuffer> messageBody = writeBody(getDelegate(),
outputMessage, String.class);
HttpHeaders headers = getDelegate().getHeaders();
if (!headers.containsKey(HttpHeaders.TRANSFER_ENCODING)
|| headers.containsKey(HttpHeaders.CONTENT_LENGTH)) {
messageBody = messageBody.doOnNext(data -> headers
.setContentLength(data.readableByteCount()));
}
// TODO: fail if isStreamingMediaType?
return getDelegate().writeWith(messageBody);
}));
}
return super.writeWith(body);
}
@Override
public Mono<Void> writeAndFlushWith(
Publisher<? extends Publisher<? extends DataBuffer>> body) {
return writeWith(Flux.from(body).flatMapSequential(p -> p));
}
private ClientResponse prepareClientResponse(Publisher<? extends DataBuffer> body,
HttpHeaders httpHeaders) {
ClientResponse.Builder builder;
builder = ClientResponse.create(exchange.getResponse().getStatusCode());
return builder.headers(headers -> headers.putAll(httpHeaders))
.body(Flux.from(body)).build();
}
private <T> Mono<T> extractBody(ServerWebExchange exchange,
ClientResponse clientResponse, Class<T> inClass) {
// if inClass is byte[] then just return body, otherwise check if
// decoding required
if (byte[].class.isAssignableFrom(inClass)) {
return clientResponse.bodyToMono(inClass);
}
List<String> encodingHeaders = exchange.getResponse().getHeaders()
.getOrEmpty(HttpHeaders.CONTENT_ENCODING);
for (String encoding : encodingHeaders) {
MessageBodyDecoder decoder = messageBodyDecoders.get(encoding);
if (decoder != null) {
return clientResponse.bodyToMono(byte[].class)
.publishOn(Schedulers.parallel()).map(decoder::decode)
.map(bytes -> exchange.getResponse().bufferFactory()
.wrap(bytes))
.map(buffer -> prepareClientResponse(Mono.just(buffer),
exchange.getResponse().getHeaders()))
.flatMap(response -> response.bodyToMono(inClass));
}
}
return clientResponse.bodyToMono(inClass);
}
private Mono<DataBuffer> writeBody(ServerHttpResponse httpResponse,
CachedBodyOutputMessage message, Class<?> outClass) {
Mono<DataBuffer> response = DataBufferUtils.join(message.getBody());
if (byte[].class.isAssignableFrom(outClass)) {
return response;
}
List<String> encodingHeaders = httpResponse.getHeaders()
.getOrEmpty(HttpHeaders.CONTENT_ENCODING);
for (String encoding : encodingHeaders) {
MessageBodyEncoder encoder = messageBodyEncoders.get(encoding);
if (encoder != null) {
DataBufferFactory dataBufferFactory = httpResponse.bufferFactory();
response = response.publishOn(Schedulers.parallel()).map(buffer -> {
byte[] encodedResponse = encoder.encode(buffer);
DataBufferUtils.release(buffer);
return encodedResponse;
}).map(dataBufferFactory::wrap);
break;
}
}
return response;
}
};
}
@Override
public int getOrder() {
return -10;
}
}
| 51.665094 | 128 | 0.574454 |
27abd518ef332c9ed5827aa1ed8761f3e4799376 | 8,612 | /*
* Copyright © 2005 - 2021 Schlichtherle IT Services.
* All rights reserved. Use is subject to license terms.
*/
package net.java.truevfs.kernel.impl;
import lombok.Value;
import lombok.val;
import net.java.truecommons.shed.ExceptionHandler;
import net.java.truecommons.shed.HashMaps;
import javax.annotation.WillCloseWhenClosed;
import javax.annotation.WillNotClose;
import javax.annotation.concurrent.ThreadSafe;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* Accounts for {@link java.io.Closeable} resources.
* <p>
* For synchronization, each accountant uses a lock which has to be provided to its constructor.
* In order to start accounting for a closeable resource, call {@link #startAccountingFor(Closeable)}.
* In order to stop accounting for a closeable resource, call {@link #stopAccountingFor(Closeable)}.
* <p>
* Note that you <em>must make sure</em> not to use two instances of this class which share the same lock.
* Otherwise {@link #awaitClosingOfOtherThreadsResources(long)} will not work as designed.
*
* @author Christian Schlichtherle
* @see ResourceController
*/
@ThreadSafe
final class ResourceAccountant implements LockAspect<Lock> {
private final Lock lock;
private final Condition condition;
ResourceAccountant(final Lock lock) {
this.lock = lock;
this.condition = lock.newCondition();
}
/**
* The map of all accounted closeable resources.
* The initial capacity for the hash map accounts for the number of available processors, a 90% blocking factor for
* typical I/O and a 2/3 map resize threshold.
*/
private static final Map<Closeable, Account> accounts;
static {
val threads = Runtime.getRuntime().availableProcessors() * 10;
val initialCapacity = HashMaps.initialCapacity(threads);
accounts = new ConcurrentHashMap<>(initialCapacity, 0.75f, threads);
}
@Value
private static class Account {
Thread owner = Thread.currentThread();
ResourceAccountant accountant;
}
@Value
static class Resources {
int local, total;
boolean needsWaiting;
Resources(final int local, final int total) {
this.local = local;
this.total = total;
needsWaiting = local < total;
}
}
@Override
public Lock lock() {
return lock;
}
/**
* Starts accounting for the given closeable resource.
*
* @param resource the closeable resource to start accounting for.
*/
void startAccountingFor(@WillCloseWhenClosed Closeable resource) {
accounts.put(resource, new Account(this));
}
/**
* Stops accounting for the given closeable resource.
* This method should be called from the implementation of the {@link Closeable#close()} method of the given
* {@link Closeable}.
*
* @param resource the closeable resource to stop accounting for.
*/
void stopAccountingFor(@WillNotClose Closeable resource) {
if (null != accounts.remove(resource)) {
locked(new Op<Object, RuntimeException>() {
@Override
public Object call() {
condition.signalAll();
return null;
}
});
}
}
/**
* Waits until all closeable resources which have been started accounting for by <em>other</em> threads get stopped
* accounting for or a timeout occurs or the current thread gets interrupted, whatever happens first.
* <p>
* Waiting for such resources can get cancelled immediately by interrupting the current thread.
* Unless the number of closeable resources which have been accounted for by <em>all</em> threads is zero, this
* will leave the interrupt status of the current thread cleared.
* If no such foreign resources exist, then interrupting the current thread does not have any effect.
* <p>
* Upon return of this method, threads may immediately start accounting for closeable resources again unless the
* caller has acquired the lock provided to the constructor - use with care!
* <p>
* Note that this method <strong>will not work</strong> if any two instances of this class share the same lock
* provided to their constructor!
*
* @param timeout the number of milliseconds to await the closing of resources which have been accounted for by
* <em>other</em> threads once the lock has been acquired.
* If this is non-positive, then there is no timeout for waiting.
*/
void awaitClosingOfOtherThreadsResources(long timeout) {
locked(new Op<Void, RuntimeException>() {
@Override
public Void call() {
try {
if (0 < timeout) {
long toWait = TimeUnit.MILLISECONDS.toNanos(timeout);
while (0 < toWait && resources().isNeedsWaiting()) {
toWait = condition.awaitNanos(toWait);
}
} else {
while (resources().isNeedsWaiting()) {
condition.await();
}
}
} catch (final InterruptedException e) {
// Fix rare racing condition between Thread.interrupt() and
// Condition.signalAll() events.
if (0 == resources().getTotal()) {
Thread.currentThread().interrupt();
}
}
return null;
}
});
}
/**
* Returns the number of closeable resources which have been accounted for.
* The first element contains the number of closeable resources which have been created by the current thread
* ({@code local}).
* The second element contains the number of closeable resources which have been created by all threads
* ({@code total}).
* Mind that this value may reduce concurrently, even while the lock is held, so it should <em>not</em> get cached!
*
* @return The number of closeable resources which have been accounted for.
*/
Resources resources() {
val currentThread = Thread.currentThread();
int local = 0;
int total = 0;
for (final Account account : accounts.values()) {
if (this.equals(account.getAccountant())) {
if (currentThread.equals(account.getOwner())) {
local += 1;
}
total += 1;
}
}
return new Resources(local, total);
}
/**
* For each accounted closeable resource, stops accounting for it and closes it.
* Upon return of this method, threads may immediately start accounting for closeable resources again unless the
* caller also locks the lock provided to the constructor - use with care!
*/
<X extends Exception> void closeAllResources(final ExceptionHandler<? super IOException, X> handler) throws X {
assert null != handler;
lock.lock();
try {
for (final Map.Entry<Closeable, Account> entry : accounts.entrySet()) {
val account = entry.getValue();
if (this.equals(account.getAccountant())) {
val closeable = entry.getKey();
accounts.remove(closeable);
try {
// This should trigger an attempt to remove the closeable from the
// map, but it can cause no ConcurrentModificationException because
// the entry is already removed and a ConcurrentHashMap doesn't do
// that anyway.
closeable.close();
} catch (IOException e) {
handler.warn(e); // may throw an exception!
}
}
}
} finally {
try {
condition.signalAll();
} finally {
lock.unlock();
}
}
}
}
| 38.968326 | 120 | 0.593242 |
1089c9d9e4b052bbe22ae9812c4db5676ef3c7a6 | 5,221 | /*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.maf;
//~--- non-JDK imports --------------------------------------------------------
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.broad.igv.PreferenceManager;
import org.broad.igv.ui.WaitCursorManager;
import org.broad.igv.util.LRUCache;
import org.broad.igv.util.ResourceLocator;
/**
* @author jrobinso
*/
public class MAFManager {
private static Logger log = Logger.getLogger(MAFManager.class);
public static String[] species = {
"panTro2", "gorGor1", "ponAbe2", "rheMac2", "calJac1",
"tarSyr1", "micMur1", "otoGar1", "tupBel1", "mm9", "rn4", "dipOrd1",
"cavPor3", "speTri1", "oryCun1", "ochPri2", "vicPac1", "turTru1",
"bosTau4", "equCab2", "felCat3", "canFam2", "myoLuc1", "pteVam1",
"eriEur1", "sorAra1", "loxAfr2", "proCap1", "echTel1", "dasNov2",
"choHof1", "monDom4", "ornAna1", "galGal3", "taeGut1", "anoCar1",
"xenTro2", "tetNig1", "fr2", "gasAcu1", "oryLat28", "danRer5", "petMar1"
};
public static Properties speciesNames;
private int tileSize = 500;
LRUCache<String, MAFTile> tileCache;
private List<String> selectedSpecies;
private List<String> allSpecies;
MAFReader reader;
static MAFManager instance;
String refId;
public MAFManager(ResourceLocator locator) {
tileCache = new LRUCache(this, 10);
if (speciesNames == null) {
loadNames();
}
if (locator.isLocal()) {
reader = new MAFLocalReader(locator.getPath());
allSpecies = ((MAFLocalReader) reader).getSequenceIds();
selectedSpecies = allSpecies.subList(1, allSpecies.size());
refId = allSpecies.get(0);
} else {
reader = new MAFRemoteReader(locator); // MAFLocalReader();
this.setSelectedSpecies(PreferenceManager.getInstance().getMafSpecies());
refId = "hg18";
}
//.asList(new ArrayList<String>(), species);
}
private void loadNames() {
try {
InputStream is = MAFUtils.class.getResourceAsStream("species.properties");
speciesNames = new Properties();
speciesNames.load(is);
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getSpeciesName(String speciesId) {
return speciesNames.getProperty(speciesId);
}
public MAFTile[] getTiles(String chr, int start, int end) {
int startTile = start / tileSize;
int endTile = end / tileSize;
MAFTile[] tiles = new MAFTile[endTile - startTile + 1];
for (int i = startTile; i <= endTile; i++) {
tiles[i - startTile] = getTile(chr, i);
}
return tiles;
}
private MAFTile getTile(String chr, int tileNo) {
String key = getKey(chr, tileNo);
MAFTile tile = tileCache.get(key);
if (tile == null) {
WaitCursorManager.CursorToken token = WaitCursorManager.showWaitCursor();
try {
int start = tileNo * tileSize;
int end = start + tileSize + 1;
tile = reader.loadTile(chr, start, end, allSpecies);
tileCache.put(key, tile);
} finally {
WaitCursorManager.removeWaitCursor(token);
}
}
return tile;
}
static String getKey(String chr, int tileNo) {
return chr + tileNo;
}
/**
* @return the selectedSpecies
*/
public List<String> getSelectedSpecies() {
return selectedSpecies;
}
/**
* @param selectedSpecies the selectedSpecies to set
*/
public void setSelectedSpecies(List<String> selectedSpecies) {
this.selectedSpecies = selectedSpecies;
this.allSpecies = new ArrayList(selectedSpecies);
allSpecies.add(0, "hg18");
}
}
| 35.760274 | 93 | 0.628041 |
a1bff3eb89f7a45db44829941b87eb618bdb555f | 11,506 | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2019 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package gwt.material.design.incubator.client.dob;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Style;
import com.google.gwt.i18n.client.DateTimeFormat;
import gwt.material.design.addins.client.combobox.MaterialComboBox;
import gwt.material.design.addins.client.inputmask.MaterialIntegerInputMask;
import gwt.material.design.client.MaterialDesignBase;
import gwt.material.design.client.base.AbstractValueWidget;
import gwt.material.design.client.base.HasFieldTypes;
import gwt.material.design.client.base.HasReadOnly;
import gwt.material.design.client.base.mixin.FieldTypeMixin;
import gwt.material.design.client.base.mixin.ToggleStyleMixin;
import gwt.material.design.client.constants.CssName;
import gwt.material.design.client.constants.FieldType;
import gwt.material.design.client.constants.StatusDisplayType;
import gwt.material.design.client.constants.TextAlign;
import gwt.material.design.incubator.client.AddinsIncubator;
import gwt.material.design.incubator.client.base.matcher.DateMonthMatcher;
import java.util.Date;
public class DateOfBirthPicker extends AbstractValueWidget<Date> implements HasFieldTypes, HasReadOnly {
static {
if (AddinsIncubator.isDebug()) {
MaterialDesignBase.injectCss(DateOfBirthPickerDebugClientBundle.INSTANCE.dobDebugCss());
} else {
MaterialDesignBase.injectCss(DateOfBirthPickerClientBundle.INSTANCE.dobCss());
}
}
private boolean showFieldLabels;
private Date value;
private DobLocaleDateProvider dataProvider = new DefaultDobLocaleDateProvider();
private MaterialComboBox<Integer> month = new MaterialComboBox();
private MaterialIntegerInputMask day = new MaterialIntegerInputMask();
private MaterialIntegerInputMask year = new MaterialIntegerInputMask();
private FieldTypeMixin<DateOfBirthPicker> fieldTypeMixin;
private ToggleStyleMixin<DateOfBirthPicker> toggleStyleMixin;
public DateOfBirthPicker() {
super(Document.get().createDivElement(), CssName.ROW);
setupLayout();
setupHandlers();
addStyleName("dob-container");
}
protected void setupLayout() {
// Month
month.addStyleName("dob-month");
month.setGrid("s12 m5");
month.setCloseOnSelect(true);
// Day
day.addStyleName("dob-day");
day.setMask("00");
day.setFloat(Style.Float.LEFT);
day.setTextAlign(TextAlign.CENTER);
day.setPlaceholder("DD");
day.setGrid("s4 m3");
// Year
year.addStyleName("dob-year");
year.setMask("0000");
year.setFloat(Style.Float.LEFT);
year.setTextAlign(TextAlign.CENTER);
year.setPlaceholder("YYYY");
year.setGrid("s8 m4");
}
protected void setupHandlers() {
// Month
if (dataProvider.get().size() > 12) {
setErrorText(dataProvider.getInvalidMonthMessage());
} else {
month.clear();
for (Integer index : dataProvider.get().keySet()) {
month.addItem(dataProvider.get().get(index), index);
}
}
month.setMatcher(DateMonthMatcher.getDefaultMonthMatcher());
month.addValueChangeHandler(event -> {
Date test = value;
if (validateDate(true)) {
value.setMonth(month.getSingleValue());
}
});
if (dataProvider.getMonthLabel() != null && !dataProvider.getMonthLabel().isEmpty()) {
month.setLabel(dataProvider.getMonthLabel());
}
// Day
day.addValueChangeHandler(event -> {
if (validateDate(true)) {
value.setDate(day.getValue());
}
});
if (dataProvider.getDayLabel() != null && !dataProvider.getDayLabel().isEmpty()) {
day.setLabel(dataProvider.getDayLabel());
}
// Year
year.addValueChangeHandler(event -> {
if (validateDate(true)) {
value.setYear(year.getValue() - 1900);
}
});
if (dataProvider.getYearLabel() != null && !dataProvider.getYearLabel().isEmpty()) {
year.setLabel(dataProvider.getYearLabel());
}
}
@Override
protected void onLoad() {
super.onLoad();
add(month);
add(day);
add(year);
if (!showFieldLabels) {
if (month != null) {
month.getLabelWidget().removeFromParent();
}
if (day != null) {
day.getLabelWidget().removeFromParent();
}
if (year != null) {
year.getLabelWidget().removeFromParent();
}
}
getToggleStyleMixin().setOn(!showFieldLabels);
}
public void reload() {
setupHandlers();
}
@Override
public void reset() {
super.reset();
month.reset();
day.reset();
year.reset();
value = null;
}
protected boolean validateDate(boolean showErrors) {
boolean valid = true;
Integer monthValue = month.getSingleValue();
Integer yearValue = year.getText() != null && !year.getText().isEmpty() ? Integer.parseInt(year.getText()) : null;
Integer dayValue = day.getText() != null && !day.getText().isEmpty() ? Integer.parseInt(day.getText()) : null;
if (!(monthValue != null && monthValue >= 0 && monthValue < 12)) {
valid = false;
if (showErrors) month.setErrorText(dataProvider.getInvalidMonthMessage());
} else {
if (showErrors) month.clearErrorText();
}
if (!(yearValue != null && yearValue >= 1900)) {
valid = false;
if (showErrors) year.setErrorText(dataProvider.getInvalidYearLabel());
} else {
if (showErrors) year.clearErrorText();
}
if (!(dayValue != null && dayValue > 0 && dayValue <= 31)) {
valid = false;
if (showErrors) day.setErrorText(dataProvider.getInvalidDayMessage());
} else {
if (showErrors) day.clearErrorText();
}
if (!validateLeapYear(monthValue, dayValue, yearValue)) {
valid = false;
if (showErrors) day.setErrorText("Invalid Date");
} else {
if (showErrors) day.clearErrorText();
}
return valid;
}
@Override
public boolean validate() {
return super.validate() && validateDate(false);
}
public boolean validateLeapYear(Integer month, Integer day, Integer year) {
if (month != null && day != null && year != null) {
String dateToValidate = month + 1 + "/" + day + "/" + year;
if (dateToValidate == null) {
return false;
}
DateTimeFormat sdf = DateTimeFormat.getFormat("MM/dd/yyyy");
try {
Date date = sdf.parse(dateToValidate);
if (date.getMonth() != month) {
return false;
}
value = date;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
@Override
public Date getValue() {
return value;
}
@Override
public void setValue(Date value) {
super.setValue(value);
this.value = value;
year.setValue(value.getYear() + 1900);
day.setValue(value.getDate());
month.setSingleValue(value.getMonth());
}
@Override
public void setFieldType(FieldType type) {
month.setFieldType(type);
day.setFieldType(type);
year.setFieldType(type);
}
@Override
public FieldType getFieldType() {
return getFieldTypeMixin().getFieldType();
}
@Override
public void setLabelWidth(double percentWidth) {
getFieldTypeMixin().setLabelWidth(percentWidth);
}
@Override
public void setFieldWidth(double percentWidth) {
getFieldTypeMixin().setLabelWidth(percentWidth);
}
@Override
public void setReadOnly(boolean value) {
month.setReadOnly(value);
year.setReadOnly(value);
day.setReadOnly(value);
}
@Override
public boolean isReadOnly() {
return month.isReadOnly() && year.isReadOnly() && day.isReadOnly();
}
@Override
public void setToggleReadOnly(boolean toggle) {
month.setToggleReadOnly(toggle);
year.setToggleReadOnly(toggle);
day.setToggleReadOnly(toggle);
}
@Override
public boolean isToggleReadOnly() {
return month.isToggleReadOnly() && year.isToggleReadOnly() && day.isToggleReadOnly();
}
@Override
public void setStatusDisplayType(StatusDisplayType displayType) {
super.setStatusDisplayType(displayType);
month.setStatusDisplayType(displayType);
year.setStatusDisplayType(displayType);
day.setStatusDisplayType(displayType);
}
@Override
public void setErrorText(String errorText) {
month.setErrorText(errorText);
day.setErrorText(errorText);
year.setErrorText(errorText);
}
@Override
public void setSuccessText(String successText) {
month.setErrorText(successText);
day.setErrorText(successText);
year.setErrorText(successText);
}
@Override
public void setHelperText(String helperText) {
month.setErrorText(helperText);
day.setErrorText(helperText);
year.setErrorText(helperText);
}
@Override
public StatusDisplayType getStatusDisplayType() {
return month.getStatusDisplayType();
}
public DobLocaleDateProvider getDataProvider() {
return dataProvider;
}
public void setDataProvider(DobLocaleDateProvider dataProvider) {
this.dataProvider = dataProvider;
}
public boolean isShowFieldLabels() {
return showFieldLabels;
}
public void setShowFieldLabels(boolean showFieldLabels) {
this.showFieldLabels = showFieldLabels;
}
public MaterialComboBox<Integer> getMonth() {
return month;
}
public MaterialIntegerInputMask getDay() {
return day;
}
public MaterialIntegerInputMask getYear() {
return year;
}
public FieldTypeMixin<DateOfBirthPicker> getFieldTypeMixin() {
if (fieldTypeMixin == null) {
fieldTypeMixin = new FieldTypeMixin<>(this);
}
return fieldTypeMixin;
}
public ToggleStyleMixin<DateOfBirthPicker> getToggleStyleMixin() {
if (toggleStyleMixin == null) {
toggleStyleMixin = new ToggleStyleMixin<>(this, "no-labels");
}
return toggleStyleMixin;
}
}
| 30.358839 | 122 | 0.622023 |
5d7734b3543c2985440628054c6cb42c298956a0 | 565 | package com.jk;
import java.io.File;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) throws Exception{
System.out.println("Start parsing...");
File file = new File(Main2.class.getResource("Add.asm").getFile());
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
System.out.println("End parsing...");
System.out.println(Integer.toBinaryString(0x10000 | 2));
}
}
| 25.681818 | 75 | 0.623009 |
a358bb8b069c591a695636c2209f412d24cdef2d | 4,511 | /*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
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 edu.ucar.dls.schemedit.test;
import java.io.*;
import java.util.*;
import java.text.*;
import edu.ucar.dls.xml.*;
import edu.ucar.dls.util.*;
import edu.ucar.dls.repository.*;
import edu.ucar.dls.schemedit.*;
import edu.ucar.dls.schemedit.config.*;
import edu.ucar.dls.schemedit.dcs.*;
import edu.ucar.dls.schemedit.vocab.layout.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import org.dom4j.Node;
/**
* Tester for {@link edu.ucar.dls.schemedit.config.FrameworkConfigReader}
*
*@author ostwald
<p>$Id: FrameworkConfigTester.java,v 1.11 2012/11/22 00:02:33 ostwald Exp $
*/
public class FrameworkConfigTester {
public FrameworkConfigReader reader = null;
public MetaDataFramework framework = null;
FrameworkRegistry registry = null;
// String configDirPath = "/devel/ostwald/projects/schemedit-project/web/WEB-INF/framework-config";
String configDirPath;
/**
* Constructor for the FrameworkConfigTester object
*/
public FrameworkConfigTester(String xmlFormat) throws Exception {
prtln ("xmlFormat: " + xmlFormat);
configDirPath = TesterUtils.getFrameworkConfigDir();
File sourceFile = new File(configDirPath, xmlFormat + ".xml");
if (!sourceFile.exists()) {
prtln("source File does not exist at " + sourceFile.toString());
return;
}
prtln ("config: " + sourceFile);
try {
reader = new FrameworkConfigReader(sourceFile);
framework = new MetaDataFramework(reader);
} catch (Exception e) {
prtln ("Initialization error: " + e.getMessage());
}
prtln ("schemaURI: " + framework.getSchemaURI());
}
FrameworkRegistry getFrameworkRegistry (String configDirPath) {
return new FrameworkRegistry(configDirPath, null);
}
/**
* Description of the Method
*/
public void showFrameworkStuff() {
prtln("\n-----------------------");
prtln("FRAMEWORK Stuff");
prtln ("name: " + framework.getName());
prtln ("renderer: " + this.framework.getRenderer());
}
public void showReaderStuff() {
prtln("\n-----------------------");
prtln ("READER Stuff");
prtln ("name: " + this.reader.getName());
prtln ("xmlFormat: " + this.reader.getXmlFormat());
prtln ("renderer: " + this.reader.getRenderer());
}
/**
* The main program for the FrameworkConfigTester class
*
*@param args The command line arguments
*/
public static void main(String[] args) throws Exception {
prtln("FrameworkConfigTester");
edu.ucar.dls.schemedit.autoform.RendererHelper.setLogging(false);
String xmlFormat = "adn";
if (args.length > 0)
xmlFormat = args[0];
FrameworkConfigTester tester = new FrameworkConfigTester(xmlFormat);
tester.showSchemaPathMap();
// pp (tester.reader.getDocMap().getDocument());
// tester.showReaderStuff ();
// tester.showFrameworkStuff();
// DocMap docMap = reader.getDocMap();
pp (tester.getMinimalRecord());
}
public void showSchemaPathMap () {
prtln (reader.getSchemaPathMap().toString());
}
public Document getMinimalRecord () {
Document minnie = null;
try {
framework.loadSchemaHelper();
File file = new File ("C:/Program Files/Apache Software Foundation/Tomcat 5.5/var/dcs_conf/collections/1249343349394.xml");
CollectionConfig config = new CollectionConfig (file, null);
if (config == null)
throw new Exception ("collection config is NULL!");
minnie = framework.makeMinimalRecord("FOO-ID", config);
// pp(minnie);
} catch (Exception e) {
prtln (e.getMessage());
}
return minnie;
}
/**
* Utility to show XML in pretty form
*
*@param node Description of the Parameter
*/
public static void pp(Node node) {
prtln(Dom4jUtils.prettyPrint(node));
}
/**
* Description of the Method
*
*@param s Description of the Parameter
*/
public static void prtln(String s) {
System.out.println(s);
}
}
| 28.371069 | 126 | 0.706495 |
99aa8c730abfb816da810cbd2064262e46024a6a | 730 | package net.alexheavens.graphlib.graph;
public class SimpleEdgeFactory<DataClass> implements EdgeFactory<DataClass> {
public AbstractEdge<DataClass> generate(AbstractGraph<DataClass> graph, AbstractNode<DataClass> fromNode,
AbstractNode<DataClass> toNode) {
return new SimpleEdge<>(graph, fromNode, toNode);
}
@Override
public AbstractEdge<DataClass> generate(final AbstractEdgeFactoryParameterSet<DataClass> generateParameters){
final AbstractGraph<DataClass> graph = generateParameters.getGraph();
final AbstractNode<DataClass> fromNode = generateParameters.getFromNode();
final AbstractNode<DataClass> toNode = generateParameters.getToNode();
return new SimpleEdge<>(graph, fromNode, toNode);
}
}
| 33.181818 | 110 | 0.79589 |
529f265f8c18eab4fb3730f0d5034902abb9f5a3 | 529 | package com.airbnb.epoxy;
import android.content.Context;
import android.view.View;
import com.airbnb.epoxy.AfterPropsSet;
import com.airbnb.epoxy.ModelProp;
import com.airbnb.epoxy.ModelProp.Option;
import com.airbnb.epoxy.ModelView;
@ModelView(autoLayout = ModelView.Size.WRAP_WIDTH_WRAP_HEIGHT)
public class TestFieldPropThrowsIfStaticView extends View {
@ModelProp private String value;
public TestFieldPropThrowsIfStaticView(Context context) {
super(context);
}
@AfterPropsSet
public void call() {
}
}
| 22.041667 | 62 | 0.79206 |
8233b26032f4056362b4c2ae9a66f6aebf9f7215 | 1,265 | package org.asaph.happynumber;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class HappyNumberTest {
@Test
public void testHappyNumbersBetweenOneAndOneThousand() {
// List of expected numbers cut/pasted from http://en.wikipedia.org/wiki/Happy_number
List<Integer> expected = Arrays.asList(1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302, 310, 313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383, 386, 391, 392, 397, 404, 409, 440, 446, 464, 469, 478, 487, 490, 496, 536, 556, 563, 565, 566, 608, 617, 622, 623, 632, 635, 637, 638, 644, 649, 653, 655, 656, 665, 671, 673, 680, 683, 694, 700, 709, 716, 736, 739, 748, 761, 763, 784, 790, 793, 802, 806, 818, 820, 833, 836, 847, 860, 863, 874, 881, 888, 899, 901, 904, 907, 910, 912, 913, 921, 923, 931, 932, 937, 940, 946, 964, 970, 973, 989, 998, 1000);
List<Integer> actual = new ArrayList<>();
for (int i=1; i<=1000; i++) {
if (HappyNumber.isHappy(i)) {
actual.add(i);
}
}
assertEquals(expected, actual);
}
} | 50.6 | 736 | 0.647431 |
5f1ce8c406a72055373237b5d76ae373e49d0103 | 2,370 | /*
* 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.aliyuncs.sas.transform.v20181203;
import com.aliyuncs.sas.model.v20181203.DescribeExposedStatisticsResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeExposedStatisticsResponseUnmarshaller {
public static DescribeExposedStatisticsResponse unmarshall(DescribeExposedStatisticsResponse describeExposedStatisticsResponse, UnmarshallerContext _ctx) {
describeExposedStatisticsResponse.setRequestId(_ctx.stringValue("DescribeExposedStatisticsResponse.RequestId"));
describeExposedStatisticsResponse.setExposedLaterVulCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedLaterVulCount"));
describeExposedStatisticsResponse.setExposedComponentCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedComponentCount"));
describeExposedStatisticsResponse.setExposedPortCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedPortCount"));
describeExposedStatisticsResponse.setExposedInstanceCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedInstanceCount"));
describeExposedStatisticsResponse.setExposedWeekPasswordMachineCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedWeekPasswordMachineCount"));
describeExposedStatisticsResponse.setExposedNntfVulCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedNntfVulCount"));
describeExposedStatisticsResponse.setGatewayAssetCount(_ctx.integerValue("DescribeExposedStatisticsResponse.GatewayAssetCount"));
describeExposedStatisticsResponse.setExposedIpCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedIpCount"));
describeExposedStatisticsResponse.setExposedAsapVulCount(_ctx.integerValue("DescribeExposedStatisticsResponse.ExposedAsapVulCount"));
return describeExposedStatisticsResponse;
}
} | 62.368421 | 160 | 0.855274 |
f3be1a3fe521f643e50f963cb72dc7c290518050 | 193 | package parser.tokenizer;
public interface IStream<T> {
T next() throws Exception;
T peek() throws Exception;
boolean eof() throws Exception;
T[] getAll() throws Exception;
}
| 19.3 | 35 | 0.683938 |
e27557e9b95c7b7d77e85d0aa858401cc63e1432 | 6,277 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.ss.usermodel;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.poi.util.LocaleUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TestExcelStyleDateFormatter {
private static final String EXCEL_DATE_FORMAT = "MMMMM";
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
private static final int jreVersion =
Integer.parseInt(System.getProperty("java.version").replaceAll("^(?:1\\.)?(\\d+).*", "$1"));
private static final String provider = System.getProperty("java.locale.providers");
private static final FieldPosition fp = new FieldPosition(java.text.DateFormat.MONTH_FIELD);
private static final ExcelStyleDateFormatter formatter = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT);
/**
* [Bug 60369] Month format 'MMMMM' issue with TEXT-formula and Java 8
*/
@ParameterizedTest
@MethodSource("initializeLocales")
void test60369(Locale locale, String expected, Date d, int month) {
// Let's iterate over the test setup.
final StringBuffer sb = new StringBuffer();
formatter.setDateFormatSymbols(DateFormatSymbols.getInstance(locale));
String result = formatter.format(d, sb, fp).toString();
String msg = "Failed testDates for locale " + locale + ", provider: " + provider +
" and date " + d + ", having: " + result;
int actIdx = localeIndex(locale);
assertNotNull(result, msg);
assertTrue(result.length() > actIdx, msg);
assertEquals(expected.charAt(month), result.charAt(actIdx), msg);
}
/**
* Depending on the JRE version, the provider setting and the locale, a different result
* is expected and selected via an index
*/
private static int localeIndex(Locale locale) {
return jreVersion < 9 ||
!locale.equals (Locale.CHINESE) ||
(provider != null && (provider.startsWith("JRE") || provider.startsWith("COMPAT")))
? 0 : 1;
}
/**
* Setting up the locale to be tested together with a list of asserted
* unicode-formatted results and put them in a map.
*/
public static Stream<Arguments> initializeLocales() throws ParseException {
Object[][] locExps = {
{ Locale.GERMAN, "JFMAMJJASOND" },
{ new Locale("de", "AT"), "JFMAMJJASOND" },
{ Locale.UK, "JFMAMJJASOND" },
{ new Locale("en", "IN"), "JFMAMJJASOND" },
{ new Locale("in", "ID"), "JFMAMJJASOND" },
{ Locale.FRENCH, "jfmamjjasond" },
{ new Locale("ru", "RU"), "\u044f\u0444\u043c\u0430\u043c\u0438\u0438\u0430\u0441\u043e\u043d\u0434" },
{ Locale.CHINESE, localeIndex(Locale.CHINESE) == 0 ? "\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u5341\u5341" : "123456789111" },
{ new Locale("tr", "TR"), "\u004f\u015e\u004d\u004e\u004d\u0048\u0054\u0041\u0045\u0045\u004b\u0041" },
{ new Locale("hu", "HU"), "\u006a\u0066\u006d\u00e1\u006d\u006a\u006a\u0061\u0073\u006f\u006e\u0064" }
};
String[] dates = {
"1980-01-12", "1995-02-11", "2045-03-10", "2016-04-09", "2017-05-08",
"1945-06-07", "1998-07-06", "2099-08-05", "1988-09-04", "2023-10-03", "1978-11-02", "1890-12-01"
};
List<Arguments> list = new ArrayList<>(locExps.length * dates.length);
for (Object[] locExp : locExps) {
int month = 0;
for (String date : dates) {
list.add(Arguments.of(locExp[0], locExp[1], DATE_FORMAT.parse(date), month++));
}
}
return list.stream();
}
@Test
void testConstruct() {
assertDoesNotThrow(() -> new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT, LocaleUtil.getUserLocale()));
assertDoesNotThrow(() -> new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT));
}
@Test
void testWithLocale() throws ParseException {
Locale before = LocaleUtil.getUserLocale();
try {
LocaleUtil.setUserLocale(Locale.GERMAN);
String dateStr = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT).format(
DATE_FORMAT.parse("2016-03-26"));
assertEquals("M", dateStr);
} finally {
LocaleUtil.setUserLocale(before);
}
}
@Test
void testWithPattern() throws ParseException {
String dateStr = new ExcelStyleDateFormatter("yyyy|" + EXCEL_DATE_FORMAT + "|").format(
DATE_FORMAT.parse("2016-03-26"));
assertEquals("2016|M|", dateStr);
}
}
| 43.590278 | 159 | 0.650948 |
2a615be120990b99102b622127d56166235be555 | 4,950 | package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.CollectionUtil.requireAllNonNull;
import static seedu.address.logic.parser.CliSyntax.PREFIX_CLASSCODE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_GROUPNUMBER;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TYPE;
import static seedu.address.model.Model.PREDICATE_SHOW_ALL_STUDENTS;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.student.Student;
import seedu.address.model.tutorialgroup.TutorialGroup;
public class DeleteStudentFromGroupCommand extends Command {
public static final String COMMAND_WORD = "deletesg";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes a student from a group in Classmate "
+ "by the index number used in the last person listing. "
+ "Parameters: INDEX (must be a positive integer) "
+ PREFIX_CLASSCODE + "CLASS_CODE "
+ PREFIX_TYPE + "GROUP_TYPE "
+ PREFIX_GROUPNUMBER + "GROUP_NUMBER "
+ "Example: " + COMMAND_WORD + " 1 "
+ PREFIX_GROUPNUMBER + "1 "
+ PREFIX_CLASSCODE + "G06 "
+ PREFIX_TYPE + "OP1 ";
public static final String MESSAGE_SUCCESS = "Index: %1$d removed from Group: %2$s";
public static final String MESSAGE_GROUP_NOT_EXIST = "The group does not exist in Classmate";
public static final String MESSAGE_NOT_BELONG_GROUP = "The student does not being to this Group";
private final Index index;
private final TutorialGroup toDeleteTutorialGroup;
/**
* Creates an DeleteStudentFromGroupCommand to delete the specified {@code TutorialCode}
*/
public DeleteStudentFromGroupCommand(Index index, TutorialGroup tutorialGroup) {
requireAllNonNull(index, tutorialGroup);
this.index = index;
this.toDeleteTutorialGroup = tutorialGroup;
// new class with the same class code created to check whether it already exists in ClassMATE
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
List<Student> lastShownList = model.getFilteredStudentList();
// Check if index is within range of student list
if (index.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_STUDENT_DISPLAYED_INDEX);
}
// check if tutorial group already exists in ClassMATE
if (!model.hasTutorialGroup(toDeleteTutorialGroup)) {
throw new CommandException(MESSAGE_GROUP_NOT_EXIST);
}
Student studentToEdit = lastShownList.get(index.getZeroBased());
// check if Student belongs to the Tutorial Group
if (!isBelongGroup(studentToEdit, toDeleteTutorialGroup)) {
throw new CommandException(MESSAGE_NOT_BELONG_GROUP);
}
Student editedStudent = deleteTutorialGroup(studentToEdit, toDeleteTutorialGroup);
model.setStudent(studentToEdit, editedStudent);
model.updateFilteredStudentList(PREDICATE_SHOW_ALL_STUDENTS);
return new CommandResult(String.format(MESSAGE_SUCCESS, index.getOneBased(), toDeleteTutorialGroup));
}
public boolean isBelongGroup(Student student, TutorialGroup tutorialGroup) {
return student.getTutorialGroups().contains(tutorialGroup);
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof DeleteStudentFromGroupCommand)) {
return false;
}
// state check
return index.equals(((DeleteStudentFromGroupCommand) other).index)
&& toDeleteTutorialGroup.equals(((DeleteStudentFromGroupCommand) other).toDeleteTutorialGroup);
}
/**
* Creates and returns a {@code Student} with the {@code TutorialGroup} deleted.
*/
private static Student deleteTutorialGroup(Student studentToEdit, TutorialGroup group) throws CommandException {
assert studentToEdit != null;
Set<TutorialGroup> updatedTutorialGroups = new HashSet<>(studentToEdit.getTutorialGroups());
updatedTutorialGroups.remove(group);
return new Student(
studentToEdit.getName(),
studentToEdit.getPhone(),
studentToEdit.getEmail(),
studentToEdit.getAddress(),
studentToEdit.getClassCode(),
studentToEdit.getTags(),
studentToEdit.getMarks(),
updatedTutorialGroups);
}
}
| 40.243902 | 116 | 0.697374 |
3682ea100d10fc7bd893583fdc09d9ed8bccde19 | 5,783 | package fr.mrmicky.worldeditselectionvisualizer.compat;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.regions.Region;
import fr.mrmicky.worldeditselectionvisualizer.WorldEditSelectionVisualizer;
import fr.mrmicky.worldeditselectionvisualizer.compat.v6.ClipboardAdapter6;
import fr.mrmicky.worldeditselectionvisualizer.compat.v6.RegionAdapter6;
import fr.mrmicky.worldeditselectionvisualizer.compat.v7.ClipboardAdapter7;
import fr.mrmicky.worldeditselectionvisualizer.compat.v7.RegionAdapter7;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.logging.Level;
/**
* Helper class to help supporting multiples Spigot and WorldEdit versions
*/
public class CompatibilityHelper {
private final WorldEditSelectionVisualizer plugin;
private final boolean supportOffHand = isOffhandSupported();
private final boolean supportActionBar = isActionBarSupported();
private final boolean worldEdit7 = isWorldEdit7();
private final boolean supportFawe;
@Nullable
private Field wandItemField;
public CompatibilityHelper(WorldEditSelectionVisualizer plugin) {
this.plugin = plugin;
plugin.getLogger().info("Using WorldEdit " + getWorldEditVersion() + " api");
supportFawe = isFaweInstalled();
if (supportFawe) {
plugin.getLogger().info("FastAsyncWorldEdit support enabled");
}
try {
wandItemField = LocalConfiguration.class.getField("wandItem");
} catch (NoSuchFieldException e) {
plugin.getLogger().warning("No field 'wandItem' in LocalConfiguration");
}
if (wandItemField != null && wandItemField.getType() != int.class && wandItemField.getType() != String.class) {
plugin.getLogger().warning("Unsupported WorldEdit configuration, try to update WorldEdit (and FAWE if you have it)");
wandItemField = null;
}
}
public RegionAdapter adaptRegion(Region region) {
return worldEdit7 ? new RegionAdapter7(region) : new RegionAdapter6(region);
}
public ClipboardAdapter adaptClipboard(Clipboard clipboard) {
return worldEdit7 ? new ClipboardAdapter7(clipboard) : new ClipboardAdapter6(clipboard);
}
public int getWorldEditVersion() {
return worldEdit7 ? 7 : 6;
}
public boolean isHoldingSelectionItem(Player player) {
return isSelectionItem(getItemInMainHand(player)) || isSelectionItem(getItemInOffHand(player));
}
public boolean isUsingFawe() {
return supportFawe;
}
public void sendActionBar(Player player, String message) {
if (!supportActionBar) {
player.sendMessage(message);
return;
}
SpigotActionBarAdapter.sendActionBar(player, message);
}
public boolean isSelectionItem(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
return false;
}
if (wandItemField == null) {
return true;
}
try {
if (wandItemField.getType() == int.class) { // WorldEdit under 1.13
//noinspection deprecation
return item.getType().getId() == wandItemField.getInt(WorldEdit.getInstance().getConfiguration());
}
if (wandItemField.getType() == String.class) { // WorldEdit 1.13+
String wandItem = (String) wandItemField.get(WorldEdit.getInstance().getConfiguration());
return BukkitAdapter.adapt(item).getType().getId().equals(wandItem);
}
} catch (ReflectiveOperationException e) {
plugin.getLogger().log(Level.WARNING, "An error occurred on isHoldingSelectionItem", e);
}
return true;
}
private ItemStack getItemInMainHand(Player player) {
//noinspection deprecation - for 1.7/1.8 servers
return player.getItemInHand();
}
private ItemStack getItemInOffHand(Player player) {
if (!supportOffHand) {
return null;
}
return player.getInventory().getItemInOffHand();
}
private boolean isActionBarSupported() {
try {
Class.forName("net.md_5.bungee.api.chat.TextComponent");
Player.class.getMethod("spigot");
SpigotActionBarAdapter.checkSupported();
return true;
} catch (ClassNotFoundException | NoSuchMethodException e) {
return false;
}
}
private boolean isOffhandSupported() {
try {
PlayerInventory.class.getMethod("getItemInOffHand");
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
private boolean isWorldEdit7() {
try {
Class.forName("com.sk89q.worldedit.math.Vector3");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
private boolean isFaweInstalled() {
if (Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") == null) {
return false;
}
try {
Class.forName("com.boydti.fawe.object.regions.PolyhedralRegion");
return true;
} catch (ClassNotFoundException e) {
plugin.getLogger().severe("A plugin with the name 'FastAsyncWorldEdit' is installed but FAWE classes was not found");
return false;
}
}
}
| 32.127778 | 129 | 0.66073 |
8963b6a8152d1b9e6ac69fc314bd4211807372a9 | 1,555 | package it.polimi.se2019.server.actions.conditions;
import it.polimi.se2019.server.games.Game;
import it.polimi.se2019.server.games.Targetable;
import it.polimi.se2019.server.games.board.Tile;
import it.polimi.se2019.server.games.player.Player;
import it.polimi.se2019.util.CommandConstants;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* This condition checks whether the target list is not visible.
*
* @author andreahuang
*
*/
public class IsTargetListNotVisible implements Condition {
/**
* Checks whether the target list is not visible.
*
* @param game the game on which to perform the evaluation.
* @param targets the targets is the input of the current player. Either tiles or players.
* @return true if not visible, false otherwise.
*/
@Override
public boolean check(Game game, Map<String, List<Targetable>> targets) {
Tile attackerTile = game.getCurrentPlayer().getCharacterState().getTile();
Logger.getGlobal().info("IsTargetListNotVisible: "+
targets.get(CommandConstants.TARGETLIST).stream()
.map(t -> (Player) t)
.allMatch(targetPlayer -> !attackerTile.getVisibleTargets(game).contains(targetPlayer)));
return targets.get(CommandConstants.TARGETLIST).stream()
.map(t -> (Player) t)
.allMatch(targetPlayer -> !attackerTile.getVisibleTargets(game).contains(targetPlayer) && targetPlayer.getCharacterState().getTile() != null);
}
}
| 37.926829 | 158 | 0.692605 |
bf23574ebcfefc0d4211148e1d27d00067998731 | 753 | package com.comfunmanager.repository;
import java.util.Collection;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import com.comfunmanager.beandata.Serverinfo;
/**
* 表Repository定义
*
*/
@RestResource(exported = false)
public interface ServerinfoRepository extends PagingAndSortingRepository<Serverinfo, Long> {
Page<Serverinfo> findByIdGreaterThan(Long startid, Pageable p);
Collection<Serverinfo> findByCreatetime(String createtime);
Collection<Serverinfo> findByServerid(String serverid);
Collection<Serverinfo> findByServerhost(String serverhost);
}
| 26.892857 | 92 | 0.828685 |
dd18447d014885ef8e67b9e8276de1b85cc15970 | 513 | package com.andyadc.codeblocks.patchca.text.renderer;
import com.andyadc.codeblocks.patchca.color.ColorFactory;
import com.andyadc.codeblocks.patchca.font.FontFactory;
import java.awt.image.BufferedImage;
public interface TextRenderer {
void setLeftMargin(int leftMargin);
void setRightMargin(int rightMargin);
void setTopMargin(int topMargin);
void setBottomMargin(int bottomMargin);
void draw(String text, BufferedImage canvas, FontFactory fontFactory, ColorFactory colorFactory);
}
| 25.65 | 101 | 0.797271 |
71f7466760601d13f0f2c28bb221543ffce2aff5 | 12,068 | package com.cm.contentmanagementapp.controllers;
import com.cm.contentmanagementapp.models.*;
import com.cm.contentmanagementapp.payload.request.*;
import com.cm.contentmanagementapp.payload.response.MessageResponse;
import com.cm.contentmanagementapp.services.MailService;
import com.cm.contentmanagementapp.services.UserService;
import com.cm.contentmanagementapp.services.resettoken.EmailResetTokenService;
import com.cm.contentmanagementapp.services.resettoken.PasswordResetTokenService;
import com.cm.contentmanagementapp.services.resettoken.ResetTokenService;
import javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/api/setting")
public class SettingsController {
private UserService userService;
private ResetTokenService resetTokenService;
private PasswordResetTokenService passwordTokenService;
private EmailResetTokenService emailTokenService;
private MailService mailService;
private static final Logger log = LoggerFactory.getLogger(SettingsController.class);
@Autowired
public SettingsController(UserService userService, ResetTokenService resetTokenService, PasswordResetTokenService passwordTokenService,
EmailResetTokenService emailTokenService, MailService mailService) {
this.userService = userService;
this.resetTokenService = resetTokenService;
this.passwordTokenService = passwordTokenService;
this.emailTokenService = emailTokenService;
this.mailService = mailService;
}
@PostMapping("/requestLostPasswordReset")
public ResponseEntity<?> requestLostPasswordReset (@Valid @RequestBody LostPasswordResetRequest lostPasswordResetRequest,
HttpServletRequest request)
throws NoSuchAlgorithmException {
if (!userService.existsByEmail(lostPasswordResetRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("You will receive an email to reset your password if this email exists" +
" in our system."));
}
User user = userService.findByEmail(lostPasswordResetRequest.getEmail());
// create new token, hash string token before storing, send email with unhashed token.
PasswordResetToken passResetToken = new PasswordResetToken();
String token = UUID.randomUUID().toString();
passResetToken.setToken(resetTokenService.hashToken(token));
passResetToken.setUser(user);
passResetToken.setExpireDateByMinute(60);
passwordTokenService.save(passResetToken);
Mail mail = new Mail();
mail.setFrom("defizzy@outlook.com");
mail.setTo(user.getEmail());
mail.setSubject("Password reset request");
Map<String, Object> model = new HashMap<>();
model.put("token", token);
model.put("user", user);
model.put("signature", "a signature here");
// replace 3000 w/ request.getServerPort() when done testing;
String url = request.getScheme() + "://" + request.getServerName() + ":" + 3000;
model.put("resetUrl", url + "/reset-password-token-" + token);
mail.setModel(model);
mailService.sendEmail(mail);
log.info("User requested a password reset");
return ResponseEntity.ok(new MessageResponse("You will receive an email to reset your password if this email exists" +
" in our system."));
}
@PostMapping("/requestSettingPasswordReset")
public ResponseEntity<?> requestSettingPasswordReset(@Valid @RequestBody PasswordResetRequest passwordResetRequest) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
if (passwordResetRequest.getCurrentPassword() == passwordResetRequest.getNewPassword()) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Current and new password must be different."));
}
User user = userService.findByUsername(authentication.getName()).get();
if (!userService.isValidPassword(user, passwordResetRequest.getCurrentPassword())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Invalid entry for current password"));
}
userService.updatePassword(user, passwordResetRequest.getNewPassword());
userService.save(user);
return ResponseEntity.ok(new MessageResponse("Account password has been updated."));
}
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error encountered while processing password reset," +
" please try again"));
}
@PostMapping("/handlePasswordReset")
public ResponseEntity<?> handlePasswordReset(@Valid @RequestBody HandlePasswordResetRequest handlePassResetReq) {
try {
if (!resetTokenService.existsByToken(handlePassResetReq.getToken())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Invalid password reset token. Please try again"));
}
ResetToken token = resetTokenService.findByToken(handlePassResetReq.getToken());
User user = token.getUser();
userService.updatePassword(user, handlePassResetReq.getPassword());
log.info("Handling user password reset");
return ResponseEntity.ok(new MessageResponse("Password successfully changed."));
} catch (NoSuchAlgorithmException nsae) {
log.info("No such hash algo: {}", nsae);
}
return ResponseEntity
.badRequest()
.body(new MessageResponse("handlePasswordReset hash error"));
}
@PostMapping("/changeEmailRequest")
public ResponseEntity<?> changeEmailRequest(@Valid @RequestBody ChangeEmailRequest changeEmailRequest,
HttpServletRequest request) throws NoSuchAlgorithmException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
if (userService.existsByEmail(changeEmailRequest.getEmail())) {
log.info("User attempted to change email but email already in use");
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email already in use"));
}
User user = userService.findByUsername(authentication.getName()).get();
if (!userService.isValidPassword(user, changeEmailRequest.getPassword())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Invalid password, please try again"));
}
EmailResetToken emailResetToken = new EmailResetToken();
String token = UUID.randomUUID().toString();
emailResetToken.setToken(resetTokenService.hashToken(token));
emailResetToken.setUser(user);
emailResetToken.setExpireDateByHour(48);
emailResetToken.setNewEmail(changeEmailRequest.getEmail());
emailTokenService.save(emailResetToken);
Mail mail = new Mail();
mail.setFrom("defizzy@outlook.com");
mail.setTo(changeEmailRequest.getEmail());
mail.setSubject("Change email request");
Map<String, Object> model = new HashMap<>();
model.put("token", token);
model.put("user", user);
model.put("signature", "a signature here");
// replace 3000 w/ request.getServerPort() when done testing;
String url = request.getScheme() + "://" + request.getServerName() + ":" + 3000;
model.put("resetUrl", url + "/email-change-confirmation-" + token);
mail.setModel(model);
mailService.sendEmail(mail);
log.info("User requested an email change");
return ResponseEntity.ok(new MessageResponse("A confirmation email will be sent to your new address. Click" +
" the link provided link to update your email."));
}
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error encountered while processing email reset request," +
" please try again"));
}
@PostMapping("/handleEmailChange")
public ResponseEntity<?> handleEmailChange(@Valid @RequestBody HandleEmailChangeRequest emailChangeRequest) {
System.out.println(emailChangeRequest.getToken());
try {
if (!resetTokenService.existsByToken(emailChangeRequest.getToken())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Link is invalid or expired, submit a new email change request"));
}
ResetToken resetToken = resetTokenService.findByToken(emailChangeRequest.getToken());
EmailResetToken emailResetToken = emailTokenService
.findByResetToken(resetToken)
.orElse(null);
User user = resetToken.getUser();
user.setEmail(emailResetToken.getNewEmail());
userService.save(user);
emailTokenService.delete(emailResetToken);
log.info("User email updated");
} catch (NoSuchAlgorithmException | NotFoundException e) {
log.info("Exception: {}", e);
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error encountered, try again"));
}
return ResponseEntity.ok(new MessageResponse("Email successfully changed."));
}
@PostMapping(value = "/handleProfilePictureUpload")
public ResponseEntity<?> handleProfilePictureUpload(@RequestParam("file") MultipartFile file) {
try {
if (file.getSize() > 512000) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Image exceeds maximum size of 500kb"));
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
User user = userService.findByUsername(currentUserName).get();
userService.updateProfilePicture(user, file);
return ResponseEntity.ok(new MessageResponse("Profile picture updated"));
}
} catch (Exception e) {
log.info("Error encountered while trying to upload profile image");
}
log.info("Error encountered while trying to upload profile image");
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error encountered while uploading file, try again"));
}
}
| 41.187713 | 139 | 0.652552 |
c3764bba3ab72a4e2d0dbb18669c3c9a3312f5ca | 5,155 | /**
* The MIT License (MIT)
* <p/>
* Copyright (c) 2015 Riccardo Cardin
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p/>
* 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.
* <p/>
* Please, insert description here.
*
* @author Riccardo Cardin
* @version 1.0
* @since 1.0
*/
/**
* Please, insert description here.
*
* @author Riccardo Cardin
* @version 1.0
* @since 1.0
*/
package it.unipd.math.pcd.actors;
import it.unipd.math.pcd.actors.exceptions.NoSuchActorException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
/*
* @author Andrey Petrov
* @version 1.0.0
* The class <i>AbsActorSystem</i> is an abstract entity
* needed by the framework to manage at abstract level the Actors within the system.
* The class offers the following interface:
* <dl>
* <dt>Public Interface</dt>
* <dd>
* <ul>
* <li>actorOf(actor:Actor, mode: ActorMode)</li>
* <li>actorOf(actor:Actor)</li>
* <li>stop(actor:ActorRef)</li>
* <li>stop()</li>
* </ul>
* </dd>
*
* <dt>Protected Interface</dt>
* <dd>
* <ul>
* <li>getActor(actorRef: ActorRef)</li>
* <li>createActorReference(mode: ActorMode)</li>
* </ul>
* </dd>
* </dl>
* */
public abstract class AbsActorSystem implements ActorSystem {
private final int nThreads = Runtime.getRuntime().availableProcessors();
protected final Map<ActorRef<?>, Actor<?>> actors = new ConcurrentHashMap<>();
protected final ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
@Override
public ActorRef<? extends Message> actorOf(Class<? extends Actor> actor, ActorMode mode) {
ActorRef<?> reference;
try {
// Create the reference to the actor
reference = this.createActorReference(mode);
// Create the new instance of the actor
Actor actorInstance = ((AbsActor) actor.newInstance()).setSelf(reference);
// Associate the reference to the actor
actors.put(reference, actorInstance);
executorService.execute((AbsActor) actorInstance);
} catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchActorException(e);
}
return reference;
}
@Override
public ActorRef<? extends Message> actorOf(Class<? extends Actor> actor) {
return this.actorOf(actor, ActorMode.LOCAL);
}
/*
* Pre-condition: The actor is defined and the actor system is initialized
* Post-condition: If the actor is null the side-effects are no one otherwise
* the method stops the given actor and removes it from the registry of actors
* */
public void stop(ActorRef actor) {
getActor(actor).stop();
actors.remove(actor);
}
/*
* Pre-condition: The actors reference is defined, in sense that the actors registry containes
* at least one actor.
* Post-condition: The method stops all actors into the registry one by one. At the end all actors
* will be stopped.
* */
public void stop() {
for (ActorRef a : actors.keySet())
stop(a);
}
/*
* Pre-condition: The actors is an Actor Registry. In containes the set of addresses to which is possible to
* interact with.
* actorRef: ActorRef is defined.
* Post-condition: The actor reference is defined && actors contains the actor's address => the method returns
* a valid actor reference. Otherwise the method throws an Exception===NoSuchActorException
* */
protected AbsActor getActor(ActorRef actorRef) throws NoSuchActorException {
if (actors.containsKey(actorRef))
return (AbsActor) actors.get(actorRef);
throw new NoSuchActorException();
}
protected abstract ActorRef createActorReference(ActorMode mode);
}
| 36.560284 | 116 | 0.650436 |
8d03917a9888fcb7478d841b631c4aca1dd6d508 | 2,072 | package no.uib.probe.csf.pr.touch.view;
import com.vaadin.server.VaadinSession;
import java.util.LinkedHashMap;
import java.util.Map;
import no.uib.probe.csf.pr.touch.view.core.BusyTaskProgressBar;
import no.uib.probe.csf.pr.touch.view.core.ControllingView;
/**
* This class represents the view controller, the controller is responsible for
* handling the requested layout and viewing it
*
* @author Yehia Farag
*
*
*/
public class LayoutViewManager {
/**
* Map of registered layout visualization.
*/
private final Map<String, ControllingView> layoutMap = new LinkedHashMap<>();
/**
* Current visualized layout.
*/
private ControllingView currentView;
/**
* System is doing long processing task to push the the system to show
* progress bar.
*/
private final BusyTaskProgressBar busyTask;
/**
* Constructor to initialize the main attributes
*
* @param busyTask progress bar controller.
*/
public LayoutViewManager(BusyTaskProgressBar busyTask) {
this.busyTask = busyTask;
}
/**
* Register layout component to the system
*
* @param component View component
*/
public void registerComponent(ControllingView component) {
layoutMap.put(component.getViewId(), component);
}
/**
* View selected layout based on user selection
*
* @param viewId View id
*/
public void viewLayout(String viewId) {
try {
VaadinSession.getCurrent().getLockInstance().lock();
this.busyTask.setVisible(true);
if (currentView != null && !currentView.getViewId().equalsIgnoreCase(viewId) && layoutMap.containsKey(viewId)) {
currentView.hide();
}
if (layoutMap.containsKey(viewId)) {
currentView = layoutMap.get(viewId);
currentView.view();
}
this.busyTask.setVisible(false);
} finally {
VaadinSession.getCurrent().getLockInstance().unlock();
}
}
}
| 27.263158 | 124 | 0.635618 |
c73b483e46af000c4af99b4c34b218c06f77b58a | 1,636 | package in.karthiks.lucenesample.controller;
import in.karthiks.lucenesample.lucene.LuceneReader;
import in.karthiks.lucenesample.lucene.LuceneWriter;
import org.apache.lucene.queryparser.classic.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Component
@RestController
@Validated
public class LuceneController {
@Autowired
private LuceneReader reader;
@Autowired
private LuceneWriter writer;
@PostMapping("/load")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
long count = writer.store(file.getInputStream());
return "Loaded " + count + " documents.";
}
@GetMapping("/search")
public ResponseEntity index(@RequestParam("search") String queryString) throws IOException, ParseException, org.json.simple.parser.ParseException {
List list = reader.query(queryString);
return ResponseEntity.ok(list);
}
}
| 35.565217 | 151 | 0.797677 |
021acd775d657e59feda192352c5e8d89125f730 | 359 | package com.github.sys.domain.role;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* Created by renhongqiang on 2019-03-19 20:35
*/
@Data
public class RoleUpdate {
@NotNull(message = "id不能为空!")
private Integer id;
/**角色名*/
private String name;
private String roleKey;
/**角色描述*/
private String mark;
}
| 15.608696 | 46 | 0.671309 |
4929bf5df5be902ffb93ef69c1328e4c3bee7760 | 617 | package com.ledboot.netmonitor;
import com.ledboot.annotation.MonitorTag;
import java.util.Set;
import okhttp3.Headers;
/**
* Created by ouyangxingyu198 on 17/3/28.
*/
@MonitorTag
public class Test {
public void addHead(Headers.Builder headerBuilder){
Headers headers = headerBuilder.build();
Set<String> names = headers.names();
for (String name: names) {
System.out.println("name:"+name+" values: "+headers.get(name));
}
}
public void add(int a,int b){
System.out.println("param1--->"+a);
System.out.println("param2--->"+b);
}
} | 20.566667 | 75 | 0.627229 |
b9783064eb20abc5eb78904c331768ae88687ac6 | 7,758 | /*
* 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 org.femass.gui;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.femass.dao.AnimalDao;
import org.femass.dao.ClienteDao;
import org.femass.model.Animal;
import org.femass.model.Cliente;
/**
*
* @author enzoappi
*/
public class GuiAnimalCliente extends javax.swing.JDialog {
private Animal animal;
public GuiAnimalCliente(java.awt.Frame parent, boolean modal, Animal animal) {
super(parent, modal);
initComponents();
this.animal = animal;
lblAnimal.setText("Animal: " + this.animal.getNome());
try {
lstClientesDisponiveis.setListData(new ClienteDao().getLista().toArray());
lstClientesRespAnimal.setListData(this.animal.getClientes().toArray());
} catch (SQLException ex) {
Logger.getLogger(GuiAnimalCliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lstClientesDisponiveis = new javax.swing.JList();
lblClientesDisponiveis = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
lstClientesRespAnimal = new javax.swing.JList();
lblClientesRespAnimal = new javax.swing.JLabel();
lblAnimal = new javax.swing.JLabel();
btnAdicionar = new javax.swing.JButton();
btnRemover = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Autores do Livro");
jScrollPane1.setViewportView(lstClientesDisponiveis);
lblClientesDisponiveis.setText("Clientes disponiveis");
jScrollPane2.setViewportView(lstClientesRespAnimal);
lblClientesRespAnimal.setText("Clientes resp Animal");
lblAnimal.setText("Animal");
btnAdicionar.setText(">");
btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarActionPerformed(evt);
}
});
btnRemover.setText("<");
btnRemover.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoverActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblAnimal)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(lblClientesDisponiveis, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnAdicionar)
.addComponent(btnRemover))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(lblClientesRespAnimal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblAnimal)
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblClientesRespAnimal, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblClientesDisponiveis))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2)
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(btnAdicionar)
.addGap(49, 49, 49)
.addComponent(btnRemover)
.addContainerGap(133, Short.MAX_VALUE))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
// TODO add your handling code here:
Cliente cliente = (Cliente) lstClientesDisponiveis.getSelectedValue();
this.animal.adicionarCliente(cliente);
try {
new AnimalDao().alterar(this.animal);
} catch (SQLException ex) {
Logger.getLogger(GuiAnimalCliente.class.getName()).log(Level.SEVERE, null, ex);
return;
}
lstClientesRespAnimal.setListData(this.animal.getClientes().toArray());
}//GEN-LAST:event_btnAdicionarActionPerformed
private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
// TODO add your handling code here:
Cliente cliente = (Cliente) lstClientesRespAnimal.getSelectedValue();
this.animal.removerAutor(cliente);
try {
new AnimalDao().alterar(this.animal);
} catch (SQLException ex) {
Logger.getLogger(GuiAnimalCliente.class.getName()).log(Level.SEVERE, null, ex);
return;
}
lstClientesRespAnimal.setListData(this.animal.getClientes().toArray());
}//GEN-LAST:event_btnRemoverActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAdicionar;
private javax.swing.JButton btnRemover;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblAnimal;
private javax.swing.JLabel lblClientesDisponiveis;
private javax.swing.JLabel lblClientesRespAnimal;
private javax.swing.JList lstClientesDisponiveis;
private javax.swing.JList lstClientesRespAnimal;
// End of variables declaration//GEN-END:variables
}
| 47.304878 | 201 | 0.660866 |
c8c6c0c1b49cfb7164a2548f59d2435fb8172a82 | 522 | package tech.maslov.rgenerator.generator.api.request;
import org.bson.types.ObjectId;
public class GeneratorFileEditRequest {
private ObjectId oldFileId;
private ObjectId newFileId;
public ObjectId getOldFileId() {
return oldFileId;
}
public void setOldFileId(ObjectId oldFileId) {
this.oldFileId = oldFileId;
}
public ObjectId getNewFileId() {
return newFileId;
}
public void setNewFileId(ObjectId newFileId) {
this.newFileId = newFileId;
}
}
| 20.88 | 53 | 0.687739 |
d5a871859a23be9bff19cb9437c7df8db86ed0e0 | 1,517 | package org.zalando.riptide;
import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;
import org.apiguardian.api.API;
import org.springframework.http.ResponseEntity;
import java.util.List;
import static org.apiguardian.api.API.Status.STABLE;
@API(status = STABLE)
public final class Types {
private Types() {
}
public static <T> TypeToken<List<T>> listOf(final Class<T> entityType) {
return listOf(TypeToken.of(entityType));
}
@SuppressWarnings("serial")
public static <T> TypeToken<List<T>> listOf(final TypeToken<T> entityType) {
final TypeToken<List<T>> listType = new TypeToken<List<T>>() {
// nothing to implement!
};
final TypeParameter<T> elementType = new TypeParameter<T>() {
// nothing to implement!
};
return listType.where(elementType, entityType);
}
public static <T> TypeToken<ResponseEntity<T>> responseEntityOf(final Class<T> entityType) {
return responseEntityOf(TypeToken.of(entityType));
}
public static <T> TypeToken<ResponseEntity<T>> responseEntityOf(final TypeToken<T> entityType) {
final TypeToken<ResponseEntity<T>> responseEntityType = new TypeToken<ResponseEntity<T>>() {
// nothing to implement!
};
final TypeParameter<T> elementType = new TypeParameter<T>() {
// nothing to implement!
};
return responseEntityType.where(elementType, entityType);
}
}
| 28.622642 | 100 | 0.669743 |
b4c8d79f8f4bd949e3e2f605ef07925cc413fed7 | 1,356 | package com.ljq.demo.springboot.xxljob.job;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description: 用户定时任务负载类(Bean 模式)
* @Author: junqiang.lu
* @Date: 2020/11/27
*/
@Slf4j
@Component
public class UserJob {
/**
* 用户定时任务处理器名称
*/
private static final String USER_JOB_HANDLE_NAME = "user-job-handle";
private final AtomicInteger count = new AtomicInteger();
/**
* 用户定时任务处理方法
*
* @param param
* @return
* @throws Exception
*/
@XxlJob(value = USER_JOB_HANDLE_NAME, init = "userJobInit", destroy = "userJobDestroy")
public ReturnT<String> userJobHandle(String param) throws Exception {
log.info("输入参数: {}", param);
log.info("[Bean模式]第[{}]次执行定时任务",count.incrementAndGet());
return ReturnT.SUCCESS;
}
/**
* 用户定时任务初始化方法,仅在执行器第一次执行前执行
* @return
*/
public ReturnT<String> userJobInit() {
log.info("[user-job-init]");
return ReturnT.SUCCESS;
}
/**
* 用户定时任务销毁方法,仅在执行器销毁时执行
* @return
*/
public ReturnT<String> userJobDestroy() {
log.info("[user-job-destroy]");
return ReturnT.SUCCESS;
}
}
| 22.983051 | 91 | 0.639381 |
76334db1d02cae7f0343ef90211daa118dea915c | 1,669 | package com.slackernews.service.Implementation;
import com.slackernews.model.Post;
import com.slackernews.model.PostCreationForm;
import com.slackernews.model.User;
import com.slackernews.repository.IPostRepository;
import com.slackernews.service.Interface.IPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
@Service
public class PostService implements IPostService {
private IPostRepository postRepository;
@Autowired
public PostService(IPostRepository postRepository) {
this.postRepository = postRepository;
}
public Optional<Post> getPostById(int id) {
return Optional.ofNullable(postRepository.findOne(id));
}
public List<Post> getAllPosts() {
return postRepository.findAll();
}
@Override
public Post create(PostCreationForm form, User user) throws MalformedURLException {
String title = form.getTitle();
URL url = new URL("https://google.com");
String text = form.getText();
Post post = new Post(title, url, text, user);
post = postRepository.save(post);
if (form.getUrl().isEmpty()) {
String urlString = "http://localhost:8080/post/" + post.getId().toString(); //TODO: get url stem from environment variable
url = new URL(urlString);
post.setURL(url);
}
return postRepository.save(post);
}
@Override
public Post updatePostInfo(Post post) {
return postRepository.save(post);
}
}
| 28.288136 | 134 | 0.700419 |
469f95de1cdcec062799effc8536abc8bfbf2fd1 | 234 | package com.github.doobo.config;
import com.github.doobo.start.AbstractIpfsInitClient;
import org.springframework.stereotype.Component;
/**
* ipfs环境初始化
*/
@Component
public class IpfsInitBackup extends AbstractIpfsInitClient {
}
| 18 | 60 | 0.807692 |
6573410db6796cbaa4723cb3f5b37d93b58fc511 | 5,435 | package omtteam.openmodularlighting.handler.recipes;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.ShapedOreRecipe;
import omtteam.openmodularlighting.init.ModBlocks;
import omtteam.openmodularlighting.init.ModItems;
class VanillaRecipeHandler {
public static void init() {
// ModItems
// Barrels
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 11), "AAA", " B ", "AAA", 'A', "ingotIron",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 10)));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 12), "AAA", " B ", "AAA", 'A', "ingotGold",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 11)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 13), "CAC", " B ", "CAC", 'A',
Items.DIAMOND, 'B', new ItemStack(ModItems.intermediateProductTiered, 1, 12),
'C', Items.QUARTZ));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 14), "AAA", "CBC", "AAA", 'A',
Blocks.OBSIDIAN, 'B', new ItemStack(ModItems.intermediateProductTiered, 1, 13),
'C', Items.GLOWSTONE_DUST));
// Chambers
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 6), "AAA", " BC", "AAA", 'A', "ingotIron",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 5), 'C', Items.REDSTONE));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 7), "AAA", " BC", "AAA", 'A', "ingotGold",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 6), 'C', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 8), "DAD", " BC", "DAD", 'A',
Items.DIAMOND, 'B', new ItemStack(ModItems.intermediateProductTiered, 1, 7), 'C', RecipeHandler.transformer,
'D', Items.QUARTZ));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 9), "ADA", " BC", "ADA", 'A',
Blocks.OBSIDIAN, 'B', new ItemStack(ModItems.intermediateProductTiered, 1, 8), 'C',
RecipeHandler.transformer, 'D', Items.QUARTZ));
// Sensors
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 1), " A ", "ABA", " C ", 'A', "ingotIron",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 0), 'C', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 2), " C ", "ABA", " C ", 'A', "ingotGold",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 1), 'C', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 3), "EDE", "CBC", "EDE", 'A', "ingotGold",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 2), 'C', RecipeHandler.transformer, 'D',
Items.DIAMOND, 'E', Items.QUARTZ));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModItems.intermediateProductTiered, 1, 4), "EDE", "CBC", "EDE", 'A', "ingotGold",
'B', new ItemStack(ModItems.intermediateProductTiered, 1, 3), 'C', RecipeHandler.transformer, 'D',
Items.GLOWSTONE_DUST, 'E', Blocks.OBSIDIAN));
// Bases
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModBlocks.lightingBase, 1, 1), "ABA", "DCD", "ADA", 'A', "ingotIron",
'B', new ItemStack(ModBlocks.lightingBase, 1, 0), 'C', new ItemStack(ModItems.intermediateProductTiered, 1, 1), 'D', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModBlocks.lightingBase, 1, 2), "ABA", "DCD", "ADA", 'A', "ingotGold",
'B', new ItemStack(ModBlocks.lightingBase, 1, 1), 'C', new ItemStack(ModItems.intermediateProductTiered, 1, 2), 'D', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModBlocks.lightingBase, 1, 3), "ABA", "DCD", "ADA", 'A',
Items.DIAMOND, 'B', new ItemStack(ModBlocks.lightingBase, 1, 2), 'C',
new ItemStack(ModItems.intermediateProductTiered, 1, 3), 'D', RecipeHandler.transformer));
GameRegistry.addRecipe(
new ShapedOreRecipe(new ItemStack(ModBlocks.lightingBase, 1, 4), "ABA", "DCD", "ADA", 'A',
Blocks.OBSIDIAN, 'B', new ItemStack(ModBlocks.lightingBase, 1, 3), 'C',
new ItemStack(ModItems.intermediateProductTiered, 1, 4), 'D', RecipeHandler.transformer));
}
}
| 58.44086 | 169 | 0.618583 |
01a55c2802b77da4633f79a759a1e3a36a753eaa | 2,432 | package com.box.l10n.mojito.security;
import com.box.l10n.mojito.entity.security.user.User;
import com.box.l10n.mojito.service.security.user.UserRepository;
import com.box.l10n.mojito.service.security.user.UserService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Map;
import static org.slf4j.LoggerFactory.getLogger;
@Configurable
public class MyUserInfoTokenServices extends UserInfoTokenServices {
/**
* logger
*/
static Logger logger = getLogger(MyUserInfoTokenServices.class);
@Autowired
UserService userService;
@Autowired
UserRepository userRepository;
public MyUserInfoTokenServices(String userInfoEndpointUrl, String clientId) {
super(userInfoEndpointUrl, clientId);
}
@Override
protected Object getPrincipal(Map<String, Object> map) {
logger.debug("Get principal: {}", map);
UserDetails userDetails = null;
map = getMapWithUserInfo(map);
String username = (String) super.getPrincipal(map);
User user = getOrCreateUser(map, username);
return new UserDetailsImpl(user);
}
User getOrCreateUser(Map<String, Object> map, String username) {
User user = userRepository.findByUsername(username);
if (user == null || user.getPartiallyCreated()) {
String givenName = (String) map.get("first_name");
String surname = (String) map.get("last_name");
String commonName = (String) map.get("name");
user = userService.createOrUpdateBasicUser(user, username, givenName, surname, commonName);
}
return user;
}
/**
* Some API retruns the user info directly and some have one level of indirection with a key name called "user".
* This function get the map that contains user information.
*
* @param map from the response
* @return the map that contains the user info
*/
private Map<String, Object> getMapWithUserInfo(Map<String, Object> map) {
Object user = map.get("user");
if (user instanceof Map) {
map = (Map<String, Object>) user;
}
return map;
}
}
| 31.584416 | 116 | 0.694079 |
aaa9d8a2f5c81d61cf6381149354f66e1e5b883b | 223 |
package com.beacon.shopping.assistant.action;
import android.content.Context;
/**
* Created by lahiru on 10/04/2018.
*/
public interface IAction {
boolean isParamRequired();
String execute(Context context);
}
| 15.928571 | 45 | 0.726457 |
d4cca34acef55fcbdb74f546ec01fb50a5c57e78 | 12,242 | /*-
* #%L
* Genome Damage and Stability Centre SMLM ImageJ Plugins
*
* Software for single molecule localisation microscopy (SMLM)
* %%
* Copyright (C) 2011 - 2020 Alex Herbert
* %%
* 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/gpl-3.0.html>.
* #L%
*/
package uk.ac.sussex.gdsc.smlm.results;
import uk.ac.sussex.gdsc.core.data.utils.Converter;
import uk.ac.sussex.gdsc.core.data.utils.IdentityTypeConverter;
import uk.ac.sussex.gdsc.core.data.utils.TypeConverter;
import uk.ac.sussex.gdsc.core.utils.LocalList;
import uk.ac.sussex.gdsc.core.utils.TextUtils;
import uk.ac.sussex.gdsc.smlm.data.config.CalibrationHelper;
import uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration;
import uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter;
import uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException;
import uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF;
import uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFParameter;
import uk.ac.sussex.gdsc.smlm.data.config.PsfHelper;
import uk.ac.sussex.gdsc.smlm.data.config.UnitHelper;
import uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.AngleUnit;
import uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit;
import uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit;
/**
* Helper class for converting peak results.
*/
public class PeakResultConversionHelper {
private final Calibration calibration;
private final PSF psf;
/**
* Instantiates a new peak result conversion helper.
*
* @param calibration the calibration
* @param psf the psf
*/
public PeakResultConversionHelper(Calibration calibration, PSF psf) {
this.calibration = calibration;
this.psf = psf;
}
/** The intensity unit. */
private IntensityUnit intensityUnit;
/** The intensity converter. */
private TypeConverter<IntensityUnit> intensityConverter;
/**
* Gets the intensity unit.
*
* @return the intensity unit
*/
public IntensityUnit getIntensityUnit() {
return intensityUnit;
}
/**
* Sets the intensity unit.
*
* @param intensityUnit the new intensity unit
*/
public void setIntensityUnit(IntensityUnit intensityUnit) {
intensityConverter = null;
this.intensityUnit = intensityUnit;
}
/**
* Checks for intensity unit.
*
* @return true, if successful
*/
public boolean hasIntensityUnit() {
return intensityUnit != null;
}
/**
* Checks for intensity converter.
*
* @return true, if successful
*/
public boolean hasIntensityConverter() {
return intensityConverter != null && intensityConverter.to() != null;
}
/**
* Gets the intensity converter for the configured units. If the calibration is null then an
* identity converter is returned.
*
* @return the intensity converter
*/
public TypeConverter<IntensityUnit> getIntensityConverter() {
if (intensityConverter == null) {
intensityConverter = (calibration == null) ? new IdentityTypeConverter<>(null)
: CalibrationHelper.getIntensityConverterSafe(calibration, intensityUnit);
}
return intensityConverter;
}
/** The distance unit. */
private DistanceUnit distanceUnit;
/** The distance converter. */
private TypeConverter<DistanceUnit> distanceConverter;
/**
* Gets the distance unit.
*
* @return the distance unit
*/
public DistanceUnit getDistanceUnit() {
return distanceUnit;
}
/**
* Sets the distance unit.
*
* @param distanceUnit the new distance unit
*/
public void setDistanceUnit(DistanceUnit distanceUnit) {
distanceConverter = null;
this.distanceUnit = distanceUnit;
}
/**
* Checks for distance unit.
*
* @return true, if successful
*/
public boolean hasDistanceUnit() {
return distanceUnit != null;
}
/**
* Checks for distance converter.
*
* @return true, if successful
*/
public boolean hasDistanceConverter() {
return distanceConverter != null && distanceConverter.to() != null;
}
/**
* Gets the distance converter for the configured units. If the calibration is null then an
* identity converter is returned.
*
* @return the distance converter
*/
public TypeConverter<DistanceUnit> getDistanceConverter() {
if (distanceConverter == null) {
distanceConverter = (calibration == null) ? new IdentityTypeConverter<>(null)
: CalibrationHelper.getDistanceConverterSafe(calibration, distanceUnit);
}
return distanceConverter;
}
/** The angle unit. */
private AngleUnit angleUnit;
/** The angle converter. */
private TypeConverter<AngleUnit> angleConverter;
/**
* Gets the angle unit.
*
* @return the angle unit
*/
public AngleUnit getAngleUnit() {
return angleUnit;
}
/**
* Sets the angle unit.
*
* @param angleUnit the new angle unit
*/
public void setAngleUnit(AngleUnit angleUnit) {
angleConverter = null;
this.angleUnit = angleUnit;
}
/**
* Checks for angle unit.
*
* @return true, if successful
*/
public boolean hasAngleUnit() {
return angleUnit != null;
}
/**
* Checks for angle converter.
*
* @return true, if successful
*/
public boolean hasAngleConverter() {
return angleConverter != null && angleConverter.to() != null;
}
/**
* Gets the angle converter for the configured units. If the calibration is null then an identity
* converter is returned.
*
* @return the angle converter
*/
public TypeConverter<AngleUnit> getAngleConverter() {
if (angleConverter == null) {
angleConverter = (calibration == null) ? new IdentityTypeConverter<>(null)
: CalibrationHelper.getAngleConverterSafe(calibration, angleUnit);
}
return angleConverter;
}
/**
* Gets the converters for the peak results parameters. This includes the standard parameters and
* any additional parameters defined in the PSF. If a parameter unit type is undefined then an
* identity converter is created.
*
* @return the converters
*/
public Converter[] getConverters() {
final LocalList<Converter> list = new LocalList<>(5);
getIntensityConverter();
getDistanceConverter();
list.add(intensityConverter);
list.add(intensityConverter);
list.add(distanceConverter);
list.add(distanceConverter);
list.add(distanceConverter);
if (psf != null) {
try {
for (final PSFParameter p : PsfHelper.getParameters(psf)) {
switch (p.getUnit()) {
case DISTANCE:
list.add(distanceConverter);
break;
case INTENSITY:
list.add(intensityConverter);
break;
case ANGLE:
list.add(getAngleConverter());
break;
default:
list.add(new IdentityTypeConverter<>(p.getUnit()));
}
}
} catch (final ConfigurationException ex) {
// Ignore
}
}
return list.toArray(new Converter[0]);
}
/**
* Gets the names for the peak results parameters. This includes the standard parameters and any
* additional parameters defined in the PSF. If a parameter name is undefined then unknown is
* returned.
*
* @return the converters
*/
public String[] getNames() {
final LocalList<String> list = new LocalList<>(5);
list.add("Background");
list.add("Intensity");
list.add("X");
list.add("Y");
list.add("Z");
if (psf != null) {
try {
for (final PSFParameter p : PsfHelper.getParameters(psf)) {
final String name = p.getName();
list.add(TextUtils.isNullOrEmpty(name) ? "unknown" : name);
}
} catch (final ConfigurationException ex) {
// Ignore
}
}
return list.toArray(new String[0]);
}
/**
* Gets the unit names for the peak results parameters. This includes the standard parameters and
* any additional parameters defined in the PSF. If a parameter unit is undefined then an empty
* string is returned.
*
* @return the converters
*/
public String[] getUnitNames() {
final LocalList<String> list = new LocalList<>(5);
getIntensityConverter();
getDistanceConverter();
final String safeIntensityUnit =
(intensityConverter.to() != null) ? UnitHelper.getShortName(intensityConverter.to()) : "";
final String safeDistanceUnit =
(distanceConverter.to() != null) ? UnitHelper.getShortName(distanceConverter.to()) : "";
String safeAngleUnit = null;
list.add(safeIntensityUnit);
list.add(safeIntensityUnit);
list.add(safeDistanceUnit);
list.add(safeDistanceUnit);
list.add(safeDistanceUnit);
if (psf != null) {
try {
for (final PSFParameter p : PsfHelper.getParameters(psf)) {
switch (p.getUnit()) {
case DISTANCE:
list.add(safeDistanceUnit);
break;
case INTENSITY:
list.add(safeIntensityUnit);
break;
case ANGLE:
safeAngleUnit = getOrCreateAngleUnit(safeAngleUnit);
list.add(safeAngleUnit);
break;
default:
list.add("");
}
}
} catch (final ConfigurationException ex) {
// Ignore
}
}
return list.toArray(new String[0]);
}
private String getOrCreateAngleUnit(String angleUnit) {
if (angleUnit == null) {
getAngleConverter();
angleUnit = (angleConverter.to() != null) ? UnitHelper.getShortName(angleConverter.to()) : "";
}
return angleUnit;
}
/**
* Test if the current converters will cause the calibration to be changed, i.e. new units.
*
* @return true, if successful
*/
public boolean isCalibrationChanged() {
if (calibration == null) {
return false;
}
if (hasIntensityConverter() && getIntensityConverter().from() != getIntensityConverter().to()) {
return true;
}
if (hasDistanceConverter() && getDistanceConverter().from() != getDistanceConverter().to()) {
return true;
}
return (hasAngleConverter() && getAngleConverter().from() != getAngleConverter().to());
}
/**
* Test if the current converters will changed to desired units.
*
* @return true, if successful
*/
public boolean isValidConversion() {
boolean bad = false;
// The conversion is bad if the output unit is specified and either:
// there is no converter; or the converter will output the wrong units.
//@formatter:off
bad |= (hasIntensityUnit()
&& (!hasIntensityConverter() || intensityUnit != getIntensityConverter().to()));
bad |= (hasDistanceUnit()
&& (!hasDistanceConverter() || distanceUnit != getDistanceConverter().to()));
bad |= (hasAngleUnit()
&& (!hasAngleConverter() || angleUnit != getAngleConverter().to()));
//@formatter:on
return !bad;
}
/**
* Gets the calibration, updated with the current output units of the converters.
*
* @return the calibration
*/
public Calibration getCalibration() {
if (calibration == null) {
return null;
}
final CalibrationWriter calibrationWriter = new CalibrationWriter(this.calibration);
if (hasIntensityConverter()) {
calibrationWriter.setIntensityUnit(getIntensityConverter().to());
}
if (hasDistanceConverter()) {
calibrationWriter.setDistanceUnit(getDistanceConverter().to());
}
if (hasAngleConverter()) {
calibrationWriter.setAngleUnit(getAngleConverter().to());
}
return calibrationWriter.getCalibration();
}
}
| 28.737089 | 100 | 0.662228 |
f4e4ba9fb98aba631e32890fc4b22c019c4f0c55 | 2,648 | package com.lanking.uxb.service.file.api.impl;
import org.springframework.stereotype.Component;
import com.lanking.cloud.domain.base.file.FileType;
import com.lanking.cloud.sdk.util.StringUtils;
import com.lanking.cloud.springboot.environment.Env;
@Component("linuxMediaHandle")
public class LinuxMediaHandle extends AbstractMediaHandle {
@Override
public void convert(String srcFilePath, String destFilePath, FileType type) {
try {
String shell = null;
if (type == FileType.AUDIO) {
if (StringUtils.isNotBlank(Env.getString("file.audio.convert"))) {
shell = ffmpeg() + " -i " + srcFilePath + " " + Env.getString("file.audio.convert") + " "
+ destFilePath;
} else {
shell = ffmpeg() + " -i " + srcFilePath + " " + destFilePath;
}
} else if (type == FileType.VIDEO) {
if (StringUtils.isNotBlank(Env.getString("file.video.convert"))) {
shell = ffmpeg() + " -i " + srcFilePath + " " + Env.getString("file.video.convert") + " "
+ destFilePath;
} else {
shell = ffmpeg() + " -i " + srcFilePath + " " + destFilePath;
}
}
if (shell != null) {
logger.info("convert start:{}", srcFilePath);
runShell(shell);
logger.info("convert end:{}", destFilePath);
}
} catch (Exception e) {
logger.error("convert fail:", e);
}
}
@Override
public void segment(String srcFilePath, String destFilePath, FileType type, int start, int end) {
try {
String startTime = processTime(start);
String endTime = processTime(end);
String shell = null;
if (type == FileType.AUDIO) {
shell = ffmpeg() + " -ss " + startTime + " -i " + srcFilePath + " "
+ Env.getString("file.audio.segment") + " -t " + endTime + " " + destFilePath;
} else if (type == FileType.VIDEO) {
shell = ffmpeg() + " -ss " + startTime + " -i " + srcFilePath + " "
+ Env.getString("file.video.segment") + " -t " + endTime + " " + destFilePath;
}
if (shell != null) {
runShell(shell);
}
} catch (Exception e) {
logger.error("segment fail:", e);
}
}
private void runShell(String shell) {
try {
Process process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", shell }, null, null);
// InputStream stderr = process.getErrorStream();
// InputStreamReader isr = new InputStreamReader(stderr);
// BufferedReader br = new BufferedReader(isr);
// String line = null;
// while ((line = br.readLine()) != null) {
// logger.info(line);
// }
process.waitFor();
} catch (Exception e) {
logger.error("execute command fail:", e);
}
}
}
| 33.518987 | 101 | 0.606873 |
2f43410e18c5159a72a6cbd2ff68e2c4f1b55e79 | 729 | package cloud.tenon.gradle.bom.library;
import java.util.List;
public class Group {
private final String id;
private final List<Module> modules;
private final List<String> plugins;
private final List<String> boms;
public Group(String id, List<Module> modules, List<String> plugins, List<String> boms) {
this.id = id;
this.modules = modules;
this.plugins = plugins;
this.boms = boms;
}
public String getId() {
return this.id;
}
public List<Module> getModules() {
return this.modules;
}
public List<String> getPlugins() {
return this.plugins;
}
public List<String> getBoms() {
return this.boms;
}
}
| 18.692308 | 92 | 0.611797 |
0afc1fce0bcbc6f0760039e7c74d3234eda1c2eb | 2,541 | package uo.ri.business.impl.transactionScript.contractType;
import java.sql.Connection;
import java.sql.SQLException;
import alb.util.jdbc.Jdbc;
import uo.ri.business.dto.ContractTypeDto;
import uo.ri.business.exception.BusinessException;
import uo.ri.conf.GatewayFactory;
import uo.ri.persistence.ContractTypeGateway;
import uo.ri.persistence.exception.PersistanceException;
/**
* Clase que contiene la logica para la creacion de un tipo de contrato.
*/
public class AddContractType {
private final ContractTypeGateway contractTypeGateway =
GatewayFactory.getContractTypeGateway();
private ContractTypeDto contractTypeDto;
private Connection connection;
public AddContractType(ContractTypeDto contractTypeDto) {
this.contractTypeDto = contractTypeDto;
}
/**
* Metodo que crea un nuevo tipo de contrato si es posible.
*
* @throws BusinessException
*/
public void execute() throws BusinessException {
try {
connection = Jdbc.createThreadConnection();
connection.setAutoCommit(false);
checkData();
contractTypeGateway.addContractType(contractTypeDto);
connection.commit();
} catch (PersistanceException e) {
try {
connection.rollback();
throw new BusinessException
("Error al añadir el tipo de contr" +
"ato.\n\t" + e.getMessage());
} catch (SQLException ignored) {
throw new BusinessException("Error en rollback.");
}
} catch (SQLException e1) {
try {
connection.rollback();
throw new BusinessException
("Error al añadir el tipo de contrato.\n\t" + e1);
} catch (SQLException ignored) {
throw new BusinessException("Error en rollback.");
}
} finally {
Jdbc.close(connection);
}
}
private void checkData() throws BusinessException,
PersistanceException {
if (contractTypeDto.compensationDays < 0)
throw new BusinessException
("El numero de dias de compensacion " +
"debe ser mayor que 0.");
if (contractTypeGateway
.findContractTypeByName(contractTypeDto.name) != null)
throw new BusinessException
("Ya existe un tipo de contrato con ese nombre.");
}
}
| 32.576923 | 74 | 0.607635 |
fbb5cbb7123b9b41bee3fb1c76606f857b95b606 | 1,778 | /*
* Copyright 2018 austen.
*
* 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 actors.subclassses;
import actors.Placeable;
import actors.Unit;
import actors.Warrior;
import utils.Dice;
/**
*
* @author austen
*/
public class Berserker extends Warrior{
private void init()
{
Dice attackDice = new Dice(100,100);
Dice defenseDice = new Dice(1,12);
Dice damageDice = new Dice(1,8);
super.init(2, attackDice, defenseDice, damageDice, 30);
super.addAttack("cleaving strike");
super.addAttack("dash");
}
public Berserker()
{
super("Jerry",12,'B');
init();
}
public Berserker(String name)
{
super(name,12,'B');
init();
}
public Berserker(String name, int maxHP)
{
super(name,maxHP,'B');
init();
}
public Berserker(String name, int maxHP, char token)
{
super(name, maxHP,token);
init();
}
public Berserker(String name, int maxHP, char token, int UID)
{
super(name,maxHP,token,UID);
init();
}
@Override
public String getUnitType() {
return "Berserker";
}
@Override
public void levelUp() {
}
}
| 22.794872 | 75 | 0.613048 |
48630fa07a189a0136fb8f5183572555dee440e7 | 1,125 | package com.webank.wecube.platform.auth.server.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "AUTH_SYS_USER_ROLE")
public class UserRoleRelationshipEntity extends AbstractTraceableEntity {
@Id
@GeneratedValue
@Column(name = "ID")
private Long id;
@ManyToOne
@JoinColumn(name = "USER_ID")
private SysUserEntity user;
@ManyToOne
@JoinColumn(name = "ROLE_ID")
private SysRoleEntity role;
public UserRoleRelationshipEntity() {
}
public UserRoleRelationshipEntity(SysUserEntity user, SysRoleEntity role) {
this.setUser(user);
this.setRole(role);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public SysUserEntity getUser() {
return user;
}
public void setUser(SysUserEntity user) {
this.user = user;
}
public SysRoleEntity getRole() {
return role;
}
public void setRole(SysRoleEntity role) {
this.role = role;
}
}
| 18.75 | 76 | 0.751111 |
290b4d4828dc06cf142979bd77656dd3b19bd710 | 3,126 | package dk.alexandra.fresco.framework.sce.evaluator;
import dk.alexandra.fresco.framework.ProtocolEvaluator;
import dk.alexandra.fresco.framework.ProtocolProducer;
import dk.alexandra.fresco.framework.network.Network;
import dk.alexandra.fresco.framework.sce.resources.ResourcePool;
import dk.alexandra.fresco.suite.ProtocolSuite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Protocol evaluator implementation which works by evaluating native protocols in batches of a
* certain batch size. How each batch is evaluated is up to the given batch evaluation strategy.
* Each batch is required to contain only functionally independent native protocols.
*
* @param <ResourcePoolT> The resource pool type to use
*/
public class BatchedProtocolEvaluator<ResourcePoolT extends ResourcePool>
implements ProtocolEvaluator<ResourcePoolT> {
private Logger logger = LoggerFactory.getLogger(BatchedProtocolEvaluator.class);
private static final int MAX_EMPTY_BATCHES_IN_A_ROW = 10;
private final BatchEvaluationStrategy<ResourcePoolT> batchEvaluator;
private final ProtocolSuite<ResourcePoolT, ?> protocolSuite;
private final int maxBatchSize;
public BatchedProtocolEvaluator(
BatchEvaluationStrategy<ResourcePoolT> batchEvaluator,
ProtocolSuite<ResourcePoolT, ?> protocolSuite) {
this(batchEvaluator, protocolSuite, 4096);
}
public BatchedProtocolEvaluator(
BatchEvaluationStrategy<ResourcePoolT> batchEvaluator,
ProtocolSuite<ResourcePoolT, ?> protocolSuite, int maxBatchSize) {
this.batchEvaluator = batchEvaluator;
this.maxBatchSize = maxBatchSize;
this.protocolSuite = protocolSuite;
}
@Override
public EvaluationStatistics eval(ProtocolProducer protocolProducer, ResourcePoolT resourcePool,
Network network) {
int batch = 0;
int totalProtocols = 0;
int totalBatches = 0;
NetworkBatchDecorator networkBatchDecorator = createSceNetwork(resourcePool, network);
ProtocolSuite.RoundSynchronization<ResourcePoolT> roundSynchronization =
protocolSuite.createRoundSynchronization();
do {
ProtocolCollectionList<ResourcePoolT> protocols = new ProtocolCollectionList<>(maxBatchSize);
protocolProducer.getNextProtocols(protocols);
int size = protocols.size();
roundSynchronization.beforeBatch(protocols, resourcePool, network);
batchEvaluator.processBatch(protocols, resourcePool, networkBatchDecorator);
logger.trace("Done evaluating batch: " + batch++ + " with " + size + " native protocols");
if (size == 0) {
logger.debug("Batch " + batch + " is empty");
}
totalProtocols += size;
totalBatches += 1;
roundSynchronization.finishedBatch(size, resourcePool, network);
} while (protocolProducer.hasNextProtocols());
roundSynchronization.finishedEval(resourcePool, network);
return new EvaluationStatistics(totalProtocols, totalBatches);
}
private NetworkBatchDecorator createSceNetwork(ResourcePool resourcePool, Network network) {
return new NetworkBatchDecorator(resourcePool.getNoOfParties(), network);
}
}
| 41.131579 | 99 | 0.773193 |
11f002917f938b2d97841136f2b79aaace34281f | 1,481 | package leitor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public abstract class LeitorAbstrato implements Leitor{
private String fileName;
private int inic;
public LeitorAbstrato(String fileName , int inic) {
this.fileName = fileName;
this.inic = inic;
}
public ArrayList<String> getList() throws FileNotFoundException {
Scanner scan = new Scanner(new File(fileName));
String line;
ArrayList<String> lista = new ArrayList<>();
String[] t = new String[2];
while(scan.hasNextLine()) {
line = scan.nextLine();
t = line.split(",");
lista.add(t[getIndex()]);
}
scan.close();
return lista;
}
public int getNumOfX() throws FileNotFoundException {
return (getList().size()-inic);
}
public int getMaxX() throws FileNotFoundException {
LeitorX x = new LeitorX(fileName,0);
ArrayList<String> listaX = x.getList();
int max = 0 , result = 0;
for(int i=inic; i<listaX.size(); i++) {
result = Integer.parseInt(listaX.get(i));
if(result > max)
max = result;
}
return max;
}
public int getMaxY() throws FileNotFoundException {
ArrayList<String> listaY = getList();
int max = 0 , result = 0;
for(int i=inic; i<listaY.size(); i++) {
result = Integer.parseInt(listaY.get(i));
if(result > max)
max = result;
}
return max;
}
public abstract int getIndex();
}
| 23.507937 | 67 | 0.642134 |
fb07d5c4fbd7707d585f601f8474cdf879ac45c9 | 10,356 | ///*|-----------------------------------------------------------------------------
// *| This source code is provided under the Apache 2.0 license --
// *| and is provided AS IS with no warranty or guarantee of fit for purpose. --
// *| See the project's LICENSE.md for details. --
// *| Copyright (C) 2019 Refinitiv. All rights reserved. --
///*|-----------------------------------------------------------------------------
package com.refinitiv.ema.access;
import java.util.ArrayList;
import java.util.List;
import com.refinitiv.eta.transport.CompressionTypes;
import com.refinitiv.eta.transport.ConnectionTypes;
import com.refinitiv.eta.valueadd.domainrep.rdm.dictionary.DictionaryRequest;
import com.refinitiv.eta.valueadd.domainrep.rdm.directory.DirectoryRefresh;
import com.refinitiv.eta.valueadd.domainrep.rdm.directory.DirectoryRequest;
import com.refinitiv.eta.valueadd.domainrep.rdm.login.LoginRequest;
abstract class ActiveConfig extends BaseConfig
{
final static int DEFAULT_COMPRESSION_THRESHOLD = 30;
final static int DEFAULT_COMPRESSION_THRESHOLD_LZ4 = 300;
final static int DEFAULT_COMPRESSION_TYPE = CompressionTypes.NONE;
final static int DEFAULT_CONNECTION_TYPE = ConnectionTypes.SOCKET;
final static int DEFAULT_ENCRYPTED_PROTOCOL_TYPE = ConnectionTypes.HTTP;
final static int DEFAULT_CONNECTION_PINGTIMEOUT = 30000;
final static int DEFAULT_INITIALIZATION_TIMEOUT = 5;
final static int DEFAULT_INITIALIZATION_ACCEPT_TIMEOUT = 60;
final static int DEFAULT_DICTIONARY_REQUEST_TIMEOUT = 45000;
final static int DEFAULT_DIRECTORY_REQUEST_TIMEOUT = 45000;
final static boolean DEFAULT_ENABLE_SESSION_MGNT = false;
final static int DEFAULT_GUARANTEED_OUTPUT_BUFFERS = 100;
final static String DEFAULT_REGION_LOCATION = "us-east";
final static int DEFAULT_NUM_INPUT_BUFFERS = 10;
final static int DEFAULT_SYS_SEND_BUFFER_SIZE = 0;
final static int DEFAULT_SYS_RECEIVE_BUFFER_SIZE = 0;
final static int DEFAULT_HIGH_WATER_MARK = 0;
final static boolean DEFAULT_HANDLE_EXCEPTION = true;
final static String DEFAULT_HOST_NAME = "localhost";
final static String DEFAULT_CHANNEL_SET_NAME = "";
final static boolean DEFAULT_INCLUDE_DATE_IN_LOGGER_OUTPUT = false;
final static String DEFAULT_INTERFACE_NAME = "" ;
final static int DEFAULT_LOGIN_REQUEST_TIMEOUT = 45000;
final static int DEFAULT_MAX_OUTSTANDING_POSTS = 100000;
final static boolean DEFAULT_MSGKEYINUPDATES = true;
final static int DEFAULT_OBEY_OPEN_WINDOW = 1;
final static int DEFAULT_PIPE_PORT = 9001;
final static int DEFAULT_POST_ACK_TIMEOUT = 15000;
final static int DEFAULT_REACTOR_EVENTFD_PORT = 55000;
final static int DEFAULT_RECONNECT_ATTEMPT_LIMIT = -1;
final static int DEFAULT_RECONNECT_MAX_DELAY = 5000;
final static int DEFAULT_RECONNECT_MIN_DELAY = 1000;
final static String DEFAULT_OBJECT_NAME = "";
final static boolean DEFAULT_TCP_NODELAY = true;
final static String DEFAULT_CONS_MCAST_CFGSTRING = "";
final static int DEFAULT_PACKET_TTL = 5;
final static int DEFAULT_NDATA = 7;
final static int DEFAULT_NMISSING = 128;
final static int DEFAULT_NREQ = 3;
final static int DEFAULT_PKT_POOLLIMIT_HIGH = 190000;
final static int DEFAULT_PKT_POOLLIMIT_LOW = 180000;
final static int DEFAULT_TDATA = 1;
final static int DEFAULT_TRREQ = 4;
final static int DEFAULT_TWAIT = 3;
final static int DEFAULT_TBCHOLD = 3;
final static int DEFAULT_TPPHOLD = 3;
final static int DEFAULT_USER_QLIMIT = 65535;
final static int DEFAULT_REST_REQUEST_TIMEOUT = 45000;
final static int DEFAULT_REISSUE_TOKEN_ATTEMPT_LIMIT = -1;
final static int DEFAULT_REISSUE_TOKEN_ATTEMPT_INTERVAL = 5000;
final static double DEFAULT_TOKEN_REISSUE_RATIO = 0.8;
final static boolean DEFAULT_XML_TRACE_ENABLE = false;
final static boolean DEFAULT_DIRECT_SOCKET_WRITE = false;
final static boolean DEFAULT_HTTP_PROXY = false;
final static String DEFAULT_CONS_NAME = "EmaConsumer";
final static String DEFAULT_IPROV_NAME = "EmaIProvider";
final static String DEFAULT_NIPROV_NAME = "EmaNiProvider";
final static int SOCKET_CONN_HOST_CONFIG_BY_FUNCTION_CALL = 0x01; /*!< Indicates that host set though EMA interface function calls for RSSL_SOCKET connection type */
final static int SOCKET_SERVER_PORT_CONFIG_BY_FUNCTION_CALL = 0x02; /*!< Indicates that server listen port set though EMA interface function call from server client*/
final static int TUNNELING_PROXY_HOST_CONFIG_BY_FUNCTION_CALL = 0x04; /*!< Indicates that tunneling proxy host set though EMA interface function calls for HTTP/ENCRYPTED connection type*/
final static int TUNNELING_PROXY_PORT_CONFIG_BY_FUNCTION_CALL = 0x08; /*!< Indicates that tunneling proxy host set though EMA interface function calls for HTTP/ENCRYPTED connection type*/
final static int TUNNELING_OBJNAME_CONFIG_BY_FUNCTION_CALL = 0x10; /*!< Indicates that tunneling proxy host set though EMA interface function calls for HTTP/ENCRYPTED connection type*/
int obeyOpenWindow;
int postAckTimeout;
int maxOutstandingPosts;
int loginRequestTimeOut;
int directoryRequestTimeOut;
int dictionaryRequestTimeOut;
List<ChannelConfig> channelConfigSet;
LoginRequest rsslRDMLoginRequest;
DirectoryRequest rsslDirectoryRequest;
DirectoryRefresh rsslDirectoryRefresh;
DictionaryRequest rsslFldDictRequest;
DictionaryRequest rsslEnumDictRequest;
int reissueTokenAttemptLimit;
int reissueTokenAttemptInterval;
int restRequestTimeout;
double tokenReissueRatio;
String fldDictReqServiceName;
String enumDictReqServiceName;
DictionaryConfig dictionaryConfig;
static String defaultServiceName;
int reconnectAttemptLimit;
int reconnectMinDelay;
int reconnectMaxDelay;
boolean msgKeyInUpdates;
ActiveConfig(String defaultServiceName)
{
super();
obeyOpenWindow = DEFAULT_OBEY_OPEN_WINDOW;
postAckTimeout = DEFAULT_POST_ACK_TIMEOUT;
maxOutstandingPosts = DEFAULT_MAX_OUTSTANDING_POSTS;
loginRequestTimeOut = DEFAULT_LOGIN_REQUEST_TIMEOUT;
directoryRequestTimeOut = DEFAULT_DIRECTORY_REQUEST_TIMEOUT;
dictionaryRequestTimeOut = DEFAULT_DICTIONARY_REQUEST_TIMEOUT;
userDispatch = DEFAULT_USER_DISPATCH;
reconnectAttemptLimit = ActiveConfig.DEFAULT_RECONNECT_ATTEMPT_LIMIT;
reconnectMinDelay = ActiveConfig.DEFAULT_RECONNECT_MIN_DELAY;
reconnectMaxDelay = ActiveConfig.DEFAULT_RECONNECT_MAX_DELAY;
msgKeyInUpdates = ActiveConfig.DEFAULT_MSGKEYINUPDATES ;
ActiveConfig.defaultServiceName = defaultServiceName;
reissueTokenAttemptLimit = DEFAULT_REISSUE_TOKEN_ATTEMPT_LIMIT;
reissueTokenAttemptInterval = DEFAULT_REISSUE_TOKEN_ATTEMPT_INTERVAL;
restRequestTimeout = DEFAULT_REST_REQUEST_TIMEOUT;
tokenReissueRatio = DEFAULT_TOKEN_REISSUE_RATIO;
channelConfigSet = new ArrayList<>();
}
void clear()
{
super.clear();
obeyOpenWindow = DEFAULT_OBEY_OPEN_WINDOW;
postAckTimeout = DEFAULT_POST_ACK_TIMEOUT;
maxOutstandingPosts = DEFAULT_MAX_OUTSTANDING_POSTS;
loginRequestTimeOut = DEFAULT_LOGIN_REQUEST_TIMEOUT;
directoryRequestTimeOut = DEFAULT_DIRECTORY_REQUEST_TIMEOUT;
dictionaryRequestTimeOut = DEFAULT_DICTIONARY_REQUEST_TIMEOUT;
userDispatch = DEFAULT_USER_DISPATCH;
reconnectAttemptLimit = ActiveConfig.DEFAULT_RECONNECT_ATTEMPT_LIMIT;
reconnectMinDelay = ActiveConfig.DEFAULT_RECONNECT_MIN_DELAY;
reconnectMaxDelay = ActiveConfig.DEFAULT_RECONNECT_MAX_DELAY;
msgKeyInUpdates = ActiveConfig.DEFAULT_MSGKEYINUPDATES;
reissueTokenAttemptLimit = DEFAULT_REISSUE_TOKEN_ATTEMPT_LIMIT;
reissueTokenAttemptInterval = DEFAULT_REISSUE_TOKEN_ATTEMPT_INTERVAL;
restRequestTimeout = DEFAULT_REST_REQUEST_TIMEOUT;
tokenReissueRatio = DEFAULT_TOKEN_REISSUE_RATIO;
dictionaryConfig.clear();
rsslRDMLoginRequest = null;
rsslDirectoryRequest = null;
rsslFldDictRequest = null;
rsslEnumDictRequest = null;
}
StringBuilder configTrace()
{
super.configTrace();
traceStr.append("\n\t obeyOpenWindow: ").append(obeyOpenWindow)
.append("\n\t postAckTimeout: ").append(postAckTimeout)
.append("\n\t maxOutstandingPosts: ").append(maxOutstandingPosts)
.append("\n\t userDispatch: ").append(userDispatch)
.append("\n\t reconnectAttemptLimit: ").append(reconnectAttemptLimit)
.append("\n\t reconnectMinDelay: ").append(reconnectMinDelay)
.append("\n\t reconnectMaxDelay: ").append(reconnectMaxDelay)
.append("\n\t msgKeyInUpdates: ").append(msgKeyInUpdates)
.append("\n\t directoryRequestTimeOut: ").append(directoryRequestTimeOut)
.append("\n\t dictionaryRequestTimeOut: ").append(dictionaryRequestTimeOut)
.append("\n\t reissueTokenAttemptLimit: ").append(reissueTokenAttemptLimit)
.append("\n\t reissueTokenAttemptInterval: ").append(reissueTokenAttemptInterval)
.append("\n\t restRequestTimeOut: ").append(restRequestTimeout)
.append("\n\t tokenReissueRatio: ").append(tokenReissueRatio)
.append("\n\t loginRequestTimeOut: ").append(loginRequestTimeOut);
return traceStr;
}
void reconnectAttemptLimit(long value)
{
if (value >= 0)
reconnectAttemptLimit = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
}
void reconnectMinDelay(long value)
{
if ( value > 0 )
reconnectMinDelay = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
}
void reconnectMaxDelay(long value)
{
if ( value > 0 )
reconnectMaxDelay = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
}
void reissueTokenAttemptLimit(long value)
{
if (value >= 0)
reissueTokenAttemptLimit = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
else
reissueTokenAttemptLimit = DEFAULT_REISSUE_TOKEN_ATTEMPT_LIMIT;
}
void reissueTokenAttemptInterval(long value)
{
if (value >= 0)
reissueTokenAttemptInterval = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
else
reissueTokenAttemptInterval = 0;
}
void restRequestTimeout(long value)
{
if (value >= 0)
restRequestTimeout = (int)(value > Integer.MAX_VALUE ? Integer.MAX_VALUE : value);
else
restRequestTimeout = 0;
}
}
| 45.823009 | 189 | 0.761974 |
9fd0f71339945b98af814f1094da52207601f58e | 2,085 |
package pubmed.article;
import jam.app.JamLogger;
import pubmed.mesh.MeshDescriptor;
import pubmed.mesh.MeshDescriptorKey;
/**
* Defines distinct article publication types.
*/
public final class PublicationType {
private final MeshDescriptorKey descriptorKey;
private PublicationType(MeshDescriptorKey descriptorKey) {
this.descriptorKey = descriptorKey;
}
/**
* Creates a new publication type with a fixed descriptor key.
*
* @param descriptorKey the key of the {@code MeSH} descriptor for
* this publication type.
*
* @return the decorated {@code PublicationType} elements.
*/
public static PublicationType create(String descriptorKey) {
try {
return create(MeshDescriptorKey.instance(descriptorKey));
}
catch (RuntimeException ex) {
JamLogger.warn(ex);
return null;
}
}
/**
* Creates a new publication type with a fixed descriptor key.
*
* @param descriptorKey the key of the {@code MeSH} descriptor for
* this publication type.
*
* @return the decorated {@code PublicationType} elements.
*/
public static PublicationType create(MeshDescriptorKey descriptorKey) {
return new PublicationType(descriptorKey);
}
/**
* Returns the {@code MeSH} descriptor for this publication type.
*
* @return the {@code MeSH} descriptor for this publication type.
*/
public MeshDescriptor getDescriptor() {
return MeshDescriptor.instance(descriptorKey);
}
/**
* Returns the key of the {@code MeSH} descriptor for this
* publication type.
*
* @return the key of the {@code MeSH} descriptor for this
* publication type.
*/
public MeshDescriptorKey getDescriptorKey() {
return descriptorKey;
}
/**
* Returns the name of this publication type.
*
* @return the name of this publication type.
*/
public String getTypeName() {
return getDescriptor().getName().getName();
}
}
| 26.730769 | 75 | 0.646043 |
83f10d1edbc7ca216feca1ffe86b66b3f74445e1 | 277 | package com.unco.photoliarary;
/**
* ==============中康=================
*
* @Author: 陈振
* @Email : 18620156376@163.com
* @Action :用于提供图片url的接口
* @Time : 2016/9/21 13:28
* ==============中康=================
*/
public interface ImageUrl {
String getUrl();//获取图片url
} | 19.785714 | 36 | 0.487365 |
6b69bf8b5f09cfb8d5d7ffe0225918782668184a | 21,173 | /**
* 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.bookkeeper.mledger;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Charsets;
import java.time.Clock;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.client.EnsemblePlacementPolicy;
import org.apache.bookkeeper.client.api.DigestType;
import org.apache.bookkeeper.common.annotation.InterfaceAudience;
import org.apache.bookkeeper.common.annotation.InterfaceStability;
import org.apache.bookkeeper.mledger.impl.NullLedgerOffloader;
import org.apache.bookkeeper.mledger.intercept.ManagedLedgerInterceptor;
import org.apache.pulsar.common.util.collections.ConcurrentOpenLongPairRangeSet;
/**
* Configuration class for a ManagedLedger.
*/
@InterfaceAudience.LimitedPrivate
@InterfaceStability.Stable
public class ManagedLedgerConfig {
private boolean createIfMissing = true;
private int maxUnackedRangesToPersist = 10000;
private int maxBatchDeletedIndexToPersist = 10000;
private boolean deletionAtBatchIndexLevelEnabled = true;
private int maxUnackedRangesToPersistInZk = 1000;
private int maxEntriesPerLedger = 50000;
private int maxSizePerLedgerMb = 100;
private int minimumRolloverTimeMs = 0;
private long maximumRolloverTimeMs = TimeUnit.HOURS.toMillis(4);
private int ensembleSize = 3;
private int writeQuorumSize = 2;
private int ackQuorumSize = 2;
private int metadataEnsembleSize = 3;
private int metadataWriteQuorumSize = 2;
private int metadataAckQuorumSize = 2;
private int metadataMaxEntriesPerLedger = 50000;
private int ledgerRolloverTimeout = 4 * 3600;
private double throttleMarkDelete = 0;
private long retentionTimeMs = 0;
private long retentionSizeInMB = 0;
private boolean autoSkipNonRecoverableData;
private boolean lazyCursorRecovery = false;
private long metadataOperationsTimeoutSeconds = 60;
private long readEntryTimeoutSeconds = 120;
private long addEntryTimeoutSeconds = 120;
private DigestType digestType = DigestType.CRC32C;
private byte[] password = "".getBytes(Charsets.UTF_8);
private boolean unackedRangesOpenCacheSetEnabled = true;
private Class<? extends EnsemblePlacementPolicy> bookKeeperEnsemblePlacementPolicyClassName;
private Map<String, Object> bookKeeperEnsemblePlacementPolicyProperties;
private LedgerOffloader ledgerOffloader = NullLedgerOffloader.INSTANCE;
private int newEntriesCheckDelayInMillis = 10;
private Clock clock = Clock.systemUTC();
private ManagedLedgerInterceptor managedLedgerInterceptor;
private Map<String, String> properties;
public boolean isCreateIfMissing() {
return createIfMissing;
}
public ManagedLedgerConfig setCreateIfMissing(boolean createIfMissing) {
this.createIfMissing = createIfMissing;
return this;
}
/**
* @return the lazyCursorRecovery
*/
public boolean isLazyCursorRecovery() {
return lazyCursorRecovery;
}
/**
* Whether to recover cursors lazily when trying to recover a
* managed ledger backing a persistent topic. It can improve write availability of topics.
* The caveat is now when recovered ledger is ready to write we're not sure if all old consumers last mark
* delete position can be recovered or not.
* @param lazyCursorRecovery if enable lazy cursor recovery.
*/
public ManagedLedgerConfig setLazyCursorRecovery(boolean lazyCursorRecovery) {
this.lazyCursorRecovery = lazyCursorRecovery;
return this;
}
/**
* @return the maxEntriesPerLedger
*/
public int getMaxEntriesPerLedger() {
return maxEntriesPerLedger;
}
/**
* @param maxEntriesPerLedger
* the maxEntriesPerLedger to set
*/
public ManagedLedgerConfig setMaxEntriesPerLedger(int maxEntriesPerLedger) {
this.maxEntriesPerLedger = maxEntriesPerLedger;
return this;
}
/**
* @return the maxSizePerLedgerMb
*/
public int getMaxSizePerLedgerMb() {
return maxSizePerLedgerMb;
}
/**
* @param maxSizePerLedgerMb
* the maxSizePerLedgerMb to set
*/
public ManagedLedgerConfig setMaxSizePerLedgerMb(int maxSizePerLedgerMb) {
this.maxSizePerLedgerMb = maxSizePerLedgerMb;
return this;
}
/**
* @return the minimum rollover time
*/
public int getMinimumRolloverTimeMs() {
return minimumRolloverTimeMs;
}
/**
* Set the minimum rollover time for ledgers in this managed ledger.
*
* <p/>If this time is > 0, a ledger will not be rolled over more frequently than the specified time, even if it has
* reached the maximum number of entries or maximum size. This parameter can be used to reduce the amount of
* rollovers on managed ledger with high write throughput.
*
* @param minimumRolloverTime
* the minimum rollover time
* @param unit
* the time unit
*/
public void setMinimumRolloverTime(int minimumRolloverTime, TimeUnit unit) {
this.minimumRolloverTimeMs = (int) unit.toMillis(minimumRolloverTime);
checkArgument(maximumRolloverTimeMs >= minimumRolloverTimeMs,
"Minimum rollover time needs to be less than maximum rollover time");
}
/**
* @return the maximum rollover time.
*/
public long getMaximumRolloverTimeMs() {
return maximumRolloverTimeMs;
}
/**
* Set the maximum rollover time for ledgers in this managed ledger.
*
* <p/>If the ledger is not rolled over until this time, even if it has not reached the number of entry or size
* limit, this setting will trigger rollover. This parameter can be used for topics with low request rate to force
* rollover, so recovery failure does not have to go far back.
*
* @param maximumRolloverTime
* the maximum rollover time
* @param unit
* the time unit
*/
public void setMaximumRolloverTime(int maximumRolloverTime, TimeUnit unit) {
this.maximumRolloverTimeMs = unit.toMillis(maximumRolloverTime);
checkArgument(maximumRolloverTimeMs >= minimumRolloverTimeMs,
"Maximum rollover time needs to be greater than minimum rollover time");
}
/**
* @return the ensembleSize
*/
public int getEnsembleSize() {
return ensembleSize;
}
/**
* @param ensembleSize
* the ensembleSize to set
*/
public ManagedLedgerConfig setEnsembleSize(int ensembleSize) {
this.ensembleSize = ensembleSize;
return this;
}
/**
* @return the ackQuorumSize
*/
public int getAckQuorumSize() {
return ackQuorumSize;
}
/**
* @return the writeQuorumSize
*/
public int getWriteQuorumSize() {
return writeQuorumSize;
}
/**
* @param writeQuorumSize
* the writeQuorumSize to set
*/
public ManagedLedgerConfig setWriteQuorumSize(int writeQuorumSize) {
this.writeQuorumSize = writeQuorumSize;
return this;
}
/**
* @param ackQuorumSize
* the ackQuorumSize to set
*/
public ManagedLedgerConfig setAckQuorumSize(int ackQuorumSize) {
this.ackQuorumSize = ackQuorumSize;
return this;
}
/**
* @return the digestType
*/
public DigestType getDigestType() {
return digestType;
}
/**
* @param digestType
* the digestType to set
*/
public ManagedLedgerConfig setDigestType(DigestType digestType) {
this.digestType = digestType;
return this;
}
/**
* @return the password
*/
public byte[] getPassword() {
return Arrays.copyOf(password, password.length);
}
/**
* @param password
* the password to set
*/
public ManagedLedgerConfig setPassword(String password) {
this.password = password.getBytes(Charsets.UTF_8);
return this;
}
/**
* should use {@link ConcurrentOpenLongPairRangeSet} to store unacked ranges.
* @return
*/
public boolean isUnackedRangesOpenCacheSetEnabled() {
return unackedRangesOpenCacheSetEnabled;
}
public ManagedLedgerConfig setUnackedRangesOpenCacheSetEnabled(boolean unackedRangesOpenCacheSetEnabled) {
this.unackedRangesOpenCacheSetEnabled = unackedRangesOpenCacheSetEnabled;
return this;
}
/**
* @return the metadataEnsemblesize
*/
public int getMetadataEnsemblesize() {
return metadataEnsembleSize;
}
/**
* @param metadataEnsembleSize
* the metadataEnsembleSize to set
*/
public ManagedLedgerConfig setMetadataEnsembleSize(int metadataEnsembleSize) {
this.metadataEnsembleSize = metadataEnsembleSize;
return this;
}
/**
* @return the metadataAckQuorumSize
*/
public int getMetadataAckQuorumSize() {
return metadataAckQuorumSize;
}
/**
* @return the metadataWriteQuorumSize
*/
public int getMetadataWriteQuorumSize() {
return metadataWriteQuorumSize;
}
/**
* @param metadataAckQuorumSize
* the metadataAckQuorumSize to set
*/
public ManagedLedgerConfig setMetadataAckQuorumSize(int metadataAckQuorumSize) {
this.metadataAckQuorumSize = metadataAckQuorumSize;
return this;
}
/**
* @param metadataWriteQuorumSize
* the metadataWriteQuorumSize to set
*/
public ManagedLedgerConfig setMetadataWriteQuorumSize(int metadataWriteQuorumSize) {
this.metadataWriteQuorumSize = metadataWriteQuorumSize;
return this;
}
/**
* @return the metadataMaxEntriesPerLedger
*/
public int getMetadataMaxEntriesPerLedger() {
return metadataMaxEntriesPerLedger;
}
/**
* @param metadataMaxEntriesPerLedger
* the metadataMaxEntriesPerLedger to set
*/
public ManagedLedgerConfig setMetadataMaxEntriesPerLedger(int metadataMaxEntriesPerLedger) {
this.metadataMaxEntriesPerLedger = metadataMaxEntriesPerLedger;
return this;
}
/**
* @return the ledgerRolloverTimeout
*/
public int getLedgerRolloverTimeout() {
return ledgerRolloverTimeout;
}
/**
* @param ledgerRolloverTimeout
* the ledgerRolloverTimeout to set
*/
public ManagedLedgerConfig setLedgerRolloverTimeout(int ledgerRolloverTimeout) {
this.ledgerRolloverTimeout = ledgerRolloverTimeout;
return this;
}
/**
* @return the throttling rate limit for mark-delete calls
*/
public double getThrottleMarkDelete() {
return throttleMarkDelete;
}
/**
* Set the rate limiter on how many mark-delete calls per second are allowed. If the value is set to 0, the rate
* limiter is disabled. Default is 0.
*
* @param throttleMarkDelete
* the max number of mark-delete calls allowed per second
*/
public ManagedLedgerConfig setThrottleMarkDelete(double throttleMarkDelete) {
checkArgument(throttleMarkDelete >= 0.0);
this.throttleMarkDelete = throttleMarkDelete;
return this;
}
/**
* Set the retention time for the ManagedLedger.
* <p>
* Retention time and retention size ({@link #setRetentionSizeInMB(long)}) are together used to retain the
* ledger data when when there are no cursors or when all the cursors have marked the data for deletion.
* Data will be deleted in this case when both retention time and retention size settings don't prevent deleting
* the data marked for deletion.
* <p>
* A retention time of 0 (default) will make data to be deleted immediately.
* <p>
* A retention time of -1, means to have an unlimited retention time.
*
* @param retentionTime
* duration for which messages should be retained
* @param unit
* time unit for retention time
*/
public ManagedLedgerConfig setRetentionTime(int retentionTime, TimeUnit unit) {
this.retentionTimeMs = unit.toMillis(retentionTime);
return this;
}
/**
* @return duration for which messages are retained
*
*/
public long getRetentionTimeMillis() {
return retentionTimeMs;
}
/**
* The retention size is used to set a maximum retention size quota on the ManagedLedger.
* <p>
* Retention size and retention time ({@link #setRetentionTime(int, TimeUnit)}) are together used to retain the
* ledger data when when there are no cursors or when all the cursors have marked the data for deletion.
* Data will be deleted in this case when both retention time and retention size settings don't prevent deleting
* the data marked for deletion.
* <p>
* A retention size of 0 (default) will make data to be deleted immediately.
* <p>
* A retention size of -1, means to have an unlimited retention size.
*
* @param retentionSizeInMB
* quota for message retention
*/
public ManagedLedgerConfig setRetentionSizeInMB(long retentionSizeInMB) {
this.retentionSizeInMB = retentionSizeInMB;
return this;
}
/**
* @return quota for message retention
*
*/
public long getRetentionSizeInMB() {
return retentionSizeInMB;
}
/**
* Skip reading non-recoverable/unreadable data-ledger under managed-ledger's list. It helps when data-ledgers gets
* corrupted at bookkeeper and managed-cursor is stuck at that ledger.
*/
public boolean isAutoSkipNonRecoverableData() {
return autoSkipNonRecoverableData;
}
public void setAutoSkipNonRecoverableData(boolean skipNonRecoverableData) {
this.autoSkipNonRecoverableData = skipNonRecoverableData;
}
/**
* @return max unacked message ranges that will be persisted and recovered.
*
*/
public int getMaxUnackedRangesToPersist() {
return maxUnackedRangesToPersist;
}
/**
* @return max batch deleted index that will be persisted and recoverd.
*/
public int getMaxBatchDeletedIndexToPersist() {
return maxBatchDeletedIndexToPersist;
}
/**
* @param maxUnackedRangesToPersist
* max unacked message ranges that will be persisted and receverd.
*/
public ManagedLedgerConfig setMaxUnackedRangesToPersist(int maxUnackedRangesToPersist) {
this.maxUnackedRangesToPersist = maxUnackedRangesToPersist;
return this;
}
/**
* @return max unacked message ranges up to which it can store in Zookeeper
*
*/
public int getMaxUnackedRangesToPersistInZk() {
return maxUnackedRangesToPersistInZk;
}
public void setMaxUnackedRangesToPersistInZk(int maxUnackedRangesToPersistInZk) {
this.maxUnackedRangesToPersistInZk = maxUnackedRangesToPersistInZk;
}
/**
* Get ledger offloader which will be used to offload ledgers to longterm storage.
*
* The default offloader throws an exception on any attempt to offload.
*
* @return a ledger offloader
*/
public LedgerOffloader getLedgerOffloader() {
return ledgerOffloader;
}
/**
* Set ledger offloader to use for offloading ledgers to longterm storage.
*
* @param offloader the ledger offloader to use
*/
public ManagedLedgerConfig setLedgerOffloader(LedgerOffloader offloader) {
this.ledgerOffloader = offloader;
return this;
}
/**
* Get clock to use to time operations.
*
* @return a clock
*/
public Clock getClock() {
return clock;
}
/**
* Set clock to use for time operations.
*
* @param clock the clock to use
*/
public ManagedLedgerConfig setClock(Clock clock) {
this.clock = clock;
return this;
}
/**
*
* Ledger-Op (Create/Delete) timeout.
*
* @return
*/
public long getMetadataOperationsTimeoutSeconds() {
return metadataOperationsTimeoutSeconds;
}
/**
* Ledger-Op (Create/Delete) timeout after which callback will be completed with failure.
*
* @param metadataOperationsTimeoutSeconds
*/
public ManagedLedgerConfig setMetadataOperationsTimeoutSeconds(long metadataOperationsTimeoutSeconds) {
this.metadataOperationsTimeoutSeconds = metadataOperationsTimeoutSeconds;
return this;
}
/**
* Ledger read-entry timeout.
*
* @return
*/
public long getReadEntryTimeoutSeconds() {
return readEntryTimeoutSeconds;
}
/**
* Ledger read entry timeout after which callback will be completed with failure. (disable timeout by setting.
* readTimeoutSeconds <= 0)
*
* @param readEntryTimeoutSeconds
* @return
*/
public ManagedLedgerConfig setReadEntryTimeoutSeconds(long readEntryTimeoutSeconds) {
this.readEntryTimeoutSeconds = readEntryTimeoutSeconds;
return this;
}
public long getAddEntryTimeoutSeconds() {
return addEntryTimeoutSeconds;
}
/**
* Add-entry timeout after which add-entry callback will be failed if add-entry is not succeeded.
*
* @param addEntryTimeoutSeconds
*/
public ManagedLedgerConfig setAddEntryTimeoutSeconds(long addEntryTimeoutSeconds) {
this.addEntryTimeoutSeconds = addEntryTimeoutSeconds;
return this;
}
/**
* Managed-ledger can setup different custom EnsemblePlacementPolicy (eg: affinity to write ledgers to only setup of
* group of bookies).
*
* @return
*/
public Class<? extends EnsemblePlacementPolicy> getBookKeeperEnsemblePlacementPolicyClassName() {
return bookKeeperEnsemblePlacementPolicyClassName;
}
/**
* Returns EnsemblePlacementPolicy configured for the Managed-ledger.
*
* @param bookKeeperEnsemblePlacementPolicyClassName
*/
public void setBookKeeperEnsemblePlacementPolicyClassName(
Class<? extends EnsemblePlacementPolicy> bookKeeperEnsemblePlacementPolicyClassName) {
this.bookKeeperEnsemblePlacementPolicyClassName = bookKeeperEnsemblePlacementPolicyClassName;
}
/**
* Returns properties required by configured bookKeeperEnsemblePlacementPolicy.
*
* @return
*/
public Map<String, Object> getBookKeeperEnsemblePlacementPolicyProperties() {
return bookKeeperEnsemblePlacementPolicyProperties;
}
/**
* Managed-ledger can setup different custom EnsemblePlacementPolicy which needs
* bookKeeperEnsemblePlacementPolicy-Properties.
*
* @param bookKeeperEnsemblePlacementPolicyProperties
*/
public void setBookKeeperEnsemblePlacementPolicyProperties(
Map<String, Object> bookKeeperEnsemblePlacementPolicyProperties) {
this.bookKeeperEnsemblePlacementPolicyProperties = bookKeeperEnsemblePlacementPolicyProperties;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public boolean isDeletionAtBatchIndexLevelEnabled() {
return deletionAtBatchIndexLevelEnabled;
}
public void setDeletionAtBatchIndexLevelEnabled(boolean deletionAtBatchIndexLevelEnabled) {
this.deletionAtBatchIndexLevelEnabled = deletionAtBatchIndexLevelEnabled;
}
public int getNewEntriesCheckDelayInMillis() {
return newEntriesCheckDelayInMillis;
}
public void setNewEntriesCheckDelayInMillis(int newEntriesCheckDelayInMillis) {
this.newEntriesCheckDelayInMillis = newEntriesCheckDelayInMillis;
}
public ManagedLedgerInterceptor getManagedLedgerInterceptor() {
return managedLedgerInterceptor;
}
public void setManagedLedgerInterceptor(ManagedLedgerInterceptor managedLedgerInterceptor) {
this.managedLedgerInterceptor = managedLedgerInterceptor;
}
}
| 32.226788 | 120 | 0.688424 |
b458ea1295b2f39e72341a8353f53ffea0f87c44 | 2,881 | package edu.cs4730.dialogdemo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class myDialogFragment extends DialogFragment {
static final int DIALOG_TYPE_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
/*
* Create an instance of this fragment. Uses the "ID numbers" above to determine which
* dialog box to display.
*/
public static myDialogFragment newInstance(int id) {
myDialogFragment frag = new myDialogFragment();
Bundle args = new Bundle();
args.putInt("id", id);
frag.setArguments(args);
return frag;
}
/*
* Instead of using onCreateView, we use the onCreateDialog
* This uses the ID above to determine which dialog to build.
* Note, this calls back into the activity, so the methods
* doItem(String), doPositiveClick(), and doNegativeClick() need to be implemented. (not call backs either)
*
* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onCreateDialog(android.os.Bundle)
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int id = getArguments().getInt("id");
Dialog dialog = null;
AlertDialog.Builder builder;
switch (id) {
case DIALOG_TYPE_ID:
final String[] items = { "Remove Walls", "Add Walls",
"Add/Remove Objects", "Add/Remove Score" };
builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Type:");
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
dialog.dismiss(); //the dismiss is needed here or the dialog stays showing.
((DialFragActivity)getActivity()).doItem(items[item]);
}
});
dialog = builder.create();
break;
case DIALOG_GAMEOVER_ID:
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((DialFragActivity)getActivity()).doPositiveClick();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((DialFragActivity)getActivity()).doNegativeClick();
}
});
dialog = builder.create();
break;
}
return dialog;
}
}
| 38.413333 | 111 | 0.607775 |
9319c9a3b833cc304c4ab0cadde5b6f0ac2ae84f | 3,562 | package com.hy.micro.service.dingding.service.impl;
import java.lang.reflect.InvocationTargetException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hy.micro.service.dingding.dto.OrderDTO;
import com.hy.micro.service.dingding.enums.ExceptionCode;
import com.hy.micro.service.dingding.exception.BloomingException;
import com.hy.micro.service.dingding.service.OrderService;
import com.hy.micro.service.dingding.service.PayService;
import com.hy.micro.service.dingding.utils.MathUtil;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lly835.bestpay.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
/**
*
* @Author: Eddie.Wei
* @Date: 2018-10-12
* @github: https://github.com/weixuan2008
*/
@Service
@Slf4j
public class PayServiceImpl implements PayService {
private static final String ORDER_NAME = "Order by weichat";
@Autowired
private BestPayServiceImpl bestPayService;
@Autowired
private OrderService orderService;
@Override
public PayResponse create(OrderDTO orderDTO) {
PayRequest payRequest = new PayRequest();
payRequest.setOpenid(orderDTO.getBuyerOpenid());
payRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
payRequest.setOrderId(orderDTO.getOrderId());
payRequest.setOrderName(ORDER_NAME);
payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
log.info("【微信支付】发起支付, request={}", JsonUtil.toJson(payRequest));
PayResponse payResponse = bestPayService.pay(payRequest);
log.info("【微信支付】发起支付, response={}", JsonUtil.toJson(payResponse));
return payResponse;
}
@Override
public PayResponse notify(String notifyData) throws IllegalAccessException, InvocationTargetException {
// 1. 验证签名
// 2. 支付的状态
// 3. 支付金额
// 4. 支付人(下单人 == 支付人)
PayResponse payResponse = bestPayService.asyncNotify(notifyData);
log.info("【微信支付】异步通知, payResponse={}", JsonUtil.toJson(payResponse));
// 查询订单
OrderDTO orderDTO = orderService.findByOrderId(payResponse.getOrderId());
// 判断订单是否存在
if (orderDTO == null) {
log.error("【微信支付】异步通知, 订单不存在, orderId={}", payResponse.getOrderId());
throw new BloomingException(ExceptionCode.ORDER_NOT_FOUND);
}
// 判断金额是否一致(0.10 0.1)
if (!MathUtil.equals(payResponse.getOrderAmount(), orderDTO.getOrderAmount().doubleValue())) {
log.error("【微信支付】异步通知, 订单金额不一致, orderId={}, 微信通知金额={}, 系统金额={}", payResponse.getOrderId(),
payResponse.getOrderAmount(), orderDTO.getOrderAmount());
throw new BloomingException(ExceptionCode.WXPAY_NOTIFY_MONEY_VERIFY_ERROR);
}
// 修改订单的支付状态
orderService.pay(orderDTO);
return payResponse;
}
/**
* 退款
*
* @param orderDTO
*/
@Override
public RefundResponse refund(OrderDTO orderDTO) {
RefundRequest refundRequest = new RefundRequest();
refundRequest.setOrderId(orderDTO.getOrderId());
refundRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
log.info("【微信退款】request={}", JsonUtil.toJson(refundRequest));
RefundResponse refundResponse = bestPayService.refund(refundRequest);
log.info("【微信退款】response={}", JsonUtil.toJson(refundResponse));
return refundResponse;
}
}
| 32.678899 | 105 | 0.746771 |
b98f0baab59bc3f0bb875725418a21f42f82f458 | 1,276 | /*
* 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 el;
import data_classes.Employee;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
/**
* FXML Controller class
*
* @author Tarun Bisht
*/
public class CheckleaveController implements Initializable
{
@FXML
Label id,name,fname,dob,doj,tl,l6,l12;
/**
* Initializes the controller class.
* @param emp
*/
public void SetLabels(Employee emp)
{
id.setText("Employee Id: "+String.valueOf(emp.Employee_Id));
name.setText("Name: "+emp.Employee_Name);
fname.setText("Father's Name: "+emp.Employee_Father);
dob.setText("Date of Birth: "+emp.DOB);
doj.setText("Date of Joining: "+emp.DOJ);
tl.setText(String.valueOf(emp.leave.Total_Leave));
l6.setText(String.valueOf(emp.leave.Leave_6));
l12.setText(String.valueOf(emp.leave.Leave_12));
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
| 28.355556 | 80 | 0.648903 |
7aaefa5c1636b793eecb310a192e0717e82ba66b | 512 | package play.mvc.results;
import play.mvc.Http;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
/**
* 401 Unauthorized
*/
public class Unauthorized extends Result {
String realm;
public Unauthorized(String realm) {
super(realm);
this.realm = realm;
}
public void apply(Request request, Response response) {
response.status = Http.StatusCode.UNAUTHORIZED;
response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
}
}
| 21.333333 | 80 | 0.652344 |
27de93c292856af923bbd39ef8c8b516c7b9677e | 1,099 | package org.ovirt.engine.core.dao;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.storage_pool_iso_map;
import org.ovirt.engine.core.compat.Guid;
/**
* StoragePoolIsoMap DAO
*
*/
public interface StoragePoolIsoMapDAO extends GenericDao<storage_pool_iso_map, StoragePoolIsoMapId>,
StatusAwareDao<StoragePoolIsoMapId, StorageDomainStatus> {
/**
* Gets all maps for a given storage pool ID
*
* @param storagePoolId
* storage pool ID for which the maps will be returned
* @return list of maps
*/
public List<storage_pool_iso_map> getAllForStoragePool(Guid storagePoolId);
/**
* Gets all maps for a given storage ID
*
* @param storageId
* storage ID to return all the maps for
* @return list of maps (empty list if there is no matching map)
*/
public List<storage_pool_iso_map> getAllForStorage(Guid storageId);
}
| 32.323529 | 100 | 0.722475 |
07434dcbca8cb9ff59e741182b55de8c90e7e0dc | 595 | package com.dnsimple.data;
import java.util.List;
import com.google.api.client.util.Key;
public class TldExtendedAttribute {
@Key("name")
private String name;
@Key("description")
private String description;
@Key("required")
private Boolean required;
@Key("options")
private List<TldExtendedAttributeOption> options;
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Boolean getRequired() {
return required;
}
public List<TldExtendedAttributeOption> getOptions() {
return options;
}
}
| 16.527778 | 56 | 0.705882 |
22d82df52182bb1a70ab8967af6a64304972b429 | 11,255 | /*
* 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.flink.table.formats.raw;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RawValueData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.types.DeserializationException;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Deserialization schema from raw (byte based) value to Flink Table/SQL internal data structure
* {@link RowData}.
*/
@Internal
public class RawFormatDeserializationSchema implements DeserializationSchema<RowData> {
private static final long serialVersionUID = 1L;
private final LogicalType deserializedType;
private final TypeInformation<RowData> producedTypeInfo;
private final String charsetName;
private final boolean isBigEndian;
private final DeserializationRuntimeConverter converter;
private final DataLengthValidator validator;
private transient GenericRowData reuse;
public RawFormatDeserializationSchema(
LogicalType deserializedType,
TypeInformation<RowData> producedTypeInfo,
String charsetName,
boolean isBigEndian) {
this.deserializedType = checkNotNull(deserializedType);
this.producedTypeInfo = checkNotNull(producedTypeInfo);
this.converter = createConverter(deserializedType, charsetName, isBigEndian);
this.validator = createDataLengthValidator(deserializedType);
this.charsetName = charsetName;
this.isBigEndian = isBigEndian;
}
@Override
public void open(InitializationContext context) throws Exception {
reuse = new GenericRowData(1);
converter.open();
}
@Override
public RowData deserialize(byte[] message) throws IOException {
final Object field;
if (message == null) {
field = null;
} else {
validator.validate(message);
field = converter.convert(message);
}
reuse.setField(0, field);
return reuse;
}
@Override
public boolean isEndOfStream(RowData nextElement) {
return false;
}
@Override
public TypeInformation<RowData> getProducedType() {
return producedTypeInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RawFormatDeserializationSchema that = (RawFormatDeserializationSchema) o;
return producedTypeInfo.equals(that.producedTypeInfo)
&& deserializedType.equals(that.deserializedType)
&& charsetName.equals(that.charsetName)
&& isBigEndian == that.isBigEndian;
}
@Override
public int hashCode() {
return Objects.hash(producedTypeInfo, deserializedType, charsetName, isBigEndian);
}
// ------------------------------------------------------------------------
/** Runtime converter that convert byte[] to internal data structure object. */
@FunctionalInterface
private interface DeserializationRuntimeConverter extends Serializable {
default void open() {}
Object convert(byte[] data) throws IOException;
}
/** Creates a runtime converter. */
private static DeserializationRuntimeConverter createConverter(
LogicalType type, String charsetName, boolean isBigEndian) {
switch (type.getTypeRoot()) {
case CHAR:
case VARCHAR:
return createStringConverter(charsetName);
case VARBINARY:
case BINARY:
return data -> data;
case RAW:
return RawValueData::fromBytes;
case BOOLEAN:
return data -> data[0] != 0;
case TINYINT:
return data -> data[0];
case SMALLINT:
return createEndiannessAwareConverter(
isBigEndian,
segment -> segment.getShortBigEndian(0),
segment -> segment.getShortLittleEndian(0));
case INTEGER:
return createEndiannessAwareConverter(
isBigEndian,
segment -> segment.getIntBigEndian(0),
segment -> segment.getIntLittleEndian(0));
case BIGINT:
return createEndiannessAwareConverter(
isBigEndian,
segment -> segment.getLongBigEndian(0),
segment -> segment.getLongLittleEndian(0));
case FLOAT:
return createEndiannessAwareConverter(
isBigEndian,
segment -> segment.getFloatBigEndian(0),
segment -> segment.getFloatLittleEndian(0));
case DOUBLE:
return createEndiannessAwareConverter(
isBigEndian,
segment -> segment.getDoubleBigEndian(0),
segment -> segment.getDoubleLittleEndian(0));
default:
throw new UnsupportedOperationException(
"'raw' format currently doesn't support type: " + type);
}
}
private static DeserializationRuntimeConverter createStringConverter(final String charsetName) {
// this also checks the charsetName is valid
Charset charset = Charset.forName(charsetName);
if (charset == StandardCharsets.UTF_8) {
// avoid UTF-8 decoding if the given charset is UTF-8
// because the underlying bytes of StringData is in UTF-8 encoding
return StringData::fromBytes;
}
return new DeserializationRuntimeConverter() {
private static final long serialVersionUID = 1L;
private transient Charset charset;
@Override
public void open() {
charset = Charset.forName(charsetName);
}
@Override
public Object convert(byte[] data) {
String str = new String(data, charset);
return StringData.fromString(str);
}
};
}
private static DeserializationRuntimeConverter createEndiannessAwareConverter(
final boolean isBigEndian,
final MemorySegmentConverter bigEndianConverter,
final MemorySegmentConverter littleEndianConverter) {
if (isBigEndian) {
return new EndiannessAwareDeserializationConverter(bigEndianConverter);
} else {
return new EndiannessAwareDeserializationConverter(littleEndianConverter);
}
}
// ------------------------------------------------------------------------------------
// Utilities to check received size of data
// ------------------------------------------------------------------------------------
/** Creates a validator for the received data. */
private static DataLengthValidator createDataLengthValidator(LogicalType type) {
// please keep the order the same with createNotNullConverter()
switch (type.getTypeRoot()) {
case CHAR:
case VARCHAR:
case VARBINARY:
case BINARY:
case RAW:
return data -> {};
case BOOLEAN:
return createDataLengthValidator(1, "BOOLEAN");
case TINYINT:
return createDataLengthValidator(1, "TINYINT");
case SMALLINT:
return createDataLengthValidator(2, "SMALLINT");
case INTEGER:
return createDataLengthValidator(4, "INT");
case BIGINT:
return createDataLengthValidator(8, "BIGINT");
case FLOAT:
return createDataLengthValidator(4, "FLOAT");
case DOUBLE:
return createDataLengthValidator(8, "DOUBLE");
default:
throw new UnsupportedOperationException(
"'raw' format currently doesn't support type: " + type);
}
}
private static DataLengthValidator createDataLengthValidator(
int expectedLength, String typeName) {
return data -> {
if (data.length != expectedLength) {
throw new DeserializationException(
String.format(
"Size of data received for deserializing %s type is not %s.",
typeName, expectedLength));
}
};
}
/** Validator to checks the length of received data. */
private interface DataLengthValidator extends Serializable {
void validate(byte[] data);
}
// ------------------------------------------------------------------------------------
// Utilities to deserialize endianness numeric
// ------------------------------------------------------------------------------------
private static final class EndiannessAwareDeserializationConverter
implements DeserializationRuntimeConverter {
private static final long serialVersionUID = 1L;
private final MemorySegmentConverter innerConverter;
private EndiannessAwareDeserializationConverter(MemorySegmentConverter innerConverter) {
this.innerConverter = innerConverter;
}
@Override
public Object convert(byte[] data) {
MemorySegment segment = MemorySegmentFactory.wrap(data);
return innerConverter.convert(segment);
}
}
/** Runtime converter that convert {@link MemorySegment} to internal data structure object. */
private interface MemorySegmentConverter extends Serializable {
Object convert(MemorySegment segment);
}
}
| 36.306452 | 100 | 0.608796 |
3d948e5928fe8492ace6d134b1d0734a13ae61a0 | 815 | package itx.fileserver.services.dto;
import java.util.ArrayList;
import java.util.List;
public class FileList {
private final String path;
private final List<FileInfo> fileInfo;
private final List<DirectoryInfo> directoryInfo;
public FileList(String path) {
this.path = path;
this.fileInfo = new ArrayList<>();
this.directoryInfo = new ArrayList<>();
}
public String getPath() {
return path;
}
public List<FileInfo> getFileInfo() {
return fileInfo;
}
public List<DirectoryInfo> getDirectoryInfo() {
return directoryInfo;
}
public void add(FileInfo fileInfo) {
this.fileInfo.add(fileInfo);
}
public void add(DirectoryInfo directoryInfo) {
this.directoryInfo.add(directoryInfo);
}
}
| 20.897436 | 52 | 0.650307 |
88476452ac899b6508f28c249837ed147d3aa8d2 | 1,819 | /*
* Copyright © 2019 The GWT Project 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.gwtproject.dom.client;
import com.google.gwt.junit.client.GWTTestCase;
/** Tests the {@link FormElement} and {@link InputElement} classes. */
public class FormTests extends GWTTestCase {
@Override
public String getModuleName() {
return "org.gwtproject.dom.DOMTest";
}
/** getElements. */
public void testGetElements() {
Document doc = Document.get();
FormElement form = doc.createFormElement();
doc.getBody().appendChild(form);
form.setInnerHTML(
"<div>"
+ "<input name='text' id='text' type='text'>"
+ "<input name='hidden' id='hidden' type='hidden'>"
+ "<textarea name='textarea' id='textarea'>"
+ "</div>");
NodeCollection<Element> formElems = form.getElements();
assertEquals(3, formElems.getLength());
assertEquals("text", formElems.getItem(0).getId());
assertEquals("hidden", formElems.getItem(1).getId());
assertEquals("textarea", formElems.getItem(2).getId());
assertEquals("text", formElems.getNamedItem("text").getId());
assertEquals("hidden", formElems.getNamedItem("hidden").getId());
assertEquals("textarea", formElems.getNamedItem("textarea").getId());
}
}
| 34.980769 | 75 | 0.683342 |
6b3a11c30091e92890b6761e31db12bb3d301f2a | 230 | package com.c332030.constant.enums.data;
import com.c332030.constant.enums.base.IEnum;
/**
* <p>
* Description: IDataDictEnum
* </p>
*
* @author c332030
* @version 1.0
*/
public interface IDataDictEnum extends IEnum {
}
| 14.375 | 46 | 0.695652 |
f3c503072035b95c1e1ca9015f4ad75761c01de8 | 339 | package com.ballistic.looks;
import java.awt.Font;
public class FontType {
public FontType(){
}
public static Font setTextFont(){
Font font = new Font("INCONSOLATA", Font.BOLD, 16);
return font;
}
public static Font setTextFontForTopMenu(){
Font font = new Font("TREBUCHET MS", Font.BOLD, 15);
return font;
}
}
| 14.73913 | 54 | 0.678466 |
1e2c0ea7af43a4497489b386239c8513bb2c35ff | 1,437 | package pl.marcinchwedczuk.javafx.mvvm.container;
import java.util.Objects;
import java.util.Set;
public class RegistrationBuilder<COMPONENT> {
private final Class<COMPONENT> componentClass;
private ComponentName componentName = null;
private final Set<Class<?>> implementingSet = null;
private ComponentInitializer<? super COMPONENT> initializer = ComponentInitializer.EMPTY;
private ComponentFinalizer<? super COMPONENT> finalizer = ComponentFinalizer.EMPTY;
private Scope scope = Scope.ALWAYS_NEW;
public RegistrationBuilder(Class<COMPONENT> componentClass) {
this.componentClass = Objects.requireNonNull(componentClass);
}
Component build() {
return new Component(componentClass);
}
public RegistrationBuilder<COMPONENT> named(String name) {
return this;
}
public RegistrationBuilder<COMPONENT> implementing(Class<? super COMPONENT> interface_) {
return this;
}
public RegistrationBuilder<COMPONENT> initializeWith(ComponentInitializer<? super COMPONENT> initializer) {
return this;
}
public RegistrationBuilder<COMPONENT> finalizeWith(ComponentInitializer<? super COMPONENT> finalizer) {
return this;
}
public RegistrationBuilder<COMPONENT> scope(Scope scope) {
return this;
}
public RegistrationBuilder<COMPONENT> asDecoratorFor(Class<?> decorated) {
return this;
}
}
| 30.574468 | 111 | 0.727209 |
c19edca2fe5b609d7849b66f73a5cc18fbd43ef4 | 3,986 | /*
* Copyright 2020 赖柄沣 bingfengdev@aliyun.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pers.lbf.yeju.common.core.exception.service;
import pers.lbf.yeju.common.core.status.enums.ServiceStatusEnum;
import pers.lbf.yeju.common.core.status.insterfaces.IStatus;
/**
* @author 赖柄沣 bingfengdev@aliyun.com
* @version 1.0
* @Description TODO
* @date 2020/12/18 10:21
*/
public class ServiceException extends RuntimeException{
/**
* 错误消息提示
*/
protected String message;
/**
* 异常编码
*/
protected String exceptionCode;
/**
* 服务调用参数
*/
protected Object[] params;
/**
* 异常所属模块
*/
protected String module;
public static ServiceException getInstance(String message, String exceptionCode) {
return new ServiceException(message, exceptionCode);
}
public static ServiceException getInstance(IStatus status) {
return new ServiceException(status);
}
public static ServiceException getInstance() {
return new ServiceException();
}
public ServiceException(IStatus statusEnum){
super(statusEnum.getMessage());
this.exceptionCode = statusEnum.getCode();
this.message = statusEnum.getMessage();
}
public ServiceException() {
this.message = ServiceStatusEnum.UNKNOWN_ERROR.getMessage();
this.exceptionCode = ServiceStatusEnum.UNKNOWN_ERROR.getCode();
}
public ServiceException(String message, String exceptionCode, Object[] params, String module) {
super(message);
this.message = message;
this.exceptionCode = exceptionCode;
this.params = params;
this.module = module;
}
public ServiceException(String message, String exceptionCode){
super(message);
this.message = message;
this.exceptionCode = exceptionCode;
}
public ServiceException(String message, Throwable cause, String exceptionCode, Object[] params, String module) {
super(message, cause);
this.message = message;
this.exceptionCode = exceptionCode;
this.params = params;
this.module = module;
}
public ServiceException(Throwable cause, String message, String exceptionCode, Object[] params, String module) {
super(cause);
this.message = message;
this.exceptionCode = exceptionCode;
this.params = params;
this.module = module;
}
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, String exceptionCode, Object[] parmas, String module) {
super(message, cause, enableSuppression, writableStackTrace);
this.message = message;
this.exceptionCode = exceptionCode;
this.params = parmas;
this.module = module;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getExceptionCode() {
return exceptionCode;
}
public void setExceptionCode(String exceptionCode) {
this.exceptionCode = exceptionCode;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
}
| 27.30137 | 171 | 0.666834 |
417514b8b15753cee4e4feb0b1b93c6e9c2447f1 | 3,275 | /*
* Copyright 2020 Confluent Inc.
*
* Licensed under the Confluent Community 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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.kafkarest.entities.v3;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import io.confluent.kafkarest.entities.ConsumerAssignment;
@AutoValue
public abstract class ConsumerAssignmentData extends Resource {
ConsumerAssignmentData() {
}
@JsonProperty("cluster_id")
public abstract String getClusterId();
@JsonProperty("consumer_group_id")
public abstract String getConsumerGroupId();
@JsonProperty("consumer_id")
public abstract String getConsumerId();
@JsonProperty("topic_name")
public abstract String getTopicName();
@JsonProperty("partition_id")
public abstract int getPartitionId();
@JsonProperty("partition")
public abstract Relationship getPartition();
public static Builder builder() {
return new AutoValue_ConsumerAssignmentData.Builder().setKind("KafkaConsumerAssignment");
}
public static Builder fromConsumerAssignment(ConsumerAssignment assignment) {
return builder()
.setClusterId(assignment.getClusterId())
.setConsumerGroupId(assignment.getConsumerGroupId())
.setConsumerId(assignment.getConsumerId())
.setTopicName(assignment.getTopicName())
.setPartitionId(assignment.getPartitionId());
}
@JsonCreator
static ConsumerAssignmentData fromJson(
@JsonProperty("kind") String kind,
@JsonProperty("metadata") Metadata metadata,
@JsonProperty("cluster_id") String clusterId,
@JsonProperty("consumer_group_id") String consumerGroupId,
@JsonProperty("consumer_id") String consumerId,
@JsonProperty("topic_name") String topicName,
@JsonProperty("partition_id") int partitionId,
@JsonProperty("partition") Relationship partition
) {
return builder()
.setKind(kind)
.setMetadata(metadata)
.setClusterId(clusterId)
.setConsumerGroupId(consumerGroupId)
.setConsumerId(consumerId)
.setTopicName(topicName)
.setPartitionId(partitionId)
.setPartition(partition)
.build();
}
@AutoValue.Builder
public abstract static class Builder extends Resource.Builder<Builder> {
Builder() {
}
public abstract Builder setClusterId(String clusterId);
public abstract Builder setConsumerGroupId(String consumerGroupId);
public abstract Builder setConsumerId(String consumerId);
public abstract Builder setTopicName(String topicName);
public abstract Builder setPartitionId(int partitionId);
public abstract Builder setPartition(Relationship partition);
public abstract ConsumerAssignmentData build();
}
}
| 31.490385 | 93 | 0.745344 |
7a79043aecec2a72f7b735308bf753d041915aa0 | 16,595 | /**
*
*/
package uk.co.jemos.podam.api;
import net.jcip.annotations.NotThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.jemos.podam.common.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Default abstract implementation of a {@link DataProviderStrategy}
* <p>
* This default implementation returns values based on a random generator.
* Convinient for subclassing and redefining behaviour.
* <b>Don't use this implementation if you seek deterministic values</b>
* </p>
*
* <p>
* All values returned by this implementation are <b>different from zero</b>.
* </p>
*
* @author mtedone
*
* @since 1.0.0
*
*/
@NotThreadSafe
public abstract class AbstractRandomDataProviderStrategy implements RandomDataProviderStrategy {
// ------------------->> Constants
/** Application logger */
private static final Logger LOG = LoggerFactory.getLogger(AbstractRandomDataProviderStrategy.class);
/** A RANDOM generator */
private static final Random RANDOM = new Random(System.currentTimeMillis());
/**
* How many times it is allowed to PODAM to create an instance of the same
* class in a recursive hierarchy
*/
public static final int MAX_DEPTH = 1;
/** The max stack trace depth. */
private final int maxDepth = MAX_DEPTH;
/** The number of collection elements. */
private int nbrOfCollectionElements;
/** Flag to enable/disable the memoization setting. */
private boolean isMemoizationEnabled = true;
/**
* A map to keep one object for each class. If memoization is enabled, the
* factory will use this table to avoid creating objects of the same class
* multiple times.
*/
private final ConcurrentMap<Class<?>, ConcurrentMap<Type[], Object>> memoizationTable = new ConcurrentHashMap<Class<?>, ConcurrentMap<Type[], Object>>();
/**
* A list of user-submitted specific implementations for interfaces and
* abstract classes
*/
private final ConcurrentMap<Class<?>, Class<?>> specificTypes = new ConcurrentHashMap<Class<?>, Class<?>>();
/**
* Mapping between annotations and attribute strategies
*/
private final ConcurrentMap<Class<? extends Annotation>, Class<AttributeStrategy<?>>> attributeStrategies
= new ConcurrentHashMap<Class<? extends Annotation>, Class<AttributeStrategy<?>>>();
/** The constructor comparator */
private AbstractConstructorComparator constructorHeavyComparator =
ConstructorHeavyFirstComparator.INSTANCE;
/** The constructor comparator */
private AbstractConstructorComparator constructorLightComparator =
ConstructorLightFirstComparator.INSTANCE;
/** The constructor comparator */
private AbstractMethodComparator methodHeavyComparator
= MethodHeavyFirstComparator.INSTANCE;
/** The constructor comparator */
private AbstractMethodComparator methodLightComparator
= MethodLightFirstComparator.INSTANCE;
// ------------------->> Instance / Static variables
// ------------------->> Constructors
/**
* Implementation of the Singleton pattern
*/
public AbstractRandomDataProviderStrategy() {
this(PodamConstants.DEFAULT_NBR_COLLECTION_ELEMENTS);
}
public AbstractRandomDataProviderStrategy(int nbrOfCollectionElements) {
this.nbrOfCollectionElements = nbrOfCollectionElements;
}
// ------------------->> Public methods
/**
* {@inheritDoc}
*/
@Override
public Boolean getBoolean(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return Boolean.TRUE;
}
/**
* {@inheritDoc}
*/
@Override
public Byte getByte(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
byte nextByte;
do {
nextByte = (byte) RANDOM.nextInt(Byte.MAX_VALUE);
} while (nextByte == 0);
return nextByte;
}
/**
* {@inheritDoc}
*/
@Override
public Byte getByteInRange(byte minValue, byte maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return (byte) (minValue + Math.random() * (maxValue - minValue) + 0.5);
}
/**
* {@inheritDoc}
*/
@Override
public Character getCharacter(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return PodamUtils.getNiceCharacter();
}
/**
* {@inheritDoc}
*/
@Override
public Character getCharacterInRange(char minValue, char maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return (char) (minValue + Math.random() * (maxValue - minValue) + 0.5);
}
/**
* {@inheritDoc}
*/
@Override
public Double getDouble(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
double retValue;
do {
retValue = RANDOM.nextDouble();
} while (retValue == 0.0);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public Double getDoubleInRange(double minValue, double maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
// This can happen. It's a way to specify a precise value
if (minValue == maxValue) {
return minValue;
}
double retValue;
do {
retValue = minValue + Math.random() * (maxValue - minValue + 1);
} while (retValue > maxValue);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public Float getFloat(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
float retValue;
do {
retValue = RANDOM.nextFloat();
} while (retValue == 0.0f);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public Float getFloatInRange(float minValue, float maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
// This can happen. It's a way to specify a precise value
if (minValue == maxValue) {
return minValue;
}
float retValue;
do {
retValue = (float) (minValue
+ Math.random() * (maxValue - minValue + 1));
} while (retValue > maxValue);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public Integer getInteger(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
Integer retValue;
do {
retValue = RANDOM.nextInt();
} while (retValue.intValue() == 0);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public int getIntegerInRange(int minValue, int maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return (int) (minValue + Math.random() * (maxValue - minValue) + 0.5);
}
/**
* This implementation returns the current time in milliseconds.
* <p>
* This can be useful for Date-like constructors which accept a long as
* argument. A complete random number would cause the instantiation of such
* classes to fail on a non-deterministic basis, e.g. when the random long
* would not be an acceptable value for, say, a YEAR field.
* </p>
* {@inheritDoc}
*/
@Override
public Long getLong(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return System.nanoTime();
}
/**
* {@inheritDoc}
*/
@Override
public Long getLongInRange(long minValue, long maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return PodamUtils.getLongInRange(minValue, maxValue);
}
/**
* {@inheritDoc}
*/
@Override
public Short getShort(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
short retValue;
do {
retValue = (short) RANDOM.nextInt(Byte.MAX_VALUE);
} while (retValue == 0);
return retValue;
}
/**
* {@inheritDoc}
*/
@Override
public Short getShortInRange(short minValue, short maxValue,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return (short) (minValue + Math.random() * (maxValue - minValue) + 0.5);
}
/**
* {@inheritDoc}
*/
@Override
public String getStringValue(AttributeMetadata attributeMetadata) {
log(attributeMetadata);
return getStringOfLength(PodamConstants.STR_DEFAULT_LENGTH,
attributeMetadata);
}
/**
* {@inheritDoc}
*/
@Override
public String getStringOfLength(int length,
AttributeMetadata attributeMetadata) {
log(attributeMetadata);
StringBuilder buff = new StringBuilder();
while (buff.length() < length) {
buff.append(getCharacter(attributeMetadata));
}
return buff.toString();
}
// ------------------->> Getters / Setters
/**
* {@inheritDoc}
*/
@Override
public int getNumberOfCollectionElements(Class<?> type) {
return nbrOfCollectionElements;
}
/**
* {@inheritDoc}
*/
@Override
public void setDefaultNumberOfCollectionElements(int newNumberOfCollectionElements) {
nbrOfCollectionElements = newNumberOfCollectionElements;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxDepth(Class<?> type) {
return maxDepth;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isMemoizationEnabled() {
return isMemoizationEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public void setMemoization(boolean isMemoizationEnabled) {
this.isMemoizationEnabled = isMemoizationEnabled;
}
/**
* {@inheritDoc}
*/
@Override
public Object getMemoizedObject(AttributeMetadata attributeMetadata) {
if (isMemoizationEnabled) {
/* No memoization for arrays, collections and maps */
Class<?> pojoClass = attributeMetadata.getPojoClass();
if (pojoClass == null ||
(!pojoClass.isArray() &&
!Collection.class.isAssignableFrom(pojoClass) &&
!Map.class.isAssignableFrom(pojoClass))) {
ConcurrentMap<Type[], Object> map = memoizationTable.get(attributeMetadata.getAttributeType());
if (map != null) {
for (Entry<Type[], Object> entry : map.entrySet()) {
if (Arrays.equals(entry.getKey(), attributeMetadata.getAttrGenericArgs())) {
return entry.getValue();
}
}
}
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void cacheMemoizedObject(AttributeMetadata attributeMetadata,
Object instance) {
if (isMemoizationEnabled) {
ConcurrentMap<Type[], Object> map = memoizationTable.get(attributeMetadata.getAttributeType());
if (map == null) {
map = new ConcurrentHashMap<Type[], Object>();
memoizationTable.putIfAbsent(attributeMetadata.getAttributeType(), map);
}
map.putIfAbsent(attributeMetadata.getAttrGenericArgs(), instance);
}
}
/**
* {@inheritDoc}
*/
@Override
public void clearMemoizationCache() {
memoizationTable.clear();
}
/**
* Rearranges POJO's constructors in order they will be tried to produce the
* POJO. Default strategy consist of putting constructors with less
* parameters to be tried first.
*
* @param constructors
* Array of POJO's constructors
* @param order
* {@link uk.co.jemos.podam.api.DataProviderStrategy.Order} how to sort constructors
*/
@Override
public void sort(Constructor<?>[] constructors, Order order) {
AbstractConstructorComparator constructorComparator;
switch(order) {
case HEAVY_FIRST:
constructorComparator = constructorHeavyComparator;
break;
default:
constructorComparator = constructorLightComparator;
break;
}
Arrays.sort(constructors, constructorComparator);
}
/**
* Rearranges POJO's methods in order they will be tried to produce the
* POJO. Default strategy consist of putting methods with more
* parameters to be tried first.
*
* @param methods
* Array of POJO's methods
* @param order
* {@link uk.co.jemos.podam.api.DataProviderStrategy.Order} how to sort constructors
*/
@Override
public void sort(Method[] methods, Order order) {
AbstractMethodComparator methodComparator;
switch(order) {
case HEAVY_FIRST:
methodComparator = methodHeavyComparator;
break;
default:
methodComparator = methodLightComparator;
break;
}
Arrays.sort(methods, methodComparator);
}
/**
* Bind an interface/abstract class to a specific implementation. If the
* strategy previously contained a binding for the interface/abstract class,
* the old value will not be replaced by the new value. If you want to force the
* value replacement, invoke removeSpecific before invoking this method.
* If you want to implement more sophisticated binding strategy, override this class.
*
* @param <T> return type
* @param abstractClass
* the interface/abstract class to bind
* @param specificClass
* the specific class implementing or extending
* {@code abstractClass}.
* @return itself
*/
@Override
public <T> DataProviderStrategy addOrReplaceSpecific(
final Class<T> abstractClass, final Class<? extends T> specificClass) {
specificTypes.put(abstractClass, specificClass);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public <T> DataProviderStrategy removeSpecific(
final Class<T> abstractClass) {
specificTypes.remove(abstractClass);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public <T> Class<? extends T> getSpecificClass(
Class<T> nonInstantiatableClass) {
Class<? extends T> found = (Class<? extends T>) specificTypes
.get(nonInstantiatableClass);
if (found == null) {
found = nonInstantiatableClass;
}
return found;
}
/**
* {@inheritDoc}
*/
@Override
public RandomDataProviderStrategy addOrReplaceAttributeStrategy(
final Class<? extends Annotation> annotationClass,
final Class<AttributeStrategy<?>> strategyClass) {
attributeStrategies.put(annotationClass, strategyClass);
return this;
}
/**
* Remove binding of an annotation to attribute strategy
*
* @param annotationClass
* the annotation class to remove binding
* @return itself
*/
@Override
public RandomDataProviderStrategy removeAttributeStrategy(
final Class<? extends Annotation> annotationClass) {
attributeStrategies.remove(annotationClass);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Class<AttributeStrategy<?>> getStrategyForAnnotation(
final Class<? extends Annotation> annotationClass) {
return attributeStrategies.get(annotationClass);
}
/**
* {@inheritDoc}
*/
@Override
public AbstractConstructorComparator getConstructorLightComparator() {
return constructorLightComparator;
}
/**
* {@inheritDoc}
*/
@Override
public void setConstructorLightComparator(AbstractConstructorComparator constructorLightComparator) {
this.constructorLightComparator = constructorLightComparator;
}
/**
* {@inheritDoc}
*/
@Override
public AbstractConstructorComparator getConstructorHeavyComparator() {
return constructorHeavyComparator;
}
/**
* {@inheritDoc}
*/
@Override
public void setConstructorHeavyComparator(AbstractConstructorComparator constructorHeavyComparator) {
this.constructorHeavyComparator = constructorHeavyComparator;
}
/**
* {@inheritDoc}
*/
@Override
public AbstractMethodComparator getMethodLightComparator() {
return methodLightComparator;
}
/**
* {@inheritDoc}
*/
@Override
public void setMethodLightComparator(AbstractMethodComparator methodLightComparator) {
this.methodLightComparator = methodLightComparator;
}
/**
* {@inheritDoc}
*/
@Override
public AbstractMethodComparator getMethodHeavyComparator() {
return methodHeavyComparator;
}
/**
* {@inheritDoc}
*/
@Override
public void setMethodHeavyComparator(AbstractMethodComparator methodHeavyComparator) {
this.methodHeavyComparator = methodHeavyComparator;
}
// ------------------->> Private methods
private void log(AttributeMetadata attributeMetadata) {
LOG.trace("Providing data for attribute {}.{}",
attributeMetadata.getPojoClass().getName(),
attributeMetadata.getAttributeName() != null ? attributeMetadata.getAttributeName() : "");
}
// ------------------->> equals() / hashcode() / toString()
// ------------------->> Inner classes
}
| 24.368576 | 155 | 0.680566 |
608214adcd081388d3084d880907f689fdc1e6dd | 417 | package com.fmatos.crazywallpapers.wallpaper.domain;
/**
* Created by fdematos on 29/12/15.
*/
public class Point {
private final float x;
private final float y;
private final int color;
public Point(float x, float y, int color) {
this.x = x;
this.y = y;
this.color = color;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public int getColor() {
return color;
}
}
| 14.37931 | 52 | 0.652278 |
710ff480cc8cb06a479f7c8ed4e3e3ac9e5f615e | 332 | package com.github.hicoincom.api.bean;
import java.io.Serializable;
import java.util.List;
/**
* 获取币种列表
* http://docs.hicoin.vip/zh/latest/API-WaaS-V2/api/user_getCoinList.html
*/
public class CoinInfoListResult extends Result<List<CoinInfo>> implements Serializable {
private static final long serialVersionUID = 1L;
}
| 23.714286 | 88 | 0.762048 |
f20a2129c19df2d5a2a5b262b14154fd10f1cc57 | 6,046 | /*
* Copyright (c) 2019 David Castañón <antik10ud@gmail.com>
*
* 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.k10ud.crl;
import com.k10ud.asn1.x509_certificate.*;
import com.k10ud.certs.Context;
import com.k10ud.certs.Item;
import com.k10ud.certs.TaggedString;
import com.k10ud.certs.util.ASN1Helper;
import com.k10ud.certs.util.ItemHelper;
import java.io.IOException;
import java.util.List;
public class CRLProc {
/*
CertificateList ::= SEQUENCE {
tbsCertList TBSCertList,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING }
*/
private final Context context;
public CRLProc(Context context) {
this.context = context;
}
public Item parse(byte[] crlBytes) {
Item out = new Item();
if (crlBytes == null||crlBytes.length==0)
return out.prop("No Data");
CertificateList certList = new CertificateList();
try {
certList.decode(0,crlBytes, true);
} catch (IOException e) {
out.prop("Unable to process data as CertificateList", e);
out.prop("Raw Value", ItemHelper.xprint(crlBytes));
return out;
}
if (certList.tbsCertList != null) {
if (certList.tbsCertList.issuer != null) {
out.prop("issuer", ItemHelper.name(context, certList.tbsCertList.issuer));
}
out.prop("tbsCertList", tbsCertList(certList.tbsCertList));
if (certList.tbsCertList.crlExtensions != null) {
Extensions extensions = certList.tbsCertList.crlExtensions;
out.prop("crlExtensions", ItemHelper.extensions(context, extensions));
}
}
if (certList.signatureAlgorithm != null)
out.prop("signatureAlgorithm", ItemHelper.algorithm(context, certList.signatureAlgorithm));
if (certList.signature != null)
out.prop("signature", certList.signature.value);
return out;
}
/*
TBSCertList ::= SEQUENCE {
version Version OPTIONAL,
-- if present, MUST be v2
signature AlgorithmIdentifier,
issuer Name,
thisUpdate Time,
nextUpdate Time OPTIONAL,
revokedCertificates SEQUENCE OF SEQUENCE {
userCertificate CertificateSerialNumber,
revocationDate Time,
crlEntryExtensions Extensions OPTIONAL
-- if present, MUST be v2
} OPTIONAL,
crlExtensions [0] Extensions OPTIONAL }
-- if present, MUST be v2
*/
private Item tbsCertList(TBSCertList tbsCertList) {
Item out = new Item();
if (tbsCertList.version != null)
out.prop("version", version(tbsCertList.version));
if (tbsCertList.thisUpdate != null)
out.prop("thisUpdate", ASN1Helper.time(tbsCertList.thisUpdate));
if (tbsCertList.nextUpdate != null)
out.prop("nextUpdate", ASN1Helper.time(tbsCertList.nextUpdate));
if (tbsCertList.revokedCertificates != null)
out.prop("revokedCertificates", tbsRevokedCertificate(tbsCertList.revokedCertificates.seqOf));
if (tbsCertList.signature != null)
out.prop("signature", ItemHelper.algorithm(context, tbsCertList.signature));
return out;
}
private Item tbsRevokedCertificate(List<TBSRevokedCertificate> list) {
Item out = new Item();
int k = 0;
for (TBSRevokedCertificate i : list)
out.prop(ItemHelper.index((k++)), tbsCertListSeqItem(i));
return out;
}
/*
userCertificate CertificateSerialNumber,
revocationDate Time,
crlEntryExtensions Extensions OPTIONAL
-- if present, MUST be v2
} OPTIONAL,
*/
private Item tbsCertListSeqItem(TBSRevokedCertificate i) {
Item out = new Item();
if (i.userCertificate != null)
out.prop("userCertificate", i.userCertificate.getPositiveValue());
if (i.revocationDate != null)
out.prop("revocationDate", ASN1Helper.time(i.revocationDate));
if (i.crlEntryExtensions != null)
out.prop("crlEntryExtensions", ItemHelper.extensions(context, i.crlEntryExtensions));
return out;
}
public static Object version(Version version) {
if (version == null) {
return new TaggedString(String.valueOf(0)).addTag("v2").addTag("default");
}
switch (version.getInt()) {
case 1:
return new TaggedString(String.valueOf(version.getPositiveValue())).addTag("v2");
}
return version.getValue();
}
} | 36.203593 | 106 | 0.611479 |
6b0fccec3eba0ef460d4c2dabc00395d1aa2e6fb | 587 | package com.laniakea.annotation;
import java.lang.annotation.*;
import static com.laniakea.config.KearpcConstants.DEFAULT_SIZE;
/**
* @author luochang
* @version KearpcReference.java, v 0.1 2019年05月29日 17:40 luochang Exp
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface KearpcReference {
String uniqueId();
String protocol() default "PROTOSTUFFSERIALIZE"; //非订阅需要指定点对点连接
String address() default ""; //非订阅需要指定点对点连接
int maximumSize() default DEFAULT_SIZE;
boolean isSubscribe() default true;
}
| 19.566667 | 70 | 0.746167 |
1b7244d04a95a0a527fff8d94dd970db1082138e | 1,514 | package com.github.bottomlessarchive.loa.queue.service.conductor;
import com.github.bottomlessarchive.loa.conductor.service.client.extension.InstancePropertyExtensionProvider;
import com.github.bottomlessarchive.loa.conductor.service.client.extension.domain.InstanceExtensionContext;
import com.github.bottomlessarchive.loa.queue.service.domain.Queue;
import lombok.RequiredArgsConstructor;
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class QueueInstancePropertyExtensionProvider implements InstancePropertyExtensionProvider {
private final EmbeddedActiveMQ embeddedActiveMQ;
@Override
public void extendInstanceWithProperty(final InstanceExtensionContext instanceExtensionContext) {
instanceExtensionContext.setProperty("locationQueueCount", getMessageCount(Queue.DOCUMENT_LOCATION_QUEUE));
instanceExtensionContext.setProperty("archivingQueueCount", getMessageCount(Queue.DOCUMENT_ARCHIVING_QUEUE));
}
private String getMessageCount(final Queue queue) {
return String.valueOf(
Optional.ofNullable(embeddedActiveMQ.getActiveMQServer())
.flatMap(activeMQServer -> Optional.ofNullable(activeMQServer.locateQueue(queue.getName())))
.map(org.apache.activemq.artemis.core.server.Queue::getMessageCount)
.orElse(-1L)
);
}
}
| 45.878788 | 117 | 0.781374 |
f4da520f68af95360ff89092e993c0f228c95589 | 2,119 | package com.asolutions.scmsshd.commands.git;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){
throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument());
}
try{
String strRepoBase = config
.getProperty(GitSCMCommandFactory.REPOSITORY_BASE);
File repoBase = new File(strRepoBase);
Repository repo = repositoryProvider.provide(repoBase, filteredCommand
.getArgument());
ReceivePack rp = receivePackProvider.provide(repo);
rp.receive(inputStream, outputStream, errorStream);
}
catch (IOException e){
log.error("rp caught ioe: ", e);
throw e;
}
}
}
| 33.109375 | 103 | 0.809344 |
62d6305a343725555bb1cc67657250c62a18b604 | 1,359 | package datadog.trace.instrumentation.vertx_sql_client;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import com.google.auto.service.AutoService;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.bootstrap.instrumentation.jdbc.DBInfo;
import java.util.Map;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
@AutoService(Instrumenter.class)
public class MySQLPoolImplInstrumentation extends Instrumenter.Tracing {
public MySQLPoolImplInstrumentation() {
super("vertx", "vertx-sql-client");
}
@Override
public Map<String, String> contextStore() {
return singletonMap("io.vertx.sqlclient.SqlClient", DBInfo.class.getName());
}
@Override
public ElementMatcher<? super TypeDescription> typeMatcher() {
return named("io.vertx.mysqlclient.impl.MySQLPoolImpl");
}
@Override
public void adviceTransformations(AdviceTransformation transformation) {
transformation.applyAdvice(
isConstructor().and(takesArgument(2, named("io.vertx.mysqlclient.MySQLConnectOptions"))),
packageName + ".MySQLPoolImplConstructorAdvice");
}
}
| 35.763158 | 97 | 0.797645 |
b4a402f0c9647fc6564507e82782f20f33ce6bb4 | 2,646 | package uk.ac.ebi.interpro.scan.model.raw;
import uk.ac.ebi.interpro.scan.model.PatternScanMatch;
import uk.ac.ebi.interpro.scan.model.SignatureLibrary;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.Index;
import javax.persistence.Table;
/**
* <a href="http://www.expasy.ch/prosite/">PROSITE</a> Pattern raw match.
*
* @author Antony Quinn
* @author Phil Jones
* @version $Id$
*/
@Entity
@Table(name = ProSitePatternRawMatch.TABLE_NAME, indexes = {
@Index(name = "PROSITE_PAT_RW_SEQ_IDX", columnList = RawMatch.COL_NAME_SEQUENCE_IDENTIFIER),
@Index(name = "PROSITE_PAT_RW_NUM_SEQ_IDX", columnList = RawMatch.COL_NAME_NUMERIC_SEQUENCE_ID),
@Index(name = "PROSITE_PAT_RW_MODEL_IDX", columnList = RawMatch.COL_NAME_MODEL_ID),
@Index(name = "PROSITE_PAT_RW_SIGLIB_IDX", columnList = RawMatch.COL_NAME_SIGNATURE_LIBRARY),
@Index(name = "PROSITE_PAT_RW_SIGLIB_REL_IDX", columnList = RawMatch.COL_NAME_SIGNATURE_LIBRARY_RELEASE)
})
public class ProSitePatternRawMatch extends PfScanRawMatch {
public static final String TABLE_NAME = "PROSITE_PAT_RAW_MATCH";
protected ProSitePatternRawMatch() {
}
@Enumerated(javax.persistence.EnumType.STRING)
@Column(nullable = false)
private PatternScanMatch.PatternScanLocation.Level patternLevel;
public ProSitePatternRawMatch(String sequenceIdentifier, String model,
String signatureLibraryRelease,
int locationStart, int locationEnd, String cigarAlignment, PatternScanMatch.PatternScanLocation.Level patternLevel) {
super(sequenceIdentifier, model, SignatureLibrary.PROSITE_PATTERNS, signatureLibraryRelease, locationStart, locationEnd, cigarAlignment);
setPatternLevel(patternLevel);
}
public void setPatternLevel(PatternScanMatch.PatternScanLocation.Level patternLevel) {
this.patternLevel = patternLevel;
}
public PatternScanMatch.PatternScanLocation.Level getPatternLevel() {
return patternLevel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ProSitePatternRawMatch)) return false;
if (!super.equals(o)) return false;
ProSitePatternRawMatch that = (ProSitePatternRawMatch) o;
if (patternLevel != that.patternLevel) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + patternLevel.hashCode();
return result;
}
}
| 36.246575 | 151 | 0.719955 |
11e233484846d5c3aa41df9f3d9fa03c876b4bfb | 503 | package com.stackroute.recommendation.service;
import com.stackroute.recommendation.domain.User;
import org.springframework.stereotype.Service;
import java.util.Collection;
@Service
public interface UserService {
public Collection<User> getAllUsers();
public User findByName(String name);
public User create(long id, String name,String email,int uid);
public User delete(Long id);
public User deleteAll();
public User updateUser(long id, String name,String email,int uid);
}
| 27.944444 | 70 | 0.767396 |
2bef50d8d8e83c7585c0d28388425bc2d338d870 | 3,010 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.controller;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import edu.wpi.first.wpilibj.geometry.Pose2d;
import edu.wpi.first.wpilibj.geometry.Rotation2d;
import edu.wpi.first.wpilibj.geometry.Twist2d;
import edu.wpi.first.wpilibj.trajectory.TrajectoryConfig;
import edu.wpi.first.wpilibj.trajectory.TrajectoryGenerator;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RamseteControllerTest {
private static final double kTolerance = 1 / 12.0;
private static final double kAngularTolerance = Math.toRadians(2);
private static double boundRadians(double value) {
while (value > Math.PI) {
value -= Math.PI * 2;
}
while (value <= -Math.PI) {
value += Math.PI * 2;
}
return value;
}
@Test
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
void testReachesReference() {
final var controller = new RamseteController(2.0, 0.7);
var robotPose = new Pose2d(2.7, 23.0, Rotation2d.fromDegrees(0.0));
final var waypoints = new ArrayList<Pose2d>();
waypoints.add(new Pose2d(2.75, 22.521, new Rotation2d(0)));
waypoints.add(new Pose2d(24.73, 19.68, new Rotation2d(5.846)));
var config = new TrajectoryConfig(8.8, 0.1);
final var trajectory = TrajectoryGenerator.generateTrajectory(waypoints, config);
final double kDt = 0.02;
final var totalTime = trajectory.getTotalTimeSeconds();
for (int i = 0; i < (totalTime / kDt); ++i) {
var state = trajectory.sample(kDt * i);
var output = controller.calculate(robotPose, state);
robotPose = robotPose.exp(new Twist2d(output.vxMetersPerSecond * kDt, 0,
output.omegaRadiansPerSecond * kDt));
}
final var states = trajectory.getStates();
final var endPose = states.get(states.size() - 1).poseMeters;
// Java lambdas require local variables referenced from a lambda expression
// must be final or effectively final.
final var finalRobotPose = robotPose;
assertAll(
() -> assertEquals(endPose.getTranslation().getX(), finalRobotPose.getTranslation().getX(),
kTolerance),
() -> assertEquals(endPose.getTranslation().getY(), finalRobotPose.getTranslation().getY(),
kTolerance),
() -> assertEquals(0.0,
boundRadians(endPose.getRotation().getRadians()
- finalRobotPose.getRotation().getRadians()),
kAngularTolerance)
);
}
}
| 39.090909 | 99 | 0.63588 |
aefe4897b6d36fb6eedea3a72aec9d64da4b09be | 3,283 | /*-
* #%L
* jira-cli
*
* Copyright (C) 2019 László-Róbert, Albert (robert@albertlr.ro)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package ro.albertlr.jira.action;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.Transition;
import io.atlassian.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import ro.albertlr.jira.Action;
import ro.albertlr.jira.Configuration;
import ro.albertlr.jira.Configuration.IssueTypeConfig;
import ro.albertlr.jira.Jira;
import ro.albertlr.jira.Utils;
import java.util.Collection;
import java.util.Iterator;
import java.util.function.Function;
import java.util.stream.Collectors;
@Slf4j
public class AutoTransitionIssue implements Action<Void> {
private final Configuration configuration = Configuration.loadConfiguration();
@Override
public Void execute(Jira jira, String... params) {
String issueKeys = Action.paramAt(params, 0, "issueKey");
String phase = Action.paramAt(params, 0, "phase");
for (String issueKey : Utils.split(issueKeys)) {
Issue issue = jira.loadIssue(issueKey);
IssueTypeConfig typeConfig = configuration.configFor(issue.getIssueType().getName());
Collection<String> phases = typeConfig.getTransitionFlow(phase)
.stream()
.map(phaseChoice -> Utils.splitToList(phaseChoice, '|'))
.map(Collection::stream)
.flatMap(Function.identity())
.collect(Collectors.toList());
doTransition(jira, issue, phases);
}
return null;
}
private void doTransition(Jira jira, Issue issue, Collection<String> phases) {
Iterable<Transition> transactions = jira.loadTransitionsFor(issue);
Iterator<String> phaseIterator = phases.iterator();
Transition transitionTo = null;
phaseIt:
while (phaseIterator.hasNext()) {
String phase = phaseIterator.next();
for (Transition transition : transactions) {
if (transition.getName().equals(phase)) {
transitionTo = transition;
break phaseIt;
}
}
}
if (transitionTo != null) {
log.info("Transition {} - {} to {} {}", issue.getKey(), issue.getSummary(),
transitionTo.getId(), transitionTo.getName());
Promise<Void> transitioning = jira.transitionIssue(issue, transitionTo);
transitioning.claim();
doTransition(jira, issue, phases);
} else {
log.info("No more transition phases for {} - {}", issue.getKey(), issue.getSummary());
}
}
}
| 35.684783 | 98 | 0.647274 |
bfe4cfb8d3836ecc9f3d94b2d5a7f7b77757441f | 252 | package twgc.gm.cert;
import java.math.BigInteger;
/**
* @author liqs
* @version 1.0
* @date 2021/1/19 14:27
* ref:https://github.com/ZZMarquis/gmhelper
*/
public interface CertSNAllocator {
BigInteger nextSerialNumber() throws Exception;
}
| 18 | 51 | 0.714286 |
228c158a60395834f0f28857175bd59d03a5fe22 | 14,375 | /**
* MIT License
Copyright (c) 2015 Rob Terpilowski
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.sumzerotrading.broker.order;
import com.sumzerotrading.broker.order.OrderStatus.Status;
import com.sumzerotrading.data.Ticker;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.time.*;
import java.util.Objects;
public class TradeOrder implements Serializable {
public final static long serialVersionUID = 1L;
public enum Type {
MARKET, STOP, LIMIT, MARKET_ON_OPEN, MARKET_ON_CLOSE
};
public enum Duration {
DAY, GOOD_UNTIL_CANCELED, GOOD_UTNIL_TIME, FILL_OR_KILL, MARKET_ON_OPEN
};
protected Ticker ticker;
protected TradeDirection direction;
protected Type type;
protected ZonedDateTime goodAfterTime = null;
protected ZonedDateTime goodUntilTime = null;
protected Double limitPrice = null;
protected Double stopPrice = null;
protected Duration duration;
protected int size;
protected String orderId;
protected String parentOrderId = "";
protected String ocaGroup;
protected String positionId;
protected List<TradeOrder> childOrders = new ArrayList<TradeOrder>();
protected TradeOrder comboOrder;
protected String reference;
protected boolean submitted = false;
protected boolean submitChildOrdersFirst = false;
protected ZonedDateTime orderEntryTime;
protected ZonedDateTime orderFilledTime;
protected double orderTimeInForceMinutes = 0;
protected double filledSize = 0;
protected double filledPrice = 0;
protected double commission = 0;
protected Status currentStatus = Status.NEW;
public TradeOrder() {}
public TradeOrder(String orderId, Ticker ticker, int size, TradeDirection tradeDirection) {
type = Type.MARKET;
duration = Duration.DAY;
direction = TradeDirection.BUY;
this.ticker = ticker;
this.orderId = orderId;
this.size = size;
this.direction = tradeDirection;
}
public TradeOrder(TradeOrder original) {
this(original.getOrderId(), original.getTicker(), original.getSize(), original.getTradeDirection());
}
public boolean isSubmitted() {
return submitted;
}
public void setSubmitted(boolean submitted) {
this.submitted = submitted;
}
public boolean isSubmitChildOrdersFirst() {
return submitChildOrdersFirst;
}
public void setSubmitChildOrdersFirst(boolean submitChildOrdersFirst) {
this.submitChildOrdersFirst = submitChildOrdersFirst;
}
public Ticker getTicker() {
return ticker;
}
public void setTicker(Ticker ticker) {
this.ticker = ticker;
}
public TradeDirection getTradeDirection() {
return direction;
}
public void setTradeDirection(TradeDirection direction) {
this.direction = direction;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public ZonedDateTime getGoodAfterTime() {
return goodAfterTime;
}
public void setGoodAfterTime(ZonedDateTime goodAfterTime) {
this.goodAfterTime = goodAfterTime;
}
public ZonedDateTime getGoodUntilTime() {
return goodUntilTime;
}
public void setGoodUntilTime(ZonedDateTime goodUntilTime) {
this.goodUntilTime = goodUntilTime;
}
public Double getLimitPrice() {
return limitPrice;
}
public void setLimitPrice(Double price) {
this.limitPrice = price;
}
public Double getStopPrice() {
return stopPrice;
}
public void setStopPrice(Double stopPrice) {
this.stopPrice = stopPrice;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getParentOrderId() {
return parentOrderId;
}
public void setParentOrderId(String parentOrderId) {
this.parentOrderId = parentOrderId;
}
public String getOcaGroup() {
return ocaGroup;
}
public void setOcaGroup(String ocaGroup) {
this.ocaGroup = ocaGroup;
}
public boolean isBuyOrder() {
return (direction == TradeDirection.BUY) || (direction == TradeDirection.BUY_TO_COVER);
}
public String getPositionId() {
return positionId;
}
public void setPositionId(String positionId) {
this.positionId = positionId;
}
public List<TradeOrder> getChildOrders() {
return childOrders;
}
public void setChildOrders(List<TradeOrder> orders) {
this.childOrders = orders;
}
public void addChildOrder(TradeOrder childOrder) {
childOrder.setParentOrderId(orderId);
childOrders.add(childOrder);
}
public void removeChildOrder(TradeOrder childOrder) {
childOrders.remove(childOrder);
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public TradeOrder getComboOrder() {
return comboOrder;
}
public void setComboOrder(TradeOrder comboOrder) {
this.comboOrder = comboOrder;
}
public TradeDirection getDirection() {
return direction;
}
public void setDirection(TradeDirection direction) {
this.direction = direction;
}
public ZonedDateTime getOrderEntryTime() {
return orderEntryTime;
}
public void setOrderEntryTime(ZonedDateTime orderEntryTime) {
this.orderEntryTime = orderEntryTime;
}
public double getOrderTimeInForceMinutes() {
return orderTimeInForceMinutes;
}
public void setOrderTimeInForceMinutes(double orderTimeInForceMinutes) {
this.orderTimeInForceMinutes = orderTimeInForceMinutes;
}
public double getFilledSize() {
return filledSize;
}
public void setFilledSize(double filledSize) {
this.filledSize = filledSize;
}
public double getFilledPrice() {
return filledPrice;
}
public void setFilledPrice(double filledPrice) {
this.filledPrice = filledPrice;
}
public Status getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(Status currentStatus) {
this.currentStatus = currentStatus;
}
public ZonedDateTime getOrderFilledTime() {
return orderFilledTime;
}
public void setOrderFilledTime(ZonedDateTime orderFilledTime) {
this.orderFilledTime = orderFilledTime;
}
public double getCommission() {
return commission;
}
public void setCommission(double commission) {
this.commission = commission;
}
@Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + Objects.hashCode(this.ticker);
hash = 71 * hash + Objects.hashCode(this.direction);
hash = 71 * hash + Objects.hashCode(this.type);
hash = 71 * hash + Objects.hashCode(this.goodAfterTime);
hash = 71 * hash + Objects.hashCode(this.goodUntilTime);
hash = 71 * hash + Objects.hashCode(this.limitPrice);
hash = 71 * hash + Objects.hashCode(this.stopPrice);
hash = 71 * hash + Objects.hashCode(this.duration);
hash = 71 * hash + this.size;
hash = 71 * hash + Objects.hashCode(this.orderId);
hash = 71 * hash + Objects.hashCode(this.parentOrderId);
hash = 71 * hash + Objects.hashCode(this.ocaGroup);
hash = 71 * hash + Objects.hashCode(this.positionId);
hash = 71 * hash + Objects.hashCode(this.childOrders);
hash = 71 * hash + Objects.hashCode(this.comboOrder);
hash = 71 * hash + Objects.hashCode(this.reference);
hash = 71 * hash + (this.submitted ? 1 : 0);
hash = 71 * hash + (this.submitChildOrdersFirst ? 1 : 0);
hash = 71 * hash + Objects.hashCode(this.orderEntryTime);
hash = 71 * hash + Objects.hashCode(this.orderFilledTime);
hash = 71 * hash + (int) (Double.doubleToLongBits(this.orderTimeInForceMinutes) ^ (Double.doubleToLongBits(this.orderTimeInForceMinutes) >>> 32));
hash = 71 * hash + (int) (Double.doubleToLongBits(this.filledSize) ^ (Double.doubleToLongBits(this.filledSize) >>> 32));
hash = 71 * hash + (int) (Double.doubleToLongBits(this.filledPrice) ^ (Double.doubleToLongBits(this.filledPrice) >>> 32));
hash = 71 * hash + (int) (Double.doubleToLongBits(this.commission) ^ (Double.doubleToLongBits(this.commission) >>> 32));
hash = 71 * hash + Objects.hashCode(this.currentStatus);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TradeOrder other = (TradeOrder) obj;
if (this.size != other.size) {
return false;
}
if (this.submitted != other.submitted) {
return false;
}
if (this.submitChildOrdersFirst != other.submitChildOrdersFirst) {
return false;
}
if (Double.doubleToLongBits(this.orderTimeInForceMinutes) != Double.doubleToLongBits(other.orderTimeInForceMinutes)) {
return false;
}
if (Double.doubleToLongBits(this.filledSize) != Double.doubleToLongBits(other.filledSize)) {
return false;
}
if (Double.doubleToLongBits(this.filledPrice) != Double.doubleToLongBits(other.filledPrice)) {
return false;
}
if (Double.doubleToLongBits(this.commission) != Double.doubleToLongBits(other.commission)) {
return false;
}
if (!Objects.equals(this.orderId, other.orderId)) {
return false;
}
if (!Objects.equals(this.parentOrderId, other.parentOrderId)) {
return false;
}
if (!Objects.equals(this.ocaGroup, other.ocaGroup)) {
return false;
}
if (!Objects.equals(this.positionId, other.positionId)) {
return false;
}
if (!Objects.equals(this.reference, other.reference)) {
return false;
}
if (!Objects.equals(this.ticker, other.ticker)) {
return false;
}
if (this.direction != other.direction) {
return false;
}
if (this.type != other.type) {
return false;
}
if (!Objects.equals(this.goodAfterTime, other.goodAfterTime)) {
return false;
}
if (!Objects.equals(this.goodUntilTime, other.goodUntilTime)) {
return false;
}
if (!Objects.equals(this.limitPrice, other.limitPrice)) {
return false;
}
if (!Objects.equals(this.stopPrice, other.stopPrice)) {
return false;
}
if (this.duration != other.duration) {
return false;
}
if (!Objects.equals(this.childOrders, other.childOrders)) {
return false;
}
if (!Objects.equals(this.comboOrder, other.comboOrder)) {
return false;
}
if (!Objects.equals(this.orderEntryTime, other.orderEntryTime)) {
return false;
}
if (!Objects.equals(this.orderFilledTime, other.orderFilledTime)) {
return false;
}
if (this.currentStatus != other.currentStatus) {
return false;
}
return true;
}
@Override
public String toString() {
return "TradeOrder{" + "ticker=" + ticker + ", direction=" + direction + ", type=" + type + ", goodAfterTime=" + goodAfterTime + ", goodUntilTime=" + goodUntilTime + ", limitPrice=" + limitPrice + ", stopPrice=" + stopPrice + ", duration=" + duration + ", size=" + size + ", orderId=" + orderId + ", parentOrderId=" + parentOrderId + ", ocaGroup=" + ocaGroup + ", positionId=" + positionId + ", childOrders=" + childOrders + ", comboOrder=" + comboOrder + ", reference=" + reference + ", submitted=" + submitted + ", submitChildOrdersFirst=" + submitChildOrdersFirst + ", orderEntryTime=" + orderEntryTime + ", orderFilledTime=" + orderFilledTime + ", orderTimeInForceMinutes=" + orderTimeInForceMinutes + ", filledSize=" + filledSize + ", filledPrice=" + filledPrice + ", commission=" + commission + ", currentStatus=" + currentStatus + '}';
}
}
| 32.596372 | 851 | 0.624 |
7aa760cd71c7ffe1dde4d4a438850c0b296352b1 | 1,228 | package com.slightlyloony.jsisyphus.examples;
import com.slightlyloony.jsisyphus.ATrack;
import com.slightlyloony.jsisyphus.Point;
import java.io.IOException;
import static java.lang.Math.PI;
/**
* @author Tom Dilatush tom@dilatush.com
*/
public class PolarValentine extends ATrack {
private static final int STICKS = 3; // the number of sticks with hearts...
public PolarValentine() {
super( "PolarValentine" );
}
public void trace() throws IOException {
HeartDef heart = new HeartDef( dc );
double angle = 0;
spiralTo( Point.fromRT( 1, 0 ), Point.fromRT( 0,0 ), 0, 1 );
eraseTo( Point.fromRT( 1, PI ) );
for( int i = 0; i < STICKS; i++ ) {
lineToRT( .4, angle );
double sf = 0.02;
while( sf < 0.6 ) {
heart.draw( "bottom", sf, angle );
double nsf = sf * 1.06;
lineToRT( (nsf - sf) / 2, angle + PI );
sf = nsf;
}
home();
arcAroundTableCenter( angle + 2 * PI / STICKS );
angle += 2 * PI / STICKS;
}
renderPNG( pngFileName );
write( trackFileName );
}
}
| 22.740741 | 93 | 0.532573 |
ddf9b43753a42217d972086f6e64b27ebff7f765 | 3,280 | package com.example.macromanager;
import android.app.ActivityOptions;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.example.macromanager.triggerreceiver.BatteryLevelChanged;
import com.example.macromanager.triggerreceiver.ChargerConnected;
import com.example.macromanager.triggerreceiver.ChargerDisconnected;
import com.example.macromanager.triggerreceiver.PasswordFailed;
import com.example.macromanager.triggerreceiver.ScreenOff;
import com.example.macromanager.triggerreceiver.ScreenOn;
import com.example.macromanager.triggerreceiver.Timetick;
import com.example.macromanager.ui.Action;
import static com.example.macromanager.App.CHANNEL_ID;
public class service extends Service {
BatteryLevelChanged batteryLevelChanged = new BatteryLevelChanged();
ChargerConnected chargerConnected = new ChargerConnected();
ChargerDisconnected chargerDisconnected = new ChargerDisconnected();
PasswordFailed passwordFailed = new PasswordFailed();
ScreenOff screenOff = new ScreenOff();
ScreenOn screenOn = new ScreenOn();
Timetick timetick = new Timetick();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground();
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelChanged, filter);
IntentFilter filter1 = new IntentFilter(Intent.ACTION_POWER_CONNECTED);
registerReceiver(chargerConnected, filter1);
IntentFilter filter2 = new IntentFilter(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(chargerDisconnected, filter2);
IntentFilter filter3 = new IntentFilter(Intent.ACTION_SCREEN_ON);
registerReceiver(screenOn, filter3);
IntentFilter filter4 = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenOff, filter4);
IntentFilter filter5 = new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(timetick, filter5);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryLevelChanged);
unregisterReceiver(chargerConnected);
unregisterReceiver(chargerDisconnected);
unregisterReceiver(screenOn);
unregisterReceiver(screenOff);
unregisterReceiver(timetick);
}
private void startForeground() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Macro manager")
.setContentText("Running")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
}
| 33.814433 | 82 | 0.72561 |
7e82fb72b38260aba8b8c9843934ee48b9695674 | 588 | // Autogenerated from runtime/patterns/predicate_pattern.i
package ideal.runtime.patterns;
import ideal.library.elements.*;
import ideal.library.patterns.*;
import ideal.runtime.elements.*;
public class predicate_pattern<element_type> extends one_pattern<element_type> {
public final function1<Boolean, element_type> the_predicate;
public predicate_pattern(final function1<Boolean, element_type> the_predicate) {
this.the_predicate = the_predicate;
}
public @Override boolean matches(final element_type the_element) {
return this.the_predicate.call(the_element);
}
}
| 32.666667 | 82 | 0.79932 |
49edaaafcfa918e066b579300aeb9eecacbe423a | 2,850 | package com.example.spring.narayana.controller;
import com.example.spring.narayana.service.PortfolioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
/**
* Portfolio controller exposing REST endpoints for buying and selling shares.
*/
@RestController
public class PortfolioController {
@Autowired
private PortfolioService portfolioService;
/**
* <pre>
* $> curl -X PUT "http://localhost:8080/portfolio/username/symbol?amount=2"
* </pre>
* <p>
* An endpoint to buy shares.
* <p>
* It can be invoked with a PUT request on /portfolio/{username}/{symbol}?amount={amount} endpoint.
* <p>
* This method is transactional and all its work will be aborted if the following conditions are not met:
* 1. User must exist.
* 2. Stock must exist.
* 3. User must have enough budget.
* 4. There must be enough shares available to be bought.
* <p>
* During the execution, status messages will be sent to the "updates" queue.
*
* @param username A unique name of a user who's buying the shares.
* @param symbol A unique identifier of a share to be bought.
* @param amount A number of shares to be bought.
* @throws IllegalArgumentException if a user or a share doesn't exist, or if an amount or a budget is not sufficient.
*/
@PutMapping("/portfolio/{username}/{symbol}")
public void buy(@PathVariable String username, @PathVariable String symbol, @RequestParam("amount") int amount) {
portfolioService.buy(username, symbol, amount);
}
/**
* <pre>
* $> curl -X DELETE "http://localhost:8080/portfolio/username/symbol?amount=2"
* </pre>
* <p>
* An endpoint to sell shares.
* <p>
* It can be invoked with a DELETE request on /portfolio/{username}/{symbol}?amount={amount} endpoint.
* <p>
* This method is transactional and all its work will be aborted if the following conditions are not met:
* 1. User must exist.
* 2. Stock must exist.
* 3. User must have enough shares.
* <p>
* During the execution, status messages will be sent to the "updates" queue.
*
* @param username A unique name of a user who's selling the shares.
* @param symbol A unique identifier of a share to be sold.
* @param amount A number of shares to be sold.
* @throws IllegalArgumentException if a user or a share doesn't exist, or if user doesn't own enough shares.
*/
@DeleteMapping("/portfolio/{username}/{symbol}")
@Transactional
public void sell(@PathVariable String username, @PathVariable String symbol, @RequestParam("amount") int amount) {
portfolioService.sell(username, symbol, amount);
}
}
| 39.041096 | 122 | 0.675789 |
762466c6a31ca7c169bbb35bcb853efa721461a8 | 40,913 | /*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.service;
import edu.northwestern.bioinformatics.studycalendar.core.StudyCalendarTestCase;
import edu.northwestern.bioinformatics.studycalendar.core.accesscontrol.PossiblyReadOnlyAuthorizationManager;
import edu.northwestern.bioinformatics.studycalendar.core.accesscontrol.PscUserBuilder;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudySiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudySubjectAssignmentDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationObjectFactory;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscUser;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.VisibleSiteParameters;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.VisibleStudyParameters;
import edu.northwestern.bioinformatics.studycalendar.service.presenter.UserStudySubjectAssignmentRelationship;
import edu.northwestern.bioinformatics.studycalendar.service.presenter.VisibleAuthorizationInformation;
import edu.northwestern.bioinformatics.studycalendar.tools.MapBuilder;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.suite.authorization.CsmHelper;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembership;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembershipLoader;
import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import org.acegisecurity.LockedException;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationScopeMappings.createSuiteRoleMembership;
import static org.easymock.EasyMock.expect;
public class PscUserServiceTest extends StudyCalendarTestCase {
private PscUserService service;
private User csmUser;
private Site whatCheer, northLiberty, solon;
private Study eg1701, fh0001, gi3009;
private SiteDao siteDao;
private StudyDao studyDao;
private StudySiteDao studySiteDao;
private StudySubjectAssignmentDao assignmentDao;
private SuiteRoleMembershipLoader suiteRoleMembershipLoader;
private AuthorizationManager csmAuthorizationManager;
private PossiblyReadOnlyAuthorizationManager possiblyReadOnlyAuthorizationManager;
@Override
protected void setUp() throws Exception {
super.setUp();
csmAuthorizationManager = registerMockFor(AuthorizationManager.class);
suiteRoleMembershipLoader = registerMockFor(SuiteRoleMembershipLoader.class);
siteDao = registerDaoMockFor(SiteDao.class);
studyDao = registerDaoMockFor(StudyDao.class);
studySiteDao = registerDaoMockFor(StudySiteDao.class);
assignmentDao = registerDaoMockFor(StudySubjectAssignmentDao.class);
CsmHelper csmHelper = registerMockFor(CsmHelper.class);
csmAuthorizationManager = registerMockFor(AuthorizationManager.class);
possiblyReadOnlyAuthorizationManager =
registerMockFor(PossiblyReadOnlyAuthorizationManager.class);
service = new PscUserService();
service.setCsmAuthorizationManager(csmAuthorizationManager);
service.setSuiteRoleMembershipLoader(suiteRoleMembershipLoader);
service.setCsmHelper(csmHelper);
service.setStudyDao(studyDao);
service.setSiteDao(siteDao);
service.setStudySiteDao(studySiteDao);
service.setStudySubjectAssignmentDao(assignmentDao);
csmUser = AuthorizationObjectFactory.createCsmUser(5, "John");
for (SuiteRole role : SuiteRole.values()) {
Group g = new Group();
g.setGroupId((long) role.ordinal());
g.setGroupName(role.getCsmName());
expect(csmHelper.getRoleCsmGroup(role)).andStubReturn(g);
}
whatCheer = setId(987, createSite("What Cheer", "IA987"));
northLiberty = setId(720, createSite("North Liberty", "IA720"));
solon = setId(846, createSite("Solon", "IA846"));
expect(siteDao.getAll()).andStubReturn(Arrays.asList(whatCheer, northLiberty, solon));
eg1701 = createBasicTemplate("EG 1701");
fh0001 = createBasicTemplate("FH 0001");
gi3009 = createBasicTemplate("GI 3009");
}
public void testLoadKnownUserForAcegi() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
Map<SuiteRole,SuiteRoleMembership> expectedMemberships = Collections.singletonMap(SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getRoleMemberships(csmUser.getUserId())).andReturn(
expectedMemberships);
replayMocks();
PscUser actual = service.loadUserByUsername("John");
assertNotNull(actual);
assertSame("Wrong user", "John", actual.getUsername());
assertEquals("Wrong memberships", expectedMemberships, actual.getMemberships());
}
public void testNullCsmUserThrowsExceptionForAcegi() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(null);
replayMocks();
try {
service.loadUserByUsername(csmUser.getLoginName());
fail("Exception not thrown");
} catch (UsernameNotFoundException unfe) {
// good
}
verifyMocks();
}
public void testDeactivatedCsmUserThrowsExceptionForAcegi() throws Exception {
csmUser.setEndDate(DateTools.createDate(2006, Calendar.MAY, 3));
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
expect(suiteRoleMembershipLoader.getRoleMemberships(csmUser.getUserId())).andReturn(
Collections.<SuiteRole, SuiteRoleMembership>emptyMap());
replayMocks();
try {
service.loadUserByUsername(csmUser.getLoginName());
fail("Exception not thrown");
} catch (LockedException le) {
// good
}
verifyMocks();
}
public void testGetKnownAuthorizableUser() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
Map<SuiteRole,SuiteRoleMembership> expectedMemberships = Collections.singletonMap(
SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getRoleMemberships(csmUser.getUserId())).andReturn(
expectedMemberships);
replayMocks();
PscUser actual = service.getAuthorizableUser("John");
assertNotNull(actual);
assertSame("Wrong user", "John", actual.getUsername());
assertEquals("Wrong memberships", expectedMemberships, actual.getMemberships());
}
public void testExpiredAuthorizableUserIsStillReturned() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
csmUser.setEndDate(DateTools.createDate(2006, Calendar.MAY, 3));
Map<SuiteRole,SuiteRoleMembership> expectedMemberships = Collections.singletonMap(
SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getRoleMemberships(csmUser.getUserId())).andReturn(
expectedMemberships);
replayMocks();
PscUser actual = service.getAuthorizableUser("John");
assertNotNull(actual);
assertSame("Wrong user", "John", actual.getUsername());
assertEquals("Wrong memberships", expectedMemberships, actual.getMemberships());
}
public void testUnknownAuthorizableUserReturnsNull() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(null);
replayMocks();
PscUser actual = service.getAuthorizableUser("John");
assertNull(actual);
}
public void testGetKnownUserForProvisioning() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
Map<SuiteRole,SuiteRoleMembership> expectedMemberships =
Collections.singletonMap(SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(csmUser.getUserId())).
andReturn(expectedMemberships);
replayMocks();
PscUser actual = service.getProvisionableUser("John");
assertNotNull(actual);
assertSame("Wrong user", "John", actual.getUsername());
assertEquals("Wrong memberships", expectedMemberships, actual.getMemberships());
}
public void testGetNullCsmUserForProvisioningReturnsNull() throws Exception {
expect(csmAuthorizationManager.getUser("John")).andReturn(null);
replayMocks();
assertNull(service.getProvisionableUser(csmUser.getLoginName()));
verifyMocks();
}
public void testDeactivatedCsmUserIsReturnedForProvisioning() throws Exception {
csmUser.setEndDate(DateTools.createDate(2006, Calendar.MAY, 3));
expect(csmAuthorizationManager.getUser("John")).andReturn(csmUser);
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(csmUser.getUserId())).
andReturn(Collections.<SuiteRole, SuiteRoleMembership>emptyMap());
replayMocks();
PscUser actual = service.getProvisionableUser("John");
assertNotNull(actual);
assertSame("Wrong user", "John", actual.getUsername());
verifyMocks();
}
public void testGetCsmUsersForRole() throws Exception {
expect(csmAuthorizationManager.getUsers(Integer.toString(SuiteRole.DATA_READER.ordinal()))).
andReturn(Collections.singleton(AuthorizationObjectFactory.createCsmUser("jimbo")));
replayMocks();
Collection<User> actual =
service.getCsmUsers(PscRole.DATA_READER);
verifyMocks();
assertEquals("Wrong number of users returned", 1, actual.size());
assertEquals("Wrong user returned", "jimbo", actual.iterator().next().getLoginName());
}
public void testGetCsmUsersForRoleWhenAuthorizationManagerFails() throws Exception {
expect(csmAuthorizationManager.getUsers(Integer.toString(SuiteRole.DATA_READER.ordinal()))).
andThrow(new CSObjectNotFoundException("Nope"));
replayMocks();
Collection<gov.nih.nci.security.authorization.domainobjects.User> actual =
service.getCsmUsers(PscRole.DATA_READER);
verifyMocks();
assertTrue("Should have return no users", actual.isEmpty());
}
public void testGetPscUsersFromCsmUsers() throws Exception {
Map<SuiteRole, SuiteRoleMembership> expectedMemberships =
Collections.singletonMap(SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getRoleMemberships(5L)).andReturn(expectedMemberships);
replayMocks();
Collection<PscUser> actual = service.getPscUsers(Collections.singleton(csmUser), false);
verifyMocks();
assertEquals("Wrong number of PSC users", 1, actual.size());
PscUser actualUser = actual.iterator().next();
assertSame("Wrong CSM user", csmUser, actualUser.getCsmUser());
assertEquals("Wrong memberships", expectedMemberships, actualUser.getMemberships());
}
public void testGetPscUsersFromCsmUsersWithPartial() throws Exception {
Map<SuiteRole, SuiteRoleMembership> expectedMemberships =
Collections.singletonMap(SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(5L)).
andReturn(expectedMemberships);
replayMocks();
Collection<PscUser> actual = service.getPscUsers(Collections.singleton(csmUser), true);
verifyMocks();
assertEquals("Wrong number of PSC users", 1, actual.size());
PscUser actualUser = actual.iterator().next();
assertSame("Wrong CSM user", csmUser, actualUser.getCsmUser());
assertEquals("Wrong memberships", expectedMemberships, actualUser.getMemberships());
}
public void testGetPscUsersFromCsmUsersReSortsTheMemberships() throws Exception {
Map<SuiteRole, SuiteRoleMembership> expectedMemberships =
new MapBuilder<SuiteRole, SuiteRoleMembership>().
put(SuiteRole.SYSTEM_ADMINISTRATOR,
new SuiteRoleMembership(SuiteRole.SYSTEM_ADMINISTRATOR, null, null)).
put(SuiteRole.AE_EXPEDITED_REPORT_REVIEWER,
new SuiteRoleMembership(SuiteRole.AE_EXPEDITED_REPORT_REVIEWER, null, null)).
put(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER,
new SuiteRoleMembership(SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, null, null)).
toMap();
expect(suiteRoleMembershipLoader.getRoleMemberships(5L)).andReturn(expectedMemberships);
replayMocks();
Collection<PscUser> actual = service.getPscUsers(Collections.singleton(csmUser), false);
verifyMocks();
Map<SuiteRole, SuiteRoleMembership> actualMemberships =
actual.iterator().next().getMemberships();
Iterator<SuiteRole> it = actualMemberships.keySet().iterator();
assertEquals("Wrong 1st role", SuiteRole.STUDY_CALENDAR_TEMPLATE_BUILDER, it.next());
assertEquals("Wrong 2nd role", SuiteRole.SYSTEM_ADMINISTRATOR, it.next());
assertEquals("Wrong 3rd role", SuiteRole.AE_EXPEDITED_REPORT_REVIEWER, it.next());
}
public void testVisibleAssignments() throws Exception {
PscUser guy = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies().
toUser();
StudySubjectAssignment expectedAssignment =
createAssignment(eg1701, solon, createSubject("F", "B"));
expect(siteDao.getVisibleSiteIds(
new VisibleSiteParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(3, 7));
expect(studyDao.getVisibleStudyIds(
new VisibleStudyParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(4));
expect(assignmentDao.getAssignmentsInIntersection(Arrays.asList(4), Arrays.asList(3, 7))).
andReturn(Arrays.asList(expectedAssignment));
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual = service.getVisibleAssignments(guy);
verifyMocks();
assertEquals("Wrong number of visible assignments", 1, actual.size());
assertSame("Wrong assignment visible", expectedAssignment, actual.get(0).getAssignment());
assertSame("User not carried forward", guy, actual.get(0).getUser());
}
public void testGetVisibleAssignmentsDoesNotQueryAssignmentsForNonSubjectRoles() throws Exception {
PscUser qa = new PscUserBuilder().
add(PscRole.STUDY_QA_MANAGER).forSites(whatCheer).toUser();
expect(siteDao.getVisibleSiteIds(new VisibleSiteParameters())).
andReturn(Collections.<Integer>emptyList());
expect(studyDao.getVisibleStudyIds(new VisibleStudyParameters())).
andReturn(Collections.<Integer>emptyList());
expect(assignmentDao.getAssignmentsInIntersection(
Collections.<Integer>emptyList(), Collections.<Integer>emptyList())).
andReturn(Arrays.<StudySubjectAssignment>asList());
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual = service.getVisibleAssignments(qa);
verifyMocks();
assertEquals("Wrong number of assignments returned", 0, actual.size());
}
public void testGetVisibleStudySiteIds() throws Exception {
PscUser guy = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies().
toUser();
expect(siteDao.getVisibleSiteIds(
new VisibleSiteParameters().forParticipatingSiteIdentifiers("IA987"))).
andReturn(Arrays.asList(4));
expect(studyDao.getVisibleStudyIds(
new VisibleStudyParameters().forParticipatingSiteIdentifiers("IA987"))).
andReturn(Arrays.asList(3, 7));
expect(studySiteDao.getIntersectionIds(Arrays.asList(3, 7), Arrays.asList(4))).
andReturn(Arrays.asList(34, 47));
replayMocks();
Collection<Integer> actual = service.getVisibleStudySiteIds(guy, PscRole.STUDY_TEAM_ADMINISTRATOR);
verifyMocks();
assertEquals("Wrong number of visible study sites", 2, actual.size());
assertContains("Wrong study site IDs", actual, 34);
assertContains("Wrong study site IDs", actual, 47);
}
public void testGetVisibleStudySiteIdsWhenNoRolesSpecified() throws Exception {
PscUser guy = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies().
add(PscRole.STUDY_CREATOR).forSites(northLiberty).
toUser();
expect(siteDao.getVisibleSiteIds(
new VisibleSiteParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(21));
expect(studyDao.getVisibleStudyIds(
new VisibleStudyParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(4, 84));
expect(studySiteDao.getIntersectionIds(Arrays.asList(4, 84), Arrays.asList(21))).
andReturn(Arrays.asList(336));
replayMocks();
Collection<Integer> actual = service.getVisibleStudySiteIds(guy);
verifyMocks();
assertEquals("Wrong number of visible study sites", 1, actual.size());
assertContains("Wrong study site IDs", actual, 336);
}
public void testGetVisibleAssignmentIds() throws Exception {
PscUser guy = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies().
toUser();
expect(siteDao.getVisibleSiteIds(
new VisibleSiteParameters().forParticipatingSiteIdentifiers("IA987"))).
andReturn(Arrays.asList(4));
expect(studyDao.getVisibleStudyIds(
new VisibleStudyParameters().forParticipatingSiteIdentifiers("IA987"))).
andReturn(Arrays.asList(3, 7));
expect(assignmentDao.getAssignmentIdsInIntersection(Arrays.asList(3, 7), Arrays.asList(4))).
andReturn(Arrays.asList(34, 47));
replayMocks();
Collection<Integer> actual =
service.getVisibleAssignmentIds(guy, PscRole.STUDY_TEAM_ADMINISTRATOR);
verifyMocks();
assertEquals("Wrong number of visible study sites", 2, actual.size());
assertContains("Wrong study site IDs", actual, 34);
assertContains("Wrong study site IDs", actual, 47);
}
public void testGetVisibleAssignmentIdsWhenNoRolesSpecified() throws Exception {
PscUser guy = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies().
add(PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(northLiberty).forAllStudies().
toUser();
expect(siteDao.getVisibleSiteIds(
new VisibleSiteParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(21));
expect(studyDao.getVisibleStudyIds(
new VisibleStudyParameters().forParticipatingSiteIdentifiers("IA987", "IA846"))).
andReturn(Arrays.asList(4, 84));
expect(assignmentDao.getAssignmentIdsInIntersection(Arrays.asList(4, 84), Arrays.asList(21))).
andReturn(Arrays.asList(336));
replayMocks();
Collection<Integer> actual = service.getVisibleAssignmentIds(guy);
verifyMocks();
assertEquals("Wrong number of visible study sites", 1, actual.size());
assertContains("Wrong study site IDs", actual, 336);
}
public void testGetManagedAssignments() throws Exception {
PscUser manager = new PscUserBuilder().setCsmUserId(15L).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllSites().forAllStudies().
toUser();
StudySubjectAssignment expectedAssignment =
createAssignment(eg1701, northLiberty, createSubject("F", "B"));
expect(assignmentDao.getAssignmentsByManagerCsmUserId(15)).
andReturn(Arrays.asList(expectedAssignment));
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual
= service.getManagedAssignments(manager, manager);
verifyMocks();
assertEquals("Wrong number of visible assignments", 1, actual.size());
assertSame("Wrong assignment visible", expectedAssignment, actual.get(0).getAssignment());
assertSame("User not carried forward", manager, actual.get(0).getUser());
}
public void testGetManagedAssignmentsVisibleToOtherUser() throws Exception {
PscUser manager = new PscUserBuilder().setCsmUserId(15L).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllSites().forAllStudies().
toUser();
PscUser viewer = new PscUserBuilder().setCsmUserId(17L).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(northLiberty).forAllStudies().
toUser();
StudySubjectAssignment expectedVisibleAssignment =
createAssignment(eg1701, northLiberty, createSubject("F", "B"));
StudySubjectAssignment expectedHiddenAssignment =
createAssignment(eg1701, whatCheer, createSubject("W", "C"));
expect(assignmentDao.getAssignmentsByManagerCsmUserId(15)).
andReturn(Arrays.asList(expectedVisibleAssignment, expectedHiddenAssignment));
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual
= service.getManagedAssignments(manager, viewer);
verifyMocks();
assertEquals("Wrong number of visible assignments", 1, actual.size());
assertSame("Wrong assignment visible",
expectedVisibleAssignment, actual.get(0).getAssignment());
assertSame("Wrong user carried forward", viewer, actual.get(0).getUser());
}
public void testGetManagedAssignmentsFiltersOutNoLongerManageableAssignments() throws Exception {
PscUser manager = new PscUserBuilder().setCsmUserId(15L).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer).forAllStudies().
toUser();
StudySubjectAssignment expectedOldAssignment =
createAssignment(eg1701, northLiberty, createSubject("F", "B"));
StudySubjectAssignment expectedStillManageableAssignment =
createAssignment(eg1701, whatCheer, createSubject("W", "C"));
expect(assignmentDao.getAssignmentsByManagerCsmUserId(15)).
andReturn(Arrays.asList(expectedOldAssignment, expectedStillManageableAssignment));
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual
= service.getManagedAssignments(manager, manager);
verifyMocks();
assertEquals("Wrong number of visible assignments", 1, actual.size());
assertSame("Wrong assignment visible", expectedStillManageableAssignment, actual.get(0).getAssignment());
assertSame("User not carried forward", manager, actual.get(0).getUser());
}
public void testGetDesignatedManagedAssignmentsFiltersNothing() throws Exception {
PscUser manager = new PscUserBuilder().setCsmUserId(15L).
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer).forAllStudies().
toUser();
StudySubjectAssignment expectedOldAssignment =
createAssignment(eg1701, northLiberty, createSubject("F", "B"));
StudySubjectAssignment expectedStillManageableAssignment =
createAssignment(eg1701, whatCheer, createSubject("W", "C"));
expect(assignmentDao.getAssignmentsByManagerCsmUserId(15)).
andReturn(Arrays.asList(expectedOldAssignment, expectedStillManageableAssignment));
replayMocks();
List<UserStudySubjectAssignmentRelationship> actual =
service.getDesignatedManagedAssignments(manager);
verifyMocks();
assertEquals("Wrong number of visible assignments: " + actual, 2, actual.size());
}
public void testGetTeamMembersIncludesDataReadersAndCalendarManagers() throws Exception {
PscUser teamAdmin = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forAllSites().
toUser();
User sscm = AuthorizationObjectFactory.createCsmUser( 6, "sally");
User dr = AuthorizationObjectFactory.createCsmUser(16, "joe");
User both = AuthorizationObjectFactory.createCsmUser(96, "sigourney");
expectGetCsmUsersForSuiteRole(SuiteRole.DATA_READER, both, dr);
expectGetCsmUsersForSuiteRole(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER, sscm, both);
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(6)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
catholicRoleMembership(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER)));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(16)).andReturn(
Collections.singletonMap(SuiteRole.DATA_READER,
catholicRoleMembership(SuiteRole.DATA_READER)));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(96)).andReturn(
new MapBuilder<SuiteRole, SuiteRoleMembership>().
put(SuiteRole.DATA_READER, catholicRoleMembership(SuiteRole.DATA_READER)).
put(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
catholicRoleMembership(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER)).
toMap());
replayMocks();
List<PscUser> team = service.getTeamMembersFor(teamAdmin);
verifyMocks();
assertEquals("Wrong number of team members", 3, team.size());
}
public void testGetTeamMembersOnlyIncludesIntersectingUsers() throws Exception {
PscUser teamAdmin = new PscUserBuilder().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
toUser();
User wcSSCM = AuthorizationObjectFactory.createCsmUser( 81, "bob");
User wcDR = AuthorizationObjectFactory.createCsmUser(243, "ben");
User solonSSCM = AuthorizationObjectFactory.createCsmUser(729, "bill");
expectGetCsmUsersForSuiteRole(SuiteRole.DATA_READER, wcDR);
expectGetCsmUsersForSuiteRole(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER, wcSSCM, solonSSCM);
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(81)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer)));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(243)).andReturn(
Collections.singletonMap(SuiteRole.DATA_READER,
createSuiteRoleMembership(PscRole.DATA_READER).forSites(whatCheer)));
expect(suiteRoleMembershipLoader.getProvisioningRoleMemberships(729)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon)));
replayMocks();
List<PscUser> team = service.getTeamMembersFor(teamAdmin);
verifyMocks();
assertEquals("Wrong number of team members", 2, team.size());
assertEquals("Wrong team member selected", "ben", team.get(0).getUsername());
assertEquals("Wrong team member selected", "bob", team.get(1).getUsername());
}
public void testGetTeamMembersDoesNothingForNonTeamAdmin() throws Exception {
PscUser someGuy = new PscUserBuilder().add(PscRole.SYSTEM_ADMINISTRATOR).toUser();
replayMocks();
List<PscUser> team = service.getTeamMembersFor(someGuy);
verifyMocks();
assertEquals("Should have no team", 0, team.size());
}
public void testGetColleaguesExcludesNonIntersectingUsers() throws Exception {
PscUser main = new PscUserBuilder().
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(northLiberty, solon).forAllStudies().
toUser();
User sal = AuthorizationObjectFactory.createCsmUser( 6, "sally");
User joe = AuthorizationObjectFactory.createCsmUser( 16, "joe");
User sig = AuthorizationObjectFactory.createCsmUser( 96, "sigourney");
User gis = AuthorizationObjectFactory.createCsmUser(576, "giselle");
expectGetCsmUsersForSuiteRole(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER, sal, joe, sig, gis);
expect(suiteRoleMembershipLoader.getRoleMemberships(6)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forAllSites().forAllStudies()));
expect(suiteRoleMembershipLoader.getRoleMemberships(16)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer, solon).forAllStudies()));
expect(suiteRoleMembershipLoader.getRoleMemberships(96)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer).forAllStudies()));
// gis is only partially provisioned, so she is in the group but doesn't have the membership
expect(suiteRoleMembershipLoader.getRoleMemberships(576)).andReturn(
Collections.<SuiteRole, SuiteRoleMembership>emptyMap());
replayMocks();
List<PscUser> colleagues = service.getColleaguesOf(main, PscRole.STUDY_SUBJECT_CALENDAR_MANAGER);
verifyMocks();
assertEquals("Wrong number of colleagues", 2, colleagues.size());
assertEquals("Wrong colleague included", "joe", colleagues.get(0).getUsername());
assertEquals("Wrong colleague included", "sally", colleagues.get(1).getUsername());
}
public void testGetColleaguesRespectsCandidateRolesIfSpecified() throws Exception {
PscUser main = new PscUserBuilder().
add(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(northLiberty).forAllStudies().
add(PscRole.DATA_READER).forSites(solon).forAllStudies().
add(PscRole.STUDY_TEAM_ADMINISTRATOR).forSites(whatCheer).
toUser();
User sal = AuthorizationObjectFactory.createCsmUser( 6, "sally");
User joe = AuthorizationObjectFactory.createCsmUser( 16, "joe");
User sig = AuthorizationObjectFactory.createCsmUser( 96, "sigourney");
User gis = AuthorizationObjectFactory.createCsmUser(576, "giselle");
expectGetCsmUsersForSuiteRole(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER, sal, joe, sig, gis);
expect(suiteRoleMembershipLoader.getRoleMemberships(6)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(whatCheer).forAllStudies()));
expect(suiteRoleMembershipLoader.getRoleMemberships(16)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(northLiberty).forAllStudies()));
expect(suiteRoleMembershipLoader.getRoleMemberships(96)).andReturn(
Collections.singletonMap(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER,
createSuiteRoleMembership(PscRole.STUDY_SUBJECT_CALENDAR_MANAGER).forSites(solon).forAllStudies()));
// gis is only partially provisioned, so she is in the group but doesn't have the membership
expect(suiteRoleMembershipLoader.getRoleMemberships(576)).andReturn(
Collections.<SuiteRole, SuiteRoleMembership>emptyMap());
replayMocks();
List<PscUser> colleagues = service.getColleaguesOf(main,
PscRole.STUDY_SUBJECT_CALENDAR_MANAGER,
PscRole.DATA_READER, PscRole.STUDY_TEAM_ADMINISTRATOR);
verifyMocks();
assertEquals("Wrong number of colleagues: " + colleagues, 2, colleagues.size());
assertEquals("Wrong colleague included", "sally", colleagues.get(0).getUsername());
assertEquals("Wrong colleague included", "sigourney", colleagues.get(1).getUsername());
}
public void testGetColleaguesDoesNothingForNonMatchingRole() throws Exception {
PscUser someGuy = new PscUserBuilder().add(PscRole.SYSTEM_ADMINISTRATOR).toUser();
replayMocks();
List<PscUser> colleagues = service.getColleaguesOf(someGuy, PscRole.DATA_IMPORTER);
verifyMocks();
assertEquals("Should have no colleagues", 0, colleagues.size());
}
////// vis auth info
public void testVisibleAuthInfoForRandomUserIsEmpty() throws Exception {
replayMocks();
VisibleAuthorizationInformation actual = service.
getVisibleAuthorizationInformationFor(new PscUserBuilder().
add(PscRole.DATA_READER).forAllSites().forAllStudies().toUser());
verifyMocks();
assertTrue("Should have no sites", actual.getSites().isEmpty());
assertTrue("Should have no studies", actual.getStudiesForSiteParticipation().isEmpty());
assertTrue("Should have no studies", actual.getStudiesForTemplateManagement().isEmpty());
assertTrue("Should have no roles", actual.getRoles().isEmpty());
}
public void testVisibleAuthInfoForSystemAdmin() throws Exception {
replayMocks();
VisibleAuthorizationInformation actual = service.
getVisibleAuthorizationInformationFor(new PscUserBuilder().
add(PscRole.SYSTEM_ADMINISTRATOR).toUser());
verifyMocks();
assertTrue("Should have no sites", actual.getSites().isEmpty());
assertTrue("Should have no studies", actual.getStudiesForSiteParticipation().isEmpty());
assertTrue("Should have no studies", actual.getStudiesForTemplateManagement().isEmpty());
assertEquals("Should have 2 roles: " + actual.getRoles(), 2, actual.getRoles().size());
assertContains(actual.getRoles(), SuiteRole.SYSTEM_ADMINISTRATOR);
assertContains(actual.getRoles(), SuiteRole.USER_ADMINISTRATOR);
}
public void testVisibleAuthInfoForUnlimitedUserAdmin() throws Exception {
List<Study> expectedManaged = Arrays.asList(eg1701, fh0001);
List<Study> expectedParticipating = Arrays.asList(gi3009, fh0001);
expect(studyDao.getVisibleStudiesForTemplateManagement(
new VisibleStudyParameters().forAllManagingSites().forAllParticipatingSites())).
andReturn(expectedManaged);
expect(studyDao.getVisibleStudiesForSiteParticipation(
new VisibleStudyParameters().forAllManagingSites().forAllParticipatingSites())).
andReturn(expectedParticipating);
replayMocks();
VisibleAuthorizationInformation actual = service.
getVisibleAuthorizationInformationFor(new PscUserBuilder().
add(PscRole.USER_ADMINISTRATOR).forAllSites().toUser());
verifyMocks();
assertEquals("Should have all sites", 3, actual.getSites().size());
assertSame("Wrong participating studies", expectedParticipating,
actual.getStudiesForSiteParticipation());
assertSame("Wrong managed studies", expectedManaged,
actual.getStudiesForTemplateManagement());
assertEquals("Should have all roles: " + actual.getRoles(),
SuiteRole.values().length, actual.getRoles().size());
}
public void testVisibleAuthInfoForLimitedUserAdmin() throws Exception {
List<Study> expectedManaged = Arrays.asList(fh0001);
List<Study> expectedParticipating = Arrays.asList(eg1701);
expect(studyDao.getVisibleStudiesForTemplateManagement(
new VisibleStudyParameters().forManagingSiteIdentifiers(whatCheer.getAssignedIdentifier()).
forParticipatingSiteIdentifiers(whatCheer.getAssignedIdentifier()))).
andReturn(expectedManaged);
expect(studyDao.getVisibleStudiesForSiteParticipation(
new VisibleStudyParameters().forManagingSiteIdentifiers(whatCheer.getAssignedIdentifier()).
forParticipatingSiteIdentifiers(whatCheer.getAssignedIdentifier()))).
andReturn(expectedParticipating);
replayMocks();
VisibleAuthorizationInformation actual = service.
getVisibleAuthorizationInformationFor(new PscUserBuilder().
add(PscRole.USER_ADMINISTRATOR).forSites(whatCheer).toUser());
verifyMocks();
assertEquals("Should have one site", Arrays.asList(whatCheer), actual.getSites());
assertSame("Wrong participating studies", expectedParticipating,
actual.getStudiesForSiteParticipation());
assertSame("Wrong managed studies", expectedManaged,
actual.getStudiesForTemplateManagement());
assertEquals("Should have all non-global roles: " + actual.getRoles(),
19, actual.getRoles().size());
}
////// read-onlyness
public void testReadOnlyIfAuthorizationManagerSaysItIs() throws Exception {
service.setCsmAuthorizationManager(possiblyReadOnlyAuthorizationManager);
expect(possiblyReadOnlyAuthorizationManager.isReadOnly()).andReturn(true);
replayMocks();
assertTrue(service.isAuthorizationSystemReadOnly());
verifyMocks();
}
public void testReadOnlyIfAuthorizationManagerSaysItIsnt() throws Exception {
service.setCsmAuthorizationManager(possiblyReadOnlyAuthorizationManager);
expect(possiblyReadOnlyAuthorizationManager.isReadOnly()).andReturn(false);
replayMocks();
assertFalse(service.isAuthorizationSystemReadOnly());
verifyMocks();
}
public void testReadOnlyIfAuthorizationManagerCannotSay() throws Exception {
replayMocks();
assertFalse(service.isAuthorizationSystemReadOnly());
verifyMocks();
}
////// helpers
private SuiteRoleMembership catholicRoleMembership(SuiteRole role) {
SuiteRoleMembership srm = new SuiteRoleMembership(role, null, null);
if (role.isSiteScoped()) srm.forAllSites();
if (role.isStudyScoped()) srm.forAllStudies();
return srm;
}
private void expectGetCsmUsersForSuiteRole(SuiteRole role, User... expected) throws CSObjectNotFoundException {
expect(csmAuthorizationManager.getUsers(Integer.toString(role.ordinal()))).
andReturn(new HashSet<User>(Arrays.asList(expected)));
}
}
| 49.893902 | 136 | 0.715714 |
99dde32bea6a15563a4484f5efb2ac54b66efa42 | 4,154 | /**
* Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambkit.db.sql.column;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.lambkit.db.sql.ConditionMode;
/**
* Column 的工具类,用于方便组装sql
*/
public class Columns implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3093668879029947796L;
private List<Column> cols = new ArrayList<>();
public static Columns create() {
return new Columns();
}
public static Columns create(Column column) {
Columns that = new Columns();
that.cols.add(column);
return that;
}
public static Columns create(String name, Object value) {
return create().eq(name, value);
}
/**
* equals
*
* @param name
* @param value
* @return
*/
public Columns eq(String name, Object value) {
cols.add(Column.create(name, value));
return this;
}
/**
* not equals !=
*
* @param name
* @param value
* @return
*/
public Columns ne(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.NOT_EQUAL));
return this;
}
/**
* like
*
* @param name
* @param value
* @return
*/
public Columns like(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.FUZZY));
return this;
}
public Columns notLike(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.NOT_FUZZY));
return this;
}
/**
* 大于 great than
*
* @param name
* @param value
* @return
*/
public Columns gt(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.GREATER_THEN));
return this;
}
/**
* 大于等于 great or equal
*
* @param name
* @param value
* @return
*/
public Columns ge(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.GREATER_EQUAL));
return this;
}
/**
* 小于 less than
*
* @param name
* @param value
* @return
*/
public Columns lt(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.LESS_THEN));
return this;
}
/**
* 小于等于 less or equal
*
* @param name
* @param value
* @return
*/
public Columns le(String name, Object value) {
cols.add(Column.create(name, value, ConditionMode.LESS_EQUAL));
return this;
}
public Columns isnull(String name) {
cols.add(Column.create(name, ConditionMode.ISNULL));
return this;
}
public Columns notNull(String name) {
cols.add(Column.create(name, ConditionMode.NOT_NULL));
return this;
}
public Columns empty(String name) {
cols.add(Column.create(name, ConditionMode.EMPTY));
return this;
}
public Columns notEmpty(String name) {
cols.add(Column.create(name, ConditionMode.NOT_EMPTY));
return this;
}
public Columns add(Column column) {
cols.add(column);
return this;
}
public Columns addAll(List<Column> columns) {
cols.addAll(columns);
return this;
}
public List<Column> getList() {
return cols;
}
}
| 23.337079 | 75 | 0.581849 |
13a59cd8ce69d53fb8a62bc3107852f20026361b | 432 | package com.pbs.middleware.api.user;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@ApiModel(value = "UserUpdate", description = "User DTO for update request")
public class UserUpdate extends UserBaseDto {
@ApiModelProperty(name = "disabled", value = "Flag if user is disabled or enabled")
private Boolean disabled;
}
| 25.411765 | 87 | 0.773148 |
97d1742e3e7fe261b71c253ce19daa6f0acf58ea | 1,229 | /**
* Copyright 2017 Eternita LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.frontcache.hystrix.fr;
public class FallbackConfigEntry {
protected String fileName;
protected String urlPattern;
protected String initUrl;
public FallbackConfigEntry() { // for JSON mapper
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getUrlPattern() {
return urlPattern;
}
public void setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
}
public String getInitUrl() {
return initUrl;
}
public void setInitUrl(String initUrl) {
this.initUrl = initUrl;
}
}
| 23.188679 | 76 | 0.723352 |
1f78c3860a15b85be12ccd4076db963d205c2794 | 1,533 | package ch.obsec.net.swsimfx.model;
import javafx.beans.property.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.obsec.net.swsimfx.IdCounter;
/**
* @version 1.1
* @since 1.1
* @author mario.oberli@obsec.ch
*/
public class Device {
private static final Logger LOGGER = LoggerFactory.getLogger(Device.class);
private long deviceID = IdCounter.nextId();
private final StringProperty deviceNameProperty;
/**
* Default constructor.
*/
public Device() {
this(null);
LOGGER.trace("Device()");
}
/**
* Constructor with some initial data.
*/
public Device(String name) {
LOGGER.debug("Device({})",name);
this.deviceNameProperty = new SimpleStringProperty("Name");
}
public long getId() {
LOGGER.debug("getId(): {}",deviceID);
return deviceID;
}
/**
* getter
* @return device name
*/
public String getDeviceName() {
LOGGER.debug("getDeviceName(): {}",deviceNameProperty.get());
return deviceNameProperty.get();
}
/**
* setter
* @param name set device name
*/
public void setDeviceName(String name) {
LOGGER.debug("setDeviceName({})",name);
this.deviceNameProperty.set(name);
}
/**
* property
* @return device name property
*/
public StringProperty deviceNameProperty() {
LOGGER.debug("deviceNameProperty(): {}",deviceNameProperty);
return deviceNameProperty;
}
}
| 21.591549 | 79 | 0.612524 |
bcd3e598954565a2acdda0cedf4905fb161b2a18 | 8,398 | package com.unideb.qsa.calculator.implementation.calculator;
import java.util.HashMap;
import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.unideb.qsa.calculator.domain.SystemFeature;
/**
* Unit test for {@link SystemMMnKKCalculator}.
*/
public class SystemMMnKKCalculatorTest {
private static final double DELTA = 0.0001;
private final SystemMMnKKCalculator systemMMnKKCalculatorUnderTest = new SystemMMnKKCalculator();
@Test
public void RoTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 1.666666;
// WHEN
double result = systemMMnKKCalculatorUnderTest.Ro(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void E0Test() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.4;
// WHEN
double result = systemMMnKKCalculatorUnderTest.E0(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void SAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.66666666666666667;
// WHEN
double result = systemMMnKKCalculatorUnderTest.SAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void P0Test() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.01328740;
// WHEN
double result = systemMMnKKCalculatorUnderTest.P0(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void PnTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.22145669;
// WHEN
double result = systemMMnKKCalculatorUnderTest.Pn(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void PWTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.71801566;
// WHEN
double result = systemMMnKKCalculatorUnderTest.PW(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void mAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 1.1309055;
// WHEN
double result = systemMMnKKCalculatorUnderTest.mAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void LambdaAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 2.827263779527559;
// WHEN
double result = systemMMnKKCalculatorUnderTest.LambdaAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void QAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.9842519685;
// WHEN
double result = systemMMnKKCalculatorUnderTest.QAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void TAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 1.01479547;
// WHEN
double result = systemMMnKKCalculatorUnderTest.TAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void NAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 2.869094488;
// WHEN
double result = systemMMnKKCalculatorUnderTest.NAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void aTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.94242125;
// WHEN
double result = systemMMnKKCalculatorUnderTest.a(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void USTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.986712598;
// WHEN
double result = systemMMnKKCalculatorUnderTest.US(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void UtTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.282726;
// WHEN
double result = systemMMnKKCalculatorUnderTest.Ut(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void WAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.3481288;
// WHEN
double result = systemMMnKKCalculatorUnderTest.WAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void PinTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.3916449086;
// WHEN
double result = systemMMnKKCalculatorUnderTest.PinFin(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void FTtTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.98676339495;
// WHEN
double result = systemMMnKKCalculatorUnderTest.FTt(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void FWtTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.99954889;
// WHEN
double result = systemMMnKKCalculatorUnderTest.FWt(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void EWW0Test() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 0.4848484848;
// WHEN
double result = systemMMnKKCalculatorUnderTest.EWW0(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void eAvgTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
features.put(SystemFeature.c, 1.0);
double expected = 0.1;
// WHEN
double result = systemMMnKKCalculatorUnderTest.eAvg(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void EDeltaTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
features.put(SystemFeature.c, 1.0);
double expected = 33.6296296296;
// WHEN
double result = systemMMnKKCalculatorUnderTest.EDelta(features);
// THEN
Assert.assertEquals(result, expected, DELTA);
}
@Test
public void ECostTest() {
// GIVEN
Map<SystemFeature, Double> features = createTestFeatures();
double expected = 14.077411417322832;
// WHEN
double result = systemMMnKKCalculatorUnderTest.ECost(features);
// THEN
Assert.assertEquals(result,expected, DELTA);
}
private Map<SystemFeature, Double> createTestFeatures() {
Map<SystemFeature, Double> features = new HashMap<>();
features.put(SystemFeature.LambdaFin, 2.5);
features.put(SystemFeature.Mu, 1.5);
features.put(SystemFeature.n, 2.0);
features.put(SystemFeature.c, 2.0);
features.put(SystemFeature.KFin, 4.0);
features.put(SystemFeature.t, 3.0);
features.put(SystemFeature.CS, 2.2);
features.put(SystemFeature.CWS, 1.3);
features.put(SystemFeature.CI, 0.5);
features.put(SystemFeature.CSR, 4.5);
features.put(SystemFeature.R, 1.1);
return features;
}
}
| 29.886121 | 101 | 0.617171 |
426faf6723dde89bbf945bb70bff6cae41e55e4c | 1,811 | package pk.edu.kics.dsl.qa.qe;
import java.util.HashMap;
import java.util.Map;
import pk.edu.kics.dsl.qa.BiomedQA;
import pk.edu.kics.dsl.qa.entity.Question;
import pk.edu.kics.dsl.qa.util.CollectionHelper;
import org.apache.commons.math3.distribution.NormalDistribution;
public class BNS extends FeatureSelection {
NormalDistribution normalDistribution = new NormalDistribution();
HashMap<String, Double> truePositiveRate = new HashMap<>();
HashMap<String, Double> falsePositiveRate = new HashMap<>();
HashMap<String, Double> termsScore = new HashMap<>();
@Override
public Map<String, Double> getRelevantTerms(Question question) {
try {
super.init(question);
} catch (Exception e) {
e.printStackTrace();
}
for (String key : truePositive.keySet()) {
truePositiveRate.put(key, (double) truePositive.get(key)/BiomedQA.DOCUMENTS_FOR_QE);
}
for (String key : falsePositive.keySet()) {
falsePositiveRate.put(key, (double) falsePositive.get(key)/(BiomedQA.TOTAL_DOCUMENTS - BiomedQA.DOCUMENTS_FOR_QE));
}
for(String key: localDictionary) {
double termTPR = 0.0005;
double termFPR = 0.0005;
if(truePositiveRate.containsKey(key)) termTPR = truePositiveRate.get(key);
if(falsePositiveRate.containsKey(key)) termFPR = falsePositiveRate.get(key);
// Fix for words not appearing in global dictionary - comma words
if(termFPR<=0) termFPR = 0.0005;
if(termTPR<=0) termTPR = 0.0005;
if(termFPR == 1) termFPR = 0.99;
if(termTPR == 1) termTPR = 0.99;
double Ftpr = normalDistribution.inverseCumulativeProbability(termTPR);
double Ffpr = normalDistribution.inverseCumulativeProbability(termFPR);
double score = Math.abs(Ftpr - Ffpr);
termsScore.put(key, score);
}
return CollectionHelper.sortByComparator(termsScore, false);
}
}
| 30.694915 | 118 | 0.734401 |
48d19dc0c6c63332ac2cd89ffb18f559371e93fa | 1,266 | package org.enricogiurin.codingchallenges.leetcode.challenge072020;
/*
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
*/
//@LinkedList
//TODO - review it even if simple
public class RemoveLinkedListElements {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode removeElements(ListNode head, int val) {
ListNode forth = head;
ListNode back = null;
while (forth != null) {
if (forth.val == val) {
forth = forth.next;
if (back == null) {
head = forth;
} else {
back.next = forth;
}
//keep going on
} else {
back = forth;
forth = forth.next;
}
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
int val = 2;
ListNode listNode = new RemoveLinkedListElements().removeElements(head, val);
System.out.println(listNode);
}
}
| 23.886792 | 85 | 0.511848 |
87b0e8bd602ba310c310a642d9c63c81e2ef94fb | 2,672 | // This file is part of PDQ (https://github.com/ProofDrivenQuerying/pdq) which is released under the MIT license.
// See accompanying LICENSE for copyright notice and full details.
package uk.ac.ox.cs.pdq.datasources.schemabuilder;
/**
* A triple of elements.
*
* @author Efthymia Tsamoura
* @param <T1> Type of the first element
* @param <T2> Type of the second element
* @param <T3> Type of the third element
*/
public class Triple<T1, T2, T3> {
/** The first. */
private final T1 first;
/** The second. */
private final T2 second;
/** The third. */
private final T3 third;
/**
* Constructor for Triple.
* @param first T1
* @param second T2
* @param third T3
*/
public Triple(T1 first, T2 second, T3 third) {
this.first = first;
this.second = second;
this.third = third;
}
/**
* Gets the first.
*
* @return T1
*/
public T1 getFirst() {
return this.first;
}
/**
* Gets the second.
*
* @return T2
*/
public T2 getSecond() {
return this.second;
}
/**
* Gets the third.
*
* @return T3
*/
public T3 getThird() {
return this.third;
}
/**
* Hash code.
*
* @return int
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.first == null) ? 0 : this.first.hashCode());
result = prime * result + ((this.second == null) ? 0 : this.second.hashCode());
result = prime * result + ((this.third == null) ? 0 : this.third.hashCode());
return result;
}
/**
* Equals.
*
* @param obj Object
* @return boolean
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Triple<Object, Object, Object> other = (Triple<Object, Object, Object>) obj;
if (this.first == null) {
if (other.first != null) {
return false;
}
} else if (!this.first.equals(other.first)) {
return false;
}
if (this.second == null) {
if (other.second != null) {
return false;
}
} else if (!this.second.equals(other.second)) {
return false;
}
if (this.third == null) {
if (other.third != null) {
return false;
}
} else if (!this.third.equals(other.third)) {
return false;
}
return true;
}
/**
* To string.
*
* @return String
*/
@Override
public String toString() {
return this.first.toString() + " " + this.second.toString() + " " + this.third.toString();
}
}
| 19.50365 | 114 | 0.571482 |
9d48acdf99763eb1ab48e60838178863459d2673 | 3,853 | package com.devonfw.application.mtsj.bookingmanagement.logic.impl;
import java.util.List;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.devonfw.application.mtsj.SpringBootApp;
import com.devonfw.application.mtsj.bookingmanagement.common.api.datatype.BookingType;
import com.devonfw.application.mtsj.bookingmanagement.logic.api.Bookingmanagement;
import com.devonfw.application.mtsj.bookingmanagement.logic.api.to.BookingCto;
import com.devonfw.application.mtsj.bookingmanagement.logic.api.to.BookingEto;
import com.devonfw.application.mtsj.bookingmanagement.logic.api.to.BookingSearchCriteriaTo;
import com.devonfw.application.mtsj.general.common.ApplicationComponentTest;
import com.devonfw.application.mtsj.general.common.TestUtil;
import com.devonfw.application.mtsj.general.common.impl.security.ApplicationAccessControlConfig;
/**
* Unit Tests for {@link Bookingmanagement#findBookingsByUser}
*
*/
@SpringBootTest(classes = SpringBootApp.class)
@TestInstance(Lifecycle.PER_CLASS)
public class findBookingsByUserTest extends ApplicationComponentTest {
@Inject
private Bookingmanagement bookingmanagement;
/**
* Tests that all 3 bookings of the mock user "Lena123" are found.
*/
@Test
public void findBookingsByUserValid() {
TestUtil.login("Lena123", ApplicationAccessControlConfig.GROUP_CUSTOMER);
Pageable pageable = PageRequest.of(0, 20);
BookingSearchCriteriaTo criteria = new BookingSearchCriteriaTo();
criteria.setPageable(pageable);
List<BookingCto> bookingsByUser = this.bookingmanagement.findBookingsByUser(criteria).toList();
assertThat(bookingsByUser).hasSize(3);
BookingEto booking1 = bookingsByUser.get(0).getBooking();
BookingEto booking2 = bookingsByUser.get(1).getBooking();
BookingEto booking3 = bookingsByUser.get(2).getBooking();
assertThat(booking1.getBookingToken()).isEqualTo("CB_20170509_123502552Z");
assertThat(booking1.getName()).isEqualTo("Lena123");
assertThat(booking1.getEmail()).isEqualTo("Lena.Weber@mail.com");
assertThat(booking1.getBookingType()).isEqualTo(BookingType.COMMON);
assertThat(booking1.getAssistants()).isEqualTo(5);
assertThat(booking2.getBookingToken()).isEqualTo("CB_20170509_123502555Z");
assertThat(booking2.getName()).isEqualTo("Lena123");
assertThat(booking2.getEmail()).isEqualTo("Lena.Weber@mail.com");
assertThat(booking2.getBookingType()).isEqualTo(BookingType.COMMON);
assertThat(booking2.getAssistants()).isEqualTo(2);
assertThat(booking3.getBookingToken()).isEqualTo("CB_20170509_123502557Z");
assertThat(booking3.getName()).isEqualTo("Lena123");
assertThat(booking3.getEmail()).isEqualTo("Lena.Weber@mail.com");
assertThat(booking3.getBookingType()).isEqualTo(BookingType.COMMON);
assertThat(booking3.getAssistants()).isEqualTo(5);
TestUtil.logout();
}
/**
* Tests that no bookings are found if the user has not made any bookings.
*/
@Test
public void findBookingsByUserWithUserWithoutBookings() {
TestUtil.login("userWithoutBookings", ApplicationAccessControlConfig.GROUP_CUSTOMER);
BookingSearchCriteriaTo criteria = new BookingSearchCriteriaTo();
PageRequest pageable = PageRequest.of(0, 100);
criteria.setPageable(pageable);
Page<BookingCto> bookingsByUser = this.bookingmanagement.findBookingsByUser(criteria);
assertThat(bookingsByUser).isNull();
TestUtil.logout();
}
}
| 39.721649 | 100 | 0.767194 |
2ebb1900752474f86e33c0f9003a3162b7d5de36 | 6,943 | package com.tdlzgroup.educasa.Inicio.Class;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;
import android.view.MenuItem;
import com.tdlzgroup.educasa.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class Mapa extends FragmentActivity implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {
FusedLocationProviderClient mFusedLocationProviderClient;
Location mLastKnownLocation;
Boolean mLocationPermissionGranted;
static final int DEFAULT_ZOOM=15;
static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_mapa);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); //referencia para acceder a la aplicacion
}
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-16.32, -71.5188325);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
getLocationPermission();
updateLocationUI();
getDeviceLocation();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Mark2"));
}
});//agregar un marcador
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Mark3").icon(BitmapDescriptorFactory.fromBitmap(resizeMapIcons(BitmapFactory.decodeResource(getResources(),R.drawable.cerrar),100,100)))); //cambiar el icono de nuestro marcador
}
});
}
public Bitmap resizeMapIcons(Bitmap drawable, int width, int height){
Bitmap resizeBitmap= Bitmap.createScaledBitmap(drawable,width,height,false);
return resizeBitmap;
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)//pregunta si hay permiso para acceder a nuestra ubicacion
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},//de lo contrario tratamoss de acceder a nuestro permiso
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode){
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true); //para mostrar mi ubicacion
mMap.getUiSettings().setMyLocationButtonEnabled(true); //para poner el botoncito de obtener nuestra aplicacion getUiSettings() modificar la parte grafica de nuestro mapa
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
LatLng miubicacion=new LatLng(mLastKnownLocation.getLatitude(),mLastKnownLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(miubicacion,15));
mMap.addMarker(new MarkerOptions().position(miubicacion).title("Marke"));
} else {
}
}
});
}
} catch(SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
return false;
}
}
| 42.858025 | 253 | 0.651448 |
9d6327250bac631914a1bd1f554a95c6498ecf0a | 2,415 | package org.lpw.photon.ctrl.http.context;
import org.lpw.photon.util.DateTime;
import org.lpw.photon.util.Numeric;
import org.lpw.photon.util.Validator;
import org.springframework.stereotype.Controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller("photon.ctrl.http.cookie")
public class CookieImpl implements org.lpw.photon.ctrl.http.context.Cookie, CookieAware {
private Validator validator;
private Numeric numeric;
private DateTime dateTime;
private ThreadLocal<HttpServletRequest> request;
private ThreadLocal<HttpServletResponse> response;
public CookieImpl(Validator validator, Numeric numeric, DateTime dateTime) {
this.validator = validator;
this.numeric = numeric;
this.dateTime = dateTime;
request = new ThreadLocal<>();
response = new ThreadLocal<>();
}
@Override
public void add(String name, String value, String path, int expiry) {
Cookie cookie = new Cookie(name, value);
if (!validator.isEmpty(path))
cookie.setPath(path);
if (expiry > 0)
cookie.setMaxAge(expiry);
response.get().addCookie(cookie);
}
@Override
public String get(String name) {
String[] array = getAll(name);
return array.length == 0 ? null : array[array.length - 1];
}
@Override
public String[] getAll(String name) {
String[] array = new String[0];
Cookie[] cookies = request.get().getCookies();
if (validator.isEmpty(cookies))
return array;
List<String> list = new ArrayList<>();
for (Cookie cookie : cookies)
if (cookie.getName().equals(name))
list.add(cookie.getValue());
return list.toArray(array);
}
@Override
public int getAsInt(String name) {
return numeric.toInt(get(name));
}
@Override
public long getAsLong(String name) {
return numeric.toLong(get(name));
}
@Override
public Date getAsDate(String name) {
return dateTime.toDate(get(name));
}
@Override
public void set(HttpServletRequest request, HttpServletResponse response) {
this.request.set(request);
this.response.set(response);
}
}
| 28.75 | 89 | 0.658385 |
c85d3d50e8095db81a4f8cdde0625c5c85fddac1 | 6,223 | package imj2.draft;
import static imj2.tools.IMJTools.*;
import static java.lang.Integer.parseInt;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.round;
import static multij.swing.SwingTools.show;
import imj2.tools.SimpleImageView;
import imj2.tools.Image2DComponent.Painter;
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Locale;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import multij.swing.SwingTools;
import multij.tools.IllegalInstantiationException;
import multij.tools.Tools;
/**
* @author codistmonk (creation 2014-09-03)
*/
public final class ChannelViewer {
private ChannelViewer() {
throw new IllegalInstantiationException();
}
/**
* @param arguments
* <br>Unused
*/
public static final void main(final String[] arguments) {
SwingTools.useSystemLookAndFeel();
final JTextField channelsSpecifier = new JTextField("r g b");
final SimpleImageView imageView = new SimpleImageView();
final JPanel mainPanel = new JPanel(new BorderLayout());
final RGBTransformer[] transformer = { RGBTransformer.Predefined.ID };
mainPanel.add(channelsSpecifier, BorderLayout.NORTH);
mainPanel.add(imageView, BorderLayout.CENTER);
imageView.getPainters().add(new Painter<SimpleImageView>() {
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
final BufferedImage buffer = component.getBufferImage();
final int w = buffer.getWidth();
final int h = buffer.getHeight();
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
buffer.setRGB(x, y, transformer[0].transform(buffer.getRGB(x, y)));
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = -1045988659583024746L;
});
channelsSpecifier.getDocument().addDocumentListener(new DocumentListener() {
@Override
public final void removeUpdate(final DocumentEvent event) {
this.update(event);
}
@Override
public final void insertUpdate(final DocumentEvent event) {
this.update(event);
}
@Override
public final void changedUpdate(final DocumentEvent event) {
this.update(event);
}
private final void update(final DocumentEvent event) {
try {
final String text = channelsSpecifier.getText().toUpperCase(Locale.ENGLISH);
final String[] channelsSpecification = text.trim().split("\\s+");
transformer[0] = new Multiplexer(Arrays.stream(channelsSpecification)
.map(ChannelViewer::parse).toArray(RGBTransformer[]::new));
Tools.debugPrint((Object[]) channelsSpecification);
imageView.refreshBuffer();
} catch (final Exception exception) {
Tools.debugError(exception);
}
}
});
show(mainPanel, ChannelViewer.class.getSimpleName(), false);
}
public static final int clamp(final int value, final int minimum, final int maximum) {
return max(0, min(value, 255));
}
public static final int digitize(final float channelValue) {
return clamp(round(channelValue * 255F), 0, 255);
}
public static final RGBTransformer parse(final String string) {
try {
return new Gray(parseInt(string));
} catch (final Exception exception) {
return Channel2Gray.valueOf(string);
}
}
/**
* @author codistmonk (creation 2014-09-03)
*/
public static final class Multiplexer implements RGBTransformer {
private final RGBTransformer[] transformers;
public Multiplexer(final RGBTransformer[] transformers) {
this.transformers = transformers;
}
@Override
public final int transform(final int rgb) {
int result = 0xFF000000;
int mask = 0x00FFFFFF;
for (final RGBTransformer transformer : this.transformers) {
result = (result & ~mask) | (transformer.transform(rgb) & mask);
mask >>= Byte.SIZE;
}
return result;
}
/**
* {@value}.
*/
private static final long serialVersionUID = 4394160211395945075L;
}
/**
* @author codistmonk (creation 2014-09-03)
*/
public static final class Gray implements RGBTransformer {
private final int value;
public Gray(final int value) {
this.value = 0xFF000000 | (clamp(value, 0, 255) * 0x00010101);
}
@Override
public final int transform(final int rgb) {
return this.value;
}
/**
* {@value}.
*/
private static final long serialVersionUID = -6796486661098501344L;
}
/**
* @author codistmonk (creation 2014-09-03)
*/
public static enum Channel2Gray implements RGBTransformer {
R {
@Override
public final int transform(final int rgb) {
return 0xFF000000 | (red8(rgb) * 0x00010101);
}
}, G {
@Override
public final int transform(final int rgb) {
return 0xFF000000 | (green8(rgb) * 0x00010101);
}
}, B {
@Override
public final int transform(final int rgb) {
return 0xFF000000 | (blue8(rgb) * 0x00010101);
}
}, Y {
@Override
public final int transform(final int rgb) {
final float r = red8(rgb) / 255F;
final float g = green8(rgb) / 255F;
final float b = blue8(rgb) / 255F;
final float y = 0.299F * r + 0.587F * g + 0.114F * b;
return 0xFF000000 | (digitize(y) * 0x00010101);
}
}, U {
@Override
public final int transform(final int rgb) {
final float r = red8(rgb) / 255F;
final float g = green8(rgb) / 255F;
final float b = blue8(rgb) / 255F;
final float uMax = 0.436F;
final float u = (-0.14713F * r - 0.28886F * g + uMax * b + uMax) / uMax;
return 0xFF000000 | (digitize(u) * 0x00010101);
}
}, V {
@Override
public final int transform(final int rgb) {
final float r = red8(rgb) / 255F;
final float g = green8(rgb) / 255F;
final float b = blue8(rgb) / 255F;
final float vMax = 0.615F;
final float v = (vMax * r - 0.51499F * g - 0.10001F * b + vMax) / vMax;
return 0xFF000000 | (digitize(v) * 0x00010101);
}
};
}
}
| 24.792829 | 87 | 0.667202 |
8bb157cb35b603413270f04ac7cd111ace7cd387 | 2,595 | /*
* 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.github.housepower.protocol;
import com.github.housepower.client.NativeContext;
import com.github.housepower.exception.NotImplementedException;
import com.github.housepower.serde.BinaryDeserializer;
import java.io.IOException;
import java.sql.SQLException;
public interface Response {
ProtoType type();
static Response readFrom(BinaryDeserializer deserializer, NativeContext.ServerContext info) throws IOException, SQLException {
switch ((int) deserializer.readVarInt()) {
case 0:
return HelloResponse.readFrom(deserializer);
case 1:
return DataResponse.readFrom(deserializer, info);
case 2:
throw ExceptionResponse.readExceptionFrom(deserializer);
case 3:
return ProgressResponse.readFrom(deserializer);
case 4:
return PongResponse.readFrom(deserializer);
case 5:
return EOFStreamResponse.readFrom(deserializer);
case 6:
return ProfileInfoResponse.readFrom(deserializer);
case 7:
return TotalsResponse.readFrom(deserializer, info);
case 8:
return ExtremesResponse.readFrom(deserializer, info);
case 9:
throw new NotImplementedException("RESPONSE_TABLES_STATUS_RESPONSE");
default:
throw new IllegalStateException("Accept the id of response that is not recognized by Server.");
}
}
enum ProtoType {
RESPONSE_HELLO(0),
RESPONSE_DATA(1),
RESPONSE_EXCEPTION(2),
RESPONSE_PROGRESS(3),
RESPONSE_PONG(4),
RESPONSE_END_OF_STREAM(5),
RESPONSE_PROFILE_INFO(6),
RESPONSE_TOTALS(7),
RESPONSE_EXTREMES(8),
RESPONSE_TABLES_STATUS_RESPONSE(9);
private final int id;
ProtoType(int id) {
this.id = id;
}
public long id() {
return id;
}
}
}
| 33.269231 | 130 | 0.645087 |
33c4cc2985e7023b11d447209f77c27fe74a0add | 3,778 | package com.camnter.newlife.ui.activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.camnter.newlife.R;
import com.camnter.newlife.core.activity.BaseAppCompatActivity;
import com.camnter.newlife.utils.volley.GsonRequest;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
/**
* Description:VolleyActivity
* Created by:CaMnter
* Time:2016-05-25 11:34
*/
public class VolleyActivity extends BaseAppCompatActivity {
@BindView(R.id.volley_get_content_text) TextView mGetContentText;
/**
* Fill in layout id
*
* @return layout id
*/
@Override protected int getLayoutId() {
return R.layout.activity_volley;
}
/**
* Initialize the view in the layout
*
* @param savedInstanceState savedInstanceState
*/
@Override protected void initViews(Bundle savedInstanceState) {
ButterKnife.bind(this);
}
/**
* Initialize the View of the listener
*/
@Override protected void initListeners() {
}
/**
* Initialize the Activity data
*/
@Override protected void initData() {
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(new GsonRequest<GankData>("http://gank.io/api/data/Android/1/1", GankData.class) {
/**
* Called when a response is received.
*/
@Override public void onResponse(GankData response) {
mGetContentText.setText(response.toString());
}
/**
* Callback method that an error has been occurred with the
* provided error code and optional user-readable message.
*/
@Override public void onErrorResponse(VolleyError error) {
showToast(error.getMessage());
Log.d("GsonRequest", error.getMessage());
}
});
}
public class GankData {
private static final String TAG = "GankData";
public boolean error;
public ArrayList<GankResultData> results;
@Override public String toString() {
StringBuilder builder = new StringBuilder(TAG).append("\n\n");
for (GankResultData result : results) {
builder.append(result.toString());
builder.append("\n\n");
}
return builder.toString();
}
}
public class GankResultData {
private static final String TAG = "GankResultData";
@SerializedName("_id") public String id;
public String createdAt;
public String desc;
public String publishedAt;
public String source;
public String type;
public String url;
public boolean used;
public String who;
@Override public String toString() {
return TAG + "id: " +
this.id +
"\n" +
"createdAt: " +
this.createdAt +
"\n" +
"desc: " +
this.desc +
"\n" +
"publishedAt: " +
this.publishedAt +
"\n" +
"source: " +
this.source +
"\n" +
"type: " +
this.type +
"\n" +
"url: " +
this.url +
"\n" +
"used: " +
this.used +
"\n" +
"who: " +
this.who;
}
}
}
| 25.876712 | 100 | 0.547644 |
b4dc7c6ac499c924ea439fef841b0127319ea111 | 4,369 | package com.sap.cloud.lm.sl.mta.resolvers.v2_0;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sap.cloud.lm.sl.common.ContentException;
import com.sap.cloud.lm.sl.mta.builders.v2_0.ParametersChainBuilder;
import com.sap.cloud.lm.sl.mta.model.SystemParameters;
import com.sap.cloud.lm.sl.mta.model.v2_0.Module;
import com.sap.cloud.lm.sl.mta.model.v2_0.ProvidedDependency;
import com.sap.cloud.lm.sl.mta.model.v2_0.RequiredDependency;
import com.sap.cloud.lm.sl.mta.resolvers.PlaceholderResolver;
import com.sap.cloud.lm.sl.mta.resolvers.PropertiesPlaceholderResolver;
import com.sap.cloud.lm.sl.mta.resolvers.ResolverBuilder;
import com.sap.cloud.lm.sl.mta.util.PropertiesUtil;
public class ModulePlaceholderResolver extends PlaceholderResolver<Module> {
protected final Module module;
protected final ParametersChainBuilder parametersChainBuilder;
protected final ResolverBuilder propertiesResolverBuilder;
protected final ResolverBuilder parametersResolverBuilder;
public ModulePlaceholderResolver(Module module, String prefix, ParametersChainBuilder parametersChainBuilder,
SystemParameters systemParameters, ResolverBuilder propertiesResolverBuilder, ResolverBuilder parametersResolverBuilder) {
super(module.getName(), prefix, systemParameters);
this.module = module;
this.parametersChainBuilder = parametersChainBuilder;
this.propertiesResolverBuilder = propertiesResolverBuilder;
this.parametersResolverBuilder = parametersResolverBuilder;
}
@Override
public Module resolve() throws ContentException {
String moduleName = module.getName();
List<Map<String, Object>> parametersList = parametersChainBuilder.buildModuleChainWithoutDependencies(moduleName);
addSingularParametersIfNecessary(parametersList);
parametersList.add(getFullSystemParameters(systemParameters.getModuleParameters()
.get(moduleName)));
Map<String, Object> mergedParameters = PropertiesUtil.mergeProperties(parametersList);
module.setProperties(getResolvedProperties(mergedParameters));
module.setParameters(getResolvedParameters(mergedParameters));
module.setRequiredDependencies2_0(getResolvedRequiredDependencies());
module.setProvidedDependencies2_0(getResolvedProvidedDependencies());
return module;
}
protected Map<String, Object> getResolvedProperties(Map<String, Object> mergedParameters) throws ContentException {
return new PropertiesPlaceholderResolver(propertiesResolverBuilder).resolve(module.getProperties(), mergedParameters, prefix);
}
protected Map<String, Object> getResolvedParameters(Map<String, Object> mergedParameters) throws ContentException {
return new PropertiesPlaceholderResolver(parametersResolverBuilder).resolve(module.getParameters(), mergedParameters, prefix);
}
protected List<ProvidedDependency> getResolvedProvidedDependencies() throws ContentException {
List<ProvidedDependency> resolved = new ArrayList<ProvidedDependency>();
for (ProvidedDependency providedDependency : module.getProvidedDependencies2_0()) {
resolved.add(getProvidedDependencyResolver(providedDependency).resolve());
}
return resolved;
}
protected ProvidedDependencyPlaceholderResolver getProvidedDependencyResolver(ProvidedDependency providedDependency) {
return new ProvidedDependencyPlaceholderResolver(module, providedDependency, prefix, parametersChainBuilder, systemParameters,
propertiesResolverBuilder);
}
protected List<RequiredDependency> getResolvedRequiredDependencies() throws ContentException {
List<RequiredDependency> resolved = new ArrayList<RequiredDependency>();
for (RequiredDependency requiredDependency : module.getRequiredDependencies2_0()) {
resolved.add(getRequiredDependencyResolver(requiredDependency).resolve());
}
return resolved;
}
protected RequiredDependencyPlaceholderResolver getRequiredDependencyResolver(RequiredDependency requiredDependency) {
return new RequiredDependencyPlaceholderResolver(module, requiredDependency, prefix, parametersChainBuilder, systemParameters,
propertiesResolverBuilder, parametersResolverBuilder);
}
}
| 52.011905 | 134 | 0.786679 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.