_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q170600
WebSocketClient.getPort
test
private int getPort() { int port = uri.getPort(); if( port == -1 ) { String scheme = uri.getScheme(); if( "wss".equals( scheme ) ) { return WebSocketImpl.DEFAULT_WSS_PORT; } else if( "ws".equals( scheme ) ) { return WebSocketImpl.DEFAULT_PORT; } else { throw new IllegalArgumentException( "unknown scheme: " + scheme ); } } return port; }
java
{ "resource": "" }
q170601
WebSocketClient.sendHandshake
test
private void sendHandshake() throws InvalidHandshakeException { String path; String part1 = uri.getRawPath(); String part2 = uri.getRawQuery(); if( part1 == null || part1.length() == 0 ) path = "/"; else path = part1; if( part2 != null ) path += '?' + part2; int port = getPort(); String host = uri.getHost() + ( (port != WebSocketImpl.DEFAULT_PORT && port != WebSocketImpl.DEFAULT_WSS_PORT) ? ":" + port : "" ); HandshakeImpl1Client handshake = new HandshakeImpl1Client(); handshake.setResourceDescriptor( path ); handshake.put( "Host", host ); if( headers != null ) { for( Map.Entry<String,String> kv : headers.entrySet() ) { handshake.put( kv.getKey(), kv.getValue() ); } } engine.startHandshake( handshake ); }
java
{ "resource": "" }
q170602
AbstractWebSocket.setConnectionLostTimeout
test
public void setConnectionLostTimeout( int connectionLostTimeout ) { synchronized (syncConnectionLost) { this.connectionLostTimeout = TimeUnit.SECONDS.toNanos(connectionLostTimeout); if (this.connectionLostTimeout <= 0) { log.trace("Connection lost timer stopped"); cancelConnectionLostTimer(); return; } if (this.websocketRunning) { log.trace("Connection lost timer restarted"); //Reset all the pings try { ArrayList<WebSocket> connections = new ArrayList<WebSocket>(getConnections()); WebSocketImpl webSocketImpl; for (WebSocket conn : connections) { if (conn instanceof WebSocketImpl) { webSocketImpl = (WebSocketImpl) conn; webSocketImpl.updateLastPong(); } } } catch (Exception e) { log.error("Exception during connection lost restart", e); } restartConnectionLostTimer(); } } }
java
{ "resource": "" }
q170603
AbstractWebSocket.stopConnectionLostTimer
test
protected void stopConnectionLostTimer() { synchronized (syncConnectionLost) { if (connectionLostCheckerService != null || connectionLostCheckerFuture != null) { this.websocketRunning = false; log.trace("Connection lost timer stopped"); cancelConnectionLostTimer(); } } }
java
{ "resource": "" }
q170604
AbstractWebSocket.startConnectionLostTimer
test
protected void startConnectionLostTimer() { synchronized (syncConnectionLost) { if (this.connectionLostTimeout <= 0) { log.trace("Connection lost timer deactivated"); return; } log.trace("Connection lost timer started"); this.websocketRunning = true; restartConnectionLostTimer(); } }
java
{ "resource": "" }
q170605
AbstractWebSocket.restartConnectionLostTimer
test
private void restartConnectionLostTimer() { cancelConnectionLostTimer(); connectionLostCheckerService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker")); Runnable connectionLostChecker = new Runnable() { /** * Keep the connections in a separate list to not cause deadlocks */ private ArrayList<WebSocket> connections = new ArrayList<WebSocket>( ); @Override public void run() { connections.clear(); try { connections.addAll( getConnections() ); long minimumPongTime = (long) (System.nanoTime() - ( connectionLostTimeout * 1.5 )); for( WebSocket conn : connections ) { executeConnectionLostDetection(conn, minimumPongTime); } } catch ( Exception e ) { //Ignore this exception } connections.clear(); } }; connectionLostCheckerFuture = connectionLostCheckerService.scheduleAtFixedRate(connectionLostChecker, connectionLostTimeout, connectionLostTimeout, TimeUnit.NANOSECONDS); }
java
{ "resource": "" }
q170606
AbstractWebSocket.executeConnectionLostDetection
test
private void executeConnectionLostDetection(WebSocket webSocket, long minimumPongTime) { if (!(webSocket instanceof WebSocketImpl)) { return; } WebSocketImpl webSocketImpl = (WebSocketImpl) webSocket; if( webSocketImpl.getLastPong() < minimumPongTime ) { log.trace("Closing connection due to no pong received: {}", webSocketImpl); webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE, "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection" ); } else { if( webSocketImpl.isOpen() ) { webSocketImpl.sendPing(); } else { log.trace("Trying to ping a non open connection: {}", webSocketImpl); } } }
java
{ "resource": "" }
q170607
AbstractWebSocket.cancelConnectionLostTimer
test
private void cancelConnectionLostTimer() { if( connectionLostCheckerService != null ) { connectionLostCheckerService.shutdownNow(); connectionLostCheckerService = null; } if( connectionLostCheckerFuture != null ) { connectionLostCheckerFuture.cancel(false); connectionLostCheckerFuture = null; } }
java
{ "resource": "" }
q170608
WebSocketAdapter.onWebsocketHandshakeReceivedAsServer
test
@Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException { return new HandshakeImpl1Server(); }
java
{ "resource": "" }
q170609
WebSocketAdapter.onWebsocketPing
test
@Override public void onWebsocketPing( WebSocket conn, Framedata f ) { conn.sendFrame( new PongFrame( (PingFrame)f ) ); }
java
{ "resource": "" }
q170610
WebSocketServer.stop
test
public void stop( int timeout ) throws InterruptedException { if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections return; } List<WebSocket> socketsToClose; // copy the connections in a list (prevent callback deadlocks) synchronized ( connections ) { socketsToClose = new ArrayList<WebSocket>( connections ); } for( WebSocket ws : socketsToClose ) { ws.close( CloseFrame.GOING_AWAY ); } wsf.close(); synchronized ( this ) { if( selectorthread != null && selector != null) { selector.wakeup(); selectorthread.join( timeout ); } } }
java
{ "resource": "" }
q170611
WebSocketServer.getPort
test
public int getPort() { int port = getAddress().getPort(); if( port == 0 && server != null ) { port = server.socket().getLocalPort(); } return port; }
java
{ "resource": "" }
q170612
WebSocketServer.doAdditionalRead
test
private void doAdditionalRead() throws InterruptedException, IOException { WebSocketImpl conn; while ( !iqueue.isEmpty() ) { conn = iqueue.remove( 0 ); WrappedByteChannel c = ( (WrappedByteChannel) conn.getChannel() ); ByteBuffer buf = takeBuffer(); try { if( SocketChannelIOHelper.readMore( buf, conn, c ) ) iqueue.add( conn ); if( buf.hasRemaining() ) { conn.inQueue.put( buf ); queue( conn ); } else { pushBuffer( buf ); } } catch ( IOException e ) { pushBuffer( buf ); throw e; } } }
java
{ "resource": "" }
q170613
WebSocketServer.doAccept
test
private void doAccept(SelectionKey key, Iterator<SelectionKey> i) throws IOException, InterruptedException { if( !onConnect( key ) ) { key.cancel(); return; } SocketChannel channel = server.accept(); if(channel==null){ return; } channel.configureBlocking( false ); Socket socket = channel.socket(); socket.setTcpNoDelay( isTcpNoDelay() ); socket.setKeepAlive( true ); WebSocketImpl w = wsf.createWebSocket( this, drafts ); w.setSelectionKey(channel.register( selector, SelectionKey.OP_READ, w )); try { w.setChannel( wsf.wrapChannel( channel, w.getSelectionKey() )); i.remove(); allocateBuffers( w ); } catch (IOException ex) { if( w.getSelectionKey() != null ) w.getSelectionKey().cancel(); handleIOException( w.getSelectionKey(), null, ex ); } }
java
{ "resource": "" }
q170614
WebSocketServer.doRead
test
private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, IOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); ByteBuffer buf = takeBuffer(); if(conn.getChannel() == null){ key.cancel(); handleIOException( key, conn, new IOException() ); return false; } try { if( SocketChannelIOHelper.read( buf, conn, conn.getChannel() ) ) { if( buf.hasRemaining() ) { conn.inQueue.put( buf ); queue( conn ); i.remove(); if( conn.getChannel() instanceof WrappedByteChannel && ( (WrappedByteChannel) conn.getChannel() ).isNeedRead() ) { iqueue.add( conn ); } } else { pushBuffer(buf); } } else { pushBuffer( buf ); } } catch ( IOException e ) { pushBuffer( buf ); throw e; } return true; }
java
{ "resource": "" }
q170615
WebSocketServer.doWrite
test
private void doWrite(SelectionKey key) throws IOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); if( SocketChannelIOHelper.batch( conn, conn.getChannel() ) ) { if( key.isValid() ) { key.interestOps(SelectionKey.OP_READ); } } }
java
{ "resource": "" }
q170616
WebSocketServer.doSetupSelectorAndServerThread
test
private boolean doSetupSelectorAndServerThread() { selectorthread.setName( "WebSocketSelector-" + selectorthread.getId() ); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); ServerSocket socket = server.socket(); socket.setReceiveBufferSize( WebSocketImpl.RCVBUF ); socket.setReuseAddress( isReuseAddr() ); socket.bind( address ); selector = Selector.open(); server.register( selector, server.validOps() ); startConnectionLostTimer(); for( WebSocketWorker ex : decoders ){ ex.start(); } onStart(); } catch ( IOException ex ) { handleFatal( null, ex ); return false; } return true; }
java
{ "resource": "" }
q170617
WebSocketServer.doEnsureSingleThread
test
private boolean doEnsureSingleThread() { synchronized ( this ) { if( selectorthread != null ) throw new IllegalStateException( getClass().getName() + " can only be started once." ); selectorthread = Thread.currentThread(); if( isclosed.get() ) { return false; } } return true; }
java
{ "resource": "" }
q170618
WebSocketServer.doServerShutdown
test
private void doServerShutdown() { stopConnectionLostTimer(); if( decoders != null ) { for( WebSocketWorker w : decoders ) { w.interrupt(); } } if( selector != null ) { try { selector.close(); } catch ( IOException e ) { log.error( "IOException during selector.close", e ); onError( null, e ); } } if( server != null ) { try { server.close(); } catch ( IOException e ) { log.error( "IOException during server.close", e ); onError( null, e ); } } }
java
{ "resource": "" }
q170619
WebSocketServer.getSocket
test
private Socket getSocket( WebSocket conn ) { WebSocketImpl impl = (WebSocketImpl) conn; return ( (SocketChannel) impl.getSelectionKey().channel() ).socket(); }
java
{ "resource": "" }
q170620
WebSocketServer.broadcast
test
public void broadcast(byte[] data, Collection<WebSocket> clients) { if (data == null || clients == null) { throw new IllegalArgumentException(); } broadcast(ByteBuffer.wrap(data), clients); }
java
{ "resource": "" }
q170621
WebSocketServer.broadcast
test
public void broadcast(String text, Collection<WebSocket> clients) { if (text == null || clients == null) { throw new IllegalArgumentException(); } doBroadcast(text, clients); }
java
{ "resource": "" }
q170622
WebSocketServer.doBroadcast
test
private void doBroadcast(Object data, Collection<WebSocket> clients) { String sData = null; if (data instanceof String) { sData = (String)data; } ByteBuffer bData = null; if (data instanceof ByteBuffer) { bData = (ByteBuffer)data; } if (sData == null && bData == null) { return; } Map<Draft, List<Framedata>> draftFrames = new HashMap<Draft, List<Framedata>>(); for( WebSocket client : clients ) { if( client != null ) { Draft draft = client.getDraft(); fillFrames(draft, draftFrames, sData, bData); try { client.sendFrame( draftFrames.get( draft ) ); } catch ( WebsocketNotConnectedException e ) { //Ignore this exception in this case } } } }
java
{ "resource": "" }
q170623
WebSocketServer.fillFrames
test
private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String sData, ByteBuffer bData) { if( !draftFrames.containsKey( draft ) ) { List<Framedata> frames = null; if (sData != null) { frames = draft.createFrames( sData, false ); } if (bData != null) { frames = draft.createFrames( bData, false ); } if (frames != null) { draftFrames.put(draft, frames); } } }
java
{ "resource": "" }
q170624
ByteBufferUtils.transferByteBuffer
test
public static int transferByteBuffer( ByteBuffer source, ByteBuffer dest ) { if( source == null || dest == null ) { throw new IllegalArgumentException(); } int fremain = source.remaining(); int toremain = dest.remaining(); if( fremain > toremain ) { int limit = Math.min( fremain, toremain ); source.limit( limit ); dest.put( source ); return limit; } else { dest.put( source ); return fremain; } }
java
{ "resource": "" }
q170625
DefaultJPAApi.start
test
public JPAApi start() { jpaConfig .persistenceUnits() .forEach( persistenceUnit -> emfs.put( persistenceUnit.name, Persistence.createEntityManagerFactory(persistenceUnit.unitName))); return this; }
java
{ "resource": "" }
q170626
DefaultJPAApi.em
test
public EntityManager em(String name) { EntityManagerFactory emf = emfs.get(name); if (emf == null) { return null; } return emf.createEntityManager(); }
java
{ "resource": "" }
q170627
DefaultJPAApi.withTransaction
test
public void withTransaction(Consumer<EntityManager> block) { withTransaction( em -> { block.accept(em); return null; }); }
java
{ "resource": "" }
q170628
MessagesApi.convertArgsToScalaBuffer
test
private static Seq<Object> convertArgsToScalaBuffer(final Object... args) { return scala.collection.JavaConverters.asScalaBufferConverter(wrapArgsToListIfNeeded(args)) .asScala() .toList(); }
java
{ "resource": "" }
q170629
MessagesApi.wrapArgsToListIfNeeded
test
@SafeVarargs private static <T> List<T> wrapArgsToListIfNeeded(final T... args) { List<T> out; if (args != null && args.length == 1 && args[0] instanceof List) { out = (List<T>) args[0]; } else { out = Arrays.asList(args); } return out; }
java
{ "resource": "" }
q170630
MessagesApi.get
test
public String get(play.api.i18n.Lang lang, String key, Object... args) { Seq<Object> scalaArgs = convertArgsToScalaBuffer(args); return messages.apply(key, scalaArgs, lang); }
java
{ "resource": "" }
q170631
MessagesApi.get
test
public String get(play.api.i18n.Lang lang, List<String> keys, Object... args) { Buffer<String> keyArgs = scala.collection.JavaConverters.asScalaBufferConverter(keys).asScala(); Seq<Object> scalaArgs = convertArgsToScalaBuffer(args); return messages.apply(keyArgs.toSeq(), scalaArgs, lang); }
java
{ "resource": "" }
q170632
MessagesApi.isDefinedAt
test
public Boolean isDefinedAt(play.api.i18n.Lang lang, String key) { return messages.isDefinedAt(key, lang); }
java
{ "resource": "" }
q170633
MessagesApi.preferred
test
public Messages preferred(Collection<Lang> candidates) { Seq<Lang> cs = Scala.asScala(candidates); play.api.i18n.Messages msgs = messages.preferred((Seq) cs); return new MessagesImpl(new Lang(msgs.lang()), this); }
java
{ "resource": "" }
q170634
MessagesApi.preferred
test
public Messages preferred(Http.RequestHeader request) { play.api.i18n.Messages msgs = messages.preferred(request); return new MessagesImpl(new Lang(msgs.lang()), this); }
java
{ "resource": "" }
q170635
MessagesApi.setLang
test
public Result setLang(Result result, Lang lang) { return messages.setLang(result.asScala(), lang).asJava(); }
java
{ "resource": "" }
q170636
GuiceBuilder.bindings
test
public final Self bindings(GuiceableModule... modules) { return newBuilder(delegate.bindings(Scala.varargs(modules))); }
java
{ "resource": "" }
q170637
GuiceBuilder.bindings
test
public final Self bindings(play.api.inject.Module... modules) { return bindings(Guiceable.modules(modules)); }
java
{ "resource": "" }
q170638
GuiceBuilder.bindings
test
public final Self bindings(play.api.inject.Binding<?>... bindings) { return bindings(Guiceable.bindings(bindings)); }
java
{ "resource": "" }
q170639
GuiceBuilder.overrides
test
public final Self overrides(GuiceableModule... modules) { return newBuilder(delegate.overrides(Scala.varargs(modules))); }
java
{ "resource": "" }
q170640
GuiceBuilder.overrides
test
public final Self overrides(play.api.inject.Module... modules) { return overrides(Guiceable.modules(modules)); }
java
{ "resource": "" }
q170641
GuiceBuilder.overrides
test
public final Self overrides(play.api.inject.Binding<?>... bindings) { return overrides(Guiceable.bindings(bindings)); }
java
{ "resource": "" }
q170642
GuiceBuilder.disable
test
public final Self disable(Class<?>... moduleClasses) { return newBuilder(delegate.disable(Scala.toSeq(moduleClasses))); }
java
{ "resource": "" }
q170643
Action.call
test
@Deprecated // TODO: When you remove this method make call(Request) below abstract public CompletionStage<Result> call(Context ctx) { return call( ctx.args != null && !ctx.args.isEmpty() ? ctx.request().addAttr(CTX_ARGS, ctx.args) : ctx.request()); }
java
{ "resource": "" }
q170644
Action.call
test
public CompletionStage<Result> call( Request req) { // TODO: Make this method abstract after removing call(Context) return Context.safeCurrent() .map( threadLocalCtx -> { // A previous action did explicitly set a context onto the thread local (via // Http.Context.current.set(...)) // Let's use that context so the user doesn't loose data he/she set onto that ctx // (args,...) Context newCtx = threadLocalCtx.withRequest(req.removeAttr(CTX_ARGS)); Context.setCurrent(newCtx); return call(newCtx); }) .orElseGet( () -> { // A previous action did not set a context explicitly, we simply create a new one to // pass on the request Context ctx = new Context(req.removeAttr(CTX_ARGS), contextComponents); ctx.args = req.attrs().getOptional(CTX_ARGS).orElse(new HashMap<>()); return call(ctx); }); }
java
{ "resource": "" }
q170645
Environment.getExistingFile
test
public Optional<File> getExistingFile(String relativePath) { return OptionConverters.toJava(env.getExistingFile(relativePath)); }
java
{ "resource": "" }
q170646
Binding.in
test
public <A extends Annotation> Binding<T> in(final Class<A> scope) { return underlying.in(scope).asJava(); }
java
{ "resource": "" }
q170647
F.Tuple
test
public static <A, B> Tuple<A, B> Tuple(A a, B b) { return new Tuple<A, B>(a, b); }
java
{ "resource": "" }
q170648
F.Tuple5
test
public static <A, B, C, D, E> Tuple5<A, B, C, D, E> Tuple5(A a, B b, C c, D d, E e) { return new Tuple5<A, B, C, D, E>(a, b, c, d, e); }
java
{ "resource": "" }
q170649
F.toExecutor
test
private static Executor toExecutor(ExecutionContext ec) { ExecutionContext prepared = ec.prepare(); if (prepared instanceof Executor) { return (Executor) prepared; } else { return prepared::execute; } }
java
{ "resource": "" }
q170650
DefaultJPAConfig.of
test
public static JPAConfig of(String name, String unitName) { return new DefaultJPAConfig(new JPAConfig.PersistenceUnit(name, unitName)); }
java
{ "resource": "" }
q170651
DefaultJPAConfig.of
test
public static JPAConfig of(String n1, String u1, String n2, String u2) { return new DefaultJPAConfig( new JPAConfig.PersistenceUnit(n1, u1), new JPAConfig.PersistenceUnit(n2, u2)); }
java
{ "resource": "" }
q170652
DefaultJPAConfig.from
test
public static JPAConfig from(Map<String, String> map) { ImmutableSet.Builder<JPAConfig.PersistenceUnit> persistenceUnits = new ImmutableSet.Builder<JPAConfig.PersistenceUnit>(); for (Map.Entry<String, String> entry : map.entrySet()) { persistenceUnits.add(new JPAConfig.PersistenceUnit(entry.getKey(), entry.getValue())); } return new DefaultJPAConfig(persistenceUnits.build()); }
java
{ "resource": "" }
q170653
Comet.string
test
public static Flow<String, ByteString, NotUsed> string(String callbackName) { return Flow.of(String.class) .map( str -> { return ByteString.fromString("'" + StringEscapeUtils.escapeEcmaScript(str) + "'"); }) .via(flow(callbackName)); }
java
{ "resource": "" }
q170654
Comet.json
test
public static Flow<JsonNode, ByteString, NotUsed> json(String callbackName) { return Flow.of(JsonNode.class) .map( json -> { return ByteString.fromString(Json.stringify(json)); }) .via(flow(callbackName)); }
java
{ "resource": "" }
q170655
MappedConstraintValidatorFactory.addConstraintValidator
test
public <T extends ConstraintValidator<?, ?>> MappedConstraintValidatorFactory addConstraintValidator(Class<T> key, T constraintValidator) { validators.put(key, () -> constraintValidator); return this; }
java
{ "resource": "" }
q170656
MappedConstraintValidatorFactory.newInstance
test
private <T extends ConstraintValidator<?, ?>> T newInstance(Class<T> key) { try { return key.getDeclaredConstructor().newInstance(); } catch (InstantiationException | RuntimeException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) { throw new RuntimeException(ex); } }
java
{ "resource": "" }
q170657
MethodUtils.getMatchingAccessibleMethod
test
public static Method getMatchingAccessibleMethod( final Class<?> cls, final String methodName, final Class<?>... parameterTypes) { try { final Method method = cls.getMethod(methodName, parameterTypes); MemberUtils.setAccessibleWorkaround(method); return method; } catch (final NoSuchMethodException e) { // NOPMD - Swallow the exception } // search through all methods Method bestMatch = null; final Method[] methods = cls.getMethods(); for (final Method method : methods) { // compare name and parameters if (method.getName().equals(methodName) && MemberUtils.isMatchingMethod(method, parameterTypes)) { // get accessible version of method final Method accessibleMethod = getAccessibleMethod(method); if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareMethodFit(accessibleMethod, bestMatch, parameterTypes) < 0)) { bestMatch = accessibleMethod; } } } if (bestMatch != null) { MemberUtils.setAccessibleWorkaround(bestMatch); } if (bestMatch != null && bestMatch.isVarArgs() && bestMatch.getParameterTypes().length > 0 && parameterTypes.length > 0) { final Class<?>[] methodParameterTypes = bestMatch.getParameterTypes(); final Class<?> methodParameterComponentType = methodParameterTypes[methodParameterTypes.length - 1].getComponentType(); final String methodParameterComponentTypeName = ClassUtils.primitiveToWrapper(methodParameterComponentType).getName(); final String parameterTypeName = parameterTypes[parameterTypes.length - 1].getName(); final String parameterTypeSuperClassName = parameterTypes[parameterTypes.length - 1].getSuperclass().getName(); if (!methodParameterComponentTypeName.equals(parameterTypeName) && !methodParameterComponentTypeName.equals(parameterTypeSuperClassName)) { return null; } } return bestMatch; }
java
{ "resource": "" }
q170658
DefaultHttpErrorHandler.onClientError
test
@Override public CompletionStage<Result> onClientError( RequestHeader request, int statusCode, String message) { if (statusCode == 400) { return onBadRequest(request, message); } else if (statusCode == 403) { return onForbidden(request, message); } else if (statusCode == 404) { return onNotFound(request, message); } else if (statusCode >= 400 && statusCode < 500) { return onOtherClientError(request, statusCode, message); } else { throw new IllegalArgumentException( "onClientError invoked with non client error status code " + statusCode + ": " + message); } }
java
{ "resource": "" }
q170659
DefaultHttpErrorHandler.onBadRequest
test
protected CompletionStage<Result> onBadRequest(RequestHeader request, String message) { return CompletableFuture.completedFuture( Results.badRequest( views.html.defaultpages.badRequest.render( request.method(), request.uri(), message, request.asScala()))); }
java
{ "resource": "" }
q170660
DefaultHttpErrorHandler.onForbidden
test
protected CompletionStage<Result> onForbidden(RequestHeader request, String message) { return CompletableFuture.completedFuture( Results.forbidden(views.html.defaultpages.unauthorized.render(request.asScala()))); }
java
{ "resource": "" }
q170661
DefaultHttpErrorHandler.onNotFound
test
protected CompletionStage<Result> onNotFound(RequestHeader request, String message) { if (environment.isProd()) { return CompletableFuture.completedFuture( Results.notFound( views.html.defaultpages.notFound.render( request.method(), request.uri(), request.asScala()))); } else { return CompletableFuture.completedFuture( Results.notFound( views.html.defaultpages.devNotFound.render( request.method(), request.uri(), Some.apply(routes.get()), request.asScala()))); } }
java
{ "resource": "" }
q170662
DefaultHttpErrorHandler.onServerError
test
@Override public CompletionStage<Result> onServerError(RequestHeader request, Throwable exception) { try { UsefulException usefulException = throwableToUsefulException(exception); logServerError(request, usefulException); switch (environment.mode()) { case PROD: return onProdServerError(request, usefulException); default: return onDevServerError(request, usefulException); } } catch (Exception e) { logger.error("Error while handling error", e); return CompletableFuture.completedFuture(Results.internalServerError()); } }
java
{ "resource": "" }
q170663
DefaultHttpErrorHandler.logServerError
test
protected void logServerError(RequestHeader request, UsefulException usefulException) { logger.error( String.format( "\n\n! @%s - Internal server error, for (%s) [%s] ->\n", usefulException.id, request.method(), request.uri()), usefulException); }
java
{ "resource": "" }
q170664
DefaultHttpErrorHandler.throwableToUsefulException
test
protected final UsefulException throwableToUsefulException(final Throwable throwable) { return HttpErrorHandlerExceptions.throwableToUsefulException( sourceMapper.sourceMapper(), environment.isProd(), throwable); }
java
{ "resource": "" }
q170665
DefaultHttpErrorHandler.onDevServerError
test
protected CompletionStage<Result> onDevServerError( RequestHeader request, UsefulException exception) { return CompletableFuture.completedFuture( Results.internalServerError( views.html.defaultpages.devError.render(playEditor, exception, request.asScala()))); }
java
{ "resource": "" }
q170666
DefaultHttpErrorHandler.onProdServerError
test
protected CompletionStage<Result> onProdServerError( RequestHeader request, UsefulException exception) { return CompletableFuture.completedFuture( Results.internalServerError( views.html.defaultpages.error.render(exception, request.asScala()))); }
java
{ "resource": "" }
q170667
BuildDocHandlerFactory.fromResources
test
public static BuildDocHandler fromResources(File[] files, String[] baseDirs) throws IOException { assert (files.length == baseDirs.length); FileRepository[] repositories = new FileRepository[files.length]; List<JarFile> jarFiles = new ArrayList<>(); for (int i = 0; i < files.length; i++) { File file = files[i]; String baseDir = baseDirs[i]; if (file.isDirectory()) { repositories[i] = new FilesystemRepository(file); } else { // Assume it's a jar file JarFile jarFile = new JarFile(file); jarFiles.add(jarFile); repositories[i] = new JarRepository(jarFile, Option.apply(baseDir)); } } return new DocumentationHandler( new AggregateFileRepository(repositories), () -> { for (JarFile jarFile : jarFiles) { jarFile.close(); } }); }
java
{ "resource": "" }
q170668
BuildDocHandlerFactory.fromDirectory
test
public static BuildDocHandler fromDirectory(File directory) { FileRepository repo = new FilesystemRepository(directory); return new DocumentationHandler(repo); }
java
{ "resource": "" }
q170669
BuildDocHandlerFactory.fromDirectoryAndJar
test
public static BuildDocHandler fromDirectoryAndJar(File directory, JarFile jarFile, String base) { return fromDirectoryAndJar(directory, jarFile, base, false); }
java
{ "resource": "" }
q170670
BuildDocHandlerFactory.fromDirectoryAndJar
test
public static BuildDocHandler fromDirectoryAndJar( File directory, JarFile jarFile, String base, boolean fallbackToJar) { FileRepository fileRepo = new FilesystemRepository(directory); FileRepository jarRepo = new JarRepository(jarFile, Option.apply(base)); FileRepository manualRepo; if (fallbackToJar) { manualRepo = new AggregateFileRepository(new FileRepository[] {fileRepo, jarRepo}); } else { manualRepo = fileRepo; } return new DocumentationHandler(manualRepo, jarRepo); }
java
{ "resource": "" }
q170671
BuildDocHandlerFactory.fromJar
test
public static BuildDocHandler fromJar(JarFile jarFile, String base) { FileRepository repo = new JarRepository(jarFile, Option.apply(base)); return new DocumentationHandler(repo); }
java
{ "resource": "" }
q170672
HttpEntity.consumeData
test
public CompletionStage<ByteString> consumeData(Materializer mat) { return dataStream().runFold(ByteString.empty(), ByteString::concat, mat); }
java
{ "resource": "" }
q170673
HttpEntity.fromContent
test
public static final HttpEntity fromContent(Content content, String charset) { String body; if (content instanceof Xml) { // See https://github.com/playframework/playframework/issues/2770 body = content.body().trim(); } else { body = content.body(); } return new Strict( ByteString.fromString(body, charset), Optional.of(content.contentType() + "; charset=" + charset)); }
java
{ "resource": "" }
q170674
HttpEntity.fromString
test
public static final HttpEntity fromString(String content, String charset) { return new Strict( ByteString.fromString(content, charset), Optional.of("text/plain; charset=" + charset)); }
java
{ "resource": "" }
q170675
HttpEntity.chunked
test
public static final HttpEntity chunked(Source<ByteString, ?> data, Optional<String> contentType) { return new Chunked(data.map(HttpChunk.Chunk::new), contentType); }
java
{ "resource": "" }
q170676
Results.status
test
public static Result status(int status, JsonNode content) { return status(status, content, JsonEncoding.UTF8); }
java
{ "resource": "" }
q170677
Results.status
test
public static Result status(int status, JsonNode content, JsonEncoding encoding) { if (content == null) { throw new NullPointerException("Null content"); } return status(status).sendJson(content, encoding); }
java
{ "resource": "" }
q170678
Results.status
test
public static Result status(int status, byte[] content) { if (content == null) { throw new NullPointerException("Null content"); } return new Result( status, new HttpEntity.Strict(ByteString.fromArray(content), Optional.empty())); }
java
{ "resource": "" }
q170679
Results.status
test
public static Result status(int status, InputStream content, long contentLength) { return status(status).sendInputStream(content, contentLength); }
java
{ "resource": "" }
q170680
Results.status
test
public static Result status(int status, File content) { return status(status, content, StaticFileMimeTypes.fileMimeTypes()); }
java
{ "resource": "" }
q170681
User.findById
test
private User findById(Long id) { if (id > 3) return null; User user = new User(); user.id = id; user.name = "User " + String.valueOf(id); return user; }
java
{ "resource": "" }
q170682
Langs.preferred
test
public Lang preferred(Collection<Lang> candidates) { return new Lang( langs.preferred((scala.collection.immutable.Seq) Scala.asScala(candidates).toSeq())); }
java
{ "resource": "" }
q170683
Call.unique
test
public Call unique() { return new play.api.mvc.Call(method(), this.uniquify(this.url()), fragment()); }
java
{ "resource": "" }
q170684
Call.withFragment
test
public Call withFragment(String fragment) { return new play.api.mvc.Call(method(), url(), fragment); }
java
{ "resource": "" }
q170685
Call.absoluteURL
test
public String absoluteURL(Http.Request request) { return absoluteURL(request.secure(), request.host()); }
java
{ "resource": "" }
q170686
Call.webSocketURL
test
public String webSocketURL(Http.Request request) { return webSocketURL(request.secure(), request.host()); }
java
{ "resource": "" }
q170687
DefaultDatabase.connectionFunction
test
AbstractFunction1<Connection, BoxedUnit> connectionFunction(final ConnectionRunnable block) { return new AbstractFunction1<Connection, BoxedUnit>() { public BoxedUnit apply(Connection connection) { try { block.run(connection); return BoxedUnit.UNIT; } catch (java.sql.SQLException e) { throw new RuntimeException("Connection runnable failed", e); } } }; }
java
{ "resource": "" }
q170688
DefaultDatabase.connectionFunction
test
<A> AbstractFunction1<Connection, A> connectionFunction(final ConnectionCallable<A> block) { return new AbstractFunction1<Connection, A>() { public A apply(Connection connection) { try { return block.call(connection); } catch (java.sql.SQLException e) { throw new RuntimeException("Connection callable failed", e); } } }; }
java
{ "resource": "" }
q170689
Server.forRouter
test
public static Server forRouter(Mode mode, int port, Function<BuiltInComponents, Router> block) { return new Builder().mode(mode).http(port).build(block); }
java
{ "resource": "" }
q170690
Json.toJson
test
public static JsonNode toJson(final Object data) { try { return mapper().valueToTree(data); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q170691
Json.fromJson
test
public static <A> A fromJson(JsonNode json, Class<A> clazz) { try { return mapper().treeToValue(json, clazz); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q170692
Json.parse
test
public static JsonNode parse(String src) { try { return mapper().readTree(src); } catch (Throwable t) { throw new RuntimeException(t); } }
java
{ "resource": "" }
q170693
Json.parse
test
public static JsonNode parse(java.io.InputStream src) { try { return mapper().readTree(src); } catch (Throwable t) { throw new RuntimeException(t); } }
java
{ "resource": "" }
q170694
Paths.relative
test
public static String relative(String startPath, String targetPath) { // If the start and target path's are the same then link to the current directory if (startPath.equals(targetPath)) { return CURRENT_DIR; } String[] start = toSegments(canonical(startPath)); String[] target = toSegments(canonical(targetPath)); // If start path has no trailing separator (a "file" path), then drop file segment if (!startPath.endsWith(SEPARATOR)) start = Arrays.copyOfRange(start, 0, start.length - 1); // If target path has no trailing separator, then drop file segment, but keep a reference to add // it later String targetFile = ""; if (!targetPath.endsWith(SEPARATOR)) { targetFile = target[target.length - 1]; target = Arrays.copyOfRange(target, 0, target.length - 1); } // Work out how much of the filepath is shared by start and path. String[] common = commonPrefix(start, target); String[] parents = toParentDirs(start.length - common.length); int relativeStartIdx = common.length; String[] relativeDirs = Arrays.copyOfRange(target, relativeStartIdx, target.length); String[] relativePath = Arrays.copyOf(parents, parents.length + relativeDirs.length); System.arraycopy(relativeDirs, 0, relativePath, parents.length, relativeDirs.length); // If this is not a sibling reference append a trailing / to path String trailingSep = ""; if (relativePath.length > 0) trailingSep = SEPARATOR; return Arrays.stream(relativePath).collect(Collectors.joining(SEPARATOR)) + trailingSep + targetFile; }
java
{ "resource": "" }
q170695
Paths.canonical
test
public static String canonical(String url) { String[] urlPath = toSegments(url); Stack<String> canonical = new Stack<>(); for (String comp : urlPath) { if (comp.isEmpty() || comp.equals(CURRENT_DIR)) continue; if (!comp.equals(PARENT_DIR) || (!canonical.empty() && canonical.peek().equals(PARENT_DIR))) canonical.push(comp); else canonical.pop(); } String prefixSep = url.startsWith(SEPARATOR) ? SEPARATOR : ""; String trailingSep = url.endsWith(SEPARATOR) ? SEPARATOR : ""; return prefixSep + canonical.stream().collect(Collectors.joining(SEPARATOR)) + trailingSep; }
java
{ "resource": "" }
q170696
Constraints.displayableConstraint
test
public static List<Tuple<String, List<Object>>> displayableConstraint( Set<ConstraintDescriptor<?>> constraints) { return constraints .parallelStream() .filter(c -> c.getAnnotation().annotationType().isAnnotationPresent(Display.class)) .map(c -> displayableConstraint(c)) .collect(Collectors.toList()); }
java
{ "resource": "" }
q170697
Constraints.displayableConstraint
test
public static Tuple<String, List<Object>> displayableConstraint( ConstraintDescriptor<?> constraint) { final Display displayAnnotation = constraint.getAnnotation().annotationType().getAnnotation(Display.class); return Tuple( displayAnnotation.name(), Collections.unmodifiableList( Stream.of(displayAnnotation.attributes()) .map(attr -> constraint.getAttributes().get(attr)) .collect(Collectors.toList()))); }
java
{ "resource": "" }
q170698
DefaultFutures.timeout
test
@Override public <A> CompletionStage<A> timeout( final CompletionStage<A> stage, final long amount, final TimeUnit unit) { requireNonNull(stage, "Null stage"); requireNonNull(unit, "Null unit"); FiniteDuration duration = FiniteDuration.apply(amount, unit); return toJava(delegate.timeout(duration, Scala.asScalaWithFuture(() -> stage))); }
java
{ "resource": "" }
q170699
ClassUtils.isAssignable
test
public static boolean isAssignable( Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing) { if (arrayGetLength(classArray) != arrayGetLength(toClassArray)) { return false; } if (classArray == null) { classArray = EMPTY_CLASS_ARRAY; } if (toClassArray == null) { toClassArray = EMPTY_CLASS_ARRAY; } for (int i = 0; i < classArray.length; i++) { if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) { return false; } } return true; }
java
{ "resource": "" }