code
stringlengths
73
34.1k
label
stringclasses
1 value
public static List<Player> loadPlayers(List<String> playersFiles) throws PlayerException { log.info("[loadPlayers] Loading all players"); List<Player> players = new ArrayList<>(); if (playersFiles.size() < 1) { log.warn("[loadPlayers] No players to load"); } for (String singlePath : playersFiles) { Play...
java
public void add(Collection<Dashboard> dashboards) { for(Dashboard dashboard : dashboards) this.dashboards.put(dashboard.getId(), dashboard); }
java
@Override public synchronized void write(final Event event) throws IOException { if (!acceptsEvents) { log.warn("Writer not ready, discarding event: {}", event); return; } delegate.write(event); uncommittedWriteCount++; commitIfNeeded(); }
java
@Managed(description = "Commit locally spooled events for flushing") @Override public synchronized void forceCommit() throws IOException { log.debug("Performing commit on delegate EventWriter [{}]", delegate.getClass()); delegate.commit(); uncommittedWriteCount = 0; lastComm...
java
public OptionalFunction<T, R> orElse(Supplier<R> supplier) { return new OptionalFunction<>(function, supplier); }
java
public OptionalFunction<T, R> orElseThrow(Supplier<? extends RuntimeException> exceptionSupplier) { return new OptionalFunction<>(this.function, () -> { throw exceptionSupplier.get(); }); }
java
public static TimeZone getTimeZone(String name) { TimeZone ret = null; if(timezones != null) { for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getName().equals(name)) ret = timezones[i].getTimeZone(); ...
java
public static TimeZone getTimeZoneById(String id) { TimeZone ret = null; if(timezones != null) { for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getId().equals(id)) ret = timezones[i].getTimeZone(); ...
java
public static TimeZone getTimeZoneByIdIgnoreCase(String id) { TimeZone ret = null; if(timezones != null) { id = id.toLowerCase(); for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getId().toLowerCase().equals(id)) ...
java
private String getDisplayName() { long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()); long minutes = Math.abs(TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) -TimeUnit.HOURS.toMinutes(hours)); return String.format("(GMT%+d:%02d) %s", hours, minutes, tz.getID()); ...
java
public void report(DiagnosticPosition pos, String msg, Object... args) { JavaFileObject currentSource = log.currentSourceFile(); if (verbose) { if (sourcesWithReportedWarnings == null) sourcesWithReportedWarnings = new HashSet<JavaFileObject>(); if (log.nwarning...
java
public static long combineInts(String high, String low) throws NumberFormatException { int highInt = Integer.parseInt(high); int lowInt = Integer.parseInt(low); /* * Shift the high integer into the upper 32 bits and add the low * integer. However, since this is really a si...
java
public static Pair<String, String> splitLong(long value) { return Pair.of(String.valueOf((int)(value >> 32)), String.valueOf((int)value)); }
java
public static void sendExpectOk(SocketManager socketManager, String message) throws IOException { expectOk(socketManager.sendAndWait(message)); }
java
public static void expectOk(String response) throws ProtocolException { if (!"OK".equalsIgnoreCase(response)) { throw new ProtocolException(response, Direction.RECEIVE); } }
java
public void printError(SourcePosition pos, String msg) { if (diagListener != null) { report(DiagnosticType.ERROR, pos, msg); return; } if (nerrors < MaxErrors) { String prefix = (pos == null) ? programName : pos.toString(); errWriter.println(prefi...
java
public Object unmarshal(Object map) throws RpcException { return unmarshal(getTypeClass(), map, this.s, this.isOptional); }
java
@SuppressWarnings("unchecked") public Object marshal(Object o) throws RpcException { if (o == null) { return returnNullIfOptional(); } else if (o instanceof BStruct) { return validateMap(structToMap(o, this.s), this.s); } else if (o instanceof Map) { ...
java
private void getUploadUrl(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOGGER.debug("Get blobstore upload url"); String callback = req.getParameter(CALLBACK_PARAM); if (null == callback) { callback = req.getRequestURI(); } String keepQueryParam = r...
java
private static String getEncodeFileName(String userAgent, String fileName) { String encodedFileName = fileName; try { if (userAgent.contains("MSIE") || userAgent.contains("Opera")) { encodedFileName = URLEncoder.encode(fileName, "UTF-8"); } else { encodedFileName = "=?UTF-8?B?" + new...
java
Attribute.Compound enterAnnotation(JCAnnotation a, Type expected, Env<AttrContext> env) { return enterAnnotation(a, expected, env, false); }
java
private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation'...
java
@Override public String[] getSheetNames() { String[] ret = null; if(sheets != null) { ret = new String[sheets.size()]; for(int i = 0; i < sheets.size(); i++) { Sheet sheet = (Sheet)sheets.get(i); ret[i] = sheet.getName()...
java
public String getSharedString(int i) { String ret = null; CTRst string = strings.getSi().get(i); if(string != null && string.getT() != null) ret = string.getT().getValue(); if(ret == null) // cell has multiple formats or fonts { List<CTRElt> list = str...
java
public String getFormatCode(long id) { if(numFmts == null) cacheFormatCodes(); return (String)numFmts.get(new Long(id)); }
java
private void addFormatCode(CTNumFmt fmt) { if(numFmts == null) numFmts = new HashMap(); numFmts.put(fmt.getNumFmtId(), fmt.getFormatCode()); }
java
private long getFormatId(String formatCode) { long ret = 0L; if(formatCode != null && formatCode.length() > 0) { if(numFmts != null) { Iterator it = numFmts.entrySet().iterator(); while(it.hasNext() && ret == 0L) { ...
java
private long getMaxNumFmtId() { long ret = 163; List list = stylesheet.getNumFmts().getNumFmt(); for(int i = 0; i < list.size(); i++) { CTNumFmt numFmt = (CTNumFmt)list.get(i); if(numFmt.getNumFmtId() > ret) ret = numFmt.getNumFmtId(); ...
java
void setSize(int x, int y, int z) { this.sizeX = x; this.sizeY = y; this.sizeZ = z; }
java
public static Object invoke(Object source, String methodName, Class<?>[] parameterTypes, Object[] parameterValues) throws MethodException { Class<? extends Object> clazz = source.getClass(); Method method; if (ArrayUtils.isEmpty(parameterTypes)) { method = findMethod(cla...
java
public static Object invoke(Object source, Method method, Object[] parameterValues) throws MethodException { try { return method.invoke(source, parameterValues); } catch (Exception e) { throw new MethodException(INVOKE_METHOD_FAILED, e); } }
java
public void add(Collection<ApplicationHost> applicationHosts) { for(ApplicationHost applicationHost : applicationHosts) this.applicationHosts.put(applicationHost.getId(), applicationHost); }
java
public ApplicationInstanceCache applicationInstances(long applicationHostId) { ApplicationInstanceCache cache = applicationInstances.get(applicationHostId); if(cache == null) applicationInstances.put(applicationHostId, cache = new ApplicationInstanceCache(applicationHostId)); ret...
java
public void addApplicationInstances(Collection<ApplicationInstance> applicationInstances) { for(ApplicationInstance applicationInstance : applicationInstances) { // Add the instance to any application hosts it is associated with long applicationHostId = applicationInstance.ge...
java
public static ClassReader instance(Context context) { ClassReader instance = context.get(classReaderKey); if (instance == null) instance = new ClassReader(context, true); return instance; }
java
private void init(Symtab syms, boolean definitive) { if (classes != null) return; if (definitive) { Assert.check(packages == null || packages == syms.packages); packages = syms.packages; Assert.check(classes == null || classes == syms.classes); classes = ...
java
private void readClassFile(ClassSymbol c) throws IOException { int magic = nextInt(); if (magic != JAVA_MAGIC) throw badClassFile("illegal.start.of.class.file"); minorVersion = nextChar(); majorVersion = nextChar(); int maxMajor = Target.MAX().majorVersion; i...
java
public PackageSymbol enterPackage(Name name, PackageSymbol owner) { return enterPackage(TypeSymbol.formFullName(name, owner)); }
java
public void shutdown() { interrupt(); try { join(); } catch (Exception x) { _logger.log(Level.WARNING, "Failed to see DaySchedule thread joining", x); } }
java
@Override public void contextInitialized(ServletContextEvent sce) { Gig.bootstrap(sce.getServletContext()); Jaguar.assemble(this); }
java
protected DocumentType upsertType( String reference, String name, ExecutionContext executionContext) { DocumentType documentType = documentTypeRepository.findByReference(reference); if(documentType != null) { documentType.setName(name); } else { ...
java
public static Socket getCurrentSocket() { ConnectionHandler handler = connectionMap.get(Thread.currentThread()); return (handler == null ? null : handler.getSocket()); }
java
public void prepareParameter(Map<String, Object> extra) { if (from != null) { from.prepareParameter(extra); } }
java
public void process() { try { Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml"); XMLInputFactory factory = XMLInputFactory.newInstance(); List<String> persistenceUnits = new ArrayList<String>(); while (urls.hasMoreElements()) { URL url ...
java
public static InputStream getInputStreamFromHttp(String httpFileURL) throws IOException { URLConnection urlConnection = null; urlConnection = new URL(httpFileURL).openConnection(); urlConnection.connect(); return urlConnection.getInputStream(); }
java
public static byte[] getBytesFromHttp(String httpFileURL) throws IOException { InputStream bufferedInputStream = null; try { bufferedInputStream = getInputStreamFromHttp(httpFileURL); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); by...
java
public static <T> Link<T> make(Link<T> root, T object) { Link<T> link = new Link<>(object); if (root == null) { root = link; } else if (root.last == null) { root.next = link; } else { root.last.next = link; } root.last = link...
java
boolean foundGroupFormat(Map<String,?> map, String pkgFormat) { if (map.containsKey(pkgFormat)) { configuration.message.error("doclet.Same_package_name_used", pkgFormat); return true; } return false; }
java
public Map<String,List<PackageDoc>> groupPackages(PackageDoc[] packages) { Map<String,List<PackageDoc>> groupPackageMap = new HashMap<String,List<PackageDoc>>(); String defaultGroupName = (pkgNameGroupMap.isEmpty() && regExpGroupMap.isEmpty())? configuration.message.getText("...
java
String regExpGroupName(String pkgName) { for (int j = 0; j < sortedRegExpList.size(); j++) { String regexp = sortedRegExpList.get(j); if (pkgName.startsWith(regexp)) { return regExpGroupMap.get(regexp); } } return null; }
java
@SuppressWarnings("unchecked") public Map marshal(Contract contract) throws RpcException { Map map = new HashMap(); map.put("jsonrpc", "2.0"); if (id != null) map.put("id", id); map.put("method", method.getMethod()); if (params != null && params.length > 0) { ...
java
public void init() { int numProcessors = Runtime.getRuntime().availableProcessors(); cacheRedisClientPools = CacheBuilder.newBuilder().concurrencyLevel(numProcessors) .expireAfterAccess(3600, TimeUnit.SECONDS) .removalListener(new RemovalListener<String, JedisClientPool>(...
java
protected static String calcRedisPoolName(String host, int port, String username, String password, PoolConfig poolConfig) { StringBuilder sb = new StringBuilder(); sb.append(host != null ? host : "NULL"); sb.append("."); sb.append(port); sb.append("."); sb.app...
java
private static Pattern importStringToPattern(String s, Processor p, Log log) { if (isValidImportString(s)) { return validImportStringToPattern(s); } else { log.warning("proc.malformed.supported.string", s, p.getClass().getName()); return noMatches; // won't match any ...
java
public AbstractBuilder getProfileSummaryBuilder(Profile profile, Profile prevProfile, Profile nextProfile) throws Exception { return ProfileSummaryBuilder.getInstance(context, profile, writerFactory.getProfileSummaryWriter(profile, prevProfile, nextProfile)); }
java
public AbstractBuilder getProfilePackageSummaryBuilder(PackageDoc pkg, PackageDoc prevPkg, PackageDoc nextPkg, Profile profile) throws Exception { return ProfilePackageSummaryBuilder.getInstance(context, pkg, writerFactory.getProfilePackageSummaryWriter(pkg, prevPkg, nextPkg, ...
java
private Content getInheritedTagletOutput(boolean isNonTypeParams, Doc holder, TagletWriter writer, Object[] formalParameters, Set<String> alreadyDocumented) { Content result = writer.getOutputInstance(); if ((! alreadyDocumented.contains(null)) && holder instanceo...
java
@Override public void observe(int age) throws InterruptedException { if (System.currentTimeMillis() >= _limit) { throw new InterruptedException("Time{" + System.currentTimeMillis() + "}HasPassed{" + _limit + '}'); } }
java
private <S extends Symbol> S nameToSymbol(String nameStr, Class<S> clazz) { Name name = names.fromString(nameStr); // First check cache. Symbol sym = (clazz == ClassSymbol.class) ? syms.classes.get(name) : syms.packages.get(name); try { ...
java
public static String leftPad(String text, String padding, int linesToIgnore) { StringBuilder result = new StringBuilder(); Matcher matcher = LINE_START_PATTERN.matcher(text); while (matcher.find()) { if (linesToIgnore > 0) { linesToIgnore--; } else { ...
java
public static Predicate<Class<?>> classOrAncestorAnnotatedWith(final Class<? extends Annotation> annotationClass, boolean includeMetaAnnotations) { return candidate -> candidate != null && Classes.from(candidate) .traversingSuperclasses() .traversingInterfaces() ...
java
public static Predicate<Annotation> annotationIsOfClass(final Class<? extends Annotation> annotationClass) { return candidate -> candidate != null && candidate.annotationType().equals(annotationClass); }
java
public static Predicate<Class<?>> atLeastOneFieldAnnotatedWith(final Class<? extends Annotation> annotationClass, boolean includeMetaAnnotations) { return candidate -> candidate != null && Classes.from(candidate) .traversingSuperclasses() .fields() .an...
java
public static Predicate<Class<?>> atLeastOneMethodAnnotatedWith(final Class<? extends Annotation> annotationClass, boolean includeMetaAnnotations) { return candidate -> Classes.from(candidate) .traversingInterfaces() .traversingSuperclasses() .methods(...
java
public static boolean isValidVATIN (@Nonnull final String sVATIN, final boolean bIfNoValidator) { ValueEnforcer.notNull (sVATIN, "VATIN"); if (sVATIN.length () > 2) { final String sCountryCode = sVATIN.substring (0, 2).toUpperCase (Locale.US); final IToBooleanFunction <String> aValidator = s_a...
java
public static boolean isValidatorPresent (@Nonnull final String sVATIN) { ValueEnforcer.notNull (sVATIN, "VATIN"); if (sVATIN.length () <= 2) return false; final String sCountryCode = sVATIN.substring (0, 2).toUpperCase (Locale.US); return s_aMap.containsKey (sCountryCode); }
java
public void printFramesetDocument(String title, boolean noTimeStamp, Content frameset) throws IOException { Content htmlDocType = DocType.FRAMESET; Content htmlComment = new Comment(configuration.getText("doclet.New_Page")); Content head = new HtmlTree(HtmlTag.HEAD); head.add...
java
private void skip(boolean stopAtImport, boolean stopAtMemberDecl, boolean stopAtIdentifier, boolean stopAtStatement) { while (true) { switch (token.kind) { case SEMI: nextToken(); return; case PUBLIC: case FINA...
java
void checkNoMods(long mods) { if (mods != 0) { long lowestMod = mods & -mods; error(token.pos, "mod.not.allowed.here", Flags.asFlagSet(lowestMod)); } }
java
void attach(JCTree tree, Comment dc) { if (keepDocComments && dc != null) { // System.out.println("doc comment = ");System.out.println(dc);//DEBUG docComments.putComment(tree, dc); } }
java
List<JCStatement> forInit() { ListBuffer<JCStatement> stats = new ListBuffer<>(); int pos = token.pos; if (token.kind == FINAL || token.kind == MONKEYS_AT) { return variableDeclarators(optFinal(0), parseType(), stats).toList(); } else { JCExpression t = term(EXPR ...
java
protected JCTree resource() { JCModifiers optFinal = optFinal(Flags.FINAL); JCExpression type = parseType(); int pos = token.pos; Name ident = ident(); return variableDeclaratorRest(pos, optFinal, type, ident, true, null); }
java
public final void run() { _interrupted = null; _age = 0; while (true) { try { _strategy.observe(_age); if (_preparation != null) _preparation.run(); _result = execute(); if (_age > 0) { _reporting.emi...
java
protected void loadReport(ReportsConfig result, File report, String reportId) throws IOException { if (report.isDirectory()) { FilenameFilter configYamlFilter = new PatternFilenameFilter("^reportconf.(yaml|json)$"); File[] selectYaml = report.listFiles(configYamlFilter); ...
java
@SuppressWarnings("unchecked") public Map toMap() { HashMap map = new HashMap(); map.put("code", code); map.put("message", message); if (data != null) map.put("data", data); return map; }
java
public boolean lint(String s) { // return true if either the specific option is enabled, or // they are all enabled without the specific one being // disabled return isSet(XLINT_CUSTOM, s) || (isSet(XLINT) || isSet(XLINT_CUSTOM, "all")) && isUnset(...
java
@POST @Path("refresh") @Consumes(MediaType.APPLICATION_JSON) public Response refreshAccessToken(RefreshTokenRequest refreshToken) { // Perform all validation here to control the exact error message returned to comply with the Oauth2 standard if (null == refreshToken.getRefresh_token() || null == ...
java
@GET @Path("tokeninfo") public Response validate(@QueryParam("access_token") String access_token) { checkNotNull(access_token); DConnection connection = connectionDao.findByAccessToken(access_token); LOGGER.debug("Connection {}", connection); if (null == connection || hasAccessTokenExpired(connecti...
java
@GET @Path("logout") public Response logout() throws URISyntaxException { return Response .temporaryRedirect(new URI("/")) .cookie(createCookie(null, 0)) .build(); }
java
public static Output search(Input input) { Output output = new Output(); if (input.isInheritDocTag) { //Do nothing because "element" does not have any documentation. //All it has it {@inheritDoc}. } else if (input.taglet == null) { //We want overall documentat...
java
public void init(ServletConfig config) throws ServletException { try { String idlPath = config.getInitParameter("idl"); if (idlPath == null) { throw new ServletException("idl init param is required. Set to path to .json file, or classpath:/mycontract.json"); ...
java
public Content getTargetProfilePackageLink(PackageDoc pd, String target, Content label, String profileName) { return getHyperLink(pathString(pd, DocPaths.profilePackageSummary(profileName)), label, "", target); }
java
public Content getTargetProfileLink(String target, Content label, String profileName) { return getHyperLink(pathToRoot.resolve( DocPaths.profileSummary(profileName)), label, "", target); }
java
public String getTypeNameForProfile(ClassDoc cd) { StringBuilder typeName = new StringBuilder((cd.containingPackage()).name().replace(".", "/")); typeName.append("/") .append(cd.name().replace(".", "$")); return typeName.toString(); }
java
public boolean isTypeInProfile(ClassDoc cd, int profileValue) { return (configuration.profiles.getProfile(getTypeNameForProfile(cd)) <= profileValue); }
java
public void addBottom(Content body) { Content bottom = new RawHtml(replaceDocRootDir(configuration.bottom)); Content small = HtmlTree.SMALL(bottom); Content p = HtmlTree.P(HtmlStyle.legalCopy, small); body.addContent(p); }
java
protected void addPackageDeprecatedAPI(List<Doc> deprPkgs, String headingKey, String tableSummary, String[] tableHeader, Content contentTree) { if (deprPkgs.size() > 0) { Content table = HtmlTree.TABLE(HtmlStyle.deprecatedSummary, 0, 3, 0, tableSummary, getTableCaptio...
java
public HtmlTree getScriptProperties() { HtmlTree script = HtmlTree.SCRIPT("text/javascript", pathToRoot.resolve(DocPaths.JAVASCRIPT).getPath()); return script; }
java
private boolean addAnnotationInfo(int indent, Doc doc, AnnotationDesc[] descList, boolean lineBreak, Content htmltree) { List<Content> annotations = getAnnotations(indent, descList, lineBreak); String sep =""; if (annotations.isEmpty()) { return false; } f...
java
public static ApruveResponse<Payment> get(String paymentRequestId, String paymentId) { return ApruveClient.getInstance().get( getPaymentsPath(paymentRequestId) + paymentId, Payment.class); }
java
public static ApruveResponse<List<Payment>> getAll(String paymentRequestId) { return ApruveClient.getInstance().index( getPaymentsPath(paymentRequestId), new GenericType<List<Payment>>() { }); }
java
public void init() { Dictionary<String, String> properties = getConfigurationProperties(this.getProperties(), false); this.setProperties(properties); this.setProperty(BundleConstants.SERVICE_PID, getServicePid()); this.setProperty(BundleConstants.SERVICE_CLASS, getServiceClassName()); }
java
public void start(BundleContext context) throws Exception { ClassServiceUtility.log(context, LogService.LOG_INFO, "Starting " + this.getClass().getName() + " Bundle"); this.context = context; this.init(); // Setup the properties String interfaceClassName = getInterfaceClassNa...
java
public void stop(BundleContext context) throws Exception { ClassServiceUtility.log(context, LogService.LOG_INFO, "Stopping " + this.getClass().getName() + " Bundle"); if (this.shutdownService(service, context)) service = null; // Unregisters automatically this.context = null; }
java
public void registerService(Object service) { this.setService(service); String serviceClass = getInterfaceClassName(); if (service != null) serviceRegistration = context.registerService(serviceClass, this.service, properties); }
java
public Object getService(String interfaceClassName, String serviceClassName, String versionRange, Dictionary<String,String> filter) { return ClassServiceUtility.getClassService().getClassFinder(context).getClassBundleService(interfaceClassName, serviceClassName, versionRange, filter, -1); }
java
public String getServicePid() { String servicePid = context.getProperty(BundleConstants.SERVICE_PID); if (servicePid != null) return servicePid; servicePid = this.getServiceClassName(); if (servicePid == null) servicePid = this.getClass().getName(); re...
java
public static Dictionary<String, String> putAll(Dictionary<String, String> sourceDictionary, Dictionary<String, String> destDictionary) { if (destDictionary == null) destDictionary = new Hashtable<String, String>(); if (sourceDictionary != null) { Enumeration<String> ...
java
public static <T> T getFirstNotNullValue(final Collection<T> collection) { if (isNotEmpty(collection)) { for (T element : collection) { if (element != null) { return element; } } } return null; }
java
public static <T> List<T> toList(final Collection<T> collection) { if (isEmpty(collection)) { return new ArrayList<T>(0); } else { return new ArrayList<T>(collection); } }
java