code
stringlengths
73
34.1k
label
stringclasses
1 value
public synchronized static ServiceFactory getInstance(Class<?> aClass, String configurationPath) { if(configurationPath == null) { configurationPath = ""; } if (instances.get(configurationPath) == null) { instances.put(con...
java
public String getText() { //convert textable to map of text Object key = null; try { //read bindTemplate String bindTemplate = getTemplate(); Map<Object,String> textMap = new Hashtable<Object,String>(); for(Map.Entry<String, Textable> en...
java
public <T> Collection<T> startWorking(Callable<T>[] callables) { List<Future<T>> list = new ArrayList<Future<T>>(); for (int i = 0; i < callables.length; i++) { list.add(executor.submit(callables[i])); } ArrayList<T> resultList = new ArrayList<T>(ca...
java
public Collection<Future<?>> startWorking(WorkQueue queue, boolean background) { ArrayList<Future<?>> futures = new ArrayList<Future<?>>(queue.size()); while(queue.hasMoreTasks()) { futures.add(executor.submit(queue.nextTask())); } if(background) ret...
java
public static Mirror newInstanceForClassName(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { className = className.trim(); Class<?> objClass = Class.forName(className); return new Mirror(ClassPath.newInstance(objClass)); }
java
public static void waitFor(File aFile) { if(aFile == null) return; String path =aFile.getAbsolutePath(); long previousSize = IO.getFileSize(path); long currentSize = previousSize; long sleepTime = Config.getPropertyLong("file.monitor.file.wait.t...
java
protected synchronized void notifyChange(File file) { System.out.println("Notify change file="+file.getAbsolutePath()); this.notify(FileEvent.createChangedEvent(file)); }
java
@Override public UserProfile convert(File file) { if(file == null) return null; try { String text = IO.readFile(file); if(text == null || text.length() == 0) return null; return converter.convert(text); } catch (IOException e) { throw new SystemException("Unable to convert f...
java
public <T> void register(String subjectName, SubjectObserver<T> subjectObserver, Subject<T> subject) { subject.add(subjectObserver); this.registry.put(subjectName, subject); }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public <T> void removeRegistraion(String subjectName, SubjectObserver<T> subjectObserver) { Subject subject = (Subject)this.registry.get(subjectName); if(subject == null) return; subject.remove(subjectObserver); ...
java
@SuppressWarnings({"Duplicates"}) public static BufferByteOutput<ByteBuffer> of(final int capacity, final WritableByteChannel channel) { if (capacity <= 0) { throw new IllegalArgumentException("capacity(" + capacity + ") <= 0"); } if (channel == null) { throw new Null...
java
public static int flush(final BufferByteOutput<?> output, final WritableByteChannel channel) throws IOException { final ByteBuffer buffer = output.getTarget(); if (buffer == null) { return 0; } int written = 0; for (buffer.flip(); buffer.hasRemaining(); ) { ...
java
public static long durationMS(LocalDateTime start,LocalDateTime end) { if(start == null || end == null) { return 0; } return Duration.between(start, end).toMillis(); }
java
public static double durationSeconds(LocalDateTime start, LocalDateTime end) { return Duration.between(start, end).getSeconds(); }
java
public static long durationHours(LocalDateTime start,LocalDateTime end) { if(start == null || end == null) return ZERO; return Duration.between(start, end).toHours(); }
java
public void scheduleRecurring(Runnable runnable, Date firstTime, long period) { timer.scheduleAtFixedRate(toTimerTask(runnable), firstTime, period); }
java
public static TimerTask toTimerTask(Runnable runnable) { if(runnable instanceof TimerTask) return (TimerTask) runnable; return new TimerTaskRunnerAdapter(runnable); }
java
public String getText() { if(this.target == null) throw new RequiredException("this.target in ReplaceTextDecorator"); return Text.replaceForRegExprWith(this.target.getText(), regExp, replacement); }
java
public Integer getInteger(Class<?> aClass, String key, int defaultValue) { return getInteger(aClass.getName()+".key",defaultValue); }
java
public Character getCharacter(Class<?> aClass,String key,char defaultValue) { String results = getText(aClass,key, ""); if(results.length() == 0) return Character.valueOf(defaultValue); else return Character.valueOf(results.charAt(0));//return first character }
java
public Integer getInteger(String key) { Integer iVal = null; String sVal = getText(key); if ((sVal != null) && (sVal.length() > 0)) { iVal = Integer.valueOf(sVal); } return iVal; }
java
public Boolean getBoolean(String key) { Boolean bVal = null; String sVal = getText(key); if ((sVal != null) && (sVal.length() > 0)) { bVal = Boolean.valueOf(sVal); } return bVal; }
java
public synchronized void playMethodCalls(Memento memento, String [] savePoints) { String savePoint = null; MethodCallFact methodCallFact = null; SummaryException exceptions = new SummaryException(); //loop thru savepoints for (int i = 0; i < savePoints.length; i++) { savePoint = savePoints[i]...
java
public static void printError(Object caller, Object message) { StringBuilder text = new StringBuilder(); Class<?> c = callerBuilder(caller, text); if(message instanceof Throwable) getLog(c).error(text.append(stackTrace((Throwable)message))); else getLog(c).error(text.append(message)); ...
java
public static void printError(Object errorMessage) { if (errorMessage instanceof Throwable) { Throwable e = (Throwable) errorMessage; getLog(Debugger.class).error(stackTrace(e)); } else getLog(Debugger.class).error(errorMessage); }
java
public static void printFatal(Object message) { if (message instanceof Throwable) { Throwable e = (Throwable) message; e.printStackTrace(); } Log log = getLog(Debugger.class); if(log != null) log.fatal(message); else System.err.println(message); }
java
public static void printFatal(Object caller, Object message) { StringBuilder text = new StringBuilder(); Class<?> c = callerBuilder(caller, text); if(message instanceof Throwable) getLog(c).fatal(text.append(stackTrace((Throwable)message))); else getLog(c).fatal(text.append(message)); ...
java
public static void printInfo(Object caller, Object message) { StringBuilder text = new StringBuilder(); Class<?> c = callerBuilder(caller, text); if(message instanceof Throwable) getLog(c).info(text.append(stackTrace((Throwable)message))); else getLog(c).info(text.append(message)); }
java
public static void printInfo(Object message) { if (message instanceof Throwable) { Throwable e = (Throwable) message; getLog(Debugger.class).info(stackTrace(e)); } else getLog(Debugger.class).info(message); }
java
public static void printWarn(Object caller, Object message) { StringBuilder text = new StringBuilder(); Class<?> c = callerBuilder(caller, text); if(message instanceof Throwable) getLog(c).warn(text.append(stackTrace((Throwable)message))); else getLog(c).warn(text.append(message)); }
java
public static void printWarn(Object message) { if (message instanceof Throwable) { Throwable e = (Throwable) message; getLog(Debugger.class).warn(stackTrace(e)); } else getLog(Debugger.class).warn(message); }
java
public void registerMemoryNotifications(NotificationListener notificationListener, Object handback) { NotificationEmitter emitter = (NotificationEmitter) this.getMemory(); emitter.addNotificationListener(notificationListener, null, handback); }
java
public ProcessInfo execute(boolean background,String... command) { ProcessBuilder pb = new ProcessBuilder(command); return executeProcess(background,pb); }
java
private ProcessInfo executeProcess(boolean background,ProcessBuilder pb) { try { pb.directory(workingDirectory); pb.redirectErrorStream(false); if(log != null) pb.redirectOutput(Redirect.appendTo(log)); pb.environment().putAll(envMap); Process p = pb.start(); String out = null...
java
public static void main(String[] args) { if(args.length != 4) { System.err.println("Usage java "+SumStatsByMillisecondsFormular.class.getName()+" file msSecColumn calculateCol sumByMillisec"); System.exit(-1); } File file = Paths.get(args[0]).toFile(); try { if(!file.exists()) { thro...
java
public static String decorateEncryption(char[] password) { if(password == null || password.length == 0) return null; return new StringBuilder(ENCRYPTED_PASSWORD_PREFIX) .append(encrypt(password)).append(ENCRYPTED_PASSWORD_SUFFIX) .toString(); }
java
public static char[] decrypt(char[] password) { if(password == null || password.length == 0) return null; String passwordString = String.valueOf(password); try { byte[] decrypted = null; if (passwordString.startsWith("encrypted(") && passwordString.endsWith(")")) { passwordString = pas...
java
public static void rotateImage(File input, File output, String format, int degrees) throws IOException { BufferedImage inputImage = ImageIO.read(input); Graphics2D g = (Graphics2D) inputImage.getGraphics(); g.drawImage(inputImage, 0, 0, null); AffineTransform at = n...
java
public void close() { try { if (is != null) is.close(); } catch (IOException e) { log.error(null, e); throw new RuntimeException(e); } isClosed = true; }
java
public Iterable<String> toCSV() { checkState(!isClosed, WORKBOOK_CLOSED); Joiner joiner = Joiner.on(",").useForNull(""); Iterable<String> CSVIterable = Iterables.transform(sheet, item -> joiner.join(rowToList(item, true))); return hasHeader ? Iterables.skip(CSVIterable, 1) : CSVIterable; }
java
public Iterable<List<String>> toLists() { checkState(!isClosed, WORKBOOK_CLOSED); Iterable<List<String>> listsIterable = Iterables.transform(sheet, item -> { return rowToList(item); }); return hasHeader ? Iterables.skip(listsIterable, 1) : listsIterable; }
java
public Iterable<String[]> toArrays() { checkState(!isClosed, WORKBOOK_CLOSED); Iterable<String[]> arraysIterable = Iterables.transform(sheet, item -> { List<String> list = rowToList(item); return list.toArray(new String[list.size()]); }); return hasHeader ? Iterables.skip(arraysIterable, 1) ...
java
public Iterable<Map<String, String>> toMaps() { checkState(!isClosed, WORKBOOK_CLOSED); checkState(hasHeader, NO_HEADER); return Iterables.skip(Iterables.transform(sheet, item -> { Map<String, String> map = newLinkedHashMap(); List<String> row = rowToList(item); for (int i = 0; i < getHead...
java
@SuppressWarnings("unchecked") @Override public void start(final Listener<?> listener, final Infrastructure infra) throws MessageTransportException { this.listener = (Listener<Object>) listener; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public synchronized void start(final Listener listener, final Infrastructure infra) { if (listener == null) throw new IllegalArgumentException("Cannot pass null to " + BlockingQueueReceiver.class.getSimpleName() + ".setListener"); ...
java
public static void unwindMessages(final Object message, final List<Object> messages) { if (message instanceof Iterable) { @SuppressWarnings("rawtypes") final Iterator it = ((Iterable) message).iterator(); while (it.hasNext()) unwindMessages(it.next(), messages...
java
private Set<Integer> perNodeRelease(final C thisNodeAddress, final C[] currentState, final int nodeCount, final int nodeRank) { final int numberIShouldHave = howManyShouldIHave(totalNumShards, nodeCount, minNodes, nodeRank); // destinationsAcquired reflects what we already have according to the current...
java
private boolean registerAndConfirmIfImIt() throws ClusterInfoException { // reset the subdir watcher final Collection<String> imItSubdirs = utils.persistentGetSubdir(utils.leaderDir, this); // "there can be only one" if (imItSubdirs.size() > 1) throw new ClusterInfoException...
java
@Override public void send(final Object message) throws MessageTransportException { if (shutdown.get()) throw new MessageTransportException("send called on shutdown queue."); if (blocking) { while (true) { try { queue.put(message); ...
java
public static <A extends Annotation> List<AnnotatedClass<A>> allTypeAnnotations(final Class<?> clazz, final Class<A> annotation, final boolean recurse) { final List<AnnotatedClass<A>> ret = new ArrayList<>(); final A curClassAnnotation = clazz.getAnnotation(annotation); if (curClassA...
java
private final void cleanupAfterExceptionDuringNodeDirCheck() { if (nodeDirectory != null) { // attempt to remove the node directory try { if (session.exists(nodeDirectory, this)) { session.rmdir(nodeDirectory); } nodeDir...
java
public Cluster destination(final String... destinations) { final String applicationName = clusterId.applicationName; return destination(Arrays.stream(destinations).map(d -> new ClusterId(applicationName, d)).toArray(ClusterId[]::new)); }
java
void setAppName(final String appName) { if (clusterId.applicationName != null && !clusterId.applicationName.equals(appName)) throw new IllegalStateException("Restting the application name on a cluster is not allowed."); clusterId = new ClusterId(appName, clusterId.clusterName); }
java
protected String getName(final String key) { return MetricRegistry.name(DropwizardClusterStatsCollector.class, "cluster", clusterId.applicationName, clusterId.clusterName, key); }
java
@SuppressWarnings("unchecked") @Override public T newInstance() throws DempsyException { return wrap(() -> (T) cloneMethod.invoke(prototype)); }
java
@Override public void activate(final T instance, final Object key) throws DempsyException { wrap(() -> activationMethod.invoke(instance, key)); }
java
@Override public boolean invokeEvictable(final T instance) throws DempsyException { return isEvictionSupported() ? (Boolean) wrap(() -> evictableMethod.invoke(instance)) : false; }
java
public JobDetail getJobDetail(OutputInvoker outputInvoker) { JobBuilder jobBuilder = JobBuilder.newJob(OutputJob.class); JobDetail jobDetail = jobBuilder.build(); jobDetail.getJobDataMap().put(OUTPUT_JOB_NAME, outputInvoker); return jobDetail; }
java
public Trigger getSimpleTrigger(TimeUnit timeUnit, int timeInterval) { SimpleScheduleBuilder simpleScheduleBuilder = null; simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule(); switch (timeUnit) { case MILLISECONDS: simpleScheduleBuilder.withIntervalInMilliseconds(timeInterval).repeatFo...
java
public Trigger getCronTrigger(String cronExpression) { CronScheduleBuilder cronScheduleBuilder = null; Trigger cronTrigger = null; try { cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed(); TriggerBuilde...
java
public static <T> ListenableFuture<T> createListenableFuture(ValueSourceFuture<T> valueSourceFuture) { if (valueSourceFuture instanceof ListenableFutureBackedValueSourceFuture) { return ((ListenableFutureBackedValueSourceFuture<T>) valueSourceFuture).getWrappedFuture(); } else { ...
java
public static <T> ApiFuture<T> createApiFuture(ValueSourceFuture<T> valueSourceFuture) { if (valueSourceFuture instanceof ApiFutureBackedValueSourceFuture) { return ((ApiFutureBackedValueSourceFuture<T>) valueSourceFuture).getWrappedFuture(); } else { return new ValueSourceFuture...
java
private void getLastChild() { // nodekey of the root of the current subtree final long parent = getNode().getDataKey(); // traverse tree in pre order to the leftmost leaf of the subtree and // push // all nodes to the stack if (((ITreeStructData)getNode()).hasFirstChild...
java
public static JaxRx getInstance(final String impl) { final String path = Systems.getSystems().get(impl); if (path == null) { throw new JaxRxException(404, "Unknown implementation: " + impl); } JaxRx jaxrx = INSTANCES.get(path); if (jaxrx == null) { try { ...
java
public void add(final String prefix, final String uri) { if (prefix == null) { defaultNS = uri; } addToMap(prefix, uri); }
java
public void appendNsName(final StringBuilder sb, final QName nm) { String uri = nm.getNamespaceURI(); String abbr; if ((defaultNS != null) && uri.equals(defaultNS)) { abbr = null; } else { abbr = keyUri.get(uri); if (abbr == null) { abbr = uri; ...
java
public static String generate(final int length) { final StringBuilder password = new StringBuilder(length); double pik = random.nextDouble(); // random number [0,1] long ranno = (long) (pik * sigma); // weight by sum of frequencies long sum = 0; outer: for (int c1 = 0; c1 < 26; c1++) { f...
java
public void parseQuery() throws TTXPathException { // get first token, ignore all white spaces do { mToken = mScanner.nextToken(); } while (mToken.getType() == TokenType.SPACE); // parse the query according to the rules specified in the XPath 2.0 REC parseExpression...
java
private boolean isReservedKeyword() { final String content = mToken.getContent(); return isKindTest() || "item".equals(content) || "if".equals(content) || "empty-sequence".equals(content) || "typeswitch".equals(content); }
java
private boolean isForwardAxis() { final String content = mToken.getContent(); return (mToken.getType() == TokenType.TEXT && ("child".equals(content) || ("descendant" .equals(content) || "descendant-or-self".equals(content) || "attribute".equals(content) |...
java
private void consume(final TokenType mType, final boolean mIgnoreWhitespace) { if (!is(mType, mIgnoreWhitespace)) { // error found by parser - stopping throw new IllegalStateException("Wrong token after " + mScanner.begin() + " at position " + mScanner.getPos() + " found...
java
private void consume(final String mName, final boolean mIgnoreWhitespace) { if (!is(mName, mIgnoreWhitespace)) { // error found by parser - stopping throw new IllegalStateException("Wrong token after " + mScanner.begin() + " found " + mToken.getContent() + ". Expected " ...
java
private boolean is(final String mName, final boolean mIgnoreWhitespace) { if (!mName.equals(mToken.getContent())) { return false; } if (mToken.getType() == TokenType.COMP || mToken.getType() == TokenType.EQ || mToken.getType() == TokenType.N_EQ || mToken.getType() == To...
java
private boolean is(final TokenType mType, final boolean mIgnoreWhitespace) { if (mType != mToken.getType()) { return false; } do { // scan next token mToken = mScanner.nextToken(); } while (mIgnoreWhitespace && mToken.getType() == TokenType.SPACE); ...
java
public String newIndex(final String name, final String mappingPath) throws IndexException { try { final String newName = name + newIndexSuffix(); final IndicesAdminClient idx = getAdminIdx(); final CreateIndexRequestBuilder cirb = idx.prepareCreate(newName); final...
java
public List<String> purgeIndexes(final Set<String> prefixes) throws IndexException { final Set<IndexInfo> indexes = getIndexInfo(); final List<String> purged = new ArrayList<>(); if (Util.isEmpty(indexes)) { return purged; } purge: for (final IndexInfo ii: indexes) { fin...
java
public int swapIndex(final String index, final String alias) throws IndexException { //IndicesAliasesResponse resp = null; try { /* index is the index we were just indexing into */ final IndicesAdminClient idx = getAdminIdx(); final GetAliasesRequestBuilder igar...
java
public Collection<DavChild> syncReport(final BasicHttpClient cl, final String path, final String syncToken, final Collection<QName> props) throws Throwable { final StringWriter sw = new StringW...
java
protected void addNs(final XmlEmit xml, final String val) throws Throwable { if (xml.getNameSpace(val) == null) { xml.addNs(new NameSpace(val, null), false); } }
java
protected Document parseContent(final InputStream in) throws Throwable { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new InputStreamReader(in))); }
java
public Element parseError(final InputStream in) { try { final Document doc = parseContent(in); final Element root = doc.getDocumentElement(); expect(root, WebdavTags.error); final List<Element> els = getChildren(root); if (els.size() != 1) { return null; } retu...
java
private static Element createResultElement(final Document document) { final Element ttResponse = document.createElementNS("http://jaxrx.org/", "result"); ttResponse.setPrefix("jaxrx"); return ttResponse; }
java
public static StreamingOutput buildResponseOfDomLR(final IStorage pDatabase, final IBackendFactory pStorageFac, final IRevisioning pRevision) { final StreamingOutput sOutput = new StreamingOutput() { @Override public void write(final OutputStream output) throws IOException, Web...
java
public static String getUrl(final HttpServletRequest request) { try { final StringBuffer sb = request.getRequestURL(); if (sb != null) { return sb.toString(); } // Presumably portlet - see what happens with uri return request.getRequestURI(); } catch (Throwable t) { ...
java
protected void logSessionCounts(final HttpSession sess, final boolean start) { StringBuffer sb; String appname = getAppName(sess); Counts ct = getCounts(appname); if (start) { sb = new StringBuffer("SESSION-START:"); } else { sb = new StringBuffer("SESS...
java
private String getSessionId(final HttpSession sess) { try { if (sess == null) { return "NO-SESSIONID"; } else { return sess.getId(); } } catch (Throwable t) { return "SESSION-ID-EXCEPTION"; } }
java
public void checkBrowserType(final HttpServletRequest request) { String reqpar = request.getParameter(getBrowserTypeRequestName()); if (reqpar != null) { if (reqpar.equals("!")) { // Go back to unsticky browser type setBrowserTypeSticky(false); } else { setBrowserType(reqpar...
java
public void checkContentType(final HttpServletRequest request) { String reqpar = request.getParameter(getContentTypeRequestName()); if (reqpar != null) { if (reqpar.equals("!")) { // Go back to unsticky content type setContentTypeSticky(false); } else { setContentType(reqpar...
java
public void checkContentName(final HttpServletRequest request) { String reqpar = request.getParameter(getContentNameRequestName()); // Set to null if not found. setContentName(reqpar); }
java
public void checkSkinName(final HttpServletRequest request) { String reqpar = request.getParameter(getSkinNameRequestName()); if (reqpar != null) { if (reqpar.equals("!")) { // Go back to unsticky SkinName setSkinNameSticky(false); } else { setSkinName(reqpar); setSk...
java
public void checkRefreshXslt(final HttpServletRequest request) { String reqpar = request.getParameter(getRefreshXSLTRequestName()); if (reqpar == null) { return; } if (reqpar.equals("yes")) { setForceXSLTRefresh(true); } if (reqpar.equals("always")) { setForceXSLTRefreshAlwa...
java
public void checkNoXSLT(final HttpServletRequest request) { String reqpar = request.getParameter(getNoXSLTRequestName()); if (reqpar != null) { if (reqpar.equals("!")) { // Go back to unsticky noXslt setNoXSLTSticky(false); } else { setNoXSLT(true); } } reqpar...
java
public static Map<Long, LogEntry> getBranchLog(String[] branches, long startRevision, long endRevision, String baseUrl, String user, String pwd) throws IOException, SAXException { try (InputStream inStr = getBranchLogStream(branches, startRevision, endRevision, baseUrl, user, pwd)) { return new SVNL...
java
public static InputStream getRemoteFileContent(String file, long revision, String baseUrl, String user, String pwd) throws IOException { // svn cat -r 666 file CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_CAT); addDefaultArguments(cmdLine, user, pwd); c...
java
public static boolean branchExists(String branch, String baseUrl) { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_LOG); cmdLine.addArgument(OPT_XML); addDefaultArguments(cmdLine, null, null); cmdLine.addArgument("-r"); cmdLine.addArgument("HEAD:H...
java
public static long getBranchRevision(String branch, String baseUrl) throws IOException { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_LOG); cmdLine.addArgument(OPT_XML); addDefaultArguments(cmdLine, null, null); cmdLine.addArgument("-v"); cmdLin...
java
public static long getLastRevision(String branch, String baseUrl, String user, String pwd) throws IOException { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument("info"); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument(baseUrl + branch); try (Input...
java
public static InputStream getPendingCheckins(File directory) throws IOException { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_STATUS); addDefaultArguments(cmdLine, null, null); return ExecutionHelper.getCommandResult(cmdLine, directory, -1, 120000); }
java
public static InputStream recordMerge(File directory, String branchName, long... revisions) throws IOException { // svn merge -c 3328 --record-only ^/calc/trunk CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_MERGE); addDefaultArguments(cmdLine, null, null); ...
java
public static boolean verifyNoPendingChanges(File directory) throws IOException { log.info("Checking that there are no pending changes on trunk-working copy"); try (InputStream inStr = getPendingCheckins(directory)) { List<String> lines = IOUtils.readLines(inStr, "UTF-8"); if (li...
java