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
|
|---|---|---|---|---|---|
6c325351c5105769d403d425867950b6a86fb8fd
| 1,399
|
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.example.demo.model.entities.User;
import com.example.demo.model.request.UserCreateRequest;
import com.example.demo.repository.UserRepository;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passEncoder;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
passEncoder = new BCryptPasswordEncoder();
}
public User CreateUser(UserCreateRequest userRequest) {
if(GetUserByName(userRequest.getUsername()) != null)
return null;
User user = new User();
user.setUsername(userRequest.getUsername());
user.setPassword(passEncoder.encode(userRequest.getPassword()));
userRepository.save(user);
return user;
}
public User ValidateUser(String userName, String password) {
User user = GetUserByName(userName);
if(user == null)
return null;
if(passEncoder.matches(password, user.getPassword()))
return user;
else
return null;
}
public User GetUserByName(String userName) {
return userRepository.findByUsername(userName).orElse(null);
}
}
| 24.54386
| 72
| 0.786276
|
9af1a47aa2c092924b30da92e3a3a9d0578a9587
| 3,105
|
package de.sormuras.javacompilerscriptengine;
import java.io.BufferedReader;
import java.io.Reader;
import java.util.stream.Collectors;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
class JavaCompilerScriptEngine extends AbstractScriptEngine implements Compilable {
private final JavaCompilerScriptEngineFactory factory;
JavaCompilerScriptEngine(JavaCompilerScriptEngineFactory factory) {
this.factory = factory;
context.setBindings(new SimpleBindings(), ScriptContext.GLOBAL_SCOPE);
context.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
}
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
return compile(script).eval(context);
}
@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
String script = new BufferedReader(reader).lines().collect(Collectors.joining());
return eval(script, context);
}
@Override
public Bindings createBindings() {
return new SimpleBindings();
}
@Override
public JavaCompilerScriptEngineFactory getFactory() {
return factory;
}
@Override
public CompiledScript compile(String script) throws ScriptException {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("import javax.script.*;");
builder.append("\n");
builder.append("public class CompiledJavaScript extends CompiledScript {\n");
builder.append("\n");
builder.append(" private final ScriptEngine engine;\n");
builder.append("\n");
builder.append(" public CompiledJavaScript(ScriptEngine engine) {\n");
builder.append(" this.engine = engine;\n");
builder.append(" }\n");
builder.append("\n");
builder.append(" public Object eval(ScriptContext context) throws ScriptException {\n");
// TODO Provide helpers around 'context' parameter.
for (String scriptLine : script.split("\\R")) {
builder.append(" ");
builder.append(scriptLine);
}
builder.append(" }\n");
builder.append("\n");
builder.append(" public ScriptEngine getEngine() {\n");
builder.append(" return engine;\n");
builder.append(" }\n");
builder.append("\n");
builder.append("}\n");
try {
Class<?> evaluatorClass = JavaCompilerUtils.compile("CompiledJavaScript", builder.toString());
Object evaluatorObject = evaluatorClass.getConstructor(ScriptEngine.class).newInstance(this);
return (CompiledScript) evaluatorObject;
} catch (Exception e) {
throw new ScriptException("Compilation failed for: " + builder + "\n" + e.getMessage());
}
}
@Override
public CompiledScript compile(Reader reader) throws ScriptException {
String script = new BufferedReader(reader).lines().collect(Collectors.joining());
return compile(script);
}
}
| 35.284091
| 100
| 0.718519
|
601b04bda3627ef03d79270d51dab067d0bd5d39
| 5,087
|
/**
*
*/
package com.perforce.p4java.tests.dev.unit.features111;
import com.perforce.p4java.client.IClient;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.IFileAnnotation;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.option.server.GetFileAnnotationsOptions;
import com.perforce.p4java.tests.SimpleServerRule;
import com.perforce.p4java.tests.dev.annotations.TestId;
import com.perforce.p4java.tests.dev.unit.P4JavaRshTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Tests annotate -I option. A bit impressionistic. May fail on
* newly-(re)created servers; if so, play with some of the size constants,
* etc., below and see what happens...
*/
@TestId("Features111_IntegrationsAnnotationsTest")
public class IntegrationsAnnotationsTest extends P4JavaRshTestCase {
private static final int TIME_OUT_IN_SECONDS = 60;
private static IClient client = null;
@ClassRule
public static SimpleServerRule p4d = new SimpleServerRule("r16.1", IntegrationsAnnotationsTest.class.getSimpleName());
@BeforeClass
public static void beforeAll() throws Exception {
Properties rpcTimeOutProperties = configRpcTimeOut("IntegrationsAnnotationsTest", TIME_OUT_IN_SECONDS);
setupServer(p4d.getRSHURL(), "p4jtestuser", "p4jtestuser", true, rpcTimeOutProperties);
client = getClient(server);
}
@Test
public void testIntegrationsAnnotations() throws Exception {
final String testRoot = "//depot/102Dev/CopyFilesTest/tgt"; // shared, so be careful...
final String testFile = testRoot + "/" + "...";
final List<IFileSpec> testFiles = FileSpecBuilder.makeFileSpecList(testFile);
List<IFileSpec> syncFiles = this.forceSyncFiles(client, testRoot + "/...");
assertNotNull("null sync files list", syncFiles);
assertEquals("bad forced sync", 0, FileSpecBuilder.getInvalidFileSpecs(syncFiles).size());
int annotationsSize = 0;
List<IFileAnnotation> annotations = server.getFileAnnotations(testFiles, new GetFileAnnotationsOptions());
assertNotNull("null annotations list returned", annotations);
annotationsSize = annotations.size();
assertTrue("annotations list too small", annotationsSize > 300); // rough size...
for (IFileAnnotation annotation : annotations) {
assertNotNull("null annotation in list", annotation);
assertNull("non-null integrations list", annotation.getAllIntegrations());
}
annotations = server.getFileAnnotations(testFiles,
new GetFileAnnotationsOptions().setFollowAllIntegrations(true));
assertNotNull("null annotations list returned", annotations);
assertEquals("annotation list size mismatch", annotationsSize, annotations.size()); // Should match
boolean foundContributing = false;
boolean foundSpecificContributer = false;
for (IFileAnnotation annotation : annotations) {
assertNotNull("null annotation in list", annotation);
List<IFileAnnotation> contributingAnnotations = annotation.getAllIntegrations();
if (contributingAnnotations != null) {
foundContributing = true;
int i = 0;
for (IFileAnnotation contAnnotation : contributingAnnotations) {
assertNotNull("null contributing annotation", contAnnotation);
assertEquals("ordering mismatch", i, contAnnotation.getOrdering());
assertNotNull("null depot path in contributing annotation", contAnnotation.getDepotPath());
assertNull("non-null data line in contributing annotation", contAnnotation.getLine());
i++;
/*
* Look for specific integration we know exists:
* ... depotFile1 //depot/102Dev/CopyFilesTest/tgt/test01.txt
* ... upper1 121
* ... lower1 108
*/
if ("//depot/102Dev/CopyFilesTest/tgt/test01.txt".equals(
contAnnotation.getDepotPath())
&& (contAnnotation.getOrdering() == 1)
&& (contAnnotation.getLower() == 16)
&& (contAnnotation.getUpper() == 18)) {
foundSpecificContributer = true;
}
}
}
}
assertTrue("found no contributing annotations", foundContributing);
assertTrue("did not find specific contributing annotation", foundSpecificContributer);
}
@After
public void afterEach() throws Exception {
if (server != null) {
this.endServerSession(server);
}
}
}
| 43.853448
| 119
| 0.673875
|
266a624b4372c25b0037020d3881bd8405eb69c4
| 1,048
|
package com.github.et118.El_Macho.Events;
import com.github.et118.El_Macho.Commands.Music.MusicManager;
import discord4j.core.event.domain.guild.GuildCreateEvent;
import discord4j.core.event.domain.guild.GuildDeleteEvent;
import reactor.core.publisher.Mono;
public class MusicEvent extends Event{
public MusicEvent(EventInfo info) {
super(info);
}
@Override
public Class[] getEventSubscriptions() {
return new Class[]{GuildCreateEvent.class, GuildDeleteEvent.class};
}
@Override
public Mono<Void> execute(Class eventType, discord4j.core.event.domain.Event rawEvent) {
if(eventType.equals(GuildCreateEvent.class)) {
return MusicManager.addMusicPlayer(((GuildCreateEvent)rawEvent).getGuild());
}
if(eventType.equals(GuildDeleteEvent.class)) { //TODO Check if leaving and joining same guild multiple times messes up something
return MusicManager.removeMusicPlayer(((GuildDeleteEvent)rawEvent).getGuildId());
}
return Mono.empty();
}
}
| 36.137931
| 136
| 0.723282
|
36f5daeba867f75a9152f471e7e200eccfddf2fe
| 6,760
|
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.android.platform.useragent;
import java.util.Arrays;
import java.util.List;
import org.jivesoftware.smack.packet.IQ;
import org.societies.android.api.useragent.IAndroidUserAgent;
import org.societies.api.comm.xmpp.datatypes.Stanza;
import org.societies.api.comm.xmpp.datatypes.XMPPInfo;
import org.societies.api.comm.xmpp.exceptions.XMPPError;
import org.societies.api.comm.xmpp.interfaces.ICommCallback;
import org.societies.api.identity.IIdentity;
import org.societies.api.identity.InvalidFormatException;
import org.societies.api.personalisation.model.IAction;
import org.societies.api.schema.useragent.monitoring.MonitoringMethodType;
import org.societies.api.schema.useragent.monitoring.UserActionMonitorBean;
import org.societies.comm.xmpp.client.impl.ClientCommunicationMgr;
import org.societies.identity.IdentityManagerImpl;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class UserAgent extends Service implements IAndroidUserAgent{
private static final String LOG_TAG = UserAgent.class.getName();
private static final List<String> ELEMENT_NAMES = Arrays.asList("userActionMonitorBean");
private static final List<String> NAME_SPACES = Arrays.asList(
"http://societies.org/api/schema/useragent/monitoring");
private static final List<String> PACKAGES = Arrays.asList(
"org.societies.api.schema.useragent.monitoring");
//currently hard coded but should be injected
private static final String DESTINATION = "xcmanager.societies.local";
private IIdentity toXCManager = null;
private ClientCommunicationMgr ccm;
private IBinder binder = null;
@Override
public void onCreate () {
this.binder = new LocalBinder();
this.ccm = new ClientCommunicationMgr(this);
try {
toXCManager = IdentityManagerImpl.staticfromJid(DESTINATION);
} catch (InvalidFormatException e) {
Log.e(LOG_TAG, e.getMessage(), e);
throw new RuntimeException(e);
}
Log.d(LOG_TAG, "User Agent service starting");
}
@Override
public void onDestroy() {
Log.d(LOG_TAG, "User Agent service terminating");
}
/**
* Create Binder object for local service invocation
*/
public class LocalBinder extends Binder {
public UserAgent getService() {
return UserAgent.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return this.binder;
}
@Override
public void monitor(IIdentity identity, IAction action){
Log.d(LOG_TAG, "User Agent received monitored user action from identity " +identity.getJid()+
": "+action.getparameterName()+" = "+action.getvalue());
//CREATE MESSAGE BEAN
UserActionMonitorBean uamBean = new UserActionMonitorBean();
Log.d(LOG_TAG, "Creating message to send to virgo user agent");
uamBean.setIdentity(identity.getJid());
uamBean.setServiceResourceIdentifier(action.getServiceID());
uamBean.setServiceType(action.getServiceType());
uamBean.setParameterName(action.getparameterName());
uamBean.setValue(action.getvalue());
uamBean.setMethod(MonitoringMethodType.MONITOR);
Stanza stanza = new Stanza(toXCManager);
ICommCallback callback = new UserAgentCallback();
try {
Log.d(LOG_TAG, "registering info with comms FW:");
List<String> nameSpaces = callback.getXMLNamespaces();
List<String> jPackages = callback.getJavaPackages();
for(String nextNameSpace: nameSpaces){
Log.d(LOG_TAG, nextNameSpace);
}
for(String nextPackage: jPackages){
Log.d(LOG_TAG, nextPackage);
}
ccm.register(ELEMENT_NAMES, callback);
ccm.sendIQ(stanza, IQ.Type.SET, uamBean, callback);
Log.d(LOG_TAG, "Stanza sent!");
} catch (Exception e) {
Log.e(LOG_TAG, Log.getStackTraceString(e));
}
}
/*
* Callback - not needed
*/
private class UserAgentCallback implements ICommCallback{
public List<String> getJavaPackages() {
return PACKAGES;
}
public List<String> getXMLNamespaces() {
return NAME_SPACES;
}
public void receiveError(Stanza arg0, XMPPError arg1) {
// TODO Auto-generated method stub
}
public void receiveInfo(Stanza arg0, String arg1, XMPPInfo arg2) {
// TODO Auto-generated method stub
}
public void receiveItems(Stanza arg0, String arg1, List<String> arg2) {
// TODO Auto-generated method stub
}
public void receiveMessage(Stanza arg0, Object arg1) {
// TODO Auto-generated method stub
}
public void receiveResult(Stanza arg0, Object arg1) {
// TODO Auto-generated method stub
}
}
}
| 37.142857
| 131
| 0.736391
|
fd9998e1092622e77ceb445a0ef282a7ecf05c7a
| 3,119
|
package de.budschie.bmorph.capabilities.common;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import de.budschie.bmorph.capabilities.common.CommonCapabilitySynchronizer.CommonCapabilitySynchronizerPacket;
import de.budschie.bmorph.network.ISimpleImplPacket;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.network.NetworkEvent.Context;
public abstract class CommonCapabilitySynchronizer<P extends CommonCapabilitySynchronizerPacket, C> implements ISimpleImplPacket<P>
{
private Logger logger = LogManager.getLogger();
private Capability<C> capabilityToken;
public CommonCapabilitySynchronizer(Capability<C> capabilityToken)
{
this.capabilityToken = capabilityToken;
}
@Override
public void encode(P packet, FriendlyByteBuf buffer)
{
buffer.writeUUID(packet.getPlayer());
encodeAdditional(packet, buffer);
}
@Override
public P decode(FriendlyByteBuf buffer)
{
UUID player = buffer.readUUID();
P packet = decodeAdditional(buffer);
packet.setPlayer(player);
return packet;
}
@Override
public void handle(P packet, Supplier<Context> ctx)
{
ctx.get().enqueueWork(() ->
{
if(Minecraft.getInstance().level == null)
{
logger.info("Can't process capability sync packet because level is null");
}
else
{
Player player = Minecraft.getInstance().level.getPlayerByUUID(packet.getPlayer());
if(player == null)
{
logger.info("Can't process capability sync packet because the player with the UUID {0} could not be found.", packet.getPlayer().toString());
}
else
{
Optional<C> capabilityInterface = player.getCapability(capabilityToken).resolve();
if(capabilityInterface.isPresent())
{
ctx.get().setPacketHandled(handleCapabilitySync(packet, ctx, player, capabilityInterface.get()));
}
else
{
logger.info("Can't process capability sync packet because the capability {0} was not attached to player {1}({2})", capabilityToken.getName(), packet.getPlayer(), player.getName().getString());
}
}
}
});
}
public abstract void encodeAdditional(P packet, FriendlyByteBuf buffer);
public abstract P decodeAdditional(FriendlyByteBuf buffer);
/**
* This is an abstract method that is called when the packet is handled and the
* player and its capability was located.
*
* @return A boolean which indicates whether the handling of the capability was
* successful or not.
**/
public abstract boolean handleCapabilitySync(P packet, Supplier<Context> ctx, Player player, C capabilityInterface);
public Logger getLogger()
{
return logger;
}
public static class CommonCapabilitySynchronizerPacket
{
private UUID player;
public UUID getPlayer()
{
return player;
}
public void setPlayer(UUID player)
{
this.player = player;
}
}
}
| 27.848214
| 198
| 0.738378
|
b0c97b33af7e437ca2a140aec32af0b9a7abc181
| 517
|
package me.echeung.moemoekyun.client.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Builder
public class User {
private String uuid;
private String email;
private String username;
private String displayName;
private String avatarImage;
private String bannerImage;
private String bio;
private int additionalRequests;
private int uploads;
private int uploadLimit;
private int favorites;
@Setter
private int requestsRemaining;
}
| 20.68
| 43
| 0.738878
|
dd900a34e6066242e82b690bca299f085c49903c
| 11,395
|
package u.aly;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONException;
import org.json.JSONObject;
public class bu
{
private static final String a = bu.class.getName();
// ERROR //
private static String a(InputStream paramInputStream)
{
// Byte code:
// 0: new 24 java/io/BufferedReader
// 3: dup
// 4: new 26 java/io/InputStreamReader
// 7: dup
// 8: aload_0
// 9: invokespecial 29 java/io/InputStreamReader:<init> (Ljava/io/InputStream;)V
// 12: sipush 8192
// 15: invokespecial 32 java/io/BufferedReader:<init> (Ljava/io/Reader;I)V
// 18: astore_1
// 19: new 34 java/lang/StringBuilder
// 22: dup
// 23: invokespecial 35 java/lang/StringBuilder:<init> ()V
// 26: astore_2
// 27: aload_1
// 28: invokevirtual 38 java/io/BufferedReader:readLine ()Ljava/lang/String;
// 31: astore 7
// 33: aload 7
// 35: ifnonnull +12 -> 47
// 38: aload_0
// 39: invokevirtual 43 java/io/InputStream:close ()V
// 42: aload_2
// 43: invokevirtual 46 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 46: areturn
// 47: aload_2
// 48: new 34 java/lang/StringBuilder
// 51: dup
// 52: aload 7
// 54: invokestatic 52 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 57: invokespecial 55 java/lang/StringBuilder:<init> (Ljava/lang/String;)V
// 60: ldc 57
// 62: invokevirtual 61 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 65: invokevirtual 46 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 68: invokevirtual 61 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 71: pop
// 72: goto -45 -> 27
// 75: astore 5
// 77: getstatic 16 u/aly/bu:a Ljava/lang/String;
// 80: ldc 63
// 82: aload 5
// 84: invokestatic 69 u/aly/bt:b (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Exception;)V
// 87: aload_0
// 88: invokevirtual 43 java/io/InputStream:close ()V
// 91: aconst_null
// 92: areturn
// 93: astore 6
// 95: getstatic 16 u/aly/bu:a Ljava/lang/String;
// 98: ldc 63
// 100: aload 6
// 102: invokestatic 69 u/aly/bt:b (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Exception;)V
// 105: aconst_null
// 106: areturn
// 107: astore_3
// 108: aload_0
// 109: invokevirtual 43 java/io/InputStream:close ()V
// 112: aload_3
// 113: athrow
// 114: astore 4
// 116: getstatic 16 u/aly/bu:a Ljava/lang/String;
// 119: ldc 63
// 121: aload 4
// 123: invokestatic 69 u/aly/bt:b (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Exception;)V
// 126: aconst_null
// 127: areturn
// 128: astore 9
// 130: getstatic 16 u/aly/bu:a Ljava/lang/String;
// 133: ldc 63
// 135: aload 9
// 137: invokestatic 69 u/aly/bt:b (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Exception;)V
// 140: aconst_null
// 141: areturn
//
// Exception table:
// from to target type
// 27 33 75 java/io/IOException
// 47 72 75 java/io/IOException
// 87 91 93 java/io/IOException
// 27 33 107 finally
// 47 72 107 finally
// 77 87 107 finally
// 108 112 114 java/io/IOException
// 38 42 128 java/io/IOException
}
private static HttpParams a()
{
BasicHttpParams localBasicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 10000);
HttpConnectionParams.setSoTimeout(localBasicHttpParams, 20000);
HttpProtocolParams.setUserAgent(localBasicHttpParams, System.getProperty("http.agent"));
return localBasicHttpParams;
}
private JSONObject a(String paramString)
{
int i = new Random().nextInt(1000);
while (true)
{
InputStream localInputStream;
try
{
String str1 = System.getProperty("line.separator");
if (paramString.length() > 1)
continue;
bt.b(a, i + ":\tInvalid baseUrl.");
return null;
bt.a(a, i + ":\tget: " + paramString);
HttpGet localHttpGet = new HttpGet(paramString);
localHttpResponse = new DefaultHttpClient(a()).execute(localHttpGet);
if (localHttpResponse.getStatusLine().getStatusCode() != 200)
continue;
HttpEntity localHttpEntity = localHttpResponse.getEntity();
if (localHttpEntity == null)
break;
localInputStream = localHttpEntity.getContent();
Header localHeader = localHttpResponse.getFirstHeader("Content-Encoding");
if ((localHeader == null) || (!localHeader.getValue().equalsIgnoreCase("gzip")))
continue;
bt.a(a, i + " Use GZIPInputStream get data....");
localObject = new GZIPInputStream(localInputStream);
String str2 = a((InputStream)localObject);
bt.a(a, i + ":\tresponse: " + str1 + str2);
if (str2 == null)
break;
return new JSONObject(str2);
if ((localHeader != null) && (localHeader.getValue().equalsIgnoreCase("deflate")))
{
bt.a(a, i + " Use InflaterInputStream get data....");
localObject = new InflaterInputStream(localInputStream);
continue;
}
}
catch (ClientProtocolException localClientProtocolException)
{
HttpResponse localHttpResponse;
bt.c(a, i + ":\tClientProtocolException,Failed to send message." + paramString, localClientProtocolException);
return null;
bt.c(a, i + ":\tFailed to send message. StatusCode = " + localHttpResponse.getStatusLine().getStatusCode() + bx.a + paramString);
return null;
}
catch (Exception localException)
{
bt.c(a, i + ":\tIOException,Failed to send message." + paramString, localException);
return null;
}
Object localObject = localInputStream;
}
return (JSONObject)null;
}
private JSONObject a(String paramString, JSONObject paramJSONObject)
{
String str1 = paramJSONObject.toString();
int i = new Random().nextInt(1000);
bt.c(a, i + ":\trequest: " + paramString + bx.a + str1);
HttpPost localHttpPost = new HttpPost(paramString);
DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(a());
while (true)
{
InputStream localInputStream;
try
{
ArrayList localArrayList = new ArrayList(1);
localArrayList.add(new BasicNameValuePair("content", str1));
localHttpPost.setEntity(new UrlEncodedFormEntity(localArrayList, "UTF-8"));
HttpResponse localHttpResponse = localDefaultHttpClient.execute(localHttpPost);
if (localHttpResponse.getStatusLine().getStatusCode() != 200)
continue;
HttpEntity localHttpEntity = localHttpResponse.getEntity();
if (localHttpEntity == null)
break;
localInputStream = localHttpEntity.getContent();
Header localHeader = localHttpResponse.getFirstHeader("Content-Encoding");
if ((localHeader != null) && (localHeader.getValue().equalsIgnoreCase("deflate")))
{
localObject = new InflaterInputStream(localInputStream);
String str2 = a((InputStream)localObject);
bt.a(a, i + ":\tresponse: " + bx.a + str2);
if (str2 == null)
return null;
return new JSONObject(str2);
bt.c(a, i + ":\tFailed to send message. StatusCode = " + localHttpResponse.getStatusLine().getStatusCode() + bx.a + paramString);
return null;
}
}
catch (ClientProtocolException localClientProtocolException)
{
bt.c(a, i + ":\tClientProtocolException,Failed to send message." + paramString, localClientProtocolException);
return null;
}
catch (IOException localIOException)
{
bt.c(a, i + ":\tIOException,Failed to send message." + paramString, localIOException);
return null;
}
catch (JSONException localJSONException)
{
bt.c(a, i + ":\tIOException,Failed to send message." + paramString, localJSONException);
return null;
}
Object localObject = localInputStream;
}
return (JSONObject)null;
}
public final <T extends bw> T a(bv parambv, Class<T> paramClass)
{
String str = bv.c().trim();
if ((bx.c(str)) || (!(bv.b.equals(str.trim()) ^ bv.a.equals(str.trim()))))
throw new RuntimeException("验证请求方式失败[" + str + "]");
JSONObject localJSONObject;
if (bv.b.equals(str))
localJSONObject = a(parambv.b());
while (true)
{
if (localJSONObject == null)
{
return null;
if (bv.a.equals(str))
{
localJSONObject = a(parambv.c, parambv.a());
continue;
}
}
else
{
try
{
bw localbw = (bw)paramClass.getConstructor(new Class[] { JSONObject.class }).newInstance(new Object[] { localJSONObject });
return localbw;
}
catch (SecurityException localSecurityException)
{
bt.b(a, "SecurityException", localSecurityException);
return null;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
while (true)
bt.b(a, "NoSuchMethodException", localNoSuchMethodException);
}
catch (IllegalArgumentException localIllegalArgumentException)
{
while (true)
bt.b(a, "IllegalArgumentException", localIllegalArgumentException);
}
catch (InstantiationException localInstantiationException)
{
while (true)
bt.b(a, "InstantiationException", localInstantiationException);
}
catch (IllegalAccessException localIllegalAccessException)
{
while (true)
bt.b(a, "IllegalAccessException", localIllegalAccessException);
}
catch (InvocationTargetException localInvocationTargetException)
{
while (true)
bt.b(a, "InvocationTargetException", localInvocationTargetException);
}
}
localJSONObject = null;
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: u.aly.bu
* JD-Core Version: 0.6.0
*/
| 37.117264
| 139
| 0.637122
|
e651a3de3ec38f499a08834960b4a3555db249a4
| 1,392
|
/*******************************************************************************
* Copyright (c) 2005, 2009 SAP. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* SAP - initial API and implementation
******************************************************************************/
package org.eclipse.persistence.testing.models.wdf.jpa2.flight;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
@Embeddable
public class FlightId {
@Embedded
private ConnectionId connectionId;
@Column(name = "FLIGHT_DATE")
private java.sql.Date date;
public ConnectionId getConnectionId() {
return connectionId;
}
public void setConnectionId(ConnectionId connectionId) {
this.connectionId = connectionId;
}
public java.sql.Date getDate() {
return date;
}
public void setDate(java.sql.Date date) {
this.date = date;
}
}
| 30.26087
| 88
| 0.611351
|
1693e587082da308a25a01fab1474112f9b980bc
| 1,029
|
package com.gempukku.swccgo.logic.actions;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.timing.Effect;
/**
* An action that does not have a source card. This is used for game actions, such as performing the phases
* of a turn, performing the steps of a Force drain, or performing the steps of a battle.
*/
public class SystemQueueAction extends AbstractAction {
@Override
public Type getType() {
return Type.GAME_PROCESS;
}
@Override
public PhysicalCard getActionSource() {
return null;
}
@Override
public String getText() {
return null;
}
@Override
public Effect nextEffect(SwccgGame game) {
if (!isAnyCostFailed()) {
Effect cost = getNextCost();
if (cost != null)
return cost;
Effect effect = getNextEffect();
if (effect != null)
return effect;
}
return null;
}
}
| 24.5
| 107
| 0.626822
|
f4190308e291612e342bd3897f6546424fd73358
| 6,563
|
package palisades.lakes.dynafun.java;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import clojure.lang.IFn;
/** Utilities for 'immutable' maps.
*
* @author palisades dot lakes at gmail dot com
* @since 2017-08-30
* @version 2017-09-05
*/
@SuppressWarnings("unchecked")
public final class Util {
//--------------------------------------------------------------
// TODO: move to minimal immutable map and multimap classes
public static final Map assoc (final Map m,
final Object k,
final Object v) {
final HashMap b = new HashMap(m);
b.put(k,v);
return b; }
// public static final Map dissoc (final Map m,
// final Object k) {
// final Map b = new HashMap(m);
// b.remove(k);
// return b; }
public static final Set add (final Set s,
final Object v) {
if (null == s) { return Collections.singleton(v); }
final Set b = new HashSet(s);
b.add(v);
return b; }
public static final Map add (final Map m,
final Object k,
final Object v) {
final Map b = new HashMap(m);
b.put(k,add((Set) b.get(k),v));
return b; }
//--------------------------------------------------------------
// for code symmetry
public static final Class[] copy (final Class[] a) {
return Arrays.copyOf(a,a.length); }
public static final SignatureN[] copy (final SignatureN[] a) {
return Arrays.copyOf(a,a.length); }
public static final IFn[] copy (final IFn[] a) {
return Arrays.copyOf(a,a.length); }
public static final Class[][] copy (final Class[][] a) {
final int n0 = a.length;
final Class[][] copy = new Class[n0][];
for (int j0=0;j0<n0;j0++) {
copy[j0] = Arrays.copyOf(a[j0],a[j0].length); }
return copy; }
public static final IFn[][] copy (final IFn[][] a) {
final int n0 = a.length;
final IFn[][] copy = new IFn[n0][];
for (int j0=0;j0<n0;j0++) {
copy[j0] = Arrays.copyOf(a[j0],a[j0].length); }
return copy; }
public static final Class[][][] copy (final Class[][][] a) {
final int n0 = a.length;
final Class[][][] copy = new Class[n0][][];
for (int j0=0;j0<n0;j0++) { copy[j0] = copy(a[j0]); }
return copy; }
public static final IFn[][][] copy (final IFn[][][] a) {
final int n0 = a.length;
final IFn[][][] copy = new IFn[n0][][];
for (int j0=0;j0<n0;j0++) { copy[j0] = copy(a[j0]); }
return copy; }
//--------------------------------------------------------------
// append to the leading dimension
public static final Class[] append (final Class[] a,
final Class c) {
final int n = a.length;
final Class[] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final SignatureN[] append (final SignatureN[] a,
final SignatureN c) {
final int n = a.length;
final SignatureN[] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final IFn[] append (final IFn[] a,
final IFn c) {
final int n = a.length;
final IFn[] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final Class[][] append (final Class[][] a,
final Class[] c) {
final int n = a.length;
final Class[][] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final IFn[][] append (final IFn[][] a,
final IFn[] c) {
final int n = a.length;
final IFn[][] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final Class[][][] append (final Class[][][] a,
final Class[][] c) {
final int n = a.length;
final Class[][][] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
public static final IFn[][][] append (final IFn[][] []a,
final IFn[][] c) {
final int n = a.length;
final IFn[][][] b = Arrays.copyOf(a,n+1);
b[n] = c;
return b; }
//--------------------------------------------------------------
// append to the 2nd dimension at the 1st dim index
public static final Class[][] append (final Class[][] a,
final int i0,
final Class c) {
final Class[][] b = copy(a);
b[i0] = append(b[i0],c);
return b; }
public static final IFn[][] append (final IFn[][] a,
final int i0,
final IFn c) {
final IFn[][] b = copy(a);
b[i0] = append(b[i0],c);
return b; }
public static final Class[][][] append (final Class[][][] a,
final int i0,
final Class[] c) {
final Class[][][] b = copy(a);
b[i0] = append(b[i0],c);
return b; }
public static final IFn[][][] append (final IFn[][][] a,
final int i0,
final IFn[] c) {
final IFn[][][] b = copy(a);
b[i0] = append(b[i0],c);
return b; }
//--------------------------------------------------------------
// append to the 3rd dimension at the 1st and 2nd dim indexes
public static final Class[][][] append (final Class[][][] a,
final int i0,
final int i1,
final Class c) {
final Class[][][] b = copy(a);
b[i0][i1] = append(b[i0][i1],c);
return b; }
public static final IFn[][][] append (final IFn[][][] a,
final int i0,
final int i1,
final IFn c) {
final IFn[][][] b = copy(a);
b[i0][i1] = append(b[i0][i1],c);
return b; }
//--------------------------------------------------------------
// disabled construction
//--------------------------------------------------------------
private Util () {
throw new
UnsupportedOperationException(
"can't instantiate " + getClass()); }
//--------------------------------------------------------------
}
| 32.330049
| 66
| 0.445985
|
bee60c4cc31b2d5c335bed0c1ffd81eadeb2ccc7
| 1,124
|
package String;
/**
* Author - archit.s
* Date - 05/10/18
* Time - 12:51 AM
*/
public class CountAndSay {
public String countAndSay(int A) {
if(A == 1){
return "1";
}
StringBuilder s = new StringBuilder("11");
int count = 0;
if(A == 2){
return s.toString();
}
while(A != 2){
StringBuilder temp = new StringBuilder();
char value = s.charAt(0);
count = 1;
for(int i=1;i<s.length();i++){
if(s.charAt(i) == value){
count++;
}
else{
temp.append(String.valueOf(count));
temp.append(value);
value = s.charAt(i);
count = 1;
}
}
temp.append(String.valueOf(count));
temp.append(value);
A--;
s = temp;
}
return s.toString();
}
public static void main(String[] args) {
System.out.println(new CountAndSay().countAndSay(4));
}
}
| 21.207547
| 61
| 0.41637
|
a787de4622c583679d0b9b7adc8e11ffb26fa40c
| 637
|
package com.oninvoice.models.api;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.oninvoice.models.entities.Person;
public interface IPersonApi {
/**
* This method returns a Page<Person>
*
* @return
*/
public Page<Person> findAll(Pageable pageable);
/**
* This method find a person by id
*
* @param id
* @return
*/
public Person findById(Long id);
/**
* This method saves a person
*
* @param person
*/
public void save(Person person);
/**
* This method deletes a person
*
* @param person
*/
public void delete(Person person);
}
| 16.763158
| 48
| 0.675039
|
3c725dac42d0aec65d296dd541bd4fcba7b5c7f3
| 2,719
|
package com.mongodash.dao.mapper;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.mongodash.Config;
import com.mongodash.dao.DBObjectMapper;
import com.mongodash.model.Backup;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
@Component
public class BackupDBObjectMapper implements DBObjectMapper<Backup> {
@Override
public Backup mapDBObject(BasicDBObject object) {
Backup backup = new Backup();
backup.setId(object.getInt(Config.COMMON_FIELDS._id.name()));
backup.setName(object.getString(Config.COMMON_FIELDS.name.name()));
backup.setServerId(object.getInt(Backup.fields.serverId.name()));
backup.setDumpFormat(object.getString(Backup.fields.dumpFormat.name()));
backup.setCompressFolder(object.getBoolean(Backup.fields.compressFolder.name()));
backup.setRunDaily(object.getBoolean(Backup.fields.runDaily.name()));
backup.setIncludeOpLog(object.getBoolean(Backup.fields.includeOpLog.name()));
backup.setNotifyOnFinish(object.getBoolean(Backup.fields.notifyOnFinish.name()));
backup.setOutputFolder(object.getString(Backup.fields.outputFolder.name()));
backup.setLastExecution(object.getDate(Backup.fields.lastExecution.name()));
if (object.containsField(Backup.fields.databases.name())) {
BasicDBList list = (BasicDBList) object.get(Backup.fields.databases.name());
List<String> databases = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
databases.add((String) list.get(i));
}
backup.setDatabases(databases);
}
return backup;
}
@Override
public DBObject mapObject(Backup backup) {
DBObject object = new BasicDBObject();
object.put(Config.COMMON_FIELDS._id.name(), backup.getId());
object.put(Config.COMMON_FIELDS.name.name(), backup.getName());
object.put(Backup.fields.serverId.name(), backup.getServerId());
object.put(Backup.fields.dumpFormat.name(), backup.getDumpFormat());
object.put(Backup.fields.compressFolder.name(), backup.isCompressFolder());
object.put(Backup.fields.runDaily.name(), backup.isRunDaily());
object.put(Backup.fields.includeOpLog.name(), backup.isIncludeOpLog());
object.put(Backup.fields.notifyOnFinish.name(), backup.isNotifyOnFinish());
object.put(Backup.fields.outputFolder.name(), backup.getOutputFolder());
object.put(Backup.fields.lastExecution.name(), backup.getLastExecution());
if (backup.getDatabases() != null && backup.getDatabases().size() > 0) {
BasicDBList databases = new BasicDBList();
for (String database : backup.getDatabases()) {
databases.add(database);
}
object.put(Backup.fields.databases.name(), databases);
}
return object;
}
}
| 38.842857
| 83
| 0.757999
|
ba787f5895dfc41e5bad4379bedd53b000c3f118
| 2,935
|
package com.lulu.main;
import com.lulu.main.java.models.reporters.MonitorOutputDataAdapter;
import com.lulu.main.java.models.reporters.MonitorOutputSignal;
import org.json.simple.JSONObject;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class MonitorOutputDataAdapterTest {
private static MonitorOutputDataAdapter adapter;
private static MonitorOutputSignal signal;
private static final int threadId = 1234;
private static final int iteration = 10;
private static final String threadName = "Thread1234";
private static final double data = 44.543;
private static HashMap<String, Object> dataHash = new HashMap<>() {
{
put("threadId", threadId);
put("monitorIteration", iteration);
put("threadName", threadName);
put("data", data);
}
};
@BeforeClass
public static void setUp() {
signal = new MonitorOutputSignal(threadId, iteration, threadName, data);
adapter = new MonitorOutputDataAdapter(signal);
}
@Test
public void renderString() {
String expectedOutput = dataHash.toString();
String output = adapter.renderString();
assertThat(output, is(expectedOutput));
}
@Test
public void renderJSON() {
// There is a very weird test failure here
// when we pass both JSONObject objects to
// assertEquals. The workaroundAssertion
// is how we get passed that.
JSONObject expectedOutput = new JSONObject();
for (String key : dataHash.keySet()) {
expectedOutput.put(key, dataHash.get(key));
}
JSONObject output = adapter.renderJSON();
boolean workaroundAssertion = output.toString().equals(expectedOutput.toString());
assertTrue(workaroundAssertion);
}
@Test
public void renderSQLInsertValuesAllStrings() {
String expectedOutput = "(" + "\"" + threadId + "\", "
+ "\"" + iteration + "\", "
+ "\"" + threadName + "\", "
+ "\"" + data + "\""
+ ")";
String actualOutput = adapter.renderSQLInsertValuesAllStrings(true);
assertEquals(expectedOutput, actualOutput);
}
@Test
public void renderSQLInsertValues() {
String expectedOutput = "(" + threadId + ", "
+ iteration + ", "
+ "\"" + threadName + "\", "
+ data
+ ")";
String actualOutput = adapter.renderSQLInsertValues();
actualOutput = adapter.renderSQLInsertValues();
assertEquals(expectedOutput, actualOutput);
}
}
| 36.6875
| 90
| 0.583646
|
72fca94c6bbf9be478ea2ac27b479fd605fc16ee
| 4,272
|
package com.noah.solutions.system.service.impl;
import com.noah.solutions.common.exception.CodeAndMsg;
import com.noah.solutions.common.exception.CustormException;
import com.noah.solutions.common.shiro.EndecryptUtil;
import com.noah.solutions.common.utils.BeanUtils;
import com.noah.solutions.system.entity.User;
import com.noah.solutions.system.entity.UserRole;
import com.noah.solutions.system.repository.RoleRepository;
import com.noah.solutions.system.repository.UserRepository;
import com.noah.solutions.system.repository.UserRoleRepository;
import com.noah.solutions.system.service.DriverService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import static com.noah.solutions.common.ProjectConfig.UserType.DRIVER;
@Service
public class DriverServiceImpl implements DriverService {
@Resource
private UserRepository userRepository;
@Resource
private UserRoleRepository userRoleRepository;
@Resource
private RoleRepository roleRepository;
//////////////////////////////查询部分 start//////////////////////////////////////////////////////////
//////////////////////////////查询部分 start//////////////////////////////////////////////////////////
@Override
public Page list(Integer page, Integer limit, User user) {
user.setType(DRIVER.getValue());
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("nickName", ExampleMatcher.GenericPropertyMatchers.contains())
.withMatcher("phone", ExampleMatcher.GenericPropertyMatchers.contains());
return userRepository.findAll(Example.of(user,matcher), PageRequest.of(page-1,limit));
}
@Override
public List<User> findAll() {
return userRepository.findAllByType(DRIVER.getValue());
}
//////////////////////////////查询部分 end//////////////////////////////////////////////////////////
//////////////////////////////查询部分 end//////////////////////////////////////////////////////////
//////////////////////////////增删改部分 start//////////////////////////////////////////////////////////
//////////////////////////////增删改部分 start//////////////////////////////////////////////////////////
@Override
public void add(User user) {
user.setPassword("123456");
if (userRepository.existsByUsername(user.getUsername())||userRepository.existsByPhone(user.getPhone())) {
throw new CustormException(CodeAndMsg.USER_ADDERROR);
}
user.setType(DRIVER.getValue());
user.setPassword(EndecryptUtil.encrytMd5(user.getPassword(), user.getUsername(), 3));
user.setState(0);
user.setCreateTime(new Date());
user.setTokenMoney((double) 0);
if(StringUtils.isEmpty(user.getAvatar()))
user.setAvatar("head.png");
user = userRepository.saveAndFlush(user);
userRoleRepository.save(new UserRole(user.getUserId(),roleRepository.findIdByUsername("司機")));
}
@Override
public void update(User user) {
User oldUser = userRepository.findByUserId(user.getUserId());
BeanUtils.copyNotNullProperties(user,oldUser);
oldUser.setUpdateTime(new Date());
userRepository.save(oldUser);
}
//////////////////////////////增删改部分 end//////////////////////////////////////////////////////////
//////////////////////////////增删改部分 end//////////////////////////////////////////////////////////
//////////////////////////////逻辑处理部分 start//////////////////////////////////////////////////////////
//////////////////////////////逻辑处理部分 start//////////////////////////////////////////////////////////
//////////////////////////////逻辑处理部分 end//////////////////////////////////////////////////////////
//////////////////////////////逻辑处理部分 end//////////////////////////////////////////////////////////
}
| 37.80531
| 113
| 0.545412
|
031393635516bcb4314be8f7ca4e4792ac722cca
| 21,785
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.jmxmetrics.target_systems;
import static org.assertj.core.api.Assertions.assertThat;
import io.opentelemetry.contrib.jmxmetrics.AbstractIntegrationTest;
import io.opentelemetry.proto.metrics.v1.Metric;
import io.opentelemetry.proto.metrics.v1.NumberDataPoint;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.lifecycle.Startable;
import org.testcontainers.utility.MountableFile;
abstract class KafkaIntegrationTest extends AbstractIntegrationTest {
protected KafkaIntegrationTest(String configName) {
super(false, configName);
}
@Container
GenericContainer<?> zookeeper =
new GenericContainer<>("zookeeper:3.5")
.withNetwork(Network.SHARED)
.withNetworkAliases("zookeeper")
.withStartupTimeout(Duration.ofSeconds(120))
.waitingFor(Wait.forListeningPort());
@Container
GenericContainer<?> kafka =
new GenericContainer<>("bitnami/kafka:2.8.1")
.withNetwork(Network.SHARED)
.withEnv("KAFKA_CFG_ZOOKEEPER_CONNECT", "zookeeper:2181")
.withEnv("ALLOW_PLAINTEXT_LISTENER", "yes")
.withEnv("JMX_PORT", "7199")
.withNetworkAliases("kafka")
.withExposedPorts(7199)
.withStartupTimeout(Duration.ofSeconds(120))
.waitingFor(Wait.forListeningPort())
.dependsOn(zookeeper);
Startable createTopics =
new Startable() {
@Override
public void start() {
try {
kafka.execInContainer(
"sh",
"-c",
"unset JMX_PORT; for i in `seq 3`; do kafka-topics.sh --bootstrap-server localhost:9092 --create --topic test-topic-$i; done");
} catch (Exception e) {
throw new AssertionError(e);
}
}
@Override
public void stop() {}
@Override
public Set<Startable> getDependencies() {
return Collections.singleton(kafka);
}
};
static class KafkaBrokerTargetIntegrationTest extends KafkaIntegrationTest {
KafkaBrokerTargetIntegrationTest() {
super("target-systems/kafka.properties");
}
@Test
void endToEnd() {
waitAndAssertMetrics(
metric -> assertGauge(metric, "kafka.bytes.in", "bytes in per second from clients", "by"),
metric -> assertGauge(metric, "kafka.bytes.out", "bytes out per second to clients", "by"),
metric ->
assertGauge(
metric, "kafka.controller.active.count", "controller is active on broker", "1"),
metric ->
assertGauge(
metric,
"kafka.fetch.consumer.total.time.99p",
"fetch consumer request time - 99th percentile",
"ms"),
metric ->
assertSum(
metric,
"kafka.fetch.consumer.total.time.count",
"fetch consumer request count",
"1"),
metric ->
assertGauge(
metric,
"kafka.fetch.consumer.total.time.median",
"fetch consumer request time - 50th percentile",
"ms"),
metric ->
assertGauge(
metric,
"kafka.fetch.follower.total.time.99p",
"fetch follower request time - 99th percentile",
"ms"),
metric ->
assertSum(
metric,
"kafka.fetch.follower.total.time.count",
"fetch follower request count",
"1"),
metric ->
assertGauge(
metric,
"kafka.fetch.follower.total.time.median",
"fetch follower request time - 50th percentile",
"ms"),
metric ->
assertGauge(metric, "kafka.isr.shrinks", "in-sync replica shrinks per second", "1"),
metric ->
assertGauge(
metric,
"kafka.leader.election.rate",
"leader election rate - non-zero indicates broker failures",
"1"),
metric ->
assertGauge(
metric,
"kafka.max.lag",
"max lag in messages between follower and leader replicas",
"1"),
metric ->
assertGauge(metric, "kafka.messages.in", "number of messages in per second", "1"),
metric ->
assertGauge(
metric,
"kafka.partitions.offline.count",
"number of partitions without an active leader",
"1"),
metric ->
assertGauge(
metric,
"kafka.partitions.underreplicated.count",
"number of under replicated partitions",
"1"),
metric ->
assertGauge(
metric,
"kafka.produce.total.time.99p",
"produce request time - 99th percentile",
"ms"),
metric ->
assertSum(metric, "kafka.produce.total.time.count", "produce request count", "1"),
metric ->
assertGauge(
metric,
"kafka.produce.total.time.median",
"produce request time - 50th percentile",
"ms"),
metric -> assertGauge(metric, "kafka.request.queue", "size of the request queue", "1"),
metric ->
assertGauge(
metric,
"kafka.unclean.election.rate",
"unclean leader election rate - non-zero indicates broker failures",
"1"));
}
}
static class KafkaConsumerIntegrationTest extends KafkaIntegrationTest {
KafkaConsumerIntegrationTest() {
super("target-systems/kafka-consumer.properties");
}
@Container
GenericContainer<?> consumer =
new GenericContainer<>("bitnami/kafka:latest")
.withNetwork(Network.SHARED)
.withEnv("KAFKA_CFG_ZOOKEEPER_CONNECT", "zookeeper:2181")
.withEnv("ALLOW_PLAINTEXT_LISTENER", "yes")
.withEnv("JMX_PORT", "7199")
.withNetworkAliases("kafka-consumer")
.withExposedPorts(7199)
.withCommand(
"kafka-console-consumer.sh",
"--bootstrap-server",
"kafka:9092",
"--whitelist",
"test-topic-.*",
"--max-messages",
"100")
.withStartupTimeout(Duration.ofSeconds(120))
.waitingFor(Wait.forListeningPort())
.dependsOn(createTopics);
@Test
void endToEnd() {
List<String> topics = Arrays.asList("test-topic-1", "test-topic-2", "test-topic-3");
waitAndAssertMetrics(
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.bytes-consumed-rate",
"The average number of bytes consumed per second",
"by",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.fetch-rate",
"The number of fetch requests for all topics per second",
"1"),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.fetch-size-avg",
"The average number of bytes fetched per request",
"by",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.records-consumed-rate",
"The average number of records consumed per second",
"1",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.records-lag-max",
"Number of messages the consumer lags behind the producer",
"1"),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.total.bytes-consumed-rate",
"The average number of bytes consumed for all topics per second",
"by"),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.total.fetch-size-avg",
"The average number of bytes fetched per request for all topics",
"by"),
metric ->
assertKafkaGauge(
metric,
"kafka.consumer.total.records-consumed-rate",
"The average number of records consumed for all topics per second",
"1"));
}
}
static class KafkaProducerIntegrationTest extends KafkaIntegrationTest {
KafkaProducerIntegrationTest() {
super("target-systems/kafka-producer.properties");
}
@Container
GenericContainer<?> producer =
new GenericContainer<>("bitnami/kafka:latest")
.withNetwork(Network.SHARED)
.withEnv("KAFKA_CFG_ZOOKEEPER_CONNECT", "zookeeper:2181")
.withEnv("ALLOW_PLAINTEXT_LISTENER", "yes")
.withEnv("JMX_PORT", "7199")
.withNetworkAliases("kafka-producer")
.withExposedPorts(7199)
.withCopyFileToContainer(
MountableFile.forClasspathResource("target-systems/kafka-producer.sh"),
"/usr/bin/kafka-producer.sh")
.withCommand("kafka-producer.sh")
.withStartupTimeout(Duration.ofSeconds(120))
.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("kafka-producer")))
.waitingFor(Wait.forListeningPort())
.dependsOn(createTopics);
@Test
void endToEnd() {
List<String> topics = Collections.singletonList("test-topic-1");
waitAndAssertMetrics(
metric ->
assertKafkaGauge(
metric,
"kafka.producer.byte-rate",
"The average number of bytes sent per second for a topic",
"by",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.compression-rate",
"The average compression rate of record batches for a topic",
"1",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.io-wait-time-ns-avg",
"The average length of time the I/O thread spent waiting for a socket ready for reads or writes",
"ns"),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.outgoing-byte-rate",
"The average number of outgoing bytes sent per second to all servers",
"by"),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.record-error-rate",
"The average per-second number of record sends that resulted in errors for a topic",
"1",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.record-retry-rate",
"The average per-second number of retried record sends for a topic",
"1",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.record-send-rate",
"The average number of records sent per second for a topic",
"1",
topics),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.request-latency-avg",
"The average request latency",
"ms"),
metric ->
assertKafkaGauge(
metric,
"kafka.producer.request-rate",
"The average number of requests sent per second",
"1"),
metric ->
assertKafkaGauge(
metric, "kafka.producer.response-rate", "Responses received per second", "1"));
}
}
static class KafkaAndJvmIntegrationText extends KafkaIntegrationTest {
KafkaAndJvmIntegrationText() {
super("target-systems/jvm-and-kafka.properties");
}
@Test
void endToEnd() {
List<String> gcLabels =
Arrays.asList(
"CodeHeap 'non-nmethods'",
"CodeHeap 'non-profiled nmethods'",
"CodeHeap 'profiled nmethods'",
"Compressed Class Space",
"G1 Eden Space",
"G1 Old Gen",
"G1 Survivor Space",
"Metaspace");
waitAndAssertMetrics(
metric -> assertGauge(metric, "jvm.classes.loaded", "number of loaded classes", "1"),
metric ->
assertTypedSum(
metric,
"jvm.gc.collections.count",
"total number of collections that have occurred",
"1",
Arrays.asList("G1 Young Generation", "G1 Old Generation")),
metric ->
assertTypedSum(
metric,
"jvm.gc.collections.elapsed",
"the approximate accumulated collection elapsed time in milliseconds",
"ms",
Arrays.asList("G1 Young Generation", "G1 Old Generation")),
metric -> assertGauge(metric, "jvm.memory.heap.committed", "current heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.heap.init", "current heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.heap.max", "current heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.heap.used", "current heap usage", "by"),
metric ->
assertGauge(metric, "jvm.memory.nonheap.committed", "current non-heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.nonheap.init", "current non-heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.nonheap.max", "current non-heap usage", "by"),
metric -> assertGauge(metric, "jvm.memory.nonheap.used", "current non-heap usage", "by"),
metric ->
assertTypedGauge(
metric, "jvm.memory.pool.committed", "current memory pool usage", "by", gcLabels),
metric ->
assertTypedGauge(
metric, "jvm.memory.pool.init", "current memory pool usage", "by", gcLabels),
metric ->
assertTypedGauge(
metric, "jvm.memory.pool.max", "current memory pool usage", "by", gcLabels),
metric ->
assertTypedGauge(
metric, "jvm.memory.pool.used", "current memory pool usage", "by", gcLabels),
metric -> assertGauge(metric, "jvm.threads.count", "number of threads", "1"),
metric -> assertGauge(metric, "kafka.bytes.in", "bytes in per second from clients", "by"),
metric -> assertGauge(metric, "kafka.bytes.out", "bytes out per second to clients", "by"),
metric ->
assertGauge(
metric, "kafka.controller.active.count", "controller is active on broker", "1"),
metric ->
assertGauge(
metric,
"kafka.fetch.consumer.total.time.99p",
"fetch consumer request time - 99th percentile",
"ms"),
metric ->
assertSum(
metric,
"kafka.fetch.consumer.total.time.count",
"fetch consumer request count",
"1"),
metric ->
assertGauge(
metric,
"kafka.fetch.consumer.total.time.median",
"fetch consumer request time - 50th percentile",
"ms"),
metric ->
assertGauge(
metric,
"kafka.fetch.follower.total.time.99p",
"fetch follower request time - 99th percentile",
"ms"),
metric ->
assertSum(
metric,
"kafka.fetch.follower.total.time.count",
"fetch follower request count",
"1"),
metric ->
assertGauge(
metric,
"kafka.fetch.follower.total.time.median",
"fetch follower request time - 50th percentile",
"ms"),
metric ->
assertGauge(metric, "kafka.isr.shrinks", "in-sync replica shrinks per second", "1"),
metric ->
assertGauge(
metric,
"kafka.leader.election.rate",
"leader election rate - non-zero indicates broker failures",
"1"),
metric ->
assertGauge(
metric,
"kafka.max.lag",
"max lag in messages between follower and leader replicas",
"1"),
metric ->
assertGauge(metric, "kafka.messages.in", "number of messages in per second", "1"),
metric ->
assertGauge(
metric,
"kafka.partitions.offline.count",
"number of partitions without an active leader",
"1"),
metric ->
assertGauge(
metric,
"kafka.partitions.underreplicated.count",
"number of under replicated partitions",
"1"),
metric ->
assertGauge(
metric,
"kafka.produce.total.time.99p",
"produce request time - 99th percentile",
"ms"),
metric ->
assertSum(metric, "kafka.produce.total.time.count", "produce request count", "1"),
metric ->
assertGauge(
metric,
"kafka.produce.total.time.median",
"produce request time - 50th percentile",
"ms"),
metric -> assertGauge(metric, "kafka.request.queue", "size of the request queue", "1"),
metric ->
assertGauge(
metric,
"kafka.unclean.election.rate",
"unclean leader election rate - non-zero indicates broker failures",
"1"));
}
}
static void assertKafkaGauge(Metric metric, String name, String description, String unit) {
assertThat(metric.getName()).isEqualTo(name);
assertThat(metric.getDescription()).isEqualTo(description);
assertThat(metric.getUnit()).isEqualTo(unit);
assertThat(metric.hasGauge()).isTrue();
assertThat(metric.getGauge().getDataPointsList())
.satisfiesExactly(
point ->
assertThat(point.getAttributesList())
.singleElement()
.satisfies(
attribute -> {
assertThat(attribute.getKey()).isEqualTo("client-id");
assertThat(attribute.getValue().getStringValue()).isNotEmpty();
}));
}
@SuppressWarnings("unchecked")
static void assertKafkaGauge(
Metric metric, String name, String description, String unit, List<String> topics) {
assertThat(metric.getName()).isEqualTo(name);
assertThat(metric.getDescription()).isEqualTo(description);
assertThat(metric.getUnit()).isEqualTo(unit);
assertThat(metric.hasGauge()).isTrue();
assertThat(metric.getGauge().getDataPointsList())
.satisfiesExactlyInAnyOrder(
topics.stream()
.map(
topic ->
(Consumer<NumberDataPoint>)
point ->
assertThat(point.getAttributesList())
.satisfiesExactlyInAnyOrder(
attribute -> {
assertThat(attribute.getKey()).isEqualTo("client-id");
assertThat(attribute.getValue().getStringValue())
.isNotEmpty();
},
attribute -> {
assertThat(attribute.getKey()).isEqualTo("topic");
assertThat(attribute.getValue().getStringValue())
.isEqualTo(topic);
}))
.toArray(Consumer[]::new));
}
}
| 39.537205
| 143
| 0.513289
|
ea3c5c402a5ed45500e60ee180d07dac4e85aeec
| 2,919
|
package com.example.orderservice.controller;
import com.example.orderservice.client.InventoryClient;
import com.example.orderservice.dto.OrderDTO;
import com.example.orderservice.model.Order;
import com.example.orderservice.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreaker;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.function.Supplier;
@RestController
@RequestMapping("/api/order")
@Slf4j
@RequiredArgsConstructor
public class OrderController {
private final OrderRepository orderRepository;
private final InventoryClient inventoryClient;
private final Resilience4JCircuitBreakerFactory circuitBreakerFactory;
private final StreamBridge streamBridge;
private final ExecutorService traceableExecutorService;
@GetMapping
public String getOrderNumber() {
return "sdfdfd";
}
@PostMapping
public String placeOrder(@RequestBody OrderDTO orderDTO) {
log.info("Placing order.....");
circuitBreakerFactory.configureExecutorService(traceableExecutorService);
//Casting to TraceableCircuitBreaker will be thrown if not set `spring.sleuth.circuitbreaker.enabled`
Resilience4JCircuitBreaker circuitBreaker = circuitBreakerFactory.create("inventory");
Supplier<Boolean> bs = () -> orderDTO.getOrderLineItems().stream()
.allMatch(orderLineItem -> inventoryClient.checkStock(orderLineItem.getSkuCode()));
//runs in a different thread therefore need to configure to pass the security context from parent thread to chidl
//pls see the security config
boolean allProductsInStock = circuitBreaker.run(bs, throwable -> false);
if (allProductsInStock) {
log.info("All products available....");
var order = new Order();
order.setOrderLineItems(orderDTO.getOrderLineItems());
order.setOrderNumber(UUID.randomUUID().toString());
orderRepository.save(order);
//need to add MessageBuilder.withPayload to support distributed tracing via async calls
//need to do the same change in notification service
streamBridge.send("notificationEventSupplier-out-0", MessageBuilder.withPayload(order.getId()).build());
log.info("notificationEventSupplier-out-0", order.getId());
return "Order placed successfully";
} else {
log.warn("All stocks are not available.....");
return "Order failed";
}
}
}
| 44.907692
| 121
| 0.741692
|
7b23e0f8d62c1a74bb2469102b062656fb1ee09c
| 993
|
package ru.mydesignstudio.database.metadata.extractor.output;
import java.util.Collection;
import java.util.Iterator;
import java.util.Optional;
import com.google.common.base.Preconditions;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import ru.mydesignstudio.database.metadata.extractor.extractors.model.TableMetadata;
import ru.mydesignstudio.database.metadata.extractor.extractors.model.TypeModel;
/**
* Extracts metadata type - if this metadata belongs to view or table. If there is no
* enough metadata, the Unknown value is returned.
*/
@Component
public class ObjectTypeExtractor {
public String extract(@NonNull TableMetadata metadata) {
Preconditions.checkNotNull(metadata);
return Optional.ofNullable(metadata)
.map(TableMetadata::getTypes)
.map(Collection::iterator)
.filter(Iterator::hasNext)
.map(Iterator::next)
.map(TypeModel::getObjectType)
.orElse("Unknown");
}
}
| 32.032258
| 85
| 0.763343
|
7286428732f02975766cf0d9c4b3f87031a88611
| 42,191
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp.internal.http;
import com.squareup.okhttp.Address;
import com.squareup.okhttp.CertificatePinner;
import com.squareup.okhttp.Connection;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.squareup.okhttp.Route;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.InternalCache;
import com.squareup.okhttp.internal.Util;
import com.squareup.okhttp.internal.Version;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.CookieHandler;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.security.cert.CertificateException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.GzipSource;
import okio.Okio;
import okio.Sink;
import okio.Source;
import okio.Timeout;
import static com.squareup.okhttp.internal.Util.closeQuietly;
import static com.squareup.okhttp.internal.http.StatusLine.HTTP_CONTINUE;
import static com.squareup.okhttp.internal.http.StatusLine.HTTP_PERM_REDIRECT;
import static com.squareup.okhttp.internal.http.StatusLine.HTTP_TEMP_REDIRECT;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_MULT_CHOICE;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Handles a single HTTP request/response pair. Each HTTP engine follows this
* lifecycle:
* <ol>
* <li>It is created.
* <li>The HTTP request message is sent with sendRequest(). Once the request
* is sent it is an error to modify the request headers. After
* sendRequest() has been called the request body can be written to if
* it exists.
* <li>The HTTP response message is read with readResponse(). After the
* response has been read the response headers and body can be read.
* All responses have a response body input stream, though in some
* instances this stream is empty.
* </ol>
*
* <p>The request and response may be served by the HTTP response cache, by the
* network, or by both in the event of a conditional GET.
*/
public final class HttpEngine {
/**
* How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
* curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
*/
public static final int MAX_FOLLOW_UPS = 20;
private static final ResponseBody EMPTY_BODY = new ResponseBody() {
@Override public MediaType contentType() {
return null;
}
@Override public long contentLength() {
return 0;
}
@Override public BufferedSource source() {
return new Buffer();
}
};
final OkHttpClient client;
private Connection connection;
private Address address;
private RouteSelector routeSelector;
private Route route;
private final Response priorResponse;
private Transport transport;
/** The time when the request headers were written, or -1 if they haven't been written yet. */
long sentRequestMillis = -1;
/**
* True if this client added an "Accept-Encoding: gzip" header field and is
* therefore responsible for also decompressing the transfer stream.
*/
private boolean transparentGzip;
/**
* True if the request body must be completely buffered before transmission;
* false if it can be streamed. Buffering has two advantages: we don't need
* the content-length in advance and we can retransmit if necessary. The
* upside of streaming is that we can save memory.
*/
public final boolean bufferRequestBody;
/**
* The original application-provided request. Never modified by OkHttp. When
* follow-up requests are necessary, they are derived from this request.
*/
private final Request userRequest;
/**
* The request to send on the network, or null for no network request. This is
* derived from the user request, and customized to support OkHttp features
* like compression and caching.
*/
private Request networkRequest;
/**
* The cached response, or null if the cache doesn't exist or cannot be used
* for this request. Conditional caching means this may be non-null even when
* the network request is non-null. Never modified by OkHttp.
*/
private Response cacheResponse;
/**
* The user-visible response. This is derived from either the network
* response, cache response, or both. It is customized to support OkHttp
* features like compression and caching.
*/
private Response userResponse;
private Sink requestBodyOut;
private BufferedSink bufferedRequestBody;
private final boolean callerWritesRequestBody;
private final boolean forWebSocket;
/** The cache request currently being populated from a network response. */
private CacheRequest storeRequest;
private CacheStrategy cacheStrategy;
/**
* @param request the HTTP request without a body. The body must be written via the engine's
* request body stream.
* @param callerWritesRequestBody true for the {@code HttpURLConnection}-style interaction
* model where control flow is returned to the calling application to write the request body
* before the response body is readable.
* @param connection the connection used for an intermediate response immediately prior to this
* request/response pair, such as a same-host redirect. This engine assumes ownership of the
* connection and must release it when it is unneeded.
* @param routeSelector the route selector used for a failed attempt immediately preceding this
*/
public HttpEngine(OkHttpClient client, Request request, boolean bufferRequestBody,
boolean callerWritesRequestBody, boolean forWebSocket, Connection connection,
RouteSelector routeSelector, RetryableSink requestBodyOut, Response priorResponse) {
this.client = client;
this.userRequest = request;
this.bufferRequestBody = bufferRequestBody;
this.callerWritesRequestBody = callerWritesRequestBody;
this.forWebSocket = forWebSocket;
this.connection = connection;
this.routeSelector = routeSelector;
this.requestBodyOut = requestBodyOut;
this.priorResponse = priorResponse;
if (connection != null) {
Internal.instance.setOwner(connection, this);
this.route = connection.getRoute();
} else {
this.route = null;
}
}
/**
* Figures out what the response source will be, and opens a socket to that
* source if necessary. Prepares the request headers and gets ready to start
* writing the request body if it exists.
*
* @throws RequestException if there was a problem with request setup. Unrecoverable.
* @throws RouteException if the was a problem during connection via a specific route. Sometimes
* recoverable. See {@link #recover(RouteException)}.
* @throws IOException if there was a problem while making a request. Sometimes recoverable. See
* {@link #recover(IOException)}.
*
*/
public void sendRequest() throws RequestException, RouteException, IOException {
if (cacheStrategy != null) return; // Already sent.
if (transport != null) throw new IllegalStateException();
Request request = networkRequest(userRequest);
InternalCache responseCache = Internal.instance.internalCache(client);
Response cacheCandidate = responseCache != null
? responseCache.get(request)
: null;
long now = System.currentTimeMillis();
cacheStrategy = new CacheStrategy.Factory(now, request, cacheCandidate).get();
networkRequest = cacheStrategy.networkRequest;
cacheResponse = cacheStrategy.cacheResponse;
if (responseCache != null) {
responseCache.trackResponse(cacheStrategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
if (networkRequest != null) {
// Open a connection unless we inherited one from a redirect.
if (connection == null) {
connect();
}
transport = Internal.instance.newTransport(connection, this);
// If the caller's control flow writes the request body, we need to create that stream
// immediately. And that means we need to immediately write the request headers, so we can
// start streaming the request body. (We may already have a request body if we're retrying a
// failed POST.)
if (callerWritesRequestBody && permitsRequestBody() && requestBodyOut == null) {
long contentLength = OkHeaders.contentLength(request);
if (bufferRequestBody) {
if (contentLength > Integer.MAX_VALUE) {
throw new IllegalStateException("Use setFixedLengthStreamingMode() or "
+ "setChunkedStreamingMode() for requests larger than 2 GiB.");
}
if (contentLength != -1) {
// Buffer a request body of a known length.
transport.writeRequestHeaders(networkRequest);
requestBodyOut = new RetryableSink((int) contentLength);
} else {
// Buffer a request body of an unknown length. Don't write request
// headers until the entire body is ready; otherwise we can't set the
// Content-Length header correctly.
requestBodyOut = new RetryableSink();
}
} else {
transport.writeRequestHeaders(networkRequest);
requestBodyOut = transport.createRequestBody(networkRequest, contentLength);
}
}
} else {
// We aren't using the network. Recycle a connection we may have inherited from a redirect.
if (connection != null) {
Internal.instance.recycle(client.getConnectionPool(), connection);
connection = null;
}
if (cacheResponse != null) {
// We have a valid cached response. Promote it to the user response immediately.
this.userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.build();
} else {
// We're forbidden from using the network, and the cache is insufficient.
this.userResponse = new Response.Builder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(EMPTY_BODY)
.build();
}
userResponse = unzip(userResponse);
}
}
private static Response stripBody(Response response) {
return response != null && response.body() != null
? response.newBuilder().body(null).build()
: response;
}
/** Connect to the origin server either directly or via a proxy. */
private void connect() throws RequestException, RouteException {
if (connection != null) throw new IllegalStateException();
if (routeSelector == null) {
address = createAddress(client, networkRequest);
try {
routeSelector = RouteSelector.get(address, networkRequest, client);
} catch (IOException e) {
throw new RequestException(e);
}
}
connection = createNextConnection();
Internal.instance.connectAndSetOwner(client, connection, this, networkRequest);
route = connection.getRoute();
}
private Connection createNextConnection() throws RouteException {
ConnectionPool pool = client.getConnectionPool();
// Always prefer pooled connections over new connections.
for (Connection pooled; (pooled = pool.get(address)) != null; ) {
if (networkRequest.method().equals("GET") || Internal.instance.isReadable(pooled)) {
return pooled;
}
closeQuietly(pooled.getSocket());
}
try {
Route route = routeSelector.next();
return new Connection(pool, route);
} catch (IOException e) {
throw new RouteException(e);
}
}
/**
* Called immediately before the transport transmits HTTP request headers.
* This is used to observe the sent time should the request be cached.
*/
public void writingRequestHeaders() {
if (sentRequestMillis != -1) throw new IllegalStateException();
sentRequestMillis = System.currentTimeMillis();
}
boolean permitsRequestBody() {
return HttpMethod.permitsRequestBody(userRequest.method());
}
/** Returns the request body or null if this request doesn't have a body. */
public Sink getRequestBody() {
if (cacheStrategy == null) throw new IllegalStateException();
return requestBodyOut;
}
public BufferedSink getBufferedRequestBody() {
BufferedSink result = bufferedRequestBody;
if (result != null) return result;
Sink requestBody = getRequestBody();
return requestBody != null
? (bufferedRequestBody = Okio.buffer(requestBody))
: null;
}
public boolean hasResponse() {
return userResponse != null;
}
public Request getRequest() {
return userRequest;
}
/** Returns the engine's response. */
// TODO: the returned body will always be null.
public Response getResponse() {
if (userResponse == null) throw new IllegalStateException();
return userResponse;
}
public Connection getConnection() {
return connection;
}
/**
* Attempt to recover from failure to connect via a route. Returns a new HTTP engine
* that should be used for the retry if there are other routes to try, or null if
* there are no more routes to try.
*/
public HttpEngine recover(RouteException e) {
if (routeSelector != null && connection != null) {
connectFailed(routeSelector, e.getLastConnectException());
}
if (routeSelector == null && connection == null // No connection.
|| routeSelector != null && !routeSelector.hasNext() // No more routes to attempt.
|| !isRecoverable(e)) {
return null;
}
Connection connection = close();
// For failure recovery, use the same route selector with a new connection.
return new HttpEngine(client, userRequest, bufferRequestBody, callerWritesRequestBody,
forWebSocket, connection, routeSelector, (RetryableSink) requestBodyOut, priorResponse);
}
private boolean isRecoverable(RouteException e) {
// If the application has opted-out of recovery, don't recover.
if (!client.getRetryOnConnectionFailure()) {
return false;
}
// Problems with a route may mean the connection can be retried with a new route, or may
// indicate a client-side or server-side issue that should not be retried. To tell, we must look
// at the cause.
IOException ioe = e.getLastConnectException();
// If there was a protocol problem, don't recover.
if (ioe instanceof ProtocolException) {
return false;
}
// If there was an interruption don't recover, but if there was a timeout
// we should try the next route (if there is one).
if (ioe instanceof InterruptedIOException) {
return ioe instanceof SocketTimeoutException;
}
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different route.
if (ioe instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry.
if (ioe.getCause() instanceof CertificateException) {
return false;
}
}
if (ioe instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
// An example of one we might want to retry with a different route is a problem connecting to a
// proxy and would manifest as a standard IOException. Unless it is one we know we should not
// retry, we return true and try a new route.
return true;
}
/**
* Report and attempt to recover from a failure to communicate with a server. Returns a new
* HTTP engine that should be used for the retry if {@code e} is recoverable, or null if
* the failure is permanent. Requests with a body can only be recovered if the
* body is buffered.
*/
public HttpEngine recover(IOException e, Sink requestBodyOut) {
if (routeSelector != null && connection != null) {
connectFailed(routeSelector, e);
}
boolean canRetryRequestBody = requestBodyOut == null || requestBodyOut instanceof RetryableSink;
if (routeSelector == null && connection == null // No connection.
|| routeSelector != null && !routeSelector.hasNext() // No more routes to attempt.
|| !isRecoverable(e)
|| !canRetryRequestBody) {
return null;
}
Connection connection = close();
// For failure recovery, use the same route selector with a new connection.
return new HttpEngine(client, userRequest, bufferRequestBody, callerWritesRequestBody,
forWebSocket, connection, routeSelector, (RetryableSink) requestBodyOut, priorResponse);
}
private void connectFailed(RouteSelector routeSelector, IOException e) {
// If this is a recycled connection, don't count its failure against the route.
if (Internal.instance.recycleCount(connection) > 0) return;
Route failedRoute = connection.getRoute();
routeSelector.connectFailed(failedRoute, e);
}
public HttpEngine recover(IOException e) {
return recover(e, requestBodyOut);
}
private boolean isRecoverable(IOException e) {
// If the application has opted-out of recovery, don't recover.
if (!client.getRetryOnConnectionFailure()) {
return false;
}
// If there was a protocol problem, don't recover.
if (e instanceof ProtocolException) {
return false;
}
// If there was an interruption or timeout, don't recover.
if (e instanceof InterruptedIOException) {
return false;
}
return true;
}
/**
* Returns the route used to retrieve the response. Null if we haven't
* connected yet, or if no connection was necessary.
*/
public Route getRoute() {
return route;
}
private void maybeCache() throws IOException {
InternalCache responseCache = Internal.instance.internalCache(client);
if (responseCache == null) return;
// Should we cache this response for this request?
if (!CacheStrategy.isCacheable(userResponse, networkRequest)) {
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
responseCache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
return;
}
// Offer this request to the cache.
storeRequest = responseCache.put(stripBody(userResponse));
}
/**
* Configure the socket connection to be either pooled or closed when it is
* either exhausted or closed. If it is unneeded when this is called, it will
* be released immediately.
*/
public void releaseConnection() throws IOException {
if (transport != null && connection != null) {
transport.releaseConnectionOnIdle();
}
connection = null;
}
/**
* Immediately closes the socket connection if it's currently held by this engine. Use this to
* interrupt an in-flight request from any thread. It's the caller's responsibility to close the
* request body and response body streams; otherwise resources may be leaked.
*
* <p>This method is safe to be called concurrently, but provides limited guarantees. If a
* transport layer connection has been established (such as a HTTP/2 stream) that is terminated.
* Otherwise if a socket connection is being established, that is terminated.
*/
public void disconnect() {
try {
if (transport != null) {
transport.disconnect(this);
} else {
Connection connection = this.connection;
if (connection != null) {
Internal.instance.closeIfOwnedBy(connection, this);
}
}
} catch (IOException ignored) {
}
}
/**
* Release any resources held by this engine. If a connection is still held by
* this engine, it is returned.
*/
public Connection close() {
if (bufferedRequestBody != null) {
// This also closes the wrapped requestBodyOut.
closeQuietly(bufferedRequestBody);
} else if (requestBodyOut != null) {
closeQuietly(requestBodyOut);
}
// If this engine never achieved a response body, its connection cannot be reused.
if (userResponse == null) {
if (connection != null) closeQuietly(connection.getSocket()); // TODO: does this break SPDY?
connection = null;
return null;
}
// Close the response body. This will recycle the connection if it is eligible.
closeQuietly(userResponse.body());
// Close the connection if it cannot be reused.
if (transport != null && connection != null && !transport.canReuseConnection()) {
closeQuietly(connection.getSocket());
connection = null;
return null;
}
// Prevent this engine from disconnecting a connection it no longer owns.
if (connection != null && !Internal.instance.clearOwner(connection)) {
connection = null;
}
Connection result = connection;
connection = null;
return result;
}
/**
* Returns a new response that does gzip decompression on {@code response}, if transparent gzip
* was both offered by OkHttp and used by the origin server.
*
* <p>In addition to decompression, this will also strip the corresponding headers. We strip the
* Content-Encoding header to prevent the application from attempting to double decompress. We
* strip the Content-Length header because it is the length of the compressed content, but the
* application is only interested in the length of the uncompressed content.
*
* <p>This method should only be used for non-empty response bodies. Response codes like "304 Not
* Modified" can include "Content-Encoding: gzip" without a response body and we will crash if we
* attempt to decompress the zero-byte source.
*/
private Response unzip(final Response response) throws IOException {
if (!transparentGzip || !"gzip".equalsIgnoreCase(userResponse.header("Content-Encoding"))) {
return response;
}
if (response.body() == null) {
return response;
}
GzipSource responseBody = new GzipSource(response.body().source());
Headers strippedHeaders = response.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
return response.newBuilder()
.headers(strippedHeaders)
.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)))
.build();
}
/**
* Returns true if the response must have a (possibly 0-length) body.
* See RFC 2616 section 4.3.
*/
public static boolean hasBody(Response response) {
// HEAD requests never yield a body regardless of the response headers.
if (response.request().method().equals("HEAD")) {
return false;
}
int responseCode = response.code();
if ((responseCode < HTTP_CONTINUE || responseCode >= 200)
&& responseCode != HTTP_NO_CONTENT
&& responseCode != HTTP_NOT_MODIFIED) {
return true;
}
// If the Content-Length or Transfer-Encoding headers disagree with the
// response code, the response is malformed. For best compatibility, we
// honor the headers.
if (OkHeaders.contentLength(response) != -1
|| "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) {
return true;
}
return false;
}
/**
* Populates request with defaults and cookies.
*
* <p>This client doesn't specify a default {@code Accept} header because it
* doesn't know what content types the application is interested in.
*/
private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();
if (request.header("Host") == null) {
result.header("Host", Util.hostHeader(request.httpUrl()));
}
if ((connection == null || connection.getProtocol() != Protocol.HTTP_1_0)
&& request.header("Connection") == null) {
result.header("Connection", "Keep-Alive");
}
if (request.header("Accept-Encoding") == null) {
transparentGzip = true;
result.header("Accept-Encoding", "gzip");
}
CookieHandler cookieHandler = client.getCookieHandler();
if (cookieHandler != null) {
// Capture the request headers added so far so that they can be offered to the CookieHandler.
// This is mostly to stay close to the RI; it is unlikely any of the headers above would
// affect cookie choice besides "Host".
Map<String, List<String>> headers = OkHeaders.toMultimap(result.build().headers(), null);
Map<String, List<String>> cookies = cookieHandler.get(request.uri(), headers);
// Add any new cookies to the request.
OkHeaders.addCookies(result, cookies);
}
if (request.header("User-Agent") == null) {
result.header("User-Agent", Version.userAgent());
}
return result.build();
}
/**
* Flushes the remaining request header and body, parses the HTTP response
* headers and starts reading the HTTP response body if it exists.
*/
public void readResponse() throws IOException {
if (userResponse != null) {
return; // Already ready.
}
if (networkRequest == null && cacheResponse == null) {
throw new IllegalStateException("call sendRequest() first!");
}
if (networkRequest == null) {
return; // No network response to read.
}
Response networkResponse;
if (forWebSocket) {
transport.writeRequestHeaders(networkRequest);
networkResponse = readNetworkResponse();
} else if (!callerWritesRequestBody) {
networkResponse = new NetworkInterceptorChain(0, networkRequest).proceed(networkRequest);
} else {
// Emit the request body's buffer so that everything is in requestBodyOut.
if (bufferedRequestBody != null && bufferedRequestBody.buffer().size() > 0) {
bufferedRequestBody.emit();
}
// Emit the request headers if we haven't yet. We might have just learned the Content-Length.
if (sentRequestMillis == -1) {
if (OkHeaders.contentLength(networkRequest) == -1
&& requestBodyOut instanceof RetryableSink) {
long contentLength = ((RetryableSink) requestBodyOut).contentLength();
networkRequest = networkRequest.newBuilder()
.header("Content-Length", Long.toString(contentLength))
.build();
}
transport.writeRequestHeaders(networkRequest);
}
// Write the request body to the socket.
if (requestBodyOut != null) {
if (bufferedRequestBody != null) {
// This also closes the wrapped requestBodyOut.
bufferedRequestBody.close();
} else {
requestBodyOut.close();
}
if (requestBodyOut instanceof RetryableSink) {
transport.writeRequestBody((RetryableSink) requestBodyOut);
}
}
networkResponse = readNetworkResponse();
}
receiveHeaders(networkResponse.headers());
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
if (validate(cacheResponse, networkResponse)) {
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
releaseConnection();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
InternalCache responseCache = Internal.instance.internalCache(client);
responseCache.trackConditionalCacheHit();
responseCache.update(cacheResponse, stripBody(userResponse));
userResponse = unzip(userResponse);
return;
} else {
closeQuietly(cacheResponse.body());
}
}
userResponse = networkResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
if (hasBody(userResponse)) {
maybeCache();
userResponse = unzip(cacheWritingResponse(storeRequest, userResponse));
}
}
class NetworkInterceptorChain implements Interceptor.Chain {
private final int index;
private final Request request;
private int calls;
NetworkInterceptorChain(int index, Request request) {
this.index = index;
this.request = request;
}
@Override public Connection connection() {
return connection;
}
@Override public Request request() {
return request;
}
@Override public Response proceed(Request request) throws IOException {
calls++;
if (index > 0) {
Interceptor caller = client.networkInterceptors().get(index - 1);
Address address = connection().getRoute().getAddress();
// Confirm that the interceptor uses the connection we've already prepared.
if (!request.httpUrl().rfc2732host().equals(address.getRfc2732Host())
|| request.httpUrl().port() != address.getUriPort()) {
throw new IllegalStateException("network interceptor " + caller
+ " must retain the same host and port");
}
// Confirm that this is the interceptor's first call to chain.proceed().
if (calls > 1) {
throw new IllegalStateException("network interceptor " + caller
+ " must call proceed() exactly once");
}
}
if (index < client.networkInterceptors().size()) {
// There's another interceptor in the chain. Call that.
NetworkInterceptorChain chain = new NetworkInterceptorChain(index + 1, request);
Interceptor interceptor = client.networkInterceptors().get(index);
Response interceptedResponse = interceptor.intercept(chain);
// Confirm that the interceptor made the required call to chain.proceed().
if (chain.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
return interceptedResponse;
}
transport.writeRequestHeaders(request);
//Update the networkRequest with the possibly updated interceptor request.
networkRequest = request;
if (permitsRequestBody() && request.body() != null) {
Sink requestBodyOut = transport.createRequestBody(request, request.body().contentLength());
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
Response response = readNetworkResponse();
int code = response.code();
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
}
private Response readNetworkResponse() throws IOException {
transport.finishRequest();
Response networkResponse = transport.readResponseHeaders()
.request(networkRequest)
.handshake(connection.getHandshake())
.header(OkHeaders.SENT_MILLIS, Long.toString(sentRequestMillis))
.header(OkHeaders.RECEIVED_MILLIS, Long.toString(System.currentTimeMillis()))
.build();
if (!forWebSocket) {
networkResponse = networkResponse.newBuilder()
.body(transport.openResponseBody(networkResponse))
.build();
}
Internal.instance.setProtocol(connection, networkResponse.protocol());
return networkResponse;
}
/**
* Returns a new source that writes bytes to {@code cacheRequest} as they are read by the source
* consumer. This is careful to discard bytes left over when the stream is closed; otherwise we
* may never exhaust the source stream and therefore not complete the cached response.
*/
private Response cacheWritingResponse(final CacheRequest cacheRequest, Response response)
throws IOException {
// Some apps return a null body; for compatibility we treat that like a null cache request.
if (cacheRequest == null) return response;
Sink cacheBodyUnbuffered = cacheRequest.body();
if (cacheBodyUnbuffered == null) return response;
final BufferedSource source = response.body().source();
final BufferedSink cacheBody = Okio.buffer(cacheBodyUnbuffered);
Source cacheWritingSource = new Source() {
boolean cacheRequestClosed;
@Override public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead;
try {
bytesRead = source.read(sink, byteCount);
} catch (IOException e) {
if (!cacheRequestClosed) {
cacheRequestClosed = true;
cacheRequest.abort(); // Failed to write a complete cache response.
}
throw e;
}
if (bytesRead == -1) {
if (!cacheRequestClosed) {
cacheRequestClosed = true;
cacheBody.close(); // The cache response is complete!
}
return -1;
}
sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead);
cacheBody.emitCompleteSegments();
return bytesRead;
}
@Override public Timeout timeout() {
return source.timeout();
}
@Override public void close() throws IOException {
if (!cacheRequestClosed
&& !Util.discard(this, Transport.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
cacheRequestClosed = true;
cacheRequest.abort();
}
source.close();
}
};
return response.newBuilder()
.body(new RealResponseBody(response.headers(), Okio.buffer(cacheWritingSource)))
.build();
}
/**
* Returns true if {@code cached} should be used; false if {@code network}
* response should be used.
*/
private static boolean validate(Response cached, Response network) {
if (network.code() == HTTP_NOT_MODIFIED) {
return true;
}
// The HTTP spec says that if the network's response is older than our
// cached response, we may return the cache's response. Like Chrome (but
// unlike Firefox), this client prefers to return the newer response.
Date lastModified = cached.headers().getDate("Last-Modified");
if (lastModified != null) {
Date networkLastModified = network.headers().getDate("Last-Modified");
if (networkLastModified != null
&& networkLastModified.getTime() < lastModified.getTime()) {
return true;
}
}
return false;
}
/**
* Combines cached headers with a network headers as defined by RFC 2616,
* 13.5.3.
*/
private static Headers combine(Headers cachedHeaders, Headers networkHeaders) throws IOException {
Headers.Builder result = new Headers.Builder();
for (int i = 0, size = cachedHeaders.size(); i < size; i++) {
String fieldName = cachedHeaders.name(i);
String value = cachedHeaders.value(i);
if ("Warning".equalsIgnoreCase(fieldName) && value.startsWith("1")) {
continue; // Drop 100-level freshness warnings.
}
if (!OkHeaders.isEndToEnd(fieldName) || networkHeaders.get(fieldName) == null) {
result.add(fieldName, value);
}
}
for (int i = 0, size = networkHeaders.size(); i < size; i++) {
String fieldName = networkHeaders.name(i);
if ("Content-Length".equalsIgnoreCase(fieldName)) {
continue; // Ignore content-length headers of validating responses.
}
if (OkHeaders.isEndToEnd(fieldName)) {
result.add(fieldName, networkHeaders.value(i));
}
}
return result.build();
}
public void receiveHeaders(Headers headers) throws IOException {
CookieHandler cookieHandler = client.getCookieHandler();
if (cookieHandler != null) {
cookieHandler.put(userRequest.uri(), OkHeaders.toMultimap(headers, null));
}
}
/**
* Figures out the HTTP request to make in response to receiving this engine's
* response. This will either add authentication headers or follow redirects.
* If a follow-up is either unnecessary or not applicable, this returns null.
*/
public Request followUpRequest() throws IOException {
if (userResponse == null) throw new IllegalStateException();
Proxy selectedProxy = getRoute() != null
? getRoute().getProxy()
: client.getProxy();
int responseCode = userResponse.code();
switch (responseCode) {
case HTTP_PROXY_AUTH:
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
// fall-through
case HTTP_UNAUTHORIZED:
return OkHeaders.processAuthHeader(client.getAuthenticator(), userResponse, selectedProxy);
case HTTP_PERM_REDIRECT:
case HTTP_TEMP_REDIRECT:
// "If the 307 or 308 status code is received in response to a request other than GET
// or HEAD, the user agent MUST NOT automatically redirect the request"
if (!userRequest.method().equals("GET") && !userRequest.method().equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
// Does the client allow redirects?
if (!client.getFollowRedirects()) return null;
String location = userResponse.header("Location");
if (location == null) return null;
HttpUrl url = userRequest.httpUrl().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) return null;
// If configured, don't follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userRequest.httpUrl().scheme());
if (!sameScheme && !client.getFollowSslRedirects()) return null;
// Redirects don't include a request body.
Request.Builder requestBuilder = userRequest.newBuilder();
if (HttpMethod.permitsRequestBody(userRequest.method())) {
requestBuilder.method("GET", null);
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(url)) {
requestBuilder.removeHeader("Authorization");
}
return requestBuilder.url(url).build();
default:
return null;
}
}
/**
* Returns true if an HTTP request for {@code followUp} can reuse the
* connection used by this engine.
*/
public boolean sameConnection(HttpUrl followUp) {
HttpUrl url = userRequest.httpUrl();
return url.host().equals(followUp.host())
&& url.port() == followUp.port()
&& url.scheme().equals(followUp.scheme());
}
private static Address createAddress(OkHttpClient client, Request request) {
SSLSocketFactory sslSocketFactory = null;
HostnameVerifier hostnameVerifier = null;
CertificatePinner certificatePinner = null;
if (request.isHttps()) {
sslSocketFactory = client.getSslSocketFactory();
hostnameVerifier = client.getHostnameVerifier();
certificatePinner = client.getCertificatePinner();
}
return new Address(request.httpUrl().rfc2732host(), request.httpUrl().port(),
client.getSocketFactory(), sslSocketFactory, hostnameVerifier, certificatePinner,
client.getAuthenticator(), client.getProxy(), client.getProtocols(),
client.getConnectionSpecs(), client.getProxySelector());
}
}
| 36.880245
| 100
| 0.683843
|
9da4e65ed63d3a0c9076150023660025defb57b4
| 329
|
package ru.job4j.list;
/**
* LIFO - last input first output.
* @author Ayup Bariev.
* @since 30.01.2018.
*/
public class SimpleStack<T> extends SimpleQueue<T> {
/**
* Retrieves and removes the last element of this deque.
* @return element.
*/
public T poll() {
return getRemoveTail();
}
}
| 19.352941
| 60
| 0.607903
|
7b8e848a7cc52f9c73ae6104406458c9fad1c554
| 2,758
|
package com.food.ordering.zinger.constant;
public class ApiConfig {
public static final String EMPTY_QUOTES = "";
public static class PlaceApi {
public static final String BASE_URL = "/place";
public static final String insertPlace = EMPTY_QUOTES;
public static final String getAllPlaces = EMPTY_QUOTES;
}
public static class ItemApi {
public static final String BASE_URL = "/menu";
public static final String insertItem = EMPTY_QUOTES;
public static final String getItemsByShopId = "/shop/{shopId}";
public static final String getItemsByName = "/{placeId}/{itemName}";
public static final String updateItem = EMPTY_QUOTES;
public static final String deleteItemById = "/delete/{itemId}";
}
public static class OrderApi {
public static final String BASE_URL = "/order";
public static final String insertOrder = EMPTY_QUOTES;
public static final String placeOrder = "/place/{orderId}";
public static final String getOrderByUserId = "/customer/{userId}/{pageNum}/{pageCount}";
public static final String getOrderBySearchQuery = "/{shopId}/{searchItem}/{pageNum}/{pageCount}";
public static final String getOrderByShopIdPagination = "/seller/{shopId}/{pageNum}/{pageCount}";
public static final String getOrderByShopId = "/seller/{shopId}";
public static final String getOrderById = "/{id}";
public static final String updateOrderRating = "/rating";
public static final String updateOrderStatus = "/status";
}
public static class UserApi {
public static final String BASE_URL = "/user";
public static final String loginRegisterCustomer = "/customer";
public static final String verifySeller = "/seller";
public static final String updateUser = EMPTY_QUOTES;
public static final String updateUserNotificationToken = "/notif";
public static final String updateUserPlaceData = "/place";
public static final String deleteSeller = "/seller/{shopId}/{userId}";
}
public static class NotifyApi {
public static final String BASE_URL = "/notify";
public static final String notifyUrl = "/url";
public static final String notifyNewArrival = "/newArrivals";
}
public static class ShopApi {
public static final String BASE_URL = "/shop";
public static final String insertShop = EMPTY_QUOTES;
public static final String getShopsByPlaceId = "/place/{placeId}";
public static final String getShopById = "/{shopId}";
public static final String updateShopConfiguration = "/config";
public static final String deleteShop = "/{shopId}";
}
}
| 45.966667
| 106
| 0.683466
|
5174a916a45507811a4acb25b2528020c02f1849
| 4,920
|
package in.aaho.android.ownr.profile;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.VolleyError;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import in.aaho.android.ownr.LoginActivity;
import in.aaho.android.ownr.common.ApiResponseListener;
import in.aaho.android.ownr.common.BaseDialogFragment;
import in.aaho.android.ownr.R;
import in.aaho.android.ownr.common.Utils;
import in.aaho.android.ownr.requests.PasswordEditRequest;
import okhttp3.internal.Util;
/**
* Created by shobhit on 8/8/16.
*/
public class PasswordChangeDialogFragment extends BaseDialogFragment {
private final String TAG = getClass().getSimpleName();
private Button doneButton, cancelButton;
private EditText curPassEditText, newPassEditText, confirmPassEditText;
private View dialogView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dialogView = inflater.inflate(R.layout.password_change_dialog, container, false);
setViewVariables();
setClickListeners();
return dialogView;
}
private void setClickListeners() {
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String currPass = curPassEditText.getText().toString();
String newPass = newPassEditText.getText().toString();
String confirmPass = confirmPassEditText.getText().toString();
if (currPass.length() == 0) {
curPassEditText.setError("This field cannot be left blank");
return;
}
if (newPass.length() == 0) {
newPassEditText.setError("This field cannot be left blank");
return;
}
if (confirmPass.length() == 0) {
confirmPassEditText.setError("This field cannot be left blank");
return;
}
if (!newPass.equals(confirmPass)) {
confirmPassEditText.setError("Passwords do not Match");
return;
}
if (newPass.length() < 8) {
newPassEditText.setError("Password must be at least 8 characters long");
return;
}
makePasswordChangeRequest(currPass, newPass);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasswordChangeDialogFragment.this.dismiss();
}
});
}
private void setViewVariables() {
doneButton = dialogView.findViewById(R.id.password_dialog_update_btn);
cancelButton = dialogView.findViewById(R.id.password_dialog_cancel_btn);
curPassEditText = dialogView.findViewById(R.id.current_password_edittext);
newPassEditText = dialogView.findViewById(R.id.new_password_edittext);
confirmPassEditText = dialogView.findViewById(R.id.confirm_new_password_edittext);
}
private void makePasswordChangeRequest(String currPass, String newPass) {
PasswordEditRequest passRequest = new PasswordEditRequest(currPass, newPass, new PasswordEditListener());
queue(passRequest);
}
private class PasswordEditListener extends ApiResponseListener {
@Override
public void onResponse(JSONObject response) {
dismissProgress();
String msg = Utils.getRequestMessage(response);
Utils.toast(msg);
dismiss();
}
@Override
public void onErrorResponse(VolleyError error) {
super.onErrorResponse(error);
dismissProgress();
try {
if (error != null && error.networkResponse != null
&& error.networkResponse.data != null) {
String errorMsg = new String(error.networkResponse.data, "UTF-8");
JSONObject errorData = new JSONObject(errorMsg);
Utils.showInfoDialog(getActivity(),
Utils.getRequestMessage(errorData),Utils.getRequestData(errorData));
Log.i(TAG, errorMsg);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception ex) {
Log.e(TAG,"Exception = "+ex.getLocalizedMessage());
}
}
/*@Override
public void onError() {
dismissProgress();
dismiss();
}*/
}
}
| 36.176471
| 113
| 0.61626
|
d941f968ffac06fa651c2be818a5f7622733f01b
| 8,069
|
/*
* #%L
* ImgLib: a general-purpose, multidimensional image processing library.
* %%
* Copyright (C) 2009 - 2013 Stephan Preibisch, Tobias Pietzsch, Barry DeZonia,
* Stephan Saalfeld, Albert Cardona, Curtis Rueden, Christian Dietz, Jean-Yves
* Tinevez, Johannes Schindelin, Lee Kamentsky, Larry Lindsey, Grant Harris,
* Mark Hiner, Aivar Grislis, Martin Horn, Nick Perry, Michael Zinsmaier,
* Steffen Jaensch, Jan Funke, Mark Longair, and Dimiter Prodanov.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package mpicbg.imglib.outofbounds;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.type.numeric.RealType;
import mpicbg.imglib.util.Util;
/**
* TODO
*
* @author Stephan Preibisch
* @author Stephan Saalfeld
*/
public class OutOfBoundsStrategyMirrorExpWindowing<T extends RealType<T>> extends OutOfBoundsStrategy<T>
{
final LocalizableCursor<T> parentCursor;
final LocalizableByDimCursor<T> mirrorCursor;
final T type, mirrorType;
final int numDimensions;
final int[] dimension, position, mirroredPosition, currentDirection, tmp;
final float[][] weights;
final float cutOff = 0.0001f;
public OutOfBoundsStrategyMirrorExpWindowing( final LocalizableCursor<T> parentCursor, final int[] fadeOutDistance, final float exponent )
{
super( parentCursor );
this.parentCursor = parentCursor;
this.mirrorCursor = parentCursor.getImage().createLocalizableByDimCursor();
this.mirrorType = mirrorCursor.getType();
this.type = mirrorType.createVariable();
this.numDimensions = parentCursor.getImage().getNumDimensions();
this.dimension = parentCursor.getImage().getDimensions();
this.position = new int[ numDimensions ];
this.mirroredPosition = new int[ numDimensions ];
this.currentDirection = new int[ numDimensions ];
this.tmp = new int[ numDimensions ];
// create lookup table for the weights
weights = new float[ numDimensions ][];
for ( int d = 0; d < numDimensions; ++d )
weights[ d ] = new float[ Math.max( 1, fadeOutDistance[ d ] ) ];
for ( int d = 0; d < numDimensions; ++d )
{
final int maxDistance = weights[ d ].length;
if ( maxDistance > 1 )
{
for ( int pos = 0; pos < maxDistance; ++pos )
{
final float relPos = pos / (float)( maxDistance - 1 );
// if exponent equals one means linear function
if ( Util.isApproxEqual( exponent, 1f, 0.0001f ) )
weights[ d ][ pos ] = 1 - relPos;
else
weights[ d ][ pos ] = (float)( 1 - ( 1 / Math.pow( exponent, 1 - relPos ) ) ) * ( 1 + 1/(exponent-1) );
}
}
else
{
weights[ d ][ 0 ] = 0;
}
}
}
@Override
public T getType(){ return type; }
@Override
final public void notifyOutOfBOunds()
{
parentCursor.getPosition( position );
getMirrorCoordinate( position, mirroredPosition );
mirrorCursor.setPosition( mirroredPosition );
type.set( mirrorType );
type.mul( getWeight( position ) );
// test current direction
// where do we have to move when we move one forward in every dimension, respectively
for ( int d = 0; d < numDimensions; ++d )
tmp[ d ] = position[ d ] + 1;
getMirrorCoordinate( tmp, currentDirection );
for ( int d = 0; d < numDimensions; ++d )
currentDirection[ d ] = currentDirection[ d ] - mirroredPosition[ d ];
}
final protected float getWeight( final int[] position )
{
float weight = 1;
for ( int d = 0; d < numDimensions; ++d )
{
final int pos = position[ d ];
final int distance;
if ( pos < 0 )
distance = -pos - 1;
else if ( pos >= dimension[ d ] )
distance = pos - dimension[ d ];
else
continue;
if ( distance < weights[ d ].length )
weight *= weights[ d ][ distance ];
else
return 0;
}
return weight;
}
@Override
public void notifyOutOfBOunds( final int steps, final int dim )
{
if ( Math.abs( steps ) > 10 )
{
notifyOutOfBOunds();
}
else if ( steps > 0 )
{
for ( int i = 0; i < steps; ++i )
notifyOutOfBOundsFwd( dim );
}
else
{
for ( int i = 0; i < -steps; ++i )
notifyOutOfBOundsBck( dim );
}
}
@Override
public void notifyOutOfBOundsFwd( final int dim )
{
if ( currentDirection[ dim ] == 1 )
{
if ( mirrorCursor.getPosition( dim ) + 1 == dimension[ dim ] )
{
mirrorCursor.bck( dim );
currentDirection[ dim ] = -1;
}
else
{
mirrorCursor.fwd( dim );
}
}
else
{
if ( mirrorCursor.getPosition( dim ) == 0 )
{
currentDirection[ dim ] = 1;
mirrorCursor.fwd( dim );
}
else
{
mirrorCursor.bck( dim );
}
}
type.set( mirrorType );
parentCursor.getPosition( position );
type.mul( getWeight( position ) );
}
@Override
public void notifyOutOfBOundsBck( final int dim )
{
// current direction of the mirror cursor when going forward
if ( currentDirection[ dim ] == 1 )
{
// so we have to move the mirror cursor back if we are not position 0
if ( mirrorCursor.getPosition( dim ) == 0 )
{
// the mirror cursor is at position 0, so we have to go forward instead
mirrorCursor.fwd( dim );
// that also means if we want to go
currentDirection[ dim ] = -1;
}
else
{
mirrorCursor.bck( dim );
}
}
else
{
if ( mirrorCursor.getPosition( dim ) + 1 == dimension[ dim ] )
{
mirrorCursor.bck( dim );
currentDirection[ dim ] = 1;
}
else
{
mirrorCursor.fwd( dim );
}
}
type.set( mirrorType );
parentCursor.getPosition( position );
type.mul( getWeight( position ) );
}
/**
* For mirroring, there is no difference between leaving the image and moving while
* being out of image bounds
*
* @see mpicbg.imglib.outofbounds.OutOfBoundsStrategy#notifyOutOfBounds()
*/
@Override
public void initOutOfBOunds() { notifyOutOfBOunds(); }
protected void getMirrorCoordinate( final int[] position, final int mirroredPosition[] )
{
for ( int d = 0; d < numDimensions; d++ )
{
mirroredPosition[ d ] = position[ d ];
if ( mirroredPosition[ d ] >= dimension[ d ])
mirroredPosition[ d ] = dimension[ d ] - (mirroredPosition[ d ] - dimension[ d ] + 2);
if ( mirroredPosition[ d ] < 0 )
{
int tmp = 0;
int dir = 1;
while ( mirroredPosition[ d ] < 0 )
{
tmp += dir;
if (tmp == dimension[ d ] - 1 || tmp == 0)
dir *= -1;
mirroredPosition[ d ]++;
}
mirroredPosition[ d ] = tmp;
}
}
}
@Override
public void close()
{
mirrorCursor.close();
}
}
| 27.824138
| 139
| 0.66142
|
891e359033f2671b62fa29731bf57b793510ec18
| 1,783
|
/********************************************************************************
* generated by de.acegen 1.6.4
********************************************************************************/
package com.anfelisa.box.data;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import de.acegen.IDataContainer;
import com.anfelisa.box.models.IScoreCardModel;
@JsonDeserialize(as=ScoreCardData.class)
public interface IScoreCardData extends IScoreCardModel, IDataContainer {
IScoreCardData withCardId(String cardId);
IScoreCardData withNextScheduledCardScheduledCardId(String nextScheduledCardScheduledCardId);
IScoreCardData withNextScheduledCardCreatedDate(java.time.LocalDateTime nextScheduledCardCreatedDate);
IScoreCardData withNextScheduledCardEf(Float nextScheduledCardEf);
IScoreCardData withNextScheduledCardInterval(Integer nextScheduledCardInterval);
IScoreCardData withNextScheduledCardN(Integer nextScheduledCardN);
IScoreCardData withNextScheduledCardCount(Integer nextScheduledCardCount);
IScoreCardData withNextScheduledCardScheduledDate(java.time.LocalDateTime nextScheduledCardScheduledDate);
IScoreCardData withNextScheduledCardLastQuality(Integer nextScheduledCardLastQuality);
IScoreCardData withScheduledCardId(String scheduledCardId);
IScoreCardData withScoredCardQuality(Integer scoredCardQuality);
IScoreCardData withScoredCardScoredDate(java.time.LocalDateTime scoredCardScoredDate);
IScoreCardData withReinforceCardId(String reinforceCardId);
IScoreCardData withReinforceCardCreatedDate(java.time.LocalDateTime reinforceCardCreatedDate);
IScoreCardData withUserId(String userId);
IScoreCardData withBoxId(String boxId);
IScoreCardData deepCopy();
}
/******* S.D.G. *******/
| 29.229508
| 107
| 0.766685
|
b0025f1da69b9dbf19b11e9e5680377f424c64a0
| 11,111
|
package me.shaftesbury.utils.functional;
import me.shaftesbury.utils.functional.monad.Option;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
public class IterableHelper {
private IterableHelper() {
}
/**
* Note this is not intended to be a wrapper for a restartable sequence. If you want a restartable sequence turn
* the underlying container into a concrete collection first.
*
* @param it the singly-traversable input sequence
* @param <T> the type of the underlying data in the input sequence
* @return an Iterable2
*/
public static <T> Iterable2<T> create(final java.lang.Iterable<T> it) {
return new Iterable2<T>() {
private final java.lang.Iterable<T> i = it;
public Iterator<T> iterator() {
return i.iterator();
}
public final Iterable2<T> filter(final Function<? super T, Boolean> f) {
return create(Functional.seq.filter(f, i));
}
public final <U> Iterable2<U> map(final Function<? super T, ? extends U> f) {
return create(Functional.seq.map(f, i));
}
public <U> Iterable2<U> mapi(final BiFunction<Integer, T, ? extends U> f) {
return create(Functional.seq.mapi(f, i));
}
public final <U> Iterable2<U> choose(final Function<? super T, Option<U>> f) {
return create(Functional.seq.choose(f, i));
}
public final boolean exists(final Function<? super T, Boolean> f) {
return Functional.exists(f, i);
}
public final boolean forAll(final Function<? super T, Boolean> f) {
return Functional.forAll(f, i);
}
public <U> boolean forAll2(final BiFunction<? super U, ? super T, Boolean> f, final Iterable<U> j) {
return Functional.forAll2(f, j, i);
}
public final <U> U fold(final BiFunction<? super U, ? super T, ? extends U> f, final U seed) {
return Functional.fold(f, seed, i);
}
public final List<T> toList() {
return Functional.toList(i);
}
public Object[] toArray() {
return Functional.toArray(i);
}
public Set<T> toSet() {
return Functional.toSet(i);
}
public <K, V> Map<K, V> toDictionary(final Function<? super T, ? extends K> keyFn, final Function<? super T, ? extends V> valueFn) {
return Functional.toDictionary(keyFn, valueFn, i);
}
public T last() {
return Functional.last(i);
}
public final Iterable2<T> sortWith(final Comparator<T> f) {
return create(Functional.sortWith(f, toList()));
}
public final Iterable2<T> concat(final Iterable2<T> list2) {
return create(Functional.seq.concat(i, list2));
}
public final T find(final Function<? super T, Boolean> f) {
return Functional.find(f, i);
}
public int findIndex(final Function<? super T, Boolean> f) {
return Functional.findIndex(f, i);
}
public final <B> B pick(final Function<? super T, Option<B>> f) {
return Functional.pick(f, i);
}
public final Iterable2<T> take(final int howMany) {
return create(Functional.seq.take(howMany, i));
}
public Iterable2<T> takeWhile(final Function<? super T, Boolean> f) {
return create(Functional.seq.takeWhile(f, i));
}
public Iterable2<T> skip(final int howMany) {
return create(Functional.seq.skip(howMany, i));
}
public Iterable2<T> skipWhile(final Function<? super T, Boolean> f) {
return create(Functional.seq.skipWhile(f, i));
}
public String join(final String delimiter) {
return Functional.join(delimiter, i);
}
public T findLast(final Function<? super T, Boolean> f) {
return Functional.findLast(f, i);
}
public Pair<List<T>, List<T>> partition(final Function<? super T, Boolean> f) {
return Functional.partition(f, i);
}
public final <U> Iterable2<Pair<T, U>> zip(final Iterable2<? extends U> l2) {
return create(Functional.seq.zip(i, l2));
}
//public final <U>Pair<List<T>,List<U>> unzip(){return Functional.unzip(i);}
public final <U, V> Iterable2<Triple<T, U, V>> zip3(final Iterable<? extends U> l2, final Iterable<? extends V> l3) {
return create(Functional.seq.zip3(i, l2, l3));
}
public final <U> Iterable2<U> collect(final Function<? super T, ? extends Iterable<U>> f) {
return create(Functional.seq.collect(f, i));
}
public <U> U in(final Function<Iterable2<T>, U> f) {
return f.apply(this);
}
public <U> Map<U, List<T>> groupBy(final Function<? super T, ? extends U> keyFn) {
return Functional.groupBy(keyFn, i);
}
};
}
public static <T> Iterable2<T> createEmpty() {
return new EmptyList<>();
}
private static class EmptyList<T> implements Iterable2<T> {
EmptyList() {
}
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
return false;
}
public T next() {
throw new java.util.NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException("Can't remove objects from this container");
}
};
}
public final Iterable2<T> filter(final Function<? super T, Boolean> f) {
return this;
}
public final <U> Iterable2<U> map(final Function<? super T, ? extends U> f) {
return new EmptyList<>();
}
public <U> Iterable2<U> mapi(final BiFunction<Integer, T, ? extends U> f) {
return new EmptyList<>();
}
public final <U> Iterable2<U> choose(final Function<? super T, Option<U>> f) {
return new EmptyList<>();
}
public final boolean exists(final Function<? super T, Boolean> f) {
return false;
}
public final boolean forAll(final Function<? super T, Boolean> f) {
return false;
}
public <U> boolean forAll2(final BiFunction<? super U, ? super T, Boolean> f, final Iterable<U> input1) {
return false;
}
public final <U> U fold(final BiFunction<? super U, ? super T, ? extends U> f, final U seed) {
return seed;
}
public final List<T> toList() {
return Functional.toList(this);
}
public Object[] toArray() {
return Functional.toArray(this);
}
public Set<T> toSet() {
return Functional.toSet(this);
}
public <K, V> Map<K, V> toDictionary(final Function<? super T, ? extends K> keyFn, final Function<? super T, ? extends V> valueFn) {
return Functional.toDictionary(keyFn, valueFn, this);
}
public T last() {
throw new NoSuchElementException();
}
public final Iterable2<T> sortWith(final Comparator<T> f) {
return this;
}
public final Iterable2<T> concat(final Iterable2<T> list2) {
return list2;
}
public final T find(final Function<? super T, Boolean> f) {
throw new NoSuchElementException();
}
public int findIndex(final Function<? super T, Boolean> f) {
throw new NoSuchElementException();
}
public final <B> B pick(final Function<? super T, Option<B>> f) {
throw new NoSuchElementException();
}
public final Iterable2<T> take(final int howMany) {
return this;
}
public Iterable2<T> takeWhile(final Function<? super T, Boolean> f) {
return this;
}
public Iterable2<T> skip(final int howMany) {
return this;
}
public Iterable2<T> skipWhile(final Function<? super T, Boolean> f) {
return this;
}
public String join(final String delimiter) {
return Functional.join(delimiter, this);
}
public T findLast(final Function<? super T, Boolean> f) {
throw new NoSuchElementException();
}
public Pair<List<T>, List<T>> partition(final Function<? super T, Boolean> f) {
return Functional.partition(f, this);
}
public final <U> Iterable2<Pair<T, U>> zip(final Iterable2<? extends U> l2) {
throw new IllegalArgumentException("Iterable2.zip: It is not possible to zip an empty list with a non-empty list");
}
//public final <U>Pair<List<T>,List<U>> unzip(){return Functional.unzip(i);}
public final <U, V> Iterable2<Triple<T, U, V>> zip3(final Iterable<? extends U> l2, final Iterable<? extends V> l3) {
throw new IllegalArgumentException("Iterable2.zip3: It is not possible to zip an empty list with a non-empty list");
}
public final <U> Iterable2<U> collect(final Function<? super T, ? extends Iterable<U>> f) {
return new EmptyList<>();
}
public <U> U in(final Function<Iterable2<T>, U> f) {
return f.apply(this);
}
public <U> Map<U, List<T>> groupBy(final Function<? super T, ? extends U> keyFn) {
return Collections.emptyMap();
}
public boolean equals(final Object o) {
return o instanceof EmptyList<?>;
}
public int hashCode() {
return 0;
}
public String toString() {
return "()";
}
}
public static <T> Iterable2<T> init(final Function<Integer, T> f, final int howMany) {
return create(Functional.seq.init(f, howMany));
}
public static <T> Iterable2<T> init(final Function<Integer, ? extends T> f) {
return create(Functional.seq.init(f));
}
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> Iterable2<T> asList(final T... a) {
return create(Arrays.asList(a));
}
}
| 33.068452
| 144
| 0.552876
|
bf0a0f77dae20a69c4fe96a4227068f818c90e7d
| 158
|
package com.mafia.core.util;
public abstract class MafiaUtil {
public static boolean isOnlineMode()
{
// TODO
return false;
}
}
| 14.363636
| 40
| 0.613924
|
898e97791174c7869a5edb34d697e7ce7672f8bb
| 1,425
|
/*
* Extremely Compiler Collection
* Copyright (c) 2015-2020, Jianping Zeng.
*
* Licensed under the BSD License version 3. Please refer LICENSE
* for details.
*/
package backend.mc;
import java.io.PrintStream;
/**
* This represents an "assembler immediate". In its most general
* form, this can hold "SymbolA - SymbolB + imm64". Not all targets supports
* relocations of this general form, but we need to represent this anyway.
*
* In the general form, SymbolB can only be defined if SymbolA is, and both
* must be in the same (non-external) section. The latter constraint is not
* enforced, since a symbol's section may not be known at construction.
*/
public class MCValue {
private MCSymbol symA, symB;
private long cst;
public long getConstant() { return cst; }
public MCSymbol getSymA() { return symA; }
public MCSymbol getSymB() { return symB; }
public boolean isAbsolute() { return symA == null && symB == null;}
public MCSection getAssociatedSection() {
return null;
}
public void print(PrintStream os, MCAsmInfo mai) {}
public void dump() {
print(System.err, null);
}
public static MCValue get(MCSymbol symA, MCSymbol symB,
long val) {
MCValue res = new MCValue();
res.cst = val;
res.symA = symA;
res.symB = symB;
return res;
}
public static MCValue get(long val) {
return get(null, null, val);
}
}
| 26.388889
| 77
| 0.674386
|
5809f3c91c98f252dd870d435b0d2c503d346c62
| 3,951
|
package pro.gravit.simplecabinet.web.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import pro.gravit.simplecabinet.web.exception.InvalidParametersException;
import pro.gravit.simplecabinet.web.model.BasicUser;
import pro.gravit.simplecabinet.web.model.User;
import pro.gravit.simplecabinet.web.repository.UserRepository;
import pro.gravit.simplecabinet.web.utils.SecurityUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
@Service
public class UserService {
private final Pattern USERNAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");
@Autowired
private UserRepository repository;
@Autowired
private PasswordCheckService passwordCheckService;
public <S extends User> S save(S entity) {
return repository.save(entity);
}
public Optional<User> findById(Long aLong) {
return repository.findById(aLong);
}
public Optional<User> findByUsername(String username) {
return repository.findByUsernameIgnoreCase(username);
}
public Optional<User> findByUsernameOrEmail(String username, String email) {
return repository.findByUsernameIgnoreCaseOrEmailIgnoreCaseAllIgnoreCase(username, email);
}
public Optional<User> findByUUID(UUID uuid) {
return repository.findByUuid(uuid);
}
public Page<User> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
public User getReference(Long aLong) {
return repository.getById(aLong);
}
public void delete(User entity) {
repository.delete(entity);
}
public User register(String username, String email, String password) {
if (!USERNAME_PATTERN.matcher(username).matches()) {
throw new InvalidParametersException("Username contains forbidden characters", 33);
}
if (!User.isCorrectEmail(email)) {
throw new InvalidParametersException("Email not in correct format", 34);
}
User user = new User();
user.setUsername(username);
user.setUuid(UUID.randomUUID());
user.setEmail(email);
passwordCheckService.setPassword(user, password);
user.setRegistrationDate(LocalDateTime.now());
user.setGroups(new ArrayList<>());
repository.save(user);
return user;
}
public CurrentUser getCurrentUser() {
var details = SecurityUtils.getUser();
return new CurrentUser(details);
}
public class CurrentUser implements BasicUser {
private final UserDetailsService.CabinetUserDetails details;
private User user;
public CurrentUser(UserDetailsService.CabinetUserDetails details) {
this.details = details;
}
public User getReference() {
if (user == null) {
user = repository.getById(getId());
}
return user;
}
public String getClient() {
return details.getClient();
}
public long getSessionId() {
return details.getSessionId();
}
public String getPermission(String key) {
var map = details.getPermissions();
return map.get(key);
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return details.getAuthorities();
}
@Override
public long getId() {
return details.getUserId();
}
public String getUsername() {
return details.getUsername();
}
@Override
public UUID getUuid() {
return null;
}
}
}
| 29.931818
| 98
| 0.665654
|
e4d517fdeace1b24d6f5a2c89aaf3eafb653e3aa
| 3,555
|
package com.runcoding.learn.algorithm.uva; /**
* In positional notation we know the position of a digit indicates the weight of that digit toward the
* value of a number. For example, in the base 10 number 362 we know that 2 has the weight 100
* , 6
* has the weight 101
* , and 3 has the weight 102
* , yielding the value 3 × 102 + 6 × 101 + 2 × 100
* , or just
* 300 + 60 + 2. The same mechanism is used for numbers expressed in other bases. While most people
* assume the numbers they encounter everyday are expressed using base 10, we know that other bases
* are possible. In particular, the number 362 in base 9 or base 14 represents a totally different value than
* 362 in base 10.
* For this problem your program will presented with a sequence of pairs of integers. Let’s call the
* members of a pair X and Y . What your program is to do is determine the smallest base for X and the
* smallest base for Y (likely different from that for X) so that X and Y represent the same value.
* Consider, for example, the integers 12 and 5. Certainly these are not equal if base 10 is used for
* each. But suppose 12 was a base 3 number and 5 was a base 6 number? 12 base 3 = 1 × 3
* 1 + 2 × 3
* 0
* ,
* or 5 base 10, and certainly 5 in any base is equal to 5 base 10. So 12 and 5 can be equal, if you select
* the right bases for each of them!
* Input
* On each line of the input data there will be a pair of integers, X and Y , separated by one or more blanks;
* leading and trailing blanks may also appear on each line, are are to be ignored. The bases associated
* with X and Y will be between 1 and 36 (inclusive), and as noted above, need not be the same for X and
* Y . In representing these numbers the digits 0 through 9 have their usual decimal interpretations. The
* uppercase alphabetic characters A through Z represent digits with values 10 through 35, respectively.
* Output
* For each pair of integers in the input display a message similar to those shown in the examples shown
* below. Of course if the two integers cannot be equal regardless of the assumed base for each, then print
* an appropriate message; a suitable illustration is given in the examples.
* Sample Input
* 12 5
* 10 A
* 12 34
* 123 456
* 1 2
* 10 2
* Sample Output
* 12 (base 3) = 5 (base 6)
* 10 (base 10) = A (base 11)
* 12 (base 17) = 34 (base 5)
* 123 is not equal to 456 in any base 2..36
* 1 is not equal to 2 in any base 2..36
* 10 (base 2) = 2 (base 3)
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=279
import java.math.BigInteger;
import java.util.Scanner;
public class WhatBaseIsThis {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String x = input.next();
String y = input.next();
boolean found = false;
for (int i = 2; i < 37 && !found; i++) {
BigInteger xConvertedToBase;
try {
xConvertedToBase = new BigInteger(x, i);
} catch (Exception e) {
continue;
}
for (int j = 2; j < 37; j++) {
BigInteger yConvertedToBase;
try {
yConvertedToBase = new BigInteger(y, j);
} catch (Exception e) {
continue;
}
if (xConvertedToBase.equals(yConvertedToBase)) {
System.out.println(x + " (base " + i + ") = " + y
+ " (base " + j + ")");
found = true;
break;
}
}
}
if (!found) {
System.out.println(x + " is not equal to " + y
+ " in any base 2..36");
}
}
}
}
| 39.065934
| 111
| 0.674543
|
74aadc0451759d808b912d136f69a25c81f56aea
| 1,232
|
/**
* 项目名称:tools
* 项目包名:com.songfayuantools.thread.concurrent.demo05
* 创建时间:2018年1月22日下午2:23:43
* 创建者:Administrator-宋发元
* 创建地点:杭州
*/
package com.songfayuantools.thread.concurrent.demo05;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* 描述: 实现一个连环炸弹,2秒后爆炸一次,3秒后爆炸一次,如此循环下去。
*
* Timer是一种线程设施,用于安排以后在后台线程中执行的任务。可以安排执行一次,或者定期重复执行,可以看成一个定时器,可以调度TimerTask。
* TimerTask是一个抽象类,实现了Runnable接口,所以具备了多线程的能力。
* schedule是Timer调度任务的方法,Timer重构了四个schedule方法。
* @author songfayuan
* 2018年1月22日下午2:23:43
*/
public class TimerTest {
static class MyTimerTask1 extends TimerTask{
@Override
public void run() {
System.out.println("爆炸!!!");
new Timer().schedule(new MyTimerTask2(), 2000);//2秒后启动任务
}
}
static class MyTimerTask2 extends TimerTask{
@Override
public void run() {
System.out.println("爆炸!!!");
new Timer().schedule(new MyTimerTask1(), 3000);//3秒后启动任务
}
}
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new MyTimerTask2(), 2000); //2秒后启动任务
while (true) {
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000); //睡眠1秒
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 22.4
| 78
| 0.696429
|
5ef303846d60b6efd9c950b8aeec9087b292c887
| 4,256
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* The path weight of a node is the sum of the integers on the unique path
* from root to that node.
*
* Determine if there exists a leaf whose path weight equals the given targetSum
*
* Approach:
*
* 1) Similar to 10.5, traverse from root to leaf
* 2) Maintain either running sum or remaining
* 3) This will be pre-order traversal
*
*
*/
public class FindRootToLeafSum {
/*
10.6
*/
public static boolean hasPathSum1(BinaryTree<Integer> tree, int targetSum) {
if (tree == null) {
return false;
}
System.out.println("*** hasPathSum1 ***");
return hasPathSumWithRunningSum(tree, targetSum, 0);
}
public static boolean hasPathSum2(BinaryTree<Integer> tree, int targetSum) {
if (tree == null) {
return false;
}
System.out.println("*** hasPathSum2 ***");
return hasPathSumWithRunningDiff(tree, targetSum);
}
/**
* This is the running sum approach. The running sum is maintained by
* the stack
*
* @param tree
* @param targetSum
* @param runningSum
* @return
*/
private static boolean hasPathSumWithRunningSum(BinaryTree<Integer> tree,
int targetSum,
int runningSum) {
if (tree == null) {
return false;
}
runningSum += tree.data;
// if leaf node then check
if (tree.left == null && tree.right == null) {
// found target sum and leaf node
return runningSum == targetSum;
}
return hasPathSumWithRunningSum(tree.left, targetSum, runningSum) ||
hasPathSumWithRunningSum(tree.right, targetSum, runningSum);
}
/**
* This is the running difference approach. The remain sum is maintained by
* the stack
*
* @param tree
* @param remaining - getting smaller as traversing down the tree
* @return
*/
private static boolean hasPathSumWithRunningDiff(BinaryTree<Integer> tree,
int remaining) {
if (tree == null) {
return false;
}
remaining -= tree.data;
// if leaf node then check
if (tree.left == null && tree.right == null) {
// found target sum and leaf node
return remaining == 0;
}
return hasPathSumWithRunningDiff(tree.left, remaining) ||
hasPathSumWithRunningDiff(tree.right, remaining);
}
/**
* Return a list of node codes if there is a path with sum euqals to
* target sum
*
* @param tree
* @param targetSum
* @return List<String>
*/
public static List<List<String>> collectPaths(BinaryTree<Integer> tree,
int targetSum) {
if (tree == null) {
return Collections.emptyList();
}
System.out.println("*** collectPaths ***");
List<List<String>> result = new ArrayList<>();
List<String> collector = new ArrayList<>();
hasPathSumWithCodesHelper(tree, targetSum, collector, result);
return result;
}
private static void hasPathSumWithCodesHelper(BinaryTree<Integer> tree,
int remaining,
List<String> codes,
List<List<String>> result) {
if (tree == null) {
return ;
}
remaining -= tree.data;
codes.add(tree.code);
if (tree.left == null && tree.right == null){
if (remaining == 0) {
// leaf node
result.add(new LinkedList<>(codes));
}
codes.remove(codes.size()-1);
return;
}
hasPathSumWithCodesHelper(tree.left, remaining, codes, result);
hasPathSumWithCodesHelper(tree.right, remaining, codes, result);
codes.remove(codes.size()-1);
}
}
| 28.373333
| 81
| 0.539239
|
27d911e3d7bd3c9fd3c46e5f2a9f35e6ef15b588
| 1,858
|
/**
* Project for the "Distributed Algorithms" course
* Academic Year: 2015/2016
* Zen Roberto, Student ID: 171182.
* Bof Michele, Student ID: NaN.
*/
package com.distributedalgorithms.project;
import java.util.Vector;
class ProcessVertex implements Comparable<ProcessVertex>{
private String peer0 = "";
private String peer1 = "";
private Vector<ProcessVertex> parent = new Vector<ProcessVertex>();
public ProcessVertex(String p0) {
this.peer0 = p0;
}
public ProcessVertex(String p0, String p1) {
this.peer0 = p0;
this.peer1 = p1;
}
public String getFirst(){
return this.peer0;
}
public String getSecond(){
return this.peer1;
}
public void addParent(ProcessVertex pv){
parent.add(pv);
}
public boolean hasParent(){ return this.parent.size()!=0; }
public String getParentsString(){
String ris="{";
for (ProcessVertex pv:this.parent) {
ris+=pv.toInt()+",";
}
return ris.substring(0,ris.length()-1)+"}";
}
public Vector<ProcessVertex> getParents(){
return this.parent;
}
@Override
public String toString() {
return this.peer0+"-"+this.peer1;
}
public int toInt() {
return Integer.parseInt(this.peer0+this.peer1);
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof ProcessVertex)) {
return false;
}
else return this.toString().equals(obj.toString());
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Integer.parseInt(this.peer0);
hash = 71 * hash + Integer.parseInt(this.peer1);
return hash;
}
public int compareTo(ProcessVertex pv) {
return this.toInt()-pv.toInt();
}
}
| 22.658537
| 71
| 0.595802
|
1e6488fa57c92d9f6e30b39e77d5d6217a528907
| 4,386
|
/*
* Copyright (c) 2017, Bart Hanssens <bart.hanssens@bosa.fgov.be>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.belgif.vocab.dao;
import be.belgif.vocab.helpers.SchemaOrg;
import java.util.Set;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.vocabulary.SKOS;
import org.eclipse.rdf4j.model.vocabulary.VOID;
/**
* DAO helper class for SKOS vocabularies
* Only used for HTML view
*
* @author Bart Hanssens
*/
public class SkosDAO extends RdfDAO {
/**
* Get SKOS root resource
*
* @return uri as string
*/
public String getRoot() {
Value v = obj(VOID.ROOT_RESOURCE);
return (v != null) ? v.toString() : "";
}
/**
* Get download URL for a full download of the vocabulary
*
* @return download URL as string
*/
public String getDownload() {
return getId().toString().replaceFirst("/auth/", "/dataset/")
.replaceFirst("#id", "");
}
/**
* Get SKOS notation
*
* @return string or empty string
*/
public String getNotation() {
return literal(SKOS.NOTATION, "");
}
/**
* Get SKOS top concepts
*
* @return set of IRIs
*/
public Set<Value> getTopConcepts() {
return objs(SKOS.HAS_TOP_CONCEPT);
}
/**
* Get alternative labels in specific language
*
* @param lang language code
* @return set of strings
*/
public Set<String> getAltLabels(String lang) {
return literals(SKOS.ALT_LABEL, lang);
}
/**
* Get preferred labels in specific language
*
* @param lang language code
* @return set of strings
*/
public Set<String> getPrefLabels(String lang) {
return literals(SKOS.PREF_LABEL, lang);
}
/**
* Get broader matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getBroaders() {
return objs(SKOS.BROADER);
}
/**
* Get narrower matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getNarrowers() {
return objs(SKOS.NARROWER);
}
/**
* Get close matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getCloseMatches() {
return objs(SKOS.CLOSE_MATCH);
}
/**
* Get exact matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getExactMatches() {
return objs(SKOS.EXACT_MATCH);
}
/**
* Get broad matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getBroadMatches() {
return objs(SKOS.BROAD_MATCH);
}
/**
* Get narrow matches
*
* @return set of IRIs or empty set
*/
public Set<Value> getNarrowMatches() {
return objs(SKOS.NARROW_MATCH);
}
/**
* Get SKOS start date
*
* @return start date as string
*/
public String getStartDate() {
String v = literal(SchemaOrg.START_DATE, "");
return (v != null) ? v : "";
}
/**
* Get SKOS end date
*
* @return end date as string
*/
public String getEndDate() {
String v = literal(SchemaOrg.END_DATE, "");
return (v != null) ? v : "";
}
/**
* Constructor
*
* @param m triples
* @param id subject ID
*/
public SkosDAO(Model m, Resource id) {
super(m, id);
}
}
| 23.454545
| 80
| 0.681259
|
fe203680431933e668c65d9ee0f8c3cfa19673df
| 1,031
|
package pl.panryba.mc.sponge.enchant;
import pl.panryba.mc.sponge.interfaces.EnchantSelector;
import pl.panryba.mc.sponge.interfaces.FishItemEnchantment;
import pl.panryba.mc.sponge.interfaces.FishItemStack;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class RandomEnchantSelector implements EnchantSelector {
@Override
public Map<FishItemEnchantment, Integer> select(List<FishItemEnchantment> valid, FishItemStack item) {
Map<FishItemEnchantment, Integer> values = new HashMap<>();
Random randomGenerator = new Random();
int toApplyIndex = randomGenerator.nextInt(valid.size());
FishItemEnchantment toApply = valid.get(toApplyIndex);
if(toApply == null) {
return values;
}
int maxLevel = toApply.getMaxLevel() - toApply.getStartLevel() + 1;
int level = randomGenerator.nextInt(maxLevel) + toApply.getStartLevel();
values.put(toApply, level);
return values;
}
}
| 32.21875
| 106
| 0.71484
|
1282211d8e79273ea0c65b85ed2d5ba6b11fd88c
| 2,271
|
/**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.core.di;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mini2Dx.core.di.bean.SingletonBean;
import org.mini2Dx.core.di.dummy.TestPrototypeBean;
/**
* Unit tests for {@link SingletonBean}
*/
public class SingletonBeanTest {
private TestPrototypeBean singleton;
private SingletonBean bean;
@Before
public void setup() {
singleton = new TestPrototypeBean();
singleton.setIntField(100);
bean = new SingletonBean(singleton);
}
@Test
public void testGetInstance() {
for (int i = 0; i < 100; i++) {
Object result = bean.getInstance();
Assert.assertEquals(true, result != null);
Assert.assertEquals(true, result.equals(singleton));
}
long endTime = System.currentTimeMillis();
}
}
| 49.369565
| 758
| 0.778512
|
20fea997a8147fc995ccc4049e805ce9e81bb47a
| 3,131
|
package com.kiselev.enemy.network.vk.api.request;
import com.kiselev.enemy.network.vk.api.model.Profile;
import com.vk.api.sdk.client.Utils;
import com.vk.api.sdk.objects.users.Fields;
import java.util.Collections;
import java.util.List;
/**
* Query for Users.get method
*/
public class ProfileRequest extends ApiRequest<ProfileRequest, List<Profile>> {
/**
* Creates a ApiRequest instance that can be used to build api request with various parameters
*
* @param token access token
*/
public ProfileRequest(String token) {
super(token, "users.get", Utils.buildParametrizedType(List.class, Profile.class));
}
/**
* user_id
*
* @param value value of "user id" parameter.
* @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern.
*/
public ProfileRequest userId(String value) {
return unsafeParam("user_ids", value);
}
/**
* user_ids
* User IDs or screen names ('screen_name'). By default, current user ID.
*
* @param value value of "user ids" parameter.
* @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern.
*/
public ProfileRequest userIds(String... value) {
return unsafeParam("user_ids", value);
}
/**
* User IDs or screen names ('screen_name'). By default, current user ID.
*
* @param value value of "user ids" parameter.
* @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern.
*/
public ProfileRequest userIds(List<String> value) {
return unsafeParam("user_ids", value);
}
/**
* fields
* Profile fields to return. Sample values: 'nickname', 'screen_name', 'sex', 'bdate' (birthdate), 'city', 'country', 'timezone', 'photo', 'photo_medium', 'photo_big', 'has_mobile', 'contacts', 'education', 'online', 'counters', 'relation', 'last_seen', 'activity', 'can_write_private_message', 'can_see_all_posts', 'can_post', 'universities',
*
* @param value value of "fields" parameter.
* @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern.
*/
public ProfileRequest fields(Fields... value) {
return unsafeParam("fields", value);
}
/**
* Profile fields to return. Sample values: 'nickname', 'screen_name', 'sex', 'bdate' (birthdate), 'city', 'country', 'timezone', 'photo', 'photo_medium', 'photo_big', 'has_mobile', 'contacts', 'education', 'online', 'counters', 'relation', 'last_seen', 'activity', 'can_write_private_message', 'can_see_all_posts', 'can_post', 'universities',
*
* @param value value of "fields" parameter.
* @return a reference to this {@code ApiRequest} object to fulfill the "Builder" pattern.
*/
public ProfileRequest fields(List<Fields> value) {
return unsafeParam("fields", value);
}
@Override
protected ProfileRequest getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Collections.singletonList("access_token");
}
}
| 36.406977
| 347
| 0.657617
|
40cc64975e22ac12cc83a85de70921492dd85252
| 1,530
|
import java.util.HashSet;
import java.util.Set;
class NaturalNumber {
private int naturalNumber;
public NaturalNumber(int naturalNumber) {
if (invalidNaturalNumber(naturalNumber)) {
throw new IllegalArgumentException(
"You must supply a natural number (positive integer)",
new Throwable(Integer.toString(naturalNumber)));
}
this.naturalNumber = naturalNumber;
}
public Classification getClassification() {
int aliquotSum = aliquotSum(naturalNumber);
if (aliquotSum > naturalNumber) {
return Classification.ABUNDANT;
} else if (aliquotSum < naturalNumber) {
return Classification.DEFICIENT;
} else {
return Classification.PERFECT;
}
}
private int aliquotSum(int number) {
return factorsExcludingNumber(number).stream().mapToInt(Integer::intValue).sum();
}
private Set<Integer> factorsExcludingNumber(int number) {
Set<Integer> factorsExcludingNumber = factorsOf(number);
factorsExcludingNumber.remove(number);
return factorsExcludingNumber;
}
private Set<Integer> factorsOf(int number) {
Set<Integer> factors = new HashSet<Integer>();
for (int potentialFactor = 1;
potentialFactor < Math.ceil(Math.sqrt(number));
potentialFactor += 1) {
if (number % potentialFactor == 0) {
factors.add(potentialFactor);
factors.add(number / potentialFactor);
}
}
return factors;
}
private boolean invalidNaturalNumber(int number) {
return number <= 0;
}
}
| 27.321429
| 85
| 0.688235
|
754db965844a69c8ca12b410c8d2dbfa7578fd65
| 711
|
package com.algaworks.curso.jpa2.service;
import java.io.Serializable;
import javax.inject.Inject;
import com.algaworks.curso.jpa2.dao.MotoristaDAO;
import com.algaworks.curso.jpa2.modelo.Motorista;
import com.algaworks.curso.jpa2.util.jpa.Transactional;
public class CadastroMotoristaService implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Inject
private MotoristaDAO motoristaDAO;
@Transactional
public void salvar(Motorista motorista) throws NegocioException {
if (motorista.getNome() == null || motorista.getNome().trim().equals("")) {
throw new NegocioException("Nome do motorista é Obrigatório!");
}
this.motoristaDAO.salvar(motorista);
}
}
| 24.517241
| 77
| 0.767932
|
6f2bbd3b3d03acf05656ee081cfc793ece1a332a
| 5,031
|
package aux;
import java.io.*;
/**
* Created with IntelliJ IDEA.
* User: miroslav
* Date: 6/21/13
* Time: 11:58 AM
*/
public class AnalyzeCSV {
private String file_path;
private int file_length;
private int max_width = Integer.MIN_VALUE;
private int min_width = Integer.MAX_VALUE;
public AnalyzeCSV(String path){
File f = new File(path);
if(!f.exists()){
System.err.println(""+f.getAbsolutePath()+" file does not exist!");
return;
}
file_path = f.getAbsolutePath();
file_length = 0;
String read_line;
// scan the file to check the length
try {
FileInputStream fstream = new FileInputStream(file_path);
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
while ( (read_line = br.readLine()) != null ) {
if(!read_line.trim().startsWith("#")) {
String[] tokens = read_line.split( ",\\s*" );
if(tokens.length>max_width) max_width = tokens.length;
if(tokens.length<min_width) min_width = tokens.length;
file_length++; // # are comments
}
}
br.close();
fstream.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
/*
* reads first col_nr columns of every line
*/
public float[][] readLn(int col_nr){
if(col_nr>min_width){
return null;
}
float[][] cols = new float[file_length][col_nr];
int read_line_number = 0;
// scan the file
try {
FileInputStream fstream = new FileInputStream(file_path);
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
String read_line;
// should loop again the same amount of times it did at the line count
while ((read_line = br.readLine()) != null) {
if(!read_line.trim().startsWith("#")){
String[] tokens = read_line.split( ",\\s*" );
for (int i = 0; i < col_nr; i++) {
cols[read_line_number][i] = Float.valueOf(tokens[i].trim()).floatValue();
}
read_line_number++;
}
} // end looping the file
br.close();
fstream.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
return cols;
}
public double[][] readLnDouble(int col_nr){
if(col_nr>min_width){
return null;
}
double[][] cols = new double[file_length][col_nr];
int read_line_number = 0;
// scan the file
try {
FileInputStream fstream = new FileInputStream(file_path);
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
String read_line;
// should loop again the same amount of times it did at the line count
while ((read_line = br.readLine()) != null) {
if(!read_line.trim().startsWith("#")){
String[] tokens = read_line.split( ",\\s*" );
for (int i = 0; i < col_nr; i++) {
cols[read_line_number][i] = Double.valueOf(tokens[i].trim()).doubleValue();
}
read_line_number++;
}
} // end looping the file
br.close();
fstream.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
return cols;
}
/*
* read last column of every line
*/
public int[] readLastCol(){
if(max_width!=min_width){
System.out.println("Warning: Lines have different lengths! in file "+file_path);
}
int[] col = new int[file_length];
int read_line_number = 0;
// scan the file
try {
FileInputStream fstream = new FileInputStream(file_path);
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
String read_line;
// should loop again the same amount of times it did at the line count
while ((read_line = br.readLine()) != null) {
if(!read_line.trim().startsWith("#")){
String[] tokens = read_line.split( ",\\s*" );
col[read_line_number] = Integer.valueOf(tokens[tokens.length-1].trim()).intValue();
read_line_number++;
}
} // end looping the file
br.close();
fstream.close();
}
catch (Exception e){
System.err.println("Error scanning the csv file: " + e.getMessage());
}
return col;
}
public int getLinesNr(){
return file_length;
}
public int getMaxWidth(){
return max_width;
}
public int getMinWidth(){
return min_width;
}
}
| 26.478947
| 107
| 0.543431
|
c10d854a6f3b6741dbb4efc7b22f689f6a1ba46d
| 420
|
package com.classroom.telus.international.dsu.javacollections.bo;
import com.classroom.telus.international.dsu.javacollections.vo.Animal;
/**
*
* @author geovanni.santos
*/
public interface AnimalInterface {
public void createAnimal(Animal animal);
public Object readAllAnimal();
public void updateAnimal(Animal aold, Animal anew);
public void deleteAnimal(Animal animal);
}
| 21
| 72
| 0.72381
|
6f8c814bc49a81ee852fb63143c7c95f747dfc58
| 2,680
|
package www.dander.com.menutestdemo;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "You click Button", Toast.LENGTH_SHORT).show();
// finish();
// Intent intent = new Intent("com.example.activitytest.ACTION_START");
// intent.addCategory("com.example.activitytest.MY_CATEGORY");
// startActivity(intent);
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setData(Uri.parse("http://www.baidu.com"));
// startActivity(intent);
// String data = "Hello Main3Activity";
// Intent intent = new Intent(MainActivity.this, Main3Activity.class);
// intent.putExtra("extra_data", data);
// startActivity(intent);
Intent intent1 = new Intent(MainActivity.this, Main3Activity.class);
startActivityForResult(intent1, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String dataBack = data.getStringExtra("data_return");
Log.d("MainActivity", dataBack);
}
break;
default:
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
Toast.makeText(this, "You click add item", Toast.LENGTH_SHORT).show();
break;
case R.id.remove_item:
Toast.makeText(this, "You click remove item", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
| 27.070707
| 96
| 0.593657
|
5dc5927aab215beedb94fba0f440ff4ecaf194f0
| 1,004
|
package nyla.solutions.commas.remote.partitioning;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Collection;
import nyla.solutions.commas.CommandFacts;
public interface CommasRemoteRegistry<KeyType,LocationType> extends Remote
{
/**
*
* @param key the routing key
* @param commandFacts the Command facts
* @return
* @throws RemoteException
*/
LocationType whereIs(KeyType key, CommandFacts commandFacts)
throws RemoteException;
void registerKey(KeyType key, CommandFacts commandFacts, LocationType location )
throws RemoteException;
//TODO: may add to add command facts
public void registerLocation(LocationType location)
throws RemoteException;
public Collection<LocationType> listRegisteredLocations()
throws RemoteException;
/**
* Unregister a location
* @param location remote all references to the location
* @throws RemoteException
*/
public void unregisterLocation(LocationType location)
throws RemoteException;
}
| 22.818182
| 81
| 0.77988
|
372baac369c462d774e480c9a223e0263bf482af
| 2,845
|
package org.nrg.containers.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import org.nrg.framework.orm.hibernate.AbstractHibernateEntity;
import javax.persistence.Entity;
import java.util.Objects;
@Entity
public class CommandEventMapping extends AbstractHibernateEntity {
@JsonProperty("event-type") private String eventType;
@JsonProperty("command-id") private Long commandId;
@JsonProperty("xnat-command-wrapper") private String xnatCommandWrapperName;
@JsonProperty("project") private String projectId;
@JsonProperty("subscription-user-name") private String subscriptionUserName;
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public Long getCommandId() {
return commandId;
}
public void setCommandId(Long commandId) {
this.commandId = commandId;
}
public String getXnatCommandWrapperName() {
return xnatCommandWrapperName;
}
public void setXnatCommandWrapperName(final String xnatCommandWrapperName) {
this.xnatCommandWrapperName = xnatCommandWrapperName;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(final String projectId) {
this.projectId = projectId;
}
public String getSubscriptionUserName() {
return subscriptionUserName;
}
public void setSubscriptionUserName(String subscriptionUserName) {
this.subscriptionUserName = subscriptionUserName;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
final CommandEventMapping that = (CommandEventMapping) o;
return Objects.equals(this.eventType, that.eventType) &&
Objects.equals(this.commandId, that.commandId) &&
Objects.equals(this.xnatCommandWrapperName, that.xnatCommandWrapperName) &&
Objects.equals(this.projectId, that.projectId) &&
Objects.equals(this.subscriptionUserName, that.subscriptionUserName);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), eventType, commandId, xnatCommandWrapperName, projectId, subscriptionUserName);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("eventType", eventType)
.add("commandId", commandId)
.add("xnatCommandWrapper", xnatCommandWrapperName)
.add("projectId", projectId)
.add("subscriptionUserName", subscriptionUserName)
.toString();
}
}
| 31.966292
| 125
| 0.679789
|
1f6faa5653c8ac0018c864e0d9aa9317d35aa066
| 724
|
/*
* Project Workday Connector
* (c) 2019-2020 VMware, Inc. All rights reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
package com.vmware.ws1connectors.workday.web.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class WorkdayResource<T> {
private int total;
private List<T> data;
public boolean hasData() {
return this.total > 0 && !CollectionUtils.isEmpty(this.data);
}
}
| 24.133333
| 69
| 0.767956
|
393b9860159fdfd9130480bad1ed7c8b7544b6d0
| 1,072
|
package com.uprint.android_pack.cloudprint4androidmanager.utils;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
/**
* Created by zhangxiaang on 15/11/27.
* 获取本地app版本的工具
*/
public class CPackageManageUtils {
public static int getAppVersion(Context context) {
int version = -1;
try {
version = context.getPackageManager().getPackageInfo("com.uprint.android_pack.cloudprint4androidmanager", 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
Log.e("NameNotFoundException", e.toString());
}
return version;
}
public static String getAppVersionName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(
"com.uprint.android_pack.cloudprint4androidmanager", 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
Log.e("NameNotFoundException", e.getMessage());
}
return verName;
}
}
| 32.484848
| 133
| 0.66791
|
3c186978871d31427b1e149abfa69a10bbd9758a
| 472
|
package org.onetwo.common.convert;
public interface TypeConvert<T> {
/****
*
* @author weishao zeng
* @param source
* @param componentType
* @return 如果source为null,则返回配置的默认值
*/
public T convertNotNull(Object source, Class<?> componentType);
/****
* 当目标类型为基本类型时,如果source为null,则返回配置的基本类型的默认值
* 否则,返回null
* @author weishao zeng
* @param source
* @param componentType
* @return
*/
public T convert(Object source, Class<?> componentType);
}
| 18.88
| 64
| 0.684322
|
7719e6da929726c8023e30f952f0792e7835d5db
| 172
|
package com.example.webappboilerplate.security;
public final class Roles {
public static final String USER = "USER";
public static final String ADMIN = "ADMIN";
}
| 24.571429
| 47
| 0.738372
|
d3f238fd07346054290aa433ea836785f84d90d3
| 5,555
|
package hu.arheu.gds.message.data.impl;
import hu.arheu.gds.message.data.EventSubResultHolder;
import hu.arheu.gds.message.util.*;
import org.msgpack.core.MessageBufferPacker;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.Value;
import org.msgpack.value.ValueType;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class EventSubResultHolderImpl implements EventSubResultHolder {
private final AckStatus subStatus;
private final String id;
private final String tableName;
private final Boolean created;
private final String version;
private final List<Value> recordValues;
public EventSubResultHolderImpl(AckStatus subStatus,
String id,
String tableName,
Boolean created,
String version,
List<Value> recordValues) {
this.subStatus = subStatus;
this.id = id;
this.tableName = tableName;
this.created = created;
this.version = version;
this.recordValues = recordValues;
checkContent(this);
}
private static void checkContent(EventSubResultHolderImpl eventSubResult) {
ExceptionHelper.requireNonNullValue(eventSubResult.getSubStatus(), eventSubResult.getClass().getSimpleName(),
"sub status");
}
@Override
public AckStatus getSubStatus() {
return this.subStatus;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getTableName() {
return this.tableName;
}
@Override
public Boolean getCreated() {
return this.created;
}
@Override
public String getVersion() {
return this.version;
}
@Override
public List<Value> getRecordValues() {
return this.recordValues;
}
@Override
public void packContent(MessageBufferPacker packer) throws IOException, ValidationException {
WriterHelper.packArrayHeader(packer, 6);
WriterHelper.packValue(packer, this.subStatus == null ? null : this.subStatus.getValue());
WriterHelper.packValue(packer, this.id);
WriterHelper.packValue(packer, this.tableName);
WriterHelper.packValue(packer, this.created);
WriterHelper.packValue(packer, version);
WriterHelper.packValueValues(packer, this.recordValues);
}
public static EventSubResultHolderImpl unpackContent(MessageUnpacker unpacker) throws ReadException, IOException {
if (!ReaderHelper.nextExpectedValueTypeIsNil(unpacker, ValueType.ARRAY, "event sub result",
EventSubResultHolderImpl.class.getSimpleName())) {
ReaderHelper.unpackArrayHeader(unpacker, 6, "event sub result",
EventSubResultHolderImpl.class.getSimpleName());
AckStatus subStatusTemp = AckStatus.valueOf(ReaderHelper.unpackIntegerValue(unpacker, "sub status",
EventSubResultHolderImpl.class.getSimpleName()));
String idTemp = ReaderHelper.unpackStringValue(unpacker, "id",
EventSubResultHolderImpl.class.getSimpleName());
String tableNameTemp = ReaderHelper.unpackStringValue(unpacker, "table name",
EventSubResultHolderImpl.class.getSimpleName());
Boolean createdTemp = ReaderHelper.unpackBooleanValue(unpacker, "created",
EventSubResultHolderImpl.class.getSimpleName());
String versionTemp = ReaderHelper.unpackStringValue(unpacker, "version",
EventSubResultHolderImpl.class.getSimpleName());
List<Value> recordValuesTemp = ReaderHelper.unpackValueValues(unpacker,
null,
"returning record values",
"field value",
EventSubResultHolderImpl.class.getSimpleName());
EventSubResultHolderImpl eventSubResultHolderTemp = new EventSubResultHolderImpl(subStatusTemp,
idTemp,
tableNameTemp,
createdTemp,
versionTemp,
recordValuesTemp);
checkContent(eventSubResultHolderTemp);
return eventSubResultHolderTemp;
} else {
unpacker.unpackNil();
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EventSubResultHolderImpl)) return false;
EventSubResultHolderImpl that = (EventSubResultHolderImpl) o;
return subStatus == that.subStatus &&
Objects.equals(id, that.id) &&
Objects.equals(tableName, that.tableName) &&
Objects.equals(created, that.created) &&
Objects.equals(version, that.version) &&
Objects.equals(recordValues, that.recordValues);
}
@Override
public int hashCode() {
return Objects.hash(subStatus, id, tableName, created, version, recordValues);
}
@Override
public String toString() {
return "EventSubResultHolderImpl{" +
"subStatus=" + subStatus +
", id='" + id + '\'' +
", tableName='" + tableName + '\'' +
", created=" + created +
", version=" + version +
", recordValues=" + recordValues +
'}';
}
}
| 35.608974
| 118
| 0.618722
|
d8cfb130653c5dcbb231c43b0f35c2a7a7a8566a
| 259
|
package ru.otus.homework.domain.quiz;
import lombok.Data;
import ru.otus.homework.domain.user.User;
import java.util.ArrayList;
import java.util.List;
@Data
public class Quiz {
private User user;
private List<Answer> answers = new ArrayList<>();
}
| 18.5
| 53
| 0.741313
|
fc78603cbbf9e78fa4afc78ed07c787be54806e6
| 1,061
|
package org.spongepowered.asm.mixin.transformer;
import org.spongepowered.asm.lib.*;
class MixinPostProcessor$1 extends ClassVisitor {
final /* synthetic */ MixinPostProcessor this$0;
MixinPostProcessor$1(final MixinPostProcessor a1, final int a2, final ClassVisitor a3) {
this.this$0 = a1;
super(a2, a3);
}
@Override
public void visit(final int a1, final int a2, final String a3, final String a4, final String a5, final String[] a6) {
super.visit(a1, a2 | 0x1, a3, a4, a5, a6);
}
@Override
public FieldVisitor visitField(int a1, final String a2, final String a3, final String a4, final Object a5) {
if ((a1 & 0x6) == 0x0) {
a1 |= 0x1;
}
return super.visitField(a1, a2, a3, a4, a5);
}
@Override
public MethodVisitor visitMethod(int a1, final String a2, final String a3, final String a4, final String[] a5) {
if ((a1 & 0x6) == 0x0) {
a1 |= 0x1;
}
return super.visitMethod(a1, a2, a3, a4, a5);
}
}
| 32.151515
| 121
| 0.606975
|
619130cd27da2ed1a95914e8deb5dc9d51c0fa49
| 2,733
|
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.diagnostics.analyzer;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.boot.context.properties.bind.UnboundConfigurationPropertiesException;
import org.springframework.boot.context.properties.source.ConfigurationProperty;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;
/**
* An {@link AbstractFailureAnalyzer} that performs analysis of failures caused by any
* {@link UnboundConfigurationPropertiesException}.
*
* @author Madhura Bhave
*/
class UnboundConfigurationPropertyFailureAnalyzer
extends AbstractFailureAnalyzer<UnboundConfigurationPropertiesException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
UnboundConfigurationPropertiesException cause) {
BindException exception = findCause(rootFailure, BindException.class);
return analyzeUnboundConfigurationPropertiesException(exception, cause);
}
private FailureAnalysis analyzeUnboundConfigurationPropertiesException(
BindException cause, UnboundConfigurationPropertiesException exception) {
StringBuilder description = new StringBuilder(
String.format("Binding to target %s failed:%n", cause.getTarget()));
for (ConfigurationProperty property : exception.getUnboundProperties()) {
buildDescription(description, property);
description.append(String.format("%n Reason: %s", exception.getMessage()));
}
return getFailureAnalysis(description, cause);
}
private void buildDescription(StringBuilder description,
ConfigurationProperty property) {
if (property != null) {
description.append(String.format("%n Property: %s", property.getName()));
description.append(String.format("%n Value: %s", property.getValue()));
description.append(String.format("%n Origin: %s", property.getOrigin()));
}
}
private FailureAnalysis getFailureAnalysis(Object description, BindException cause) {
return new FailureAnalysis(description.toString(),
"Update your application's configuration", cause);
}
}
| 40.791045
| 96
| 0.786315
|
6290fff20bff565cdd9e0973a4186c7c9a064295
| 1,182
|
package gov.nih.nci.evs.reportwriter.core.model.evs;
public class EvsSynonym {
private String code;
private String label;
private String termName;
private String termGroup;
private String termSource;
private String sourceCode;
private String subSourceName;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getTermName() {
return termName;
}
public void setTermName(String termName) {
this.termName = termName;
}
public String getTermGroup() {
return termGroup;
}
public void setTermGroup(String termGroup) {
this.termGroup = termGroup;
}
public String getTermSource() {
return termSource;
}
public void setTermSource(String termSource) {
this.termSource = termSource;
}
public String getSourceCode() {
return sourceCode;
}
public void setSourceCode(String sourceCode) {
this.sourceCode = sourceCode;
}
public String getSubSourceName() {
return subSourceName;
}
public void setSubSourceName(String subSourceName) {
this.subSourceName = subSourceName;
}
}
| 21.490909
| 53
| 0.741117
|
2e5b5845da1b4def862ee9b452d33652c70c4bd0
| 1,915
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jrh3k5.mojo.flume;
import java.util.Collections;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import com.github.jrh3k5.mojo.flume.process.AgentProcessContainer;
/**
* A mojo used to stop Flume agents.
*
* @author Joshua Hyde
* @since 2.0
*/
@Mojo(name = "stop", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST)
public class StopFlumeAgentsMojo extends AbstractMojo {
/**
* The configuration of agents to be run, expressed as {@link Agent} objects.
*/
@Parameter(required = true)
private List<Agent> agents = Collections.emptyList();
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
for (Agent agent : agents) {
AgentProcessContainer.stopAgentProcess(agent.getAgentName());
}
}
}
| 35.462963
| 81
| 0.749869
|
b7ec01eeb057f6b66d9556a0b90f63888ad1bbe9
| 3,210
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2013 Ausenco Engineering Canada Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.CalculationObjects;
import com.jaamsim.ProbabilityDistributions.Distribution;
import com.jaamsim.Samples.SampleConstant;
import com.jaamsim.Samples.SampleExpInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.ValueInput;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.units.TimeUnit;
import com.jaamsim.units.Unit;
import com.jaamsim.units.UserSpecifiedUnit;
/**
* The Integrator returns the integral of the input values.
* @author Harry King
*
*/
public class Integrator extends DoubleCalculation {
@Keyword(description = "The initial value for the integral at time = 0.",
example = "Integrator-1 InitialValue { 5.5 }")
private final ValueInput initialValue;
@Keyword(description = "The time scale for the integration: integral = InitialValue + 1/IntegralTime * integral(x)\n" +
"The input can be a number or an entity that returns a number, such as a CalculationObject, ProbabilityDistribution, or a TimeSeries.",
example = "Integrator-1 IntegralTime { 5 s }")
protected final SampleExpInput integralTime;
private double lastUpdateTime; // The time at which the last update was performed
private double integral; // The present value for the integral
{
controllerRequired = true;
initialValue = new ValueInput( "InitialValue", "Key Inputs", 0.0d);
initialValue.setUnitType(UserSpecifiedUnit.class);
this.addInput( initialValue);
integralTime = new SampleExpInput( "IntegralTime", "Key Inputs", new SampleConstant(TimeUnit.class, 1.0));
integralTime.setUnitType(TimeUnit.class);
integralTime.setEntity(this);
this.addInput( integralTime);
}
@Override
protected boolean repeatableInputs() {
return super.repeatableInputs()
&& ! (integralTime.getValue() instanceof Distribution);
}
@Override
protected void setUnitType(Class<? extends Unit> ut) {
super.setUnitType(ut);
initialValue.setUnitType(ut);
FrameBox.reSelectEntity(); // Update the units in the Output Viewer
}
@Override
public void earlyInit() {
super.earlyInit();
lastUpdateTime = 0.0;
integral = 0.0;
}
@Override
protected double calculateValue(double simTime) {
double dt = simTime - lastUpdateTime;
double scale = integralTime.getValue().getNextSample(simTime);
return ( integral + this.getInputValue(simTime) * dt )/scale + initialValue.getValue();
}
@Override
public void update(double simTime) {
super.update(simTime);
double dt = simTime - lastUpdateTime;
integral += this.getInputValue(simTime) * dt;
lastUpdateTime = simTime;
}
}
| 33.092784
| 138
| 0.747975
|
a4905d590f740775f8063f9a739a0e870424c131
| 2,915
|
package io.aftersound.weave.service.request;
import io.aftersound.weave.common.NamedType;
import io.aftersound.weave.service.message.Message;
import io.aftersound.weave.service.message.MessageRegistry;
import io.aftersound.weave.service.message.Messages;
import io.aftersound.weave.service.metadata.param.Enforcement;
import io.aftersound.weave.service.metadata.param.ParamField;
import io.aftersound.weave.service.metadata.param.Validation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Validator that validates if a given value, or a set of values, is in allowed value set
*/
public class AllowedValuesValidator implements Validator {
public static final NamedType<Validation> COMPANION_CONTROL_TYPE = AllowedValuesValidation.TYPE;
@Override
public String getType() {
return COMPANION_CONTROL_TYPE.name();
}
@Override
public Messages validate(ParamField paramField, List<String> values) {
Messages messages = new Messages();
// This validation is not responsible for checking Required or not,
// only values
if (values == null || values.isEmpty()) {
return messages;
}
AllowedValuesValidation validation = paramField.validation();
List<String> unexpected = new ArrayList<>();
Set<String> allowed = validation.getValueSet();
if (allowed == null || allowed.isEmpty()) {
// typically, this means given ParamField has problem, not values
// anyway, give out error as if values have problems
unexpected.addAll(values);
} else {
for (String value : values) {
if (!allowed.contains(value)) {
unexpected.add(value);
}
}
}
if (unexpected.size() > 0) {
Message message;
if (validation.getEnforcement() == Enforcement.Strong) {
message = MessageRegistry.INVALID_PARAMETER_VALUE.error(
paramField.getName(),
paramField.getParamType().name(),
toString(unexpected)
);
} else {
message = MessageRegistry.INVALID_PARAMETER_VALUE.warning(
paramField.getName(),
paramField.getParamType().name(),
toString(unexpected)
);
}
messages.addMessage(message);
}
return messages;
}
private String toString(List<String> values) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String v : values) {
if (!isFirst) {
sb.append('|');
} else {
isFirst = false;
}
sb.append(v);
}
return sb.toString();
}
}
| 31.684783
| 100
| 0.591081
|
d89513a0a3c4f6f187722e7684d774788d94767d
| 2,766
|
/*
* -----------------------------------------------------------------------
* Copyright 2012 - Alistair Rutherford - www.netthreads.co.uk
* -----------------------------------------------------------------------
*
* 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.netthreads.gdx.app.scene;
import com.netthreads.gdx.app.layer.ControlLayer;
import com.netthreads.gdx.app.layer.FpsLayer;
import com.netthreads.gdx.app.layer.FadeLabelLayer;
import com.netthreads.gdx.app.layer.SimulationLayer;
import com.netthreads.libgdx.scene.Layer;
import com.netthreads.libgdx.scene.Scene;
/**
* Application scene.
*
*/
public class AppScene extends Scene
{
private Layer controlLayer;
private SimulationLayer simulationLayer;
private Layer labelLayer;
private Layer fpsLayer;
/**
* Application scene.
*
*/
public AppScene()
{
// ---------------------------------------------------------------
// Control layer
// ---------------------------------------------------------------
controlLayer = new ControlLayer();
getInputMultiplexer().addProcessor(controlLayer);
addLayer(controlLayer);
// ---------------------------------------------------------------
// FPS layer.
// ---------------------------------------------------------------
fpsLayer = new FpsLayer(getWidth(), getHeight());
addLayer(fpsLayer);
// ---------------------------------------------------------------
// Label layer.
// ---------------------------------------------------------------
labelLayer = new FadeLabelLayer(getWidth(), getHeight());
// Route input events to layer.
getInputMultiplexer().addProcessor(labelLayer);
addLayer(labelLayer);
// ---------------------------------------------------------------
// Simulation layer.
// ---------------------------------------------------------------
simulationLayer = new SimulationLayer(getWidth(), getHeight());
// Route input events to layer.
getInputMultiplexer().addProcessor(labelLayer);
addLayer(simulationLayer);
}
/**
* Dispose of stuff which might have been created and required for
* application but needs to be cleaned up now.
*
*/
public void cleanup()
{
simulationLayer.cleanupView(true);
}
}
| 29.741935
| 75
| 0.541938
|
c838cc7fda4e271a19fa4ca785ddb5d14adf5a37
| 385
|
package com.example.demo.observer.mouse;
import com.example.demo.observer.core.Event;
/**
* Created by czy0218 on 2020/3/9.
*/
public class MouseEventCallback {
public void onClick(Event e) {
System.out.println("单机后触发");
System.out.println("==单击事件==\n" + e);
}
public void onDoubleClick(Event e) {
System.out.println("==双击事件==\n" + e);
}
}
| 21.388889
| 45
| 0.625974
|
f18b61ce40784333db948a150c628a3ef0f18912
| 1,629
|
package com.firebase.authwrapper.resultactivity.types.google;
import com.firebase.authwrapper.providers.types.GoogleProvider;
import com.firebase.authwrapper.resultactivity.common.ActivityInvoker;
import com.google.android.gms.common.api.GoogleApiClient;
/**
* <p>
* This class is the facebook implementation of class {@link ActivityInvoker
* ActivityInvoker} object. It contains method and properties relevant for
* authentication by using Google API.
* </p>
* <p>
* This singleton class is used for binding the
* {@link GoogleProvider FacebookProvider} to
* {@link GoogleResultActivity FacebookResultActivity}.
* </p>
*
* @author ron barnoy
* @version 1.0
* @since 10-5-2018
* @see ActivityInvoker
*/
public class GoogleActivityInvoker extends ActivityInvoker {
private GoogleApiClient googleApiClient;
private GoogleActivityInvoker() {}
private static GoogleActivityInvoker googleActivityInvoker = new
GoogleActivityInvoker();
/**
* Getter of this class singleton instance
* @return the single instance of this class
*/
public static GoogleActivityInvoker getInstance(){
return googleActivityInvoker;
}
/**
* Setter of GoogleApiClient
* @param googleApiClient sets this class GoogleApiClient object.
*/
public void setGoogleApiClient(GoogleApiClient googleApiClient){
this.googleApiClient = googleApiClient;
}
/**
* Getter of google GoogleApiClient
* @return google GoogleApiClient object
*/
public GoogleApiClient getGoogleApiClient(){
return this.googleApiClient;
}
}
| 27.610169
| 76
| 0.726826
|
5d48cc4a2cae8b74bca37b757e3c06e4654cd41b
| 3,888
|
package com.google.gson;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.bind.TypeAdapters;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class GsonBuilder {
private boolean complexMapKeySerialization = false;
private String datePattern;
private int dateStyle = 2;
private boolean escapeHtmlChars = true;
private Excluder excluder = Excluder.DEFAULT;
private final List<TypeAdapterFactory> factories = new ArrayList();
private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
private boolean generateNonExecutableJson = false;
private final List<TypeAdapterFactory> hierarchyFactories = new ArrayList();
private final Map<Type, InstanceCreator<?>> instanceCreators = new HashMap();
private boolean lenient = false;
private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT;
private boolean prettyPrinting = false;
private boolean serializeNulls = false;
private boolean serializeSpecialFloatingPointValues = false;
private int timeStyle = 2;
public GsonBuilder setLenient() {
this.lenient = true;
return this;
}
public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory typeAdapterFactory) {
this.factories.add(typeAdapterFactory);
return this;
}
public Gson create() {
ArrayList arrayList = r1;
ArrayList arrayList2 = new ArrayList(this.factories.size() + this.hierarchyFactories.size() + 3);
arrayList2.addAll(this.factories);
Collections.reverse(arrayList2);
ArrayList arrayList3 = new ArrayList(this.hierarchyFactories);
Collections.reverse(arrayList3);
arrayList2.addAll(arrayList3);
addTypeAdaptersForDate(this.datePattern, this.dateStyle, this.timeStyle, arrayList2);
return new Gson(this.excluder, this.fieldNamingPolicy, this.instanceCreators, this.serializeNulls, this.complexMapKeySerialization, this.generateNonExecutableJson, this.escapeHtmlChars, this.prettyPrinting, this.lenient, this.serializeSpecialFloatingPointValues, this.longSerializationPolicy, this.datePattern, this.dateStyle, this.timeStyle, this.factories, this.hierarchyFactories, arrayList);
}
private void addTypeAdaptersForDate(String str, int i, int i2, List<TypeAdapterFactory> list) {
DefaultDateTypeAdapter defaultDateTypeAdapter;
DefaultDateTypeAdapter defaultDateTypeAdapter2;
DefaultDateTypeAdapter defaultDateTypeAdapter3;
if (str != null && !"".equals(str.trim())) {
defaultDateTypeAdapter2 = new DefaultDateTypeAdapter(Date.class, str);
defaultDateTypeAdapter = new DefaultDateTypeAdapter(Timestamp.class, str);
defaultDateTypeAdapter3 = new DefaultDateTypeAdapter(java.sql.Date.class, str);
} else if (i != 2 && i2 != 2) {
DefaultDateTypeAdapter defaultDateTypeAdapter4 = new DefaultDateTypeAdapter(Date.class, i, i2);
DefaultDateTypeAdapter defaultDateTypeAdapter5 = new DefaultDateTypeAdapter(Timestamp.class, i, i2);
DefaultDateTypeAdapter defaultDateTypeAdapter6 = new DefaultDateTypeAdapter(java.sql.Date.class, i, i2);
defaultDateTypeAdapter2 = defaultDateTypeAdapter4;
defaultDateTypeAdapter = defaultDateTypeAdapter5;
defaultDateTypeAdapter3 = defaultDateTypeAdapter6;
} else {
return;
}
list.add(TypeAdapters.newFactory(Date.class, defaultDateTypeAdapter2));
list.add(TypeAdapters.newFactory(Timestamp.class, defaultDateTypeAdapter));
list.add(TypeAdapters.newFactory(java.sql.Date.class, defaultDateTypeAdapter3));
}
}
| 50.493506
| 403
| 0.744084
|
8482e514867a42f227a83a4deb1ae72b0dccee7a
| 3,410
|
/*
* Isilon SDK
* Isilon SDK - Language bindings for the OneFS API
*
* OpenAPI spec version: 5
* Contact: sdk@isilon.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* SettingsKrb5DomainsDomainItem
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-04-19T15:41:52.549-07:00")
public class SettingsKrb5DomainsDomainItem {
@SerializedName("domain")
private String domain = null;
@SerializedName("id")
private String id = null;
@SerializedName("realm")
private String realm = null;
public SettingsKrb5DomainsDomainItem domain(String domain) {
this.domain = domain;
return this;
}
/**
* Specifies the name of the domain.
* @return domain
**/
@ApiModelProperty(value = "Specifies the name of the domain.")
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public SettingsKrb5DomainsDomainItem id(String id) {
this.id = id;
return this;
}
/**
* ID of the domain
* @return id
**/
@ApiModelProperty(value = "ID of the domain")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SettingsKrb5DomainsDomainItem realm(String realm) {
this.realm = realm;
return this;
}
/**
* Specifies the name of the realm.
* @return realm
**/
@ApiModelProperty(value = "Specifies the name of the realm.")
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SettingsKrb5DomainsDomainItem settingsKrb5DomainsDomainItem = (SettingsKrb5DomainsDomainItem) o;
return Objects.equals(this.domain, settingsKrb5DomainsDomainItem.domain) &&
Objects.equals(this.id, settingsKrb5DomainsDomainItem.id) &&
Objects.equals(this.realm, settingsKrb5DomainsDomainItem.realm);
}
@Override
public int hashCode() {
return Objects.hash(domain, id, realm);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SettingsKrb5DomainsDomainItem {\n");
sb.append(" domain: ").append(toIndentedString(domain)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" realm: ").append(toIndentedString(realm)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 24.357143
| 125
| 0.678299
|
81972a5791659c2bd7c39ac1f4b156e6cb5d61e0
| 3,537
|
package br.com.basis.madre.madreexames.service;
import br.com.basis.madre.madreexames.domain.Sinonimo;
import br.com.basis.madre.madreexames.repository.SinonimoRepository;
import br.com.basis.madre.madreexames.repository.search.SinonimoSearchRepository;
import br.com.basis.madre.madreexames.service.dto.SinonimoDTO;
import br.com.basis.madre.madreexames.service.mapper.SinonimoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
/**
* Service Implementation for managing {@link Sinonimo}.
*/
@Service
@Transactional
public class SinonimoService {
private final Logger log = LoggerFactory.getLogger(SinonimoService.class);
private final SinonimoRepository sinonimoRepository;
private final SinonimoMapper sinonimoMapper;
private final SinonimoSearchRepository sinonimoSearchRepository;
public SinonimoService(SinonimoRepository sinonimoRepository, SinonimoMapper sinonimoMapper, SinonimoSearchRepository sinonimoSearchRepository) {
this.sinonimoRepository = sinonimoRepository;
this.sinonimoMapper = sinonimoMapper;
this.sinonimoSearchRepository = sinonimoSearchRepository;
}
/**
* Save a sinonimo.
*
* @param sinonimoDTO the entity to save.
* @return the persisted entity.
*/
public SinonimoDTO save(SinonimoDTO sinonimoDTO) {
log.debug("Request to save Sinonimo : {}", sinonimoDTO);
Sinonimo sinonimo = sinonimoMapper.toEntity(sinonimoDTO);
sinonimo = sinonimoRepository.save(sinonimo);
SinonimoDTO result = sinonimoMapper.toDto(sinonimo);
sinonimoSearchRepository.save(sinonimo);
return result;
}
/**
* Get all the sinonimos.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<SinonimoDTO> findAll(Pageable pageable) {
log.debug("Request to get all Sinonimos");
return sinonimoRepository.findAll(pageable)
.map(sinonimoMapper::toDto);
}
/**
* Get one sinonimo by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<SinonimoDTO> findOne(Long id) {
log.debug("Request to get Sinonimo : {}", id);
return sinonimoRepository.findById(id)
.map(sinonimoMapper::toDto);
}
/**
* Delete the sinonimo by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete Sinonimo : {}", id);
sinonimoRepository.deleteById(id);
sinonimoSearchRepository.deleteById(id);
}
/**
* Search for the sinonimo corresponding to the query.
*
* @param query the query of the search.
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<SinonimoDTO> search(String query, Pageable pageable) {
log.debug("Request to search for a page of Sinonimos for query {}", query);
return sinonimoSearchRepository.search(queryStringQuery(query), pageable)
.map(sinonimoMapper::toDto);
}
}
| 33.056075
| 149
| 0.705683
|
2d4453939fb8879e8d82f0e7cbfb4dcaa928cb8e
| 2,165
|
package gov.hhs.onc.dcdt.crypto.certs.impl;
import gov.hhs.onc.dcdt.beans.impl.AbstractToolBean;
import gov.hhs.onc.dcdt.beans.utils.ToolBeanFactoryUtils;
import gov.hhs.onc.dcdt.crypto.certs.CertificateInfo;
import gov.hhs.onc.dcdt.crypto.certs.CertificateValidator;
import gov.hhs.onc.dcdt.crypto.certs.CertificateValidatorContext;
import gov.hhs.onc.dcdt.mail.MailAddress;
import gov.hhs.onc.dcdt.utils.ToolValidationUtils;
import gov.hhs.onc.dcdt.validation.impl.ToolValidatorFactory;
import javax.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
@Component("certValidatorImpl")
public class CertificateValidatorImpl extends AbstractToolBean implements CertificateValidator {
@Resource(name = "validatorFactory")
protected ToolValidatorFactory validatorFactory;
@Resource(name = "messageSourceValidation")
private MessageSource msgSourceValidation;
private AbstractApplicationContext appContext;
@Override
public CertificateValidatorContext validate(MailAddress directAddr, CertificateInfo certInfo) {
CertificateValidatorContext certValidatorContext =
ToolBeanFactoryUtils.createBeanOfType(this.appContext, CertificateValidatorContext.class, directAddr, certInfo);
BindingResult certBindingResult = ToolValidationUtils.bind(this.validatorFactory, certValidatorContext, CertificateValidatorConstraintGroup.class);
if (certBindingResult.hasErrors()) {
// noinspection ConstantConditions
certValidatorContext.getMessages().addAll(ToolValidationUtils.buildErrorMessages(this.msgSourceValidation, certBindingResult.getAllErrors()));
}
return certValidatorContext;
}
@Override
public void setApplicationContext(ApplicationContext appContext) throws BeansException {
this.appContext = ((AbstractApplicationContext) appContext);
}
}
| 45.104167
| 155
| 0.8097
|
d11061a7d113cbbb10cb1b0f696f0ffbcc3d92a5
| 582
|
package com.fangm.demo.crashhandler;
import android.app.Application;
import com.fangm.app.crashhandler.CrashHandler;
import com.fangm.app.crashhandler.impl.CrashLogServiceImpl;
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CrashHandler.init(new CrashHandler.Builder(this));
// CrashHandler.init(new CrashHandler.Builder(this)
// .setCrashLogService(new CrashLogServiceImpl())
// .setCrashTips("很抱歉,程序出现异常,即将退出")
// .build()
// );
}
}
| 29.1
| 64
| 0.666667
|
c97e486bec4bfe88c00fd14eb42676b2d0a42ef3
| 4,448
|
package data;
import java.time.LocalDate;
import ui.utils.IListable;
public class Client extends Personne implements IListable {
private int id;
private String adresse;
private String numeroPermis;
private String numeoTelphone;
private String courriel;
private String note;
private LocalDate dateDeNaissance;
public String getAdresse() {
return this.adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getNumeroPermis() {
return this.numeroPermis;
}
public void setNumeroPermis(String numeroPermis) {
this.numeroPermis = numeroPermis;
}
public String getNumeoTelphone() {
return this.numeoTelphone;
}
public void setNumeoTelphone(String numeoTelphone) {
this.numeoTelphone = numeoTelphone;
}
public String getCourriel() {
return this.courriel;
}
public void setCourriel(String courriel) {
this.courriel = courriel;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public LocalDate getDateDeNaissance() {
return this.dateDeNaissance;
}
public void setDateDeNaissance(LocalDate dateDeNaissance) {
this.dateDeNaissance = dateDeNaissance;
}
/**
* Constructeur pour Client lors de la réservation
*
* @param nom
* nom du client.
* @param prenom
* prénom du client.
* @param numeoTelphone
* numéro de téléphone du client.
* @param note
* commentaire.
*/
public Client(String nom, String prenom, String numeoTelphone, String note) {
super(nom, prenom);
this.numeoTelphone = numeoTelphone;
this.note = note;
this.adresse = "";
this.numeroPermis = "";
this.courriel = "";
this.dateDeNaissance = null;
}
/**
* Constructeur pour Client
*
* @param nom
* nom du client.
* @param prenom
* prénom du client.
* @param id
* id du client.
* @param adresse
* adresse du client.
* @param numeroPermis
* numéro de permis du client.
* @param numeoTelphone
* numéro de téléphone du client.
* @param courriel
* courriel du client.
* @param note
* commentaire.
* @param dateDeNaissance
* date de naissance.
*/
public Client(String nom, String prenom, int id, String adresse, String numeroPermis,
String numeoTelphone, String courriel, String note, LocalDate dateDeNaissance) {
super(nom, prenom);
this.id = id;
this.adresse = adresse;
this.numeroPermis = numeroPermis;
this.numeoTelphone = numeoTelphone;
this.courriel = courriel;
this.note = note;
this.dateDeNaissance = dateDeNaissance;
}
/**
* Constructeur pour Client à la création
*
* @param nom
* nom du client.
* @param prenom
* prénom du client.
* @param adresse
* adresse du client.
* @param numeroPermis
* numéro de permis du client.
* @param numeoTelphone
* numéro de téléphone du client.
* @param courriel
* courriel du client.
* @param note
* commentaire.
* @param dateDeNaissance
* date de naissance.
*/
public Client(String nom, String prenom, String adresse, String numeroPermis,
String numeoTelphone, String courriel, String note, LocalDate dateDeNaissance) {
super(nom, prenom);
this.adresse = adresse;
this.numeroPermis = numeroPermis;
this.numeoTelphone = numeoTelphone;
this.courriel = courriel;
this.note = note;
this.dateDeNaissance = dateDeNaissance;
}
/**
* Constructeur pour la widget list
*
* @param id
* id du client.
* @param nom
* nom du client.
* @param prenom
* prénom du client.
*/
public Client(int id, String nom, String prenom) {
super(nom, prenom);
this.id = id;
this.dateDeNaissance = LocalDate.now();
}
@Override
public String getDisplayedText() {
String display = this.getPrenom() + " " + this.getNom();
if(this.getId() != -1){
display = this.getId() + "-" + display;
}
return display;
}
public static Client createDefault() {
return new Client(-1, "Nouveau", "Nouveau");
}
}
| 23.659574
| 87
| 0.627473
|
59771d318b5b383cbd59cd3c05001af66f018933
| 5,880
|
package uk.gov.ida.notification.eidassaml.saml.validation;
import com.google.common.base.Strings;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.saml.common.SAMLVersion;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.opensaml.security.credential.Credential;
import org.opensaml.xmlsec.signature.support.SignatureValidator;
import org.slf4j.event.Level;
import se.litsec.eidas.opensaml.ext.RequestedAttributes;
import se.litsec.eidas.opensaml.ext.SPType;
import se.litsec.opensaml.saml2.common.response.MessageReplayChecker;
import se.litsec.opensaml.saml2.common.response.MessageReplayException;
import uk.gov.ida.notification.eidassaml.saml.validation.components.AssertionConsumerServiceValidator;
import uk.gov.ida.notification.eidassaml.saml.validation.components.ComparisonValidator;
import uk.gov.ida.notification.eidassaml.saml.validation.components.RequestIssuerValidator;
import uk.gov.ida.notification.eidassaml.saml.validation.components.RequestedAttributesValidator;
import uk.gov.ida.notification.eidassaml.saml.validation.components.SpTypeValidator;
import uk.gov.ida.notification.exceptions.authnrequest.InvalidAuthnRequestException;
import uk.gov.ida.notification.saml.deprecate.DestinationValidator;
import uk.gov.ida.notification.saml.deprecate.SamlValidationException;
import uk.gov.ida.notification.saml.validation.components.LoaValidator;
import uk.gov.ida.saml.core.validation.SamlTransformationErrorException;
import javax.xml.namespace.QName;
public class EidasAuthnRequestValidator {
private SpTypeValidator spTypeValidator;
private LoaValidator loaValidator;
private RequestedAttributesValidator requestedAttributesValidator;
private RequestIssuerValidator requestIssuerValidator;
private final MessageReplayChecker messageReplayChecker;
private final ComparisonValidator comparisonValidator;
private final DestinationValidator destinationValidator;
private final AssertionConsumerServiceValidator assertionConsumerServiceValidator;
public EidasAuthnRequestValidator(RequestIssuerValidator requestIssuerValidator,
SpTypeValidator spTypeValidator,
LoaValidator loaValidator,
RequestedAttributesValidator requestedAttributesValidator,
MessageReplayChecker duplicateAuthnRequestValidator,
ComparisonValidator comparisonValidator,
DestinationValidator destinationValidator,
AssertionConsumerServiceValidator assertionConsumerServiceValidator) {
this.requestIssuerValidator = requestIssuerValidator;
this.spTypeValidator = spTypeValidator;
this.loaValidator = loaValidator;
this.requestedAttributesValidator = requestedAttributesValidator;
this.messageReplayChecker = duplicateAuthnRequestValidator;
this.comparisonValidator = comparisonValidator;
this.destinationValidator = destinationValidator;
this.assertionConsumerServiceValidator = assertionConsumerServiceValidator;
}
public void validate(AuthnRequest request, Credential signingCredential) {
if (request == null) {
throw new InvalidAuthnRequestException("Null request");
}
try {
SignatureValidator.validate(
request.getSignature(),
signingCredential
);
} catch (Exception exception) {
throw new SamlTransformationErrorException(exception.getMessage(), Level.WARN);
}
if (Strings.isNullOrEmpty(request.getID())) {
throw new InvalidAuthnRequestException("Missing Request ID");
}
if (request.getExtensions() == null) {
throw new InvalidAuthnRequestException("Missing Extensions");
}
if (request.isPassive()) {
throw new InvalidAuthnRequestException("Request should not require zero user interaction (isPassive should be missing or false)");
}
if (!request.isForceAuthn()) {
throw new InvalidAuthnRequestException("Request should require fresh authentication (forceAuthn should be true)");
}
if (!Strings.isNullOrEmpty(request.getProtocolBinding())) {
throw new InvalidAuthnRequestException("Request should not specify protocol binding");
}
if (request.getVersion() != SAMLVersion.VERSION_20) {
throw new InvalidAuthnRequestException("SAML Version should be " + SAMLVersion.VERSION_20.toString());
}
SPType spTypeElement = (SPType) getExtension(request, SPType.DEFAULT_ELEMENT_NAME);
RequestedAttributes requestedAttributesElement = (RequestedAttributes) getExtension(request, RequestedAttributes.DEFAULT_ELEMENT_NAME);
requestIssuerValidator.validate(request.getIssuer());
spTypeValidator.validate(spTypeElement);
loaValidator.validate(request.getRequestedAuthnContext());
requestedAttributesValidator.validate(requestedAttributesElement);
assertionConsumerServiceValidator.validate(request);
comparisonValidator.validate(request.getRequestedAuthnContext());
try {
messageReplayChecker.checkReplay(request.getID());
destinationValidator.validate(request.getDestination());
} catch (SamlValidationException | MessageReplayException e) {
throw new InvalidAuthnRequestException(e.getMessage(), e);
}
}
private XMLObject getExtension(AuthnRequest request, QName elementName) {
return request.getExtensions()
.getUnknownXMLObjects(elementName)
.stream()
.findFirst()
.orElse(null);
}
}
| 48.595041
| 143
| 0.726361
|
1fb2becf07f5212fb06e78cee75f56fb7e56806f
| 1,303
|
package org.impala.javaapi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.common.*;
//import com.hive.jdbcutils.HiveConnectionUtils;
public class ImpalaDML
{
static String JDBC_DRIVER = "com.cloudera.impala.jdbc41.Driver";
static String CONNECTION_URL = "jdbc:impala://192.168.0.30:21050/default";
public ResultSet getResultSet(String sql){
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
try
{
Class.forName(JDBC_DRIVER);
con = DriverManager.getConnection(CONNECTION_URL);
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
} catch(SQLException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
//关闭rs、ps和con
//SQLutil.release(con);
//SQLutil.release(ps);
}
return rs;
}
public void release(Connection conn, Statement st, ResultSet rs ){
SQLutil.release(conn ,st ,rs);
}
}
| 25.057692
| 79
| 0.578665
|
cb812770e1636768c95e7c6f3332abcb71654ba5
| 979
|
package se.umu.cs.ads.fildil.proto.utils;
import com.google.protobuf.ByteString;
import com.google.protobuf.GeneratedMessageV3;
import se.umu.cs.ads.fildil.proto.autogen.Chunk;
/**
* Created by eeemil on 2017-01-09.
*/
public class ChunkUtils {
public static final int FLAG_CHUNK_NO_EXISTS = -1;
public static final int FLAG_END_OF_STREAM = -2;
public static Chunk createNonExistantChunk() {
return createChunk(FLAG_CHUNK_NO_EXISTS,null);
}
public static Chunk createChunk(int id, byte[] data) {
ByteString byteString;
if (data == null) {
byteString = ByteString.EMPTY;
} else {
byteString = ByteString.copyFrom(data);
}
Chunk.Builder builder = Chunk.newBuilder();
builder.setId(id);
builder.setBuf(byteString);
return builder.build();
}
public static Chunk createEndOfStreamChunk() {
return createChunk(FLAG_END_OF_STREAM, null);
}
}
| 27.194444
| 58
| 0.664964
|
b6b4a8c2dbcc02fe45f550e7db17d2264adbb426
| 1,128
|
package com.deiser.jira.dc.listener;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.plugin.event.events.PluginDisabledEvent;
import com.atlassian.plugin.event.events.PluginEnabledEvent;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class LifecycleEventListener implements InitializingBean, DisposableBean {
private static final Logger LOGGER = Logger.getLogger(LifecycleEventListener.class);
private final EventPublisher eventPublisher;
public LifecycleEventListener(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
@Override
public void afterPropertiesSet() {
eventPublisher.register(this);
}
@Override
public void destroy() {
eventPublisher.unregister(this);
}
@EventListener
public void onAppEnabled(PluginEnabledEvent pluginEnabledEvent) {
LOGGER.warn("App " + pluginEnabledEvent.getPlugin().getName() + " has been enabled!!");
}
}
| 31.333333
| 95
| 0.765957
|
4612a72a7581dc2c88884830272aeb9843aac8ce
| 1,926
|
/*-
* Copyright (C) 2011, 2017 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv;
import java.io.Serializable;
/**
* For internal use only.
* @hidden
*
* Basic OAuth Credentials.<p>
*
* This class represents the basic credentials used for OAuth authentication.
* According to OAuth specification, the credentials client used to access
* resource servers are access token. However, the definition and format of
* access token are different in various implementations. This class only
* contains access token as the only field, the subclasses need to extend
* this class in order to be compatible with various OAuth2 implementations.
*/
public class BasicOAuthCredentials implements LoginCredentials, Serializable {
private static final long serialVersionUID = 1L;
protected String accessToken;
public BasicOAuthCredentials(String accessToken) {
this.accessToken = accessToken;
}
/**
* Return the OAuth access token.
*
* @return string of access token.
*/
public String getAccessToken() {
return accessToken;
}
/**
* Identifies the user owning the access token. The subclasses need to
* override this method to parse access token to get user name. In some
* implementations, this method returns client name to represent the
* identity owning this access token.
*
* @return user name who own this access token
*/
@Override
public String getUsername() {
return null;
}
}
| 30.571429
| 96
| 0.718069
|
922d69561560b4404f94cbcdfb3b079b3e26dabe
| 4,594
|
/*
* 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.jackrabbit.oak.composite;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.apache.jackrabbit.oak.composite.checks.NodeStoreChecksService;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.spi.mount.MountInfoProvider;
import org.apache.jackrabbit.oak.spi.mount.Mounts;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.spi.state.NodeStoreProvider;
import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
public class CompositeNodeStoreServiceTest {
@Rule
public final OsgiContext ctx = new OsgiContext();
/**
* Verifies that a minimally-configured <tt>CompositeNodeStore</tt> can be registered successfully
*/
@Test
public void bootstrap() {
MemoryNodeStore mount = new MemoryNodeStore();
MemoryNodeStore global = new MemoryNodeStore();
MountInfoProvider mip = Mounts.newBuilder().readOnlyMount("libs", "/libs", "/apps").build();
ctx.registerService(MountInfoProvider.class, mip);
ctx.registerService(NodeStoreProvider.class, new SimpleNodeStoreProvider(global), ImmutableMap.of("role", "composite:global", "registerDescriptors", Boolean.TRUE));
ctx.registerService(NodeStoreProvider.class, new SimpleNodeStoreProvider(mount), ImmutableMap.of("role", "composite:mount:libs"));
ctx.registerInjectActivateService(new NodeStoreChecksService());
ctx.registerInjectActivateService(new CompositeNodeStoreService());
assertThat("No NodeStore registered", ctx.getService(NodeStore.class), notNullValue());
}
/**
* Verifies that a missing mount will result in the node store not being registered
*/
@Test
public void bootstrap_missingMount() {
MemoryNodeStore mount = new MemoryNodeStore();
MemoryNodeStore global = new MemoryNodeStore();
MountInfoProvider mip = Mounts.newBuilder().readOnlyMount("libs", "/libs", "/apps").readOnlyMount("missing", "/missing").build();
ctx.registerService(MountInfoProvider.class, mip);
ctx.registerService(NodeStoreProvider.class, new SimpleNodeStoreProvider(global), ImmutableMap.of("role", "composite:global", "registerDescriptors", Boolean.TRUE));
ctx.registerService(NodeStoreProvider.class, new SimpleNodeStoreProvider(mount), ImmutableMap.of("role", "composite:mount:libs"));
ctx.registerInjectActivateService(new NodeStoreChecksService());
ctx.registerInjectActivateService(new CompositeNodeStoreService());
assertThat("NodeStore registered, but it should not have been", ctx.getService(NodeStore.class), nullValue());
}
/**
* Verifies that a missing global mount will result in the node store not being registered
*/
@Test
public void bootstrap_missingGlobalMount() {
MemoryNodeStore mount = new MemoryNodeStore();
MountInfoProvider mip = Mounts.newBuilder().readOnlyMount("libs", "/libs", "/apps").build();
ctx.registerService(MountInfoProvider.class, mip);
ctx.registerService(NodeStoreProvider.class, new SimpleNodeStoreProvider(mount), ImmutableMap.of("role", "composite:mount:libs"));
ctx.registerInjectActivateService(new NodeStoreChecksService());
ctx.registerInjectActivateService(new CompositeNodeStoreService());
assertThat("NodeStore registered, but it should not have been", ctx.getService(NodeStore.class), nullValue());
}
private static class SimpleNodeStoreProvider implements NodeStoreProvider {
private final NodeStore nodeStore;
private SimpleNodeStoreProvider(NodeStore nodeStore) {
this.nodeStore = nodeStore;
}
@Override
public NodeStore getNodeStore() {
return nodeStore;
}
}
}
| 39.264957
| 166
| 0.774924
|
f0aa4d1d3a0a35f82414d202f28674cefd5ff181
| 3,730
|
package com.javamokey.adminxx.modules.sys.controller;
import com.javamokey.adminxx.common.annotation.SysLogAnnotation;
import com.javamokey.adminxx.common.util.Constant;
import com.javamokey.adminxx.common.util.R;
import com.javamokey.adminxx.modules.sys.entity.SysDept;
import com.javamokey.adminxx.modules.sys.entity.vo.SysDeptVo;
import com.javamokey.adminxx.modules.sys.service.SysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 部门管理 前端控制器
* </p>
*
* @author Cheney
* @since 2017-12-26
*/
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController extends AbstractController {
private SysDeptService sysDeptService;
public SysDeptController(SysDeptService sysDeptService) {
this.sysDeptService = sysDeptService;
}
/**
* 获取上级部门Id(管理员则为0)
*/
@RequestMapping("/getDeptIdInfo")
@RequiresPermissions("sys:dept:list")
public R getDeptIdInfo() {
long deptId = 0;
if (getUserId() != Constant.SUPER_ADMIN) {
SysDept dept = sysDeptService.selectById(getDeptId());
deptId = dept.getParentId();
}
return R.ok().put("deptId", deptId);
}
/**
* @return
*/
@RequestMapping("/list")
@RequiresPermissions("sys:dept:list")
public List<SysDeptVo> list() {
List<SysDeptVo> deptList = sysDeptService.querySysDeptVoList(new SysDeptVo());
return deptList;
}
/**
* 获取部门详细信息
*/
@RequestMapping("/info/{deptId}")
@RequiresPermissions("sys:dept:info")
public R info(@PathVariable("deptId") Long deptId) {
SysDeptVo dept = sysDeptService.selectSysDeptVoById(deptId);
return R.ok().put("dept", dept);
}
/**
* 选择部门(添加、修改菜单)
*/
@RequestMapping("/select")
@RequiresPermissions("sys:dept:select")
public R select() {
List<SysDeptVo> deptList = sysDeptService.querySysDeptVoList(new SysDeptVo());
//添加一级部门
if (getUserId() == Constant.SUPER_ADMIN) {
SysDeptVo root = new SysDeptVo();
root.setDeptId(0L);
root.setName("一级部门");
root.setParentId(-1L);
root.setOpen(true);
deptList.add(root);
}
return R.ok().put("deptList", deptList);
}
/**
* 保存
*/
@SysLogAnnotation("添加机构")
@RequestMapping("/save")
@RequiresPermissions("sys:dept:save")
public R save(@RequestBody SysDept dept) {
sysDeptService.insertOrUpdate(dept);
return R.ok();
}
/**
* 修改
*/
@SysLogAnnotation("修改机构")
@RequestMapping("/update")
@RequiresPermissions("sys:dept:update")
public R update(@RequestBody SysDept dept) {
sysDeptService.insertOrUpdate(dept);
return R.ok();
}
/**
* 删除
*/
@SysLogAnnotation("删除机构")
@RequestMapping(value="/delete")
@RequiresPermissions("sys:dept:delete")
public R delete(@PathVariable(value = "deptId" ) long deptId){
//判断是否有子部门
SysDeptVo sysDeptVo = new SysDeptVo();
sysDeptVo.setParentId(deptId);
List<SysDeptVo> deptList = sysDeptService.querySysDeptVoList(sysDeptVo);
if (deptList.size() > 0) {
return R.error("请先删除子部门");
}
if (sysDeptService.deleteById(deptId)) {
return R.ok();
} else {
return R.error("没有删除到记录");
}
}
}
| 25.37415
| 86
| 0.634316
|
1ace3371a719bb9d055592ff92e664d52347f752
| 674
|
package recaf.paper.demo;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import recaf.paper.stm.MuJava;
public interface Times<R, S> extends MuJava<R, S> {
static Iterable<Integer> range(Integer n) {
return new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return IntStream.range(0, n).iterator();
}
};
}
default S Times(Supplier<Integer> n, S s) {
return For(() -> range(n.get()), ignored -> s);
}
default
//BEGIN_TIMES
S Times(Supplier<Integer> n, Function<Integer, S> s) {
return For(() -> range(n.get()), s);
}
//END_TIMES
}
| 21.0625
| 54
| 0.683976
|
ac709c6b9a09bdb0daf0ffcfd6175818cc8afe8c
| 9,447
|
/*
* 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.activemq.artemis.tests.integration.mqtt;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import java.util.LinkedList;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.logs.AssertionLoggerHandler;
import org.apache.activemq.artemis.tests.util.Wait;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.jgroups.util.UUID;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
public class MqttWildCardSubAutoCreateTest extends MQTTTestSupport {
private int lastId;
private MqttClient subscriber;
private MqttClient sender;
private volatile LinkedList<String> topics = new LinkedList<>();
@After
public void clean() throws MqttException {
topics.clear();
if (subscriber != null && subscriber.isConnected()) {
subscriber.disconnect();
subscriber.close();
}
if (sender != null && sender.isConnected()) {
sender.disconnect();
sender.close();
}
}
@Override
protected ActiveMQServer createServer(final boolean realFiles, final Configuration configuration) {
configuration.setGlobalMaxSize(15);
return createServer(realFiles, configuration, AddressSettings.DEFAULT_PAGE_SIZE, 10);
}
@Test
public void testWildcardSubAutoCreateDoesNotPageToWildcardAddress() throws Exception {
server.getManagementService().enableNotifications(false);
String subscriberId = UUID.randomUUID().toString();
String senderId = UUID.randomUUID().toString();
String subscribeTo = "A.*";
String publishTo = "A.a";
subscriber = createMqttClient(subscriberId);
subscriber.subscribe(subscribeTo, 2);
subscriber.disconnect();
sender = createMqttClient(senderId);
sender.publish(publishTo, UUID.randomUUID().toString().getBytes(), 2, false);
sender.publish(publishTo, UUID.randomUUID().toString().getBytes(), 2, false);
assertTrue(server.getPagingManager().getPageStore(new SimpleString(subscribeTo)).isPaging());
subscriber = createMqttClient(subscriberId);
subscriber.subscribe(subscribeTo, 2);
boolean satisfied = Wait.waitFor(() -> topics.size() == 2, 5_000);
if (!satisfied) {
Assert.fail();
}
subscriber.messageArrivedComplete(lastId, 2);
subscriber.disconnect();
subscriber.close();
for (String topic : topics) {
assertEquals("A/a", topic);
}
}
private MqttClient createMqttClient(String clientId) throws MqttException {
MqttClient client = new MqttClient("tcp://localhost:" + getPort(), clientId, new MemoryPersistence());
client.setCallback(createCallback());
client.setManualAcks(true);
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
client.connect(options);
return client;
}
private MqttCallback createCallback() {
return new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
topics.add(topic);
lastId = message.getId();
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
@Override
public void connectionLost(Throwable cause) {
}
};
}
@Test
public void testCoreHierarchicalTopic() throws Exception {
try {
AssertionLoggerHandler.startCapture();
ConnectionFactory cf = new ActiveMQConnectionFactory();
Connection connection = cf.createConnection();
connection.setClientID("CLI-ID");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topicSubscribe = ActiveMQJMSClient.createTopic("news.europe.#");
MessageConsumer messageConsumer = session.createDurableConsumer(topicSubscribe, "news-eu");
MessageProducer producer = session.createProducer(null);
Topic topicNewsUsaWrestling = ActiveMQJMSClient.createTopic("news.usa.wrestling");
Topic topicNewsEuropeSport = ActiveMQJMSClient.createTopic("news.europe.sport");
Topic topicNewsEuropeEntertainment = ActiveMQJMSClient.createTopic("news.europe.entertainment");
TextMessage messageWrestlingNews = session.createTextMessage("Hulk Hogan starts ballet classes");
addSizeProp(messageWrestlingNews);
producer.send(topicNewsUsaWrestling, messageWrestlingNews);
TextMessage messageEuropeSport = session.createTextMessage("Lewis Hamilton joins European synchronized swimming team");
producer.send(topicNewsEuropeSport, messageEuropeSport);
TextMessage messageEuropeEntertainment = session.createTextMessage("John Lennon resurrected from dead");
producer.send(topicNewsEuropeEntertainment, messageEuropeEntertainment);
connection.start();
// second consumer to page to different address
Topic topicSubscribeAllNews = ActiveMQJMSClient.createTopic("news.#");
MessageConsumer messageConsumerAllNews = session.createDurableConsumer(topicSubscribeAllNews, "news-all");
producer.send(topicNewsUsaWrestling, messageWrestlingNews);
producer.send(topicNewsEuropeEntertainment, messageEuropeEntertainment);
MessageConsumer messageConsumerEuEnt = session.createDurableConsumer(topicNewsEuropeEntertainment, "news-eu-ent");
producer.send(topicNewsUsaWrestling, messageWrestlingNews);
producer.send(topicNewsEuropeEntertainment, messageEuropeEntertainment);
System.out.println("Usage " + server.getPagingManager().getGlobalSize());
TextMessage msg = (TextMessage) messageConsumerAllNews.receive(5000);
System.out.println("1 All received message: " + msg.getText() + ", dest: " + msg.getJMSDestination());
msg = (TextMessage) messageConsumerAllNews.receive(5000);
System.out.println("2 All received message: " + msg.getText() + ", dest: " + msg.getJMSDestination());
msg = (TextMessage) messageConsumerEuEnt.receive(5000);
System.out.println("3 EuEnt received message: " + msg.getText() + ", dest: " + msg.getJMSDestination());
TextMessage messageReceived1 = (TextMessage) messageConsumer.receive(5000);
System.out.println("4 Received message: " + messageReceived1.getText() + ", dest: " + messageReceived1.getJMSDestination());
TextMessage messageReceived2 = (TextMessage) messageConsumer.receive(5000);
System.out.println("5 Received message: " + messageReceived2.getText() + ", dest: " + messageReceived2.getJMSDestination());
// verify messageConsumer gets messageEuropeEntertainment
msg = (TextMessage) messageConsumer.receive(5000);
System.out.println("6 Eu received message: " + msg.getText() + ", dest: " + msg.getJMSDestination());
assertEquals(topicNewsEuropeSport, messageReceived1.getJMSDestination());
assertEquals(topicNewsEuropeEntertainment, messageReceived2.getJMSDestination());
assertEquals(topicNewsEuropeEntertainment, msg.getJMSDestination());
messageConsumer.close();
messageConsumerAllNews.close();
int countOfPageStores = server.getPagingManager().getStoreNames().length;
assertEquals("there should be 5", 5, countOfPageStores);
connection.close();
Assert.assertFalse(AssertionLoggerHandler.findText("222295"));
} finally {
AssertionLoggerHandler.stopCapture();
}
}
private void addSizeProp(TextMessage messageWrestlingNews) throws JMSException {
messageWrestlingNews.setStringProperty("stuff", new String(new byte[1024]));
}
}
| 39.3625
| 133
| 0.722028
|
e8de9bba7b68529f2e8889022a22a5156cb5cee0
| 2,558
|
package net.exacode.spring.social.connect.mongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.stereotype.Component;
/**
* Converts data between spring social connections {@link Connection} and
* MongoDB documents {@link MongoConnection}.
*
* @author mendlik
*/
@Component
public class MongoConnectionConverter {
private final ConnectionFactoryLocator connectionFactoryLocator;
private final TextEncryptor textEncryptor;
@Autowired
public MongoConnectionConverter(
ConnectionFactoryLocator connectionFactoryLocator,
TextEncryptor textEncryptor) {
this.connectionFactoryLocator = connectionFactoryLocator;
this.textEncryptor = textEncryptor;
}
public Connection<?> convert(MongoConnection cnn) {
if (cnn == null)
return null;
ConnectionData connectionData = fillConnectionData(cnn);
ConnectionFactory<?> connectionFactory = connectionFactoryLocator
.getConnectionFactory(connectionData.getProviderId());
return connectionFactory.createConnection(connectionData);
}
private ConnectionData fillConnectionData(MongoConnection uc) {
return new ConnectionData(uc.getProviderId(), uc.getProviderUserId(),
uc.getDisplayName(), uc.getProfileUrl(), uc.getImageUrl(),
decrypt(uc.getAccessToken()), decrypt(uc.getSecret()),
decrypt(uc.getRefreshToken()), uc.getExpireTime());
}
public MongoConnection convert(Connection<?> cnn) {
ConnectionData data = cnn.createData();
MongoConnection userConn = new MongoConnection();
userConn.setProviderId(data.getProviderId());
userConn.setProviderUserId(data.getProviderUserId());
userConn.setDisplayName(data.getDisplayName());
userConn.setProfileUrl(data.getProfileUrl());
userConn.setImageUrl(data.getImageUrl());
userConn.setAccessToken(encrypt(data.getAccessToken()));
userConn.setSecret(encrypt(data.getSecret()));
userConn.setRefreshToken(encrypt(data.getRefreshToken()));
userConn.setExpireTime(data.getExpireTime());
return userConn;
}
private String decrypt(String encryptedText) {
return encryptedText != null ? textEncryptor.decrypt(encryptedText)
: encryptedText;
}
private String encrypt(String text) {
return text != null ? textEncryptor.encrypt(text) : text;
}
}
| 36.028169
| 73
| 0.794371
|
05b52dee80ebd753f9ba8e6c190ebf0bfa61f113
| 1,216
|
package com.vaadin.tests.components.combobox;
import com.vaadin.data.Item;
import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.ComboBox;
public class ComboBoxUndefinedWidthAndIcon extends TestBase {
@Override
protected void setup() {
ComboBox cb = new ComboBox();
cb.addContainerProperty("caption", String.class, null);
cb.addContainerProperty("icon", Resource.class, null);
for (int i = 1; i < 200 + 1; i++) {
Item item = cb.addItem(i);
item.getItemProperty("caption").setValue("Item " + i);
item.getItemProperty("icon").setValue(
new ThemeResource("../runo/icons/16/users.png"));
}
cb.setItemIconPropertyId("icon");
cb.setItemCaptionPropertyId("caption");
addComponent(cb);
}
@Override
protected String getDescription() {
return "The width of the ComboBox should be fixed even though it is set to undefined width. The width should not change when changing pages in the dropdown.";
}
@Override
protected Integer getTicketNumber() {
return 7013;
}
}
| 32.864865
| 166
| 0.657895
|
173d1b81a20126a298f315b780d5fb5076d60847
| 134
|
package net.ronasoft.wsfamilytracking.config.auth;
public interface FirebaseService {
TokenInfo parseToken(String idToken);
}
| 14.888889
| 50
| 0.791045
|
22cb726ad57e32649a3dbf345152709d52dee6ed
| 4,776
|
package com.me.webapi.service;
import com.me.webapi.pojo.ErrorMessage;
import com.me.webapi.pojo.User;
import com.me.webapi.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class UserService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public ResponseEntity register(User user) {
ErrorMessage err = new ErrorMessage();
String username = user.getUsername();
String password = user.getPassword();
if(username == null || username.isEmpty() && password == null || password.isEmpty())
return new ResponseEntity(HttpStatus.BAD_REQUEST);
String regex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(username);
if (!matcher.matches()) {
err.setError("Invalid UserName");
err.setMessage("Please enter a valid email address!");
return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
}
regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d-]{8,}$";
pattern = Pattern.compile(regex);
matcher = pattern.matcher(password);
if (!matcher.matches()) {
err.setError("Week Password");
err.setMessage("Minimum eight characters, at least one letter and one number!");
return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
}
String hashPassword = BCrypt.hashpw(password, BCrypt.gensalt());
user.setPassword(hashPassword);
User u = userRepository.findByUsername(username).orElse(null);
if (u != null) {
err.setError("User Existed");
err.setMessage("Username already exist, please enter another one!");
return new ResponseEntity(err, HttpStatus.CONFLICT);
}
userRepository.save(user);
logger.info(username + " registered");
err.setError("Success");
err.setMessage("Register Succeeded");
return new ResponseEntity(err, HttpStatus.OK);
}
private String[] decode(String token) {
byte[] bytes = Base64.getDecoder().decode(token.substring(6));
String decode = new String(bytes, StandardCharsets.UTF_8);
return decode.split(":");
}
public ResponseEntity login(String token) {
ErrorMessage err = new ErrorMessage();
if (token == null || !token.startsWith("Basic ")) {
err.setError("Unauthorized");
err.setMessage("Please log in first!");
return new ResponseEntity(err, HttpStatus.UNAUTHORIZED);
}
String[] params = decode(token);
User user = userRepository.findByUsername(params[0]).orElse(null);
if (user == null) {
err.setError("User Not Exit");
err.setMessage("User name does not exist!");
return new ResponseEntity(err, HttpStatus.NOT_FOUND);
}
if (!BCrypt.checkpw(params[1], user.getPassword())) {
err.setError("Invalid Token");
err.setMessage("Password is incorrect!");
return new ResponseEntity(err, HttpStatus.UNAUTHORIZED);
}
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String time = df.format(localDateTime);
logger.info(user.getUsername() + " log in at " + time);
err.setError("Success");
err.setMessage("Welcome! The time on the server is " + time);
return new ResponseEntity(err, HttpStatus.OK);
}
public User authorize(String token) {
if (token != null && token.startsWith("Basic ")) {
String[] params = decode(token);
User user = userRepository.findByUsername(params[0]).orElse(null);
if (user != null && BCrypt.checkpw(params[1], user.getPassword()))
return user;
}
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}
}
| 36.458015
| 92
| 0.644263
|
58ed7b5baf54c2dc4fb34fb81f426fb4410cf15d
| 2,233
|
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright © 2018 Massachusetts Institute of Technology, All rights reserved.
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime;
import com.google.appinventor.components.runtime.test.TestExtension;
import com.google.appinventor.components.runtime.util.IOUtils;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import static org.junit.Assert.assertEquals;
/**
* Tests for the Form component.
*
* @author ewpatton@mit.edu (Evan W. Patton)
*/
public class FormTest extends RobolectricTestBase {
private static final int BUFSIZE = 4096;
static final String TARGET_FILE = "test.txt";
/**
* Tests the ability of the Form to open an asset.
*
* @throws IOException if the asset cannot be found.
*/
@Test
public void testOpenAsset() throws IOException {
InputStream is = null;
try {
is = getForm().openAsset(TARGET_FILE);
assertEquals("Hello, world!\n", readStream(is));
} finally {
IOUtils.closeQuietly("test", is);
}
}
/**
* Tests the ability of the Form to open an asset associated with an
* extension.
*
* @throws IOException if the asset cannot be found.
*/
@Test
public void testOpenAssetExtension() throws IOException {
InputStream is = null;
try {
is = getForm().openAssetForExtension(new TestExtension(getForm()), TARGET_FILE);
assertEquals("Sample extension asset\n", readStream(is));
} finally {
IOUtils.closeQuietly("test", is);
}
}
/// Helper functions
/**
* Read the contents of a stream as a string.
*
* @param is the input stream to read
* @return the contents of the input stream as a string
* @throws IOException if the file cannot be read
*/
public static String readStream(InputStream is) throws IOException {
byte[] data = new byte[BUFSIZE];
int read;
StringBuilder sb = new StringBuilder();
while ((read = is.read(data, 0, BUFSIZE)) > 0) {
sb.append(new String(data, 0, read, Charset.forName("UTF-8")));
}
return sb.toString();
}
}
| 27.9125
| 86
| 0.68249
|
0aabc10870dbb303d58f1b063369a5f64ea9778f
| 5,473
|
package us.ihmc.avatar.roughTerrainWalking;
import static org.junit.Assert.assertTrue;
import javax.vecmath.Point3d;
import javax.vecmath.Quat4d;
import org.junit.After;
import org.junit.Before;
import us.ihmc.avatar.DRCObstacleCourseStartingLocation;
import us.ihmc.avatar.DRCStartingLocation;
import us.ihmc.avatar.MultiRobotTestInterface;
import us.ihmc.avatar.drcRobot.DRCRobotModel;
import us.ihmc.avatar.testTools.DRCSimulationTestHelper;
import us.ihmc.humanoidRobotics.communication.packets.walking.FootstepDataListMessage;
import us.ihmc.humanoidRobotics.communication.packets.walking.FootstepDataMessage;
import us.ihmc.humanoidRobotics.communication.packets.walking.FootstepDataMessage.FootstepOrigin;
import us.ihmc.robotics.robotSide.RobotSide;
import us.ihmc.simulationconstructionset.bambooTools.BambooTools;
import us.ihmc.simulationconstructionset.bambooTools.SimulationTestingParameters;
import us.ihmc.simulationconstructionset.util.environments.FlatGroundEnvironment;
import us.ihmc.simulationconstructionset.util.simulationRunner.BlockingSimulationRunner.SimulationExceededMaximumTimeException;
import us.ihmc.tools.thread.ThreadTools;
public abstract class AvatarSwingTimingsTest implements MultiRobotTestInterface
{
private SimulationTestingParameters simulationTestingParameters = SimulationTestingParameters.createFromEnvironmentVariables();
private DRCSimulationTestHelper drcSimulationTestHelper;
public void testSteppingWithChangingSwingTimes() throws SimulationExceededMaximumTimeException
{
String className = getClass().getSimpleName();
FlatGroundEnvironment environment = new FlatGroundEnvironment();
DRCStartingLocation startingLocation = DRCObstacleCourseStartingLocation.DEFAULT;
DRCRobotModel robotModel = getRobotModel();
drcSimulationTestHelper = new DRCSimulationTestHelper(environment, className, startingLocation, simulationTestingParameters, robotModel);
ThreadTools.sleep(1000);
drcSimulationTestHelper.getSimulationConstructionSet().setCameraPosition(8.0, -8.0, 5.0);
drcSimulationTestHelper.getSimulationConstructionSet().setCameraFix(1.5, 0.0, 0.8);
drcSimulationTestHelper.simulateAndBlockAndCatchExceptions(0.5);
FootstepDataListMessage footsteps = new FootstepDataListMessage(0.6, 0.3, 0.1);
for (int stepIndex = 0; stepIndex < 10; stepIndex++)
{
RobotSide side = stepIndex % 2 == 0 ? RobotSide.LEFT : RobotSide.RIGHT;
double y = side == RobotSide.LEFT ? 0.15 : -0.15;
Point3d location = new Point3d(0.3 * (stepIndex + 1), y, 0.0);
Quat4d orientation = new Quat4d(0.0, 0.0, 0.0, 1.0);
FootstepDataMessage footstepData = new FootstepDataMessage(side, location, orientation);
footstepData.setOrigin(FootstepOrigin.AT_SOLE_FRAME);
double swingTime, transferTime;
switch (stepIndex)
{
case 0:
// start with very slow swings and transfers
transferTime = 1.0; // initial transfer
swingTime = 3.0;
footstepData.setTimings(swingTime, transferTime);
break;
case 1:
// do a default step
break;
case 2:
// do a slow swing
transferTime = 1.0;
swingTime = 3.0;
footstepData.setTimings(swingTime, transferTime);
break;
case 3:
// do a default step
break;
case 4:
// do a default step
break;
case 5:
// do a fast swing and transfer
transferTime = 0.2;
swingTime = 0.6;
footstepData.setTimings(swingTime, transferTime);
break;
case 6:
// do a slow swing
transferTime = 1.0;
swingTime = 3.0;
footstepData.setTimings(swingTime, transferTime);
break;
case 7:
// do a fast swing and transfer
transferTime = 0.2;
swingTime = 0.6;
footstepData.setTimings(swingTime, transferTime);
break;
case 8:
// do a slow swing
transferTime = 1.0;
swingTime = 3.0;
footstepData.setTimings(swingTime, transferTime);
break;
case 9:
// do a slow transfer and a fast swing
transferTime = 3.0;
swingTime = 0.6;
footstepData.setTimings(swingTime, transferTime);
break;
default:
break;
}
footsteps.add(footstepData);
}
drcSimulationTestHelper.send(footsteps);
assertTrue(drcSimulationTestHelper.simulateAndBlockAndCatchExceptions(25.0));
}
@Before
public void showMemoryUsageBeforeTest()
{
BambooTools.reportTestStartedMessage(simulationTestingParameters.getShowWindows());
}
@After
public void destroySimulationAndRecycleMemory()
{
if (simulationTestingParameters.getKeepSCSUp())
{
ThreadTools.sleepForever();
}
// Do this here in case a test fails. That way the memory will be recycled.
if (drcSimulationTestHelper != null)
{
drcSimulationTestHelper.destroySimulation();
drcSimulationTestHelper = null;
}
BambooTools.reportTestFinishedMessage(simulationTestingParameters.getShowWindows());
simulationTestingParameters = null;
}
}
| 37.744828
| 143
| 0.681345
|
494c4cbf940acebae7ab25e354839307c33cbdcf
| 1,444
|
package yhao.micro.service.surety.business.apilist.model.twiceRepay;
import io.swagger.annotations.ApiModelProperty;
import yhao.infra.common.model.Entity;
import java.math.BigDecimal;
import java.util.Date;
/**
* @Description:
* @Created by ql on 2019/3/2 14:26
* @Version: v1.0
*/
public class TwiceRepayBillingInnerPageModel {
@ApiModelProperty(value = "申请金额")
private BigDecimal applyingAmount;
@ApiModelProperty(value = "申请人")
private String applyer;
@ApiModelProperty(value = "还款时间")
private Date repayDate;
@ApiModelProperty(value = "已出账金额")
private BigDecimal billedAmount = new BigDecimal(0);
@ApiModelProperty(value = "出账申请表id")
private String applicationId;
public BigDecimal getApplyingAmount() {
return applyingAmount;
}
public void setApplyingAmount(BigDecimal applyingAmount) {
this.applyingAmount = applyingAmount;
}
public String getApplyer() {
return applyer;
}
public void setApplyer(String applyer) {
this.applyer = applyer;
}
public Date getRepayDate() {
return repayDate;
}
public void setRepayDate(Date repayDate) {
this.repayDate = repayDate;
}
public BigDecimal getBilledAmount() {
return billedAmount;
}
public void setBilledAmount(BigDecimal billedAmount) {
this.billedAmount = billedAmount;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
}
| 20.628571
| 68
| 0.75554
|
334b8d6f41c858d23fdc55d1ceae85319da1b0cd
| 923
|
package com.blalp.chatdirector.common.modules.replacement;
import com.blalp.chatdirector.core.model.Context;
import com.blalp.chatdirector.core.model.IItem;
import lombok.Data;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.NoArgsConstructor;
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
@NoArgsConstructor
@Data
public class ToWordItem implements IItem {
@Override
public Context process(Context context) {
String output = "";
for (String word : context.getCurrent().split(" ")) {
if (!output.trim().isEmpty()) {
output += " ";
}
output += word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
}
return new Context(output);
}
@Override
public boolean isValid() {
return true;
}
}
| 27.969697
| 91
| 0.68039
|
2be30722866bbd734a71dd53f0e771640ea44944
| 305
|
package org.tain.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.tain.domain.TbResult;
@RepositoryRestResource
public interface TbResultRepository extends JpaRepository<TbResult, Long>{
}
| 27.727273
| 76
| 0.852459
|
1931cc09655831110fd87be26b4aa6e2fee2b24e
| 6,840
|
/*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC 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 io.bootique.shiro;
import io.bootique.BQRuntime;
import io.bootique.junit5.BQTest;
import io.bootique.junit5.BQTestFactory;
import io.bootique.junit5.BQTestTool;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@BQTest
public class ShiroModuleIT {
@BQTestTool
final BQTestFactory testFactory = new BQTestFactory();
protected Realm mockRealm() {
Realm mockRealm = mock(Realm.class);
when(mockRealm.getName()).thenReturn("TestRealm");
when(mockRealm.supports(any(AuthenticationToken.class))).then(invocation -> {
AuthenticationToken token = invocation.getArgument(0);
return token instanceof UsernamePasswordToken;
});
when(mockRealm.getAuthenticationInfo(any(AuthenticationToken.class))).then(invocation -> {
UsernamePasswordToken token = invocation.getArgument(0);
if (!"password".equals(new String(token.getPassword()))) {
throw new AuthenticationException("Bad password");
}
return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "TestRealm");
});
return mockRealm;
}
@Test
public void testFullStack() {
Realm mockRealm = mockRealm();
BQRuntime runtime = testFactory.app()
.module(b -> ShiroModule.extend(b).addRealm(mockRealm))
.autoLoadModules()
.createRuntime();
Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();
assertFalse(subject.isAuthenticated());
// try bad login
try {
subject.login(new UsernamePasswordToken("uname", "badpassword"));
fail("Should have thrown on bad auth");
} catch (AuthenticationException authEx) {
assertFalse(subject.isAuthenticated());
}
// try good login
subject.login(new UsernamePasswordToken("uname", "password"));
assertTrue(subject.isAuthenticated());
}
@Test
public void testFullStack_SecurityUtils() {
Realm mockRealm = mockRealm();
BQRuntime runtime = testFactory.app()
.module(b -> ShiroModule.extend(b).addRealm(mockRealm))
.autoLoadModules()
.createRuntime();
Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();
assertNull(ThreadContext.getSubject());
// testing Shiro idiom of wrapping lambda in a subject...
subject.execute(() -> assertSame(subject, SecurityUtils.getSubject(), "Unexpected subject, thread state is disturbed"));
}
@Test
public void testFullStack_AuthListener() {
Realm mockRealm = mockRealm();
AuthenticationListener mockListener = mock(AuthenticationListener.class);
BQRuntime runtime = testFactory.app()
.module(b -> ShiroModule
.extend(b)
.addRealm(mockRealm)
.addAuthListener(mockListener))
.autoLoadModules()
.createRuntime();
Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();
assertFalse(subject.isAuthenticated());
// try bad login
try {
subject.login(new UsernamePasswordToken("uname", "badpassword"));
fail("Should have thrown on bad auth");
} catch (AuthenticationException authEx) {
verify(mockListener).onFailure(any(AuthenticationToken.class), any(AuthenticationException.class));
}
// try good login
subject.login(new UsernamePasswordToken("uname", "password"));
verify(mockListener).onSuccess(any(AuthenticationToken.class), any(AuthenticationInfo.class));
}
@Test
public void testFullStack_AuthListenerType() {
TestAuthListener.reset();
Realm mockRealm = mockRealm();
BQRuntime runtime = testFactory.app()
.module(b -> ShiroModule
.extend(b)
.addRealm(mockRealm)
.addAuthListener(TestAuthListener.class))
.autoLoadModules()
.createRuntime();
Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();
assertFalse(subject.isAuthenticated());
// try bad login
try {
subject.login(new UsernamePasswordToken("uname", "badpassword"));
fail("Should have thrown on bad auth");
} catch (AuthenticationException authEx) {
assertTrue(TestAuthListener.onFailure);
}
// try good login
subject.login(new UsernamePasswordToken("uname", "password"));
assertTrue(TestAuthListener.onSuccess);
}
public static class TestAuthListener implements AuthenticationListener {
static boolean onSuccess;
static boolean onFailure;
static boolean onLogout;
public static void reset() {
onSuccess = false;
onLogout = false;
onFailure = false;
}
@Override
public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
onSuccess = true;
}
@Override
public void onFailure(AuthenticationToken token, AuthenticationException ae) {
onFailure = true;
}
@Override
public void onLogout(PrincipalCollection principals) {
onLogout = true;
}
}
}
| 34.371859
| 128
| 0.64883
|
706ff27f23dfd612c1f87f77cbcffeb418467da6
| 5,050
|
package net.diogomarques.wifioppish;
import net.diogomarques.utils.CountDownTimer;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Represents a Location Provider to obtain user location as precise
* as possible. It uses {@link android.content.SharedPreferences SharedPreferences} to store
* the value temporally.
*
* <p>
* The Location Provider tries to use the
* device's GPS to get the current location.
* </p>
*
* @author André Silva <asilva@lasige.di.fc.ul.pt>
*
*/
public class LocationProvider {
private Context context;
private LocationManager mLocManager;
private SharedPreferences sharedPref;
private int failedInteractions;
/**
* Limit of the backoff formula (minutes)
*/
private final int BACKOFF_LIMIT = 30;
/**
* Maximum time to wait for a GPS reply (minutes)
*/
private final int GPS_RESPONSE_LIMIT = 2;
/**
* Preference key for the last known latitude
*/
public static final String LAST_LAT_KEY = "gps.lastLatitude";
/**
* Preference key for the last known longitude
*/
public static final String LAST_LON_KEY = "gps.lastLongitude";
/**
* Preference key for the last update
*/
public static final String LAST_TIME_KEY = "gps.lastUpdate";
private LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
Editor editor = sharedPref.edit();
editor.putString(LAST_LAT_KEY, Double.toString(location.getLatitude()));
editor.putString(LAST_LON_KEY, Double.toString(location.getLongitude()));
editor.putLong(LAST_TIME_KEY, System.currentTimeMillis());
editor.commit();
Log.w("LocationProvider", "Location records updated! (" +
location.getLatitude() + "," + location.getLongitude() + ")");
}
};
/**
* Creates a new Location Provider. To start the location gathering process, invoke the
* {@link #startLocationDiscovery()} method
* @param c Android context
*/
public LocationProvider(Context c) {
context = c;
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
failedInteractions = 0;
// Clean previous location, if any
Editor prefEditor = sharedPref.edit();
prefEditor.remove(LAST_LAT_KEY);
prefEditor.remove(LAST_LON_KEY);
prefEditor.remove(LAST_TIME_KEY);
prefEditor.commit();
}
/**
* Starts the process of discovering the current and future locations
*/
public void startLocationDiscovery() {
/*CountDownTimer gpsDelay = new CountDownTimer(
calculateNextInteraction(failedInteractions) * 60 * 1000, 1000) {
@Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
}
};*/
registerLocationListener(locationListener);
}
private void startGPS() {
int responseLimit = GPS_RESPONSE_LIMIT * 60 * 1000;
CountDownTimer gpsDelay = new CountDownTimer(
responseLimit, responseLimit) {
@Override
public void onTick(long arg0) { }
@Override
public void onFinish() {
// TODO não foi obtida resposta do GPS: pedidofalhado++ e esperar novo processo
}
};
}
/**
* Registers an event listener to get GPS updates
* @param mLocListener location listener to receive coordinate updates
*/
public void registerLocationListener(LocationListener mLocListener) {
if(mLocManager == null)
mLocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
unregisterLocationListener(mLocListener);
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, mLocListener);
}
/**
* Unregisters a previously registered location listener
* @param mLocationListener location listener to remove
*/
public void unregisterLocationListener(LocationListener mLocationListener) {
if(mLocManager != null)
mLocManager.removeUpdates(mLocationListener);
}
/**
* Gives the time in minutes to wait before searching for a location
* (using the formula 2^(n-1) with a limit of {@link #BACKOFF_LIMIT} minutes)
* @param seq The position of the sequence (intended to use a number of trials after last success)
* @return Number of minutes to wait before next interaction
*/
private int calculateNextInteraction(int seq) {
if(seq <= 0)
return 0;
return Math.min( (int)Math.pow(2, seq - 1) , BACKOFF_LIMIT );
}
}
| 27.595628
| 99
| 0.726139
|
6ff485f179db3a86814dad1e1956224231c0ecd8
| 1,591
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.8
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.ogre;
public enum LayerBlendSource {
LBS_CURRENT,
LBS_TEXTURE,
LBS_DIFFUSE,
LBS_SPECULAR,
LBS_MANUAL;
public final int swigValue() {
return swigValue;
}
public static LayerBlendSource swigToEnum(int swigValue) {
LayerBlendSource[] swigValues = LayerBlendSource.class.getEnumConstants();
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (LayerBlendSource swigEnum : swigValues)
if (swigEnum.swigValue == swigValue)
return swigEnum;
throw new IllegalArgumentException("No enum " + LayerBlendSource.class + " with value " + swigValue);
}
@SuppressWarnings("unused")
private LayerBlendSource() {
this.swigValue = SwigNext.next++;
}
@SuppressWarnings("unused")
private LayerBlendSource(int swigValue) {
this.swigValue = swigValue;
SwigNext.next = swigValue+1;
}
@SuppressWarnings("unused")
private LayerBlendSource(LayerBlendSource swigEnum) {
this.swigValue = swigEnum.swigValue;
SwigNext.next = this.swigValue+1;
}
private final int swigValue;
private static class SwigNext {
private static int next = 0;
}
}
| 28.410714
| 105
| 0.639849
|
d2182e02ce4b5f833740b527dd10518b8c962184
| 7,109
|
/*
* Copyright (c) 2021 Silverwolfg11
*
* 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 me.ar00n.squaremaptowny;
import me.ar00n.squaremaptowny.objects.StaticTB;
import me.ar00n.squaremaptowny.objects.TBCluster;
import me.ar00n.squaremaptowny.util.NegativeSpaceFinder;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static me.ar00n.squaremaptowny.TestHelpers.*;
public class NegativeSpaceTest {
// Test shapes that should not have negative spaces first
// The algorithm has a higher risk of producing negative spaces when it is not supposed to
// Thus, there are more "No Negative Space" tests to verify that it functions correctly.
// Shapes test are based on production data that revealed previous bugs.
@Test
@DisplayName("No Negative Space: Single Block")
void testNoNSpaceSingleBlock() {
TBCluster cluster = clusterOf(tb(0,0));
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// +++
// + +
// + +
// +
@Test
@DisplayName("No Negative Space: Cane")
void testNoNSpaceCane() {
TBCluster cluster = clusterOf(
tb(-1, 0),
tb(-1, 1), tb(1, 1),
tb(-1, 2), tb(1, 2),
tb(-1, 3), tb(0, 3), tb(1, 3)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// ++++
// ++++ +
// + +
// ++ +
// + +
// +
// +
@Test
@DisplayName("No Negative Space: Scythe")
void testNoNSpaceFlippedCane() {
TBCluster cluster = clusterOf(
tb(0, -4), tb(1, -4), tb(2, -4), tb(3, -4),
tb(-3, -3), tb(-2, -3), tb(-1, -3), tb(0, -3), tb(3, -3),
tb(-3, -2), tb(3, -2),
tb(-4, -1), tb(-3, -1), tb(3, -1),
tb(-4, 0), tb(3, 0),
tb(3, 1),
tb(3, 2)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// +
// + +
// + +
// +++
@Test
@DisplayName("No Negative Space: U")
void testNoNSpaceU() {
TBCluster cluster = clusterOf(
tb(-1, 0), tb(0, 0), tb(1, 0),
tb(-1, 1), tb(1, 1),
tb(-1, 2), tb(1, 2),
tb(-1, 3)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// ++++
// +
// +++
@Test
@DisplayName("No Negative Space: 3-figure")
void testNoNSpace3() {
TBCluster cluster = clusterOf(
tb(1, 0), tb(2, 0), tb(3,0),
tb(3, 1),
tb(0, 2), tb(1, 2), tb(2, 2), tb(3, 2)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// +++
// +
// ++++
@Test
@DisplayName("No Negative Space: C-figure")
void testNoNSpaceC() {
TBCluster cluster = clusterOf(
tb(0, 0), tb(1, 0), tb(2, 0), tb(3,0),
tb(0, 1),
tb(0, 2), tb(1, 2), tb(2, 2)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// + +++
// + + +
// + +
// +++++
@Test
@DisplayName("No Negative Space: Sideway's G")
void testNoNSpaceSidewayG() {
TBCluster cluster = clusterOf(
tb(0,0 ), tb(2, 0), tb(3, 0), tb(4, 0),
tb(0, 1), tb(2, 1), tb(4, 1),
tb(0, 2), tb(4, 2),
tb(0, 3), tb(1, 3), tb(2, 3), tb(3, 3), tb(4, 3)
);
Collection<StaticTB> negSpace = NegativeSpaceFinder.findNegativeSpace(cluster);
assertTrue(negSpace.isEmpty());
}
// Test shapes that do have negative spaces
// +++
// + +
// +++
@Test
@DisplayName("Negative Space: 3x3")
void testNSpace3x3() {
TBCluster cluster = clusterOf(
tb(-1, 1), tb(0, 1), tb(1, 1),
tb(-1, 0), tb(1, 0),
tb(-1, -1), tb(0, -1), tb(1, -1)
);
List<StaticTB> output = NegativeSpaceFinder.findNegativeSpace(cluster);
assertEquals(output.size(), 1);
StaticTB missingTB = tb(0, 0);
assertEquals(output.get(0), missingTB);
}
// +++
// + +
// +++
// + +
// +++
@Test
@DisplayName("Negative Space: 8-figure")
void testNSpace8() {
TBCluster cluster = clusterOf(
tb(-1, 2), tb(0, 2), tb(1, 2),
tb(-1, 1), tb(1, 1),
tb(-1, 0), tb(0, 0), tb(1, 0),
tb(-1, -1), tb(1, -1),
tb(-1, 2), tb(0, -2), tb(1, -2)
);
List<StaticTB> output = NegativeSpaceFinder.findNegativeSpace(cluster);
Collection<StaticTB> expectedMissing = list(tb(0, 1), tb(0, -1));
assertEquals(output.size(), expectedMissing.size());
assertTrue(output.containsAll(expectedMissing));
}
// +++
// + +
// +++
// + +
// + +
@Test
@DisplayName("Negative Space: A-figure")
void testNSpaceA() {
TBCluster cluster = clusterOf(
tb(-1, 2), tb(0, 2), tb(1, 2),
tb(-1, 1), tb(1, 1),
tb(-1, 0), tb(0, 0), tb(1, 0),
tb(-1, -1), tb(1, -1),
tb(-1, 2), tb(1, -2)
);
List<StaticTB> output = NegativeSpaceFinder.findNegativeSpace(cluster);
Collection<StaticTB> expectedMissing = list(tb(0, 1));
assertEquals(output.size(), expectedMissing.size());
assertTrue(output.containsAll(expectedMissing));
}
}
| 30.642241
| 94
| 0.544802
|
f41a73c708cef55d53645eb19568c5988a902543
| 674
|
package org.apache.http.impl.auth;
import org.apache.http.annotation.Contract;
import org.apache.http.annotation.ThreadingBehavior;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
@Contract(
threading = ThreadingBehavior.IMMUTABLE
)
public class NTLMSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
public AuthScheme newInstance(HttpParams params) {
return new NTLMScheme();
}
public AuthScheme create(HttpContext context) {
return new NTLMScheme();
}
}
| 29.304348
| 81
| 0.793769
|
f9aecff7994f13afdbea402f9e95c1ca1600da1f
| 373
|
package microhttp;
import java.util.function.Consumer;
/**
* HTTP request handler.
*/
public interface Handler {
/**
* Handle HTTP request.
* The provided callback object has a reference to internal connection state.
* The callee MUST invoke the callback once and only once.
*/
void handle(Request request, Consumer<Response> callback);
}
| 20.722222
| 81
| 0.69437
|
5c9f1595969c39d14b99cd0464bbd068376e4ad7
| 5,851
|
package de.kekru.codeanalysisbb.reporter.spotbugs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.cdancy.bitbucket.rest.domain.insights.Annotation;
import com.cdancy.bitbucket.rest.domain.insights.Annotation.AnnotationSeverity;
import com.cdancy.bitbucket.rest.domain.insights.Annotation.AnnotationType;
import com.cdancy.bitbucket.rest.options.CreateAnnotations;
import com.cdancy.bitbucket.rest.options.CreateInsightReport;
import com.cdancy.bitbucket.rest.options.CreateInsightReport.RESULT;
import de.kekru.codeanalysisbb.CodeAnalysisBitbucketExporter;
import de.kekru.codeanalysisbb.testutils.AbstractIntegrationTest;
import de.kekru.codeanalysisbb.utils.CodeAnalysisBitbucketException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class SpotbugsReporterIntegrationTest extends AbstractIntegrationTest {
public SpotbugsReporterIntegrationTest() {
super("src/test/resources/spotbugs/01/config.yml");
}
@Test
public void testSpotbugsReporting() {
try {
new CodeAnalysisBitbucketExporter(serviceRegistry);
fail("Expected CodeAnalysisBitbucketException");
} catch (CodeAnalysisBitbucketException e) {
assertEquals("There are failed reports: spotbugs-key", e.getMessage());
}
ArgumentCaptor<CreateInsightReport> insightReportCaptor = ArgumentCaptor
.forClass(CreateInsightReport.class);
ArgumentCaptor<CreateAnnotations> annotationsCaptor = ArgumentCaptor
.forClass(CreateAnnotations.class);
verify(insightsApiMock, times(1)).createReport(
eq("some-project"),
eq("some-repo"),
eq("7281682ec6f7a47f3da5eb2afee52eba9044bb28"),
eq("spotbugs-key"),
insightReportCaptor.capture());
verify(insightsApiMock, times(1)).createAnnotations(
eq("some-project"),
eq("some-repo"),
eq("7281682ec6f7a47f3da5eb2afee52eba9044bb28"),
eq("spotbugs-key"),
annotationsCaptor.capture());
// Check report
CreateInsightReport report = insightReportCaptor.getValue();
assertEquals("Spotbugs Code Analysis Report", report.title());
assertEquals("Spotbugs", report.reporter());
assertEquals("Overall report summary:\n\nFindings by Severity:\nMEDIUM findings: 14\nHIGH findings: 2\n\nThese findings are divided into these types:\nCODE_SMELL findings: 14\nBUG findings: 2\n\nBelow only findings in changed lines are listed\n", report.details());
assertEquals("https://spotbugs.github.io", report.link());
assertEquals("https://spotbugs.github.io/images/logos/spotbugs_icon_only_zoom_256px.png", report.logoUrl());
assertEquals(0, report.data().size());
assertEquals(RESULT.FAIL, report.result());
// Check annotations
List<Annotation> annotations = annotationsCaptor.getValue()
.annotations()
.stream()
.sorted(Comparator
.comparing(Annotation::path)
.thenComparing(Comparator.comparing(Annotation::line))
.thenComparing(Comparator.comparing(Annotation::message)))
.collect(Collectors.toList());
assertEquals(16, annotations.size());
Annotation a = annotations.get(0);
assertNotNull(a.reportKey());
assertNotNull(a.externalId());
assertEquals("https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#dodgy-code-style", a.link());
assertEquals("Dead store to abc in new de.kekru.example.codeanalysisbb.Main()", a.message().trim());
assertEquals("src/main/java/de/kekru/example/codeanalysisbb/Main.java", a.path());
assertEquals(33, a.line());
assertEquals(AnnotationSeverity.MEDIUM, a.severity());
assertEquals(AnnotationType.CODE_SMELL, a.type());
a = annotations.get(4);
assertNotNull(a.reportKey());
assertNotNull(a.externalId());
assertEquals("https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#dodgy-code-style", a.link());
assertEquals("Read of unwritten public or protected field something in de.kekru.example.codeanalysisbb.SecondClass.getSomething()", a.message().trim());
assertEquals("src/main/java/de/kekru/example/codeanalysisbb/SecondClass.java", a.path());
assertEquals(14, a.line());
assertEquals(AnnotationSeverity.HIGH, a.severity());
assertEquals(AnnotationType.CODE_SMELL, a.type());
// same as get(4) above, but with path in src/main/resources/...
a = annotations.get(10);
assertNotNull(a.reportKey());
assertNotNull(a.externalId());
assertEquals("https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#dodgy-code-style", a.link());
assertEquals("Read of unwritten public or protected field something in de.kekru.example.codeanalysisbb.SecondClass.getSomething()", a.message().trim());
assertEquals("src/main/resources/de/kekru/example/codeanalysisbb/SecondClass.java", a.path());
assertEquals(14, a.line());
assertEquals(AnnotationSeverity.HIGH, a.severity());
assertEquals(AnnotationType.CODE_SMELL, a.type());
a = annotations.get(12);
assertNotNull(a.reportKey());
assertNotNull(a.externalId());
assertEquals("https://spotbugs.readthedocs.io/en/stable/bugDescriptions.html#experimental-experimental", a.link());
assertEquals("de.kekru.example.codeanalysisbb.MainTest.keepOpenStream() may fail to clean up java.io.InputStream", a.message().trim());
assertEquals("src/test/java/de/kekru/example/codeanalysisbb/MainTest.java", a.path());
assertEquals(20, a.line());
assertEquals(AnnotationSeverity.MEDIUM, a.severity());
assertEquals(AnnotationType.CODE_SMELL, a.type());
}
}
| 47.185484
| 269
| 0.742779
|
c38d5240336f5719cb24c80fa14b5c2dbcd0f4ae
| 3,443
|
package bigjun.iplab.ReversePolish;
/**
* 逆波兰表达式(包括将算术表达式转化成逆波兰表达式和计算逆波兰表达式的值)
*/
public class ReversePolish {
// 将算术表达式转换成后缀表达式
public String convertToPostfix(String expression){
LinkStack S = new LinkStack(); // 初始化一个运算符栈
String postfix = new String(); // 初始化一个用于存放输出的后缀表达式的字符串
for (int i = 0; i < expression.length() && expression != null; i++) {
char c = expression.charAt(i); // 从算数表达式中依次读取字符
if (c != ' ') { // 字符c不为空格
if (isLeftParenthesis(c)) { // 字符c为左括号的情况
S.Push(c); // 左括号直接入栈
} else if (isRightParenthesis(c)) { // 字符c为右括号的情况
char ac = (Character) S.Pop();
while (!isLeftParenthesis(ac) && !S.isEmpty()) { // 一直到匹配到左括号为止
postfix = postfix.concat(String.valueOf(ac));// 将栈中左括号前面的运算符都输出
ac = (Character) S.Pop(); // 最后将左括号也弹出栈
}
} else if (isOperator(c)) { // 字符c为运算符的情况
if (! S.isEmpty()) {
Object ac = (char) S.Pop();
// 如果栈顶的运算符的优先级比运算符c的优先级高,则将栈顶元素输出到后缀表达式
while (ac != null && priority((char) ac) >= priority(c)) {
postfix = postfix.concat(String.valueOf(ac));
ac = S.Pop();
}
if (ac != null) { // 将最后一次出栈的优先级没有高于运算符c的优先级的运算符再次入栈
S.Push(ac);
}
}
S.Push(c); // 将字符c入栈
} else { // 字符c为数字的情况
postfix = postfix.concat(String.valueOf(c)); // 直接输出
}
}
}
while (!S.isEmpty()) { // 读取完最后一个字符后,将栈内元素一次出栈输出
postfix = postfix.concat(String.valueOf(S.Pop()));
}
return postfix;
}
// 计算后缀表达式的值,仅支持计算个位数的数字运算,如果想要计算两位数以上的,可以考虑使用控制台依次输入单个字符
public double postfixCalculate(String postfix) {
LinkStack S = new LinkStack();
for (int i = 0; i < postfix.length() && postfix != null; i++) {
char c = postfix.charAt(i); // 从后缀表达式中依次读取字符
if (isOperator(c)) {
double d2 = Double.valueOf(S.Pop().toString());
double d1 = Double.valueOf(S.Pop().toString());
double result = 0;
if (c == '+') {
result = d1 + d2;
} else if (c == '-') {
result = d1 - d2;
} else if (c == '*') {
result = d1 * d2;
} else if (c == '/') {
result = d1 / d2;
} else if (c == '^') {
result = Math.pow(d1, d2);
} else if (c == '%') {
result = d1 % d2;
}
S.Push(result);
} else {
S.Push(c);
}
}
return (double) S.Pop();
}
private boolean isLeftParenthesis(char c) {
return '(' == c;
}
private boolean isRightParenthesis(char c) {
return ')' == c;
}
private boolean isOperator(char c) {
if ('+' == c || '-' == c || '*' == c || '/' == c || '%' == c || '^' == c) {
return true;
} else {
return false;
}
}
private int priority(char c) {
if (c == '^') {
return 3;
}
if ('*' == c || '/' == c || '%' == c) {
return 2;
} else if ('+' == c || '-' == c) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) throws Exception {
ReversePolish RS = new ReversePolish();
String postfix = RS.convertToPostfix("9+(3-1)*3+10/2");
System.out.print("将算术表达式转化为后缀表达式为: " + postfix);
System.out.println("*******************************");
String postfix1 = RS.convertToPostfix("(1 + 2) * ( 5 - 2 ) / 2 ^ 2 + 5 % 3 ");
System.out.print("将算术表达式转化为后缀表达式为: " + postfix1);
System.out.println();
System.out.print("计算转换后的后缀表达式的结果为: " + RS.postfixCalculate(postfix1));
}
}
| 28.932773
| 81
| 0.530351
|
01b9956e062f040e90b82fc3190c575803fa097d
| 509
|
package ru.shestakov.models;
/**
* Init class for "find by name" operation
*/
public class FilterByName implements Filter {
final private String name;
/**
* Initializes a newly created filter by name
* @param name
*/
public FilterByName(String name) {
this.name = name;
}
/**
* Checks value on equals
* @param item
* @return
*/
public boolean check(Item item) {
return (item != null) && (item.getName().contains(name));
}
}
| 18.851852
| 65
| 0.585462
|
0e65441703fcec8d23958cece3893448c69e580f
| 3,775
|
/*
* Copyright 2009 Kantega AS
*
* 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 no.kantega.useradmin.controls;
import no.kantega.commons.client.util.RequestParameters;
import no.kantega.commons.client.util.ValidationErrors;
import no.kantega.security.api.role.DefaultRole;
import no.kantega.security.api.role.DefaultRoleId;
import no.kantega.security.api.role.RoleManager;
import no.kantega.security.api.role.RoleUpdateManager;
import no.kantega.useradmin.model.RoleManagementConfiguration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class EditRoleController extends AbstractUserAdminController {
public ModelAndView doHandleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
RequestParameters param = new RequestParameters(request);
String id = param.getString("roleId");
// Trim whitespace
id = id == null ? null : id.trim();
String domain = param.getString("domain");
String save = param.getString("save");
ValidationErrors errors = new ValidationErrors();
Map<String, Object> model = new HashMap<>();
model.put("domain", domain);
model.put("errors", errors);
model.put("configurations", getRoleConfiguration());
model.put("numConfigurations", getRoleConfiguration().size());
RoleManagementConfiguration config = getRoleConfiguration(domain);
RoleManager manager = config.getRoleManager();
RoleUpdateManager updateManager = config.getRoleUpdateManager();
if (save != null) {
DefaultRole role = new DefaultRole();
role.setDomain(domain);
role.setId(id);
role.setName(id);
if (id == null || id.length() == 0) {
model.put("isNew", Boolean.TRUE);
model.put("canEdit", Boolean.TRUE);
model.put("role", role);
model.put("domain", role.getDomain());
errors.add(null, "useradmin.role.rolenamemissing");
return new ModelAndView("role/edit", model);
} else if (updateManager != null) {
updateManager.saveOrUpdateRole(role);
return new ModelAndView(new RedirectView("search?message=useradmin.role.saved&domain=" + URLEncoder.encode(domain, "iso-8859-1")));
}
} else {
// Existing role
if (id != null && id.length() > 0) {
DefaultRoleId role = new DefaultRoleId();
role.setDomain(domain);
role.setId(id);
model.put("role", manager.getRoleById(role));
model.put("domain", role.getDomain());
} else {
// New role
if (updateManager != null) {
model.put("canEdit", Boolean.TRUE);
}
}
}
model.put("configurations", getRoleConfiguration());
return new ModelAndView("role/edit", model);
}
}
| 38.131313
| 147
| 0.645298
|
0dcac0e9c11c36f91d4210bcd584d412e549f26a
| 578
|
package io.mosaicnetworks.babblesweeper;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;
import static android.content.Context.WIFI_SERVICE;
public class Utils {
public static String getIPAddr(Context context) {
WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Log.d(MainActivity.TAG, "Got IP address: " + ip);
return ip;
}
}
| 30.421053
| 102
| 0.747405
|
c8b96cf39fa3c140b311755d4982f46a806c4a67
| 4,019
|
/*
* ******************************************************************************
* Copyright 2019 Korea University & Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ******************************************************************************
* Developed by Libera team, Operating Systems Lab of Korea University
* ******************************************************************************
*/
package net.onrc.openvirtex.messages;
import net.onrc.openvirtex.elements.datapath.OVXSwitch;
import net.onrc.openvirtex.elements.datapath.PhysicalSwitch;
import net.onrc.openvirtex.exceptions.MappingException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.projectfloodlight.openflow.protocol.OFFlowMod;
import org.projectfloodlight.openflow.protocol.OFFlowModFlags;
import org.projectfloodlight.openflow.protocol.OFFlowRemoved;
import org.projectfloodlight.openflow.protocol.OFMessage;
public class OVXFlowRemoved extends OVXMessage implements Virtualizable {
Logger log = LogManager.getLogger(OVXFlowRemoved.class.getName());
public OVXFlowRemoved(OFMessage msg) {
super(msg);
}
public OFFlowRemoved getFlowRemoved() {
return (OFFlowRemoved)this.getOFMessage();
}
@Override
public void virtualize(final PhysicalSwitch sw) {
//this.log.info("virtualize");
long thisCookie = this.getFlowRemoved().getCookie().getValue();
int tid = (int) ( thisCookie >> 32);
/* a PhysSwitch can be a OVXLink */
if (!(sw.getMap().hasVirtualSwitch(sw, tid))) {
return;
}
try {
OVXSwitch vsw = sw.getMap().getVirtualSwitch(sw, tid);
/*
* If we are a Big Switch we might receive multiple same-cookie FR's
* from multiple PhysicalSwitches. Only handle if the FR's newly
* seen
*/
if (vsw.getFlowTable().hasFlowMod(thisCookie)) {
OVXFlowMod fm = vsw.getFlowMod(thisCookie);
/*
* send north ONLY if tenant controller wanted a FlowRemoved for
* the FlowMod
*/
vsw.deleteFlowMod(thisCookie);
if (fm.getFlowMod().getFlags().contains(OFFlowModFlags.SEND_FLOW_REM)) {
this.setOFMessage(
this.getFlowRemoved().createBuilder()
.setCookie(fm.getFlowMod().getCookie())
.setMatch(fm.getFlowMod().getMatch())
.setPriority(fm.getFlowMod().getPriority())
.setIdleTimeout(fm.getFlowMod().getIdleTimeout())
.build()
);
vsw.sendMsg(this, sw);
}
}
} catch (MappingException e) {
log.warn("Exception fetching FlowMod from FlowTable: {}", e);
}
}
@Override
public String toString() {
return "OVXFlowRemoved: cookie = " + this.getFlowRemoved().getCookie().getValue()
+ " priority = " + this.getFlowRemoved().getPriority()
+ " match = " + this.getFlowRemoved().getMatch().toString()
+ " reason = " + this.getFlowRemoved().getReason();
}
@Override
public int hashCode() {
return this.getOFMessage().hashCode();
}
}
| 38.644231
| 89
| 0.573775
|
ad98a7ea2121430fa20b390a0b49c0978a951d0e
| 4,154
|
/*
* Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.registry.cmis.impl;
import org.apache.chemistry.opencmis.commons.data.Properties;
import org.apache.chemistry.opencmis.commons.definitions.TypeDefinition;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
import org.apache.chemistry.opencmis.commons.exceptions.CmisStorageException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.FolderTypeDefinitionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.registry.cmis.RegistryFolder;
import org.wso2.carbon.registry.cmis.RegistryTypeManager;
import org.wso2.carbon.registry.cmis.util.CommonUtil;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.cmis.PathManager;
/**
* Type handler that provides cmis:folder.
*/
public class FolderTypeHandler extends AbstractTypeHandler {
public FolderTypeHandler(Registry repository, PathManager pathManager,
RegistryTypeManager typeManager) {
super(repository, pathManager, typeManager);
}
private static final Logger log = LoggerFactory.getLogger(FolderTypeHandler.class);
/*private static class FolderIdentifierMap extends DefaultIdentifierMapBase {
public FolderIdentifierMap() {
super("nt:folder");
// xxx not supported: PARENT_ID, ALLOWED_CHILD_OBJECT_TYPE_IDS, PATH
}
}*/
public String getTypeId() {
return BaseTypeId.CMIS_FOLDER.value();
}
public TypeDefinition getTypeDefinition() {
FolderTypeDefinitionImpl folderType = new FolderTypeDefinitionImpl();
folderType.setBaseTypeId(BaseTypeId.CMIS_FOLDER);
folderType.setIsControllableAcl(false);
folderType.setIsControllablePolicy(false);
folderType.setIsCreatable(true);
folderType.setDescription("Folder");
folderType.setDisplayName("Folder");
folderType.setIsFileable(true);
folderType.setIsFulltextIndexed(false);
folderType.setIsIncludedInSupertypeQuery(true);
folderType.setLocalName("Folder");
folderType.setLocalNamespace(RegistryTypeManager.NAMESPACE);
folderType.setIsQueryable(true);
folderType.setQueryName(RegistryTypeManager.FOLDER_TYPE_ID);
folderType.setId(RegistryTypeManager.FOLDER_TYPE_ID);
RegistryTypeManager.addBasePropertyDefinitions(folderType);
RegistryTypeManager.addFolderPropertyDefinitions(folderType);
return folderType;
}
public RegistryFolder getGregNode(Resource node) {
return new RegistryFolder(repository, node, typeManager, pathManager);
}
public RegistryFolder createFolder(RegistryFolder parentFolder, String name, Properties properties) {
try {
Collection node = repository.newCollection();
String destinationPath = CommonUtil.getTargetPathOfNode(parentFolder, name);
repository.put(destinationPath, node);
Resource resource = repository.get(destinationPath);
// compile the properties
RegistryFolder.setProperties(repository, resource, getTypeDefinition(), properties);
return getGregNode(resource);
}
catch (RegistryException e) {
log.debug(e.getMessage(), e);
throw new CmisStorageException(e.getMessage(), e);
}
}
}
| 38.82243
| 105
| 0.735195
|
6d6e3af41c35ed4f18c39c2cbd7e257aad7f6984
| 1,477
|
import com.github.theholywaffle.lolchatapi.ChatServer;
import com.github.theholywaffle.lolchatapi.FriendRequestPolicy;
import com.github.theholywaffle.lolchatapi.LolChat;
import com.github.theholywaffle.lolchatapi.listeners.ChatListener;
import com.github.theholywaffle.lolchatapi.riotapi.RateLimit;
import com.github.theholywaffle.lolchatapi.riotapi.RiotApiKey;
import com.github.theholywaffle.lolchatapi.wrapper.Friend;
public class ChatExample {
public static void main(String[] args) {
new ChatExample();
}
public ChatExample() {
final LolChat api = new LolChat(ChatServer.EUW,
FriendRequestPolicy.ACCEPT_ALL, new RiotApiKey("RIOT-API-KEY",
RateLimit.DEFAULT));
if (api.login("myusername", "mypassword")) {
// Example 1: Send Chat Message to all your friends
for (final Friend f : api.getFriends()) {
f.sendMessage("Hello " + f.getName());
}
// Example 2: Send Chat Message to all your friends and wait for an
// response
for (final Friend f : api.getFriends()) {
f.sendMessage("Hello " + f.getName(), new ChatListener() {
@Override
public void onMessage(Friend friend, String message) {
System.out.println("Friend " + friend.getName()
+ " responded to my Hello World!");
}
});
}
// Example3: Send Chat Message to an specific friend
final Friend f = api.getFriendByName("Dyrus");
if (f != null && f.isOnline()) {
f.sendMessage("Hi, I'm your biggest fan!");
}
}
}
}
| 30.770833
| 70
| 0.703453
|
a3618c2e5190cd8d043418e4b518c6b96b78eaf4
| 1,122
|
/**
* 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.jivesoftware.smackx.entitycaps.cache;
import java.io.IOException;
import org.jivesoftware.smackx.packet.DiscoverInfo;
public interface EntityCapsPersistentCache {
/**
* Add an DiscoverInfo to the persistent Cache
*
* @param node
* @param info
*/
void addDiscoverInfoByNodePersistent(String node, DiscoverInfo info);
/**
* Replay the Caches data into EntityCapsManager
*/
void replay() throws IOException;
/**
* Empty the Cache
*/
void emptyCache();
}
| 28.769231
| 87
| 0.707665
|
2f929e5ed2b45121b34c23ae3692577e150eb456
| 569
|
package com.fr.swift.query.aggregator.funnel;
import java.util.List;
/**
* This class created on 2018/12/13
*
* @author Lucifer
* @description
*/
public interface ITimeWindowFilter {
void init();
void setDictSize(int size);
/**
* 添加一条明细记录
* @param event 事件
* @param timestamp 时间戳
* @return 如果已经得到完整步骤,则返回true,否则返回false
*/
void add(int event, int timestamp, int dateDictIndex, int associatedValue, Object groupValue);
/**
* 返回结果
*
* @return
*/
List<IHead> getResult();
void reset();
}
| 16.735294
| 98
| 0.616872
|
60a44e345b736dd6f007325ecc9618ce021a2b21
| 3,634
|
/**
* Copyright 2012-2018 The Feign 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 feign.optionals;
import feign.Feign;
import feign.RequestLine;
import feign.codec.Decoder;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Test;
import java.io.IOException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
public class OptionalDecoderTests {
interface OptionalInterface {
@RequestLine("GET /")
Optional<String> getAsOptional();
@RequestLine("GET /")
String get();
}
@Test
public void simple404OptionalTest() throws IOException, InterruptedException {
final MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
server.enqueue(new MockResponse().setBody("foo"));
final OptionalInterface api = Feign.builder()
.decode404()
.decoder(new OptionalDecoder(new Decoder.Default()))
.target(OptionalInterface.class, server.url("/").toString());
assertThat(api.getAsOptional().isPresent()).isFalse();
assertThat(api.getAsOptional().get()).isEqualTo("foo");
}
@Test
public void simple204OptionalTest() throws IOException, InterruptedException {
final MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(204));
final OptionalInterface api = Feign.builder()
.decoder(new OptionalDecoder(new Decoder.Default()))
.target(OptionalInterface.class, server.url("/").toString());
assertThat(api.getAsOptional().isPresent()).isFalse();
}
@Test
public void test200WithOptionalString() throws IOException, InterruptedException {
final MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(200).setBody("foo"));
final OptionalInterface api = Feign.builder()
.decoder(new OptionalDecoder(new Decoder.Default()))
.target(OptionalInterface.class, server.url("/").toString());
Optional<String> response = api.getAsOptional();
assertThat(response.isPresent()).isTrue();
assertThat(response).isEqualTo(Optional.of("foo"));
}
@Test
public void test200WhenResponseBodyIsNull() throws IOException, InterruptedException {
final MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(200));
final OptionalInterface api = Feign.builder()
.decoder(new OptionalDecoder(((response, type) -> null)))
.target(OptionalInterface.class, server.url("/").toString());
assertThat(api.getAsOptional().isPresent()).isFalse();
}
@Test
public void test200WhenDecodingNoOptional() throws IOException, InterruptedException {
final MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(200).setBody("foo"));
final OptionalInterface api = Feign.builder()
.decoder(new OptionalDecoder(new Decoder.Default()))
.target(OptionalInterface.class, server.url("/").toString());
assertThat(api.get()).isEqualTo("foo");
}
}
| 35.627451
| 100
| 0.727023
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.