code
stringlengths
73
34.1k
label
stringclasses
1 value
public static String stripTrailingSlash(String s) { return s == null ? null : CharMatcher.is('/').trimTrailingFrom(s); }
java
public static Timestamp fromEpoch(long epochMillis) { return Timestamp .newBuilder() .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI)) .setSeconds(epochMillis / MILLIS_PER_SECOND) .build(); }
java
public static void pushCurrentThreadValidationContext(Supplier<String> supplier) { Stack<Supplier<String>> stack = contextLocal.get(); if (stack == null) { stack = new Stack<>(); contextLocal.set(stack); } stack.push(supplier); }
java
public boolean report(ReportRequest req) { if (cache == null) { return false; } Preconditions.checkArgument(req.getServiceName().equals(serviceName), "service name mismatch"); if (hasHighImportanceOperation(req)) { return false; } Map<String, Operation> bySignature = opsBySignature(r...
java
public static String getRealHttpMethod(ServletRequest req) { HttpServletRequest httpRequest = (HttpServletRequest) req; String method = (String) httpRequest.getAttribute(HTTP_METHOD_OVERRIDE_ATTRIBUTE); if (method != null) { return method; } return httpRequest.getMethod(); }
java
public PathTemplate parentTemplate() { int i = segments.size(); Segment seg = segments.get(--i); if (seg.kind() == SegmentKind.END_BINDING) { while (i > 0 && segments.get(--i).kind() != SegmentKind.BINDING) {} } if (i == 0) { throw new ValidationException("template does not have a parent...
java
public PathTemplate withoutVars() { StringBuilder result = new StringBuilder(); ListIterator<Segment> iterator = segments.listIterator(); boolean start = true; while (iterator.hasNext()) { Segment seg = iterator.next(); switch (seg.kind()) { case BINDING: case END_BINDING: ...
java
@Nullable public String singleVar() { if (bindings.size() == 1) { return bindings.entrySet().iterator().next().getKey(); } return null; }
java
public void validate(String path, String exceptionMessagePrefix) { if (!matches(path)) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", exceptionMessagePrefix, path, this.toString())); } }
java
public ImmutableMap<String, String> validatedMatch(String path, String exceptionMessagePrefix) { ImmutableMap<String, String> matchMap = match(path); if (matchMap == null) { throw new ValidationException( String.format( "%s: Parameter \"%s\" must be in the form \"%s\"", ...
java
@Nullable public ImmutableMap<String, String> match(String path) { return match(path, false); }
java
private ImmutableMap<String, String> match(String path, boolean forceHostName) { // Quick check for trailing custom verb. Segment last = segments.get(segments.size() - 1); if (last.kind() == SegmentKind.CUSTOM_VERB) { Matcher matcher = CUSTOM_VERB_PATTERN.matcher(path); if (!matcher.find() || !d...
java
private boolean match( List<String> input, int inPos, List<Segment> segments, int segPos, Map<String, String> values) { String currentVar = null; while (segPos < segments.size()) { Segment seg = segments.get(segPos++); switch (seg.kind()) { case END_BINDING: ...
java
public String encode(String... values) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); int i = 0; for (String value : values) { builder.put("$" + i++, value); } // We will get an error if there are named bindings which are not reached by values. return instantiate(...
java
public List<String> decode(String path) { Map<String, String> match = match(path); if (match == null) { throw new IllegalArgumentException(String.format("template '%s' does not match '%s'", this, path)); } List<String> result = Lists.newArrayList(); for (Map.Entry<String, String> ent...
java
private static boolean peek(ListIterator<Segment> segments, SegmentKind... kinds) { int start = segments.nextIndex(); boolean success = false; for (SegmentKind kind : kinds) { if (!segments.hasNext() || segments.next().kind() != kind) { success = false; break; } } if (suc...
java
@Override public void filter(final ContainerRequestContext containerRequestContext) { if (backend.getConfiguration().shouldProcessContext(IncomingRequest)) { final List<String> serializedTraceeHeaders = containerRequestContext.getHeaders().get(TraceeConstants.TPIC_HEADER); if (serializedTraceeHeaders != null ...
java
@Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) { if (backend.getConfiguration().shouldProcessContext(OutgoingResponse)) { final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingResp...
java
public Map<String, String> parseSoapHeader(final Element soapHeader) { final NodeList tpicHeaders = soapHeader.getElementsByTagNameNS(TraceeConstants.SOAP_HEADER_NAMESPACE, TraceeConstants.TPIC_HEADER); final HashMap<String, String> contextMap = new HashMap<>(); if (tpicHeaders != null && tpicHeaders.getLength() ...
java
public void renderSoapHeader(final Map<String, String> context, final SOAPHeader soapHeader) { renderSoapHeader(SOAP_HEADER_MARSHALLER, context, soapHeader); }
java
protected Client createClient(String configServiceName) throws GeneralSecurityException, IOException { return new Client.Builder(configServiceName) .setStatsLogFrequency(statsLogFrequency()) .setHttpTransport(new NetHttpTransport()) .build(); }
java
private static String constructOpenIdUrl(String issuer) { String url = issuer; if (!URI.create(issuer).isAbsolute()) { // Use HTTPS if the protocol scheme is not specified in the URL. url = HTTPS_PROTOCOL_PREFIX + issuer; } if (!url.endsWith("/")) { url += "/"; } return url + O...
java
protected void writeTraceeContextToMessage(Message message) throws JMSException { if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(AsyncDispatch)) { final Map<String, String> filteredContext = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), AsyncDispatch); final Stri...
java
public UserInfo authenticate( HttpServletRequest httpServletRequest, AuthInfo authInfo, String serviceName) { Preconditions.checkNotNull(httpServletRequest); Preconditions.checkNotNull(authInfo); Optional<String> maybeAuthToken = extractAuthToken(httpServletRequest); if (!maybeAuthTo...
java
private void checkJwtClaims(JwtClaims jwtClaims) { Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims); if (!expiration.isPresent()) { throw new UnauthenticatedException("Missing expiration field"); } Optional<NumericDate> notBefore = getDateClaim(Reserve...
java
public static String getCurrentContextClassLoaderClassPath(){ URLClassLoader contextClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); return getUrlClassLoaderClassPath(contextClassLoader); }
java
public static LambdaFactory get(LambdaFactoryConfiguration configuration) { JavaCompiler compiler = Optional.ofNullable(configuration.getJavaCompiler()).orElseThrow(JavaCompilerNotFoundException::new); return new LambdaFactory( configuration.getDefaultHelperClassSourceProvider(), ...
java
public <T> T createLambda(String code, TypeReference<T> typeReference) throws LambdaCreationException { String helperClassSource = helperProvider.getHelperClassSource(typeReference.toString(), code, imports, staticImports); try { Class<?> helperClass = classFactory.createClass(helperProvider...
java
@Override public Long zadd(final String key, final ZsetPair scoremember, final ZsetPair ... scoresmembers) throws WrongTypeException { if (scoremember == null) { return null; } Map<String, Double> sms = new HashMap<String, Double>(); sms.put(scoremember.member, scoremember.sc...
java
public Set<Instance> runOnceOn(InetAddress localhost) throws IOException { logger.debug("Running query on {}", localhost); initialQuestion = new Question(service, domain); instances = Collections.synchronizedSet(new HashSet<>()); try { Thread listener = null; if (...
java
private void fetchMissingRecords() throws IOException { logger.debug("Records includes:"); records.forEach(r -> logger.debug("{}", r)); for (PtrRecord ptr : records.stream().filter(r -> r instanceof PtrRecord).map(r -> (PtrRecord) r).collect(Collectors.toList())) { fetchMissingSrvRec...
java
public boolean matches(String path, MatchingStrategy matchingStrategy) { return path!=null && matchingStrategy.matches(clause, path); }
java
public void addGroup(Group section) { if (section != null) { if (section.isAnyAgent()) { if (this.defaultSection == null) { this.defaultSection = section; } else { this.defaultSection.getAccessList().importAccess(section.getAccessList()); } } else { Gr...
java
private Group findExactSection(Group section) { for (Group s : groups) { if (s.isExact(section)) { return s; } } return null; }
java
public RobotsTxt readRobotsTxt(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); Group currentGroup = null; boolean startGroup = false; RobotsTxtImpl robots = new RobotsTxtImpl(matchingStrategy, winningStrategy); f...
java
private Entry readEntry(BufferedReader reader) throws IOException { for (String line = reader.readLine(); line != null; line = reader.readLine()) { Entry entry = parseEntry(line); if (entry != null) { return entry; } } return null; }
java
public boolean isExact(Group group) { if (isAnyAgent() && group.isAnyAgent()) return true; if ((isAnyAgent() && !group.isAnyAgent() || (!isAnyAgent() && group.isAnyAgent()))) return false; return group.userAgents.stream().anyMatch(sectionUserAgent->userAgents.stream().anyMatch(userAgent->userAgent.equalsIg...
java
public void addUserAgent(String userAgent) { if (userAgent.equals("*")) { anyAgent = true; } else { this.userAgents.add(userAgent); } }
java
public boolean matchUserAgent(String userAgent) { if (anyAgent) return true; if (!anyAgent && userAgent==null) return false; return userAgents.stream().anyMatch(agent->agent.equalsIgnoreCase(userAgent)); }
java
public static Path getNextPath(String prefix) { Path path; do { path = Paths.get(String.format("%s%s", prefix, Integer.toString(nextDumpPathSuffix))); nextDumpPathSuffix++; } while (Files.exists(path)); return path; }
java
public static void printBuffer(byte[] buffer, String msg) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buffer.length; i++) { if (i % 20 == 0) { sb.append("\n\t"); } sb.append(String.format("%02x", buffer[i])); } logge...
java
public <T> T getHeader(String name, Class<T> type) { return (T) headers.get(name); }
java
public static long readVariableValueLength(final byte[] array, final int offset, final boolean reverse) { long len = 0; byte v; long p = 0; int i = offset; do { v = array[i]; len += ((long) (v & (byte) 0x7f)) << p; p += 7; if (reverse) { --i; } else { ++i; } } while (...
java
protected VPackSlice translateUnchecked() { final VPackSlice result = attributeTranslator.translate(getAsInt()); return result != null ? result : new VPackSlice(); }
java
@Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { if(this.jmsProvider == null || this.producer == null){ throw new IllegalStateException("JMS Provider and MessageProducer not set."); } this.collector = collector; LOG.debug("Connecting JMS.."); try { C...
java
public static <E> E decorateElement(Class<E> clazz, WebElement webElement) { WiseDecorator decorator = new WiseDecorator(new DefaultElementLocatorFactory(webElement)); return decorator.decorate(clazz, webElement); }
java
public static <E> List<E> decorateElements(Class<E> clazz, List<WebElement> webElements) { List<E> elements = Lists.newArrayList(); for (WebElement webElement : webElements) { E element = decorateElement(clazz, webElement); if (element != null) elements.add(element); } return elements; }
java
void addCallbacks(Consumer<? super T> successCallback, Consumer<Throwable> failureCallback, Executor executor) { Objects.requireNonNull(successCallback, "'successCallback' must not be null"); Objects.requireNonNull(failureCallback, "'failureCallback' must not be null"); Objects.requireNonNull(ex...
java
boolean success(T result) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getSuccessState(result); } oldState.callSuccessCallbacks(result); retur...
java
boolean failure(Throwable failure) { State<T> oldState; synchronized (mutex) { if (state.isCompleted()) { return false; } oldState = state; state = state.getFailureState(failure); } oldState.callFailureCallbacks(failure); ...
java
public <E> E initNextPage(Class<E> clazz) { return WisePageFactory.initElements(this.driver, clazz); }
java
private static <T> void acceptResult(CompletableCompletionStage<T> s, Supplier<? extends T> supplier) { try { // exception can be thrown only by supplier. All callbacks are generated by us and they do not throw any exceptions s.complete(supplier.get()); } catch (Throwable e) { ...
java
private static <T> BiConsumer<T, Throwable> completeHandler(CompletableCompletionStage<T> s) { return (result, failure) -> { if (failure == null) { s.complete(result); } else { handleFailure(s, failure); } }; }
java
public final <T> CompletionStage<T> completedStage(T value) { CompletableCompletionStage<T> result = createCompletionStage(); result.complete(value); return result; }
java
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier) { return supplyAsync(supplier, defaultAsyncExecutor); }
java
public final <U> CompletionStage<U> supplyAsync(Supplier<U> supplier, Executor executor) { Objects.requireNonNull(supplier, "supplier must not be null"); return completedStage(null).thenApplyAsync((ignored) -> supplier.get(), executor); }
java
public final CompletionStage<Void> runAsync(Runnable runnable, Executor executor) { Objects.requireNonNull(runnable, "runnable must not be null"); return completedStage(null).thenRunAsync(runnable, executor); }
java
public static <E> void rootElement(WebElement root, E element) { if (element == null || root == null) return; if (element instanceof WebElement) return; for (Class<?> clazz = element.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; ...
java
public static <E> void rootDriver(WebDriver root, E page) { if (page == null || root == null) return; for (Class<?> clazz = page.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { if (Enhancer.isEnhanced(clazz)) continue; Field[] fields = clazz.getDeclaredFields(); for...
java
public static WebDriver getDriver() { WebDriver driver = WEB_DRIVER_THREAD_LOCAL.get(); if (driver == null) throw new IllegalStateException("Driver not set on the WiseContext"); return driver; }
java
public static <A extends Annotation> boolean isAnnotationPresent(Class<?> clazz, Class<A> annotationType) { if (findAnnotation(clazz, annotationType) != null) return true; return false; }
java
public static <T> T initElements(SearchContext searchContext, T instance) { Class<?> currentInstanceHierarchyClass = instance.getClass(); while (currentInstanceHierarchyClass != Object.class) { proxyElements(searchContext, instance, currentInstanceHierarchyClass); currentInstanceHierarchyClass = currentInstan...
java
public SearchResults search(OmdbParameters searchParams) throws OMDBException { SearchResults resultList; if (!searchParams.has(Param.APIKEY)) { searchParams.add(Param.APIKEY, this.apiKey); } String url = OmdbUrlBuilder.create(searchParams); LOG.trace("URL: {}", url);...
java
public SearchResults search(String title) throws OMDBException { return search(new OmdbBuilder() .setApiKey(apiKey) .setSearchTerm(title) .build()); }
java
public OmdbVideoFull getInfo(OmdbParameters parameters) throws OMDBException { OmdbVideoFull result; //Api key should be added only if parameters do not have it already if (!parameters.has(Param.APIKEY)) { parameters.add(Param.APIKEY, this.apiKey); } URL url = OmdbUrl...
java
@JsonAnySetter protected void handleUnknown(String key, Object value) { StringBuilder unknown = new StringBuilder(this.getClass().getSimpleName()); unknown.append(": Unknown property='").append(key); unknown.append("' value='").append(value).append("'"); LOG.trace(unknown.toString()...
java
public static String create(final OmdbParameters params) throws OMDBException { StringBuilder sb = new StringBuilder(BASE_URL); sb.append(DELIMITER_FIRST); //Add the APIKey first if (params.has(Param.APIKEY)) { String apikey = (String) params.get(Param.APIKEY); s...
java
private static void appendParam(final OmdbParameters params, final Param key, StringBuilder sb) { if (params.has(key)) { sb.append(DELIMITER_SUBSEQUENT).append(key.getValue()).append(params.get(key)); } }
java
public static URL generateUrl(final String url) throws OMDBException { try { return new URL(url); } catch (MalformedURLException ex) { throw new OMDBException(ApiExceptionType.INVALID_URL, "Failed to create URL", url, ex); } }
java
public OmdbBuilder setSearchTerm(final String searchTerm) throws OMDBException { if (StringUtils.isBlank(searchTerm)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a search term!"); } params.add(Param.SEARCH, searchTerm); return this; }
java
public OmdbBuilder setImdbId(final String imdbId) throws OMDBException { if (StringUtils.isBlank(imdbId)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide an IMDB ID!"); } params.add(Param.IMDB, imdbId); return this; }
java
public OmdbBuilder setTitle(final String title) throws OMDBException { if (StringUtils.isBlank(title)) { throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide a title!"); } params.add(Param.TITLE, title); return this; }
java
public OmdbBuilder setTypeMovie() { if (!ResultType.isDefault(ResultType.MOVIE)) { params.add(Param.RESULT, ResultType.MOVIE); } return this; }
java
public OmdbBuilder setTypeSeries() { if (!ResultType.isDefault(ResultType.SERIES)) { params.add(Param.RESULT, ResultType.SERIES); } return this; }
java
public OmdbBuilder setTypeEpisode() { if (!ResultType.isDefault(ResultType.EPISODE)) { params.add(Param.RESULT, ResultType.EPISODE); } return this; }
java
public OmdbBuilder setPlot(final PlotType plotType) { if (!PlotType.isDefault(plotType)) { params.add(Param.PLOT, plotType); } return this; }
java
public OmdbBuilder setPlotFull() { if (!PlotType.isDefault(PlotType.FULL)) { params.add(Param.PLOT, PlotType.FULL); } return this; }
java
public OmdbBuilder setPlotShort() { if (!PlotType.isDefault(PlotType.SHORT)) { params.add(Param.PLOT, PlotType.SHORT); } return this; }
java
public OmdbBuilder setTomatoes(boolean tomatoes) { if (DEFAULT_TOMATOES != tomatoes) { params.add(Param.TOMATOES, tomatoes); } return this; }
java
public OmdbBuilder setApiKey(final String apiKey) throws OMDBException { if (StringUtils.isBlank(apiKey)) { throw new OMDBException(ApiExceptionType.AUTH_FAILURE, "Must provide an ApiKey"); } params.add(Param.APIKEY, apiKey); return this; }
java
public void add(Param key, Object value) { // check to see if we have a default value and skip it if (defaults.containsKey(key) && defaults.get(key).equals(value)) { // We already have this value, so skip it return; } parameters.put(key, value); }
java
public void setDateTypeFace(String fontName) { mDateTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mDateTypeFaceSet = true; }
java
public void setMonthTypeFace(String fontName) { mMonthTypeFace = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + fontName); mMonthTypeFaceSet = true; }
java
public static int getDefaultSize(final int size, final int measureSpec) { final int result; final int specMode = MeasureSpec.getMode(measureSpec); final int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.AT_MOST: result = Ma...
java
public void setAdapter(final BaseCircularViewAdapter adapter) { mAdapter = adapter; if (mAdapter != null) { mAdapter.registerDataSetObserver(mAdapterDataSetObserver); } postInvalidate(); }
java
public double distanceFromCenter(final float x, final float y) { return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2)); }
java
public void updateDrawableState(int state, boolean flag) { final int oldState = mCombinedState; // Update the combined state flag if (flag) mCombinedState |= state; else mCombinedState &= ~state; // Set the combined state if (oldState != mCombinedState) { set...
java
public void setVisibility(int visibility) { if (this.visibility != visibility) { final boolean hasSpace = this.visibility == View.VISIBLE || this.visibility == View.INVISIBLE; final boolean removingSpace = visibility == View.GONE; final boolean change = hasSpace && removingSp...
java
public int onTouchEvent(final MotionEvent event) { int status = -2; if (visibility != View.GONE) { final int action = event.getAction(); final boolean isEventInCenterCircle = isInCenterCircle(event.getX(), event.getY()); if (action == MotionEvent.ACTION_DOWN) { ...
java
public Date getExpirationDateAsDate() { if (hasExpirationDate()) { final LocalDateTime endOfMonth = expirationDate.atEndOfMonth() .atStartOfDay().plus(1, ChronoUnit.DAYS).minus(1, ChronoUnit.NANOS); final Instant instant = endOfMonth.atZone(ZoneId.systemDefault()) .toInstant(); ...
java
public Cursor getItem(int position) { if (mDataValid && mCursor != null) { mCursor.moveToPosition(position); return mCursor; } else { return null; } }
java
public void execute() throws MojoExecutionException { if (skipProject()) { getLog().info("POM project detected; skipping"); }else { URLClassLoader classLoader = new URLClassLoader(generateClassPathUrls()); List<Class<?>> interfaceClasses = loadServiceClasses(classLoad...
java
private void writeServiceFiles( Map<String, List<String>> serviceImplementations) throws MojoExecutionException { // TODO give the user an option to write them to the source folder or // any other folder? File parentFolder = new File(getClassFolder(), "META-INF" + File.se...
java
private List<Class<?>> loadServiceClasses(ClassLoader loader) throws MojoExecutionException { List<Class<?>> serviceClasses = new ArrayList<Class<?>>(); for (String serviceClassName : getServices()) { try { Class<?> serviceClass = loader.loadClass(serviceClassName...
java
private Map<String, List<String>> findImplementations(ClassLoader loader, List<Class<?>> interfaceClasses) throws MojoExecutionException { Map<String, List<String>> serviceImplementations = new HashMap<String, List<String>>(); for (String interfa...
java
List<String> listCompiledClasses(final File classFolder) { List<String> classNames = new ArrayList<String>(); if (!classFolder.exists()) { getLog().info("Class folder does not exist; skipping scan"); return classNames; } final String extension = ".class"; ...
java
private List<String> listCompiledClassesRegex(File classFolder) { List<String> classNames = new ArrayList<String>(); Stack<File> todo = new Stack<File>(); todo.push(classFolder); String classFolderPath = classFolder.getAbsolutePath(); getLog().info("ClassFolderPath=" + classFold...
java
public void auth() throws DockerException { try { client.resource(restEndpointUrl + "/auth") .header("Content-Type", MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(authConfig()); } catch (UniformInterfaceException e) { throw new DockerException(e); } }
java
public ClientResponse push(final String name) throws DockerException { if (name == null) { throw new IllegalArgumentException("name is null"); } try { final String registryAuth = registryAuth(); return client.resource(restEndpointUrl + "/images/" + name(name) + "/push") .header("X-Registry-Auth", re...
java
public int tag(String image, String repository, String tag, boolean force) throws DockerException { Preconditions.checkNotNull(image, "image was not specified"); Preconditions.checkNotNull(repository, "repository was not specified"); Preconditions.checkNotNull(tag, " tag was not provided"); MultivaluedMap<Stri...
java