code
stringlengths
73
34.1k
label
stringclasses
1 value
protected URL[] getCompileClasspathElementURLs() throws DependencyResolutionRequiredException { // build class loader to get classes to generate resources for return project.getCompileClasspathElements().stream() .map(path -> { try { return new File(path).toURI().toURL(); ...
java
protected File getGeneratedResourcesDirectory() { if (generatedResourcesFolder == null) { String generatedResourcesFolderAbsolutePath = this.project.getBuild().getDirectory() + "/" + getGeneratedResourcesDirectoryPath(); generatedResourcesFolder = new File(generatedResourcesFolderAbsolutePath); if...
java
public static String getAPIVersion(final String resourceFileName, final String versionProperty) { final Properties props = new Properties(); final URL url = ClassLoader.getSystemResource(resourceFileName); if (url != null) { InputStream is = null; try { is...
java
public String getExtendsInterface() { if (this.getExtendsInterfaces().isEmpty()){ // return "Empty"; return this.getInstanceType(); } else { String tName = this.getExtendsInterfaces().get(0).replaceAll("\\W+", ""); return tName; } }
java
public static String escapeTitle(final String title) { final String escapedTitle = title.replaceAll("^[^" + UNICODE_TITLE_START_CHAR + "]*", "").replaceAll("[^" + UNICODE_WORD + ". -]", ""); if (isNullOrEmpty(escapedTitle)) { return ""; } else { // Remove ...
java
public static String escapeForXML(final String content) { if (content == null) return ""; /* * Note: The following characters should be escaped: & < > " ' * * However, all but ampersand pose issues when other elements are included in the title. * * eg <title...
java
public static boolean validateTableRows(final Element table) { assert table != null; assert table.getNodeName().equals("table") || table.getNodeName().equals("informaltable"); final NodeList tgroups = table.getElementsByTagName("tgroup"); for (int i = 0; i < tgroups.getLength(); i++) { ...
java
public static boolean validateTableGroup(final Element tgroup) { assert tgroup != null; assert tgroup.getNodeName().equals("tgroup"); final Integer numColumns = Integer.parseInt(tgroup.getAttribute("cols")); // Check that all the thead, tbody and tfoot elements have the correct number ...
java
public static boolean validateTableRow(final Node row, final int numColumns) { assert row != null; assert row.getNodeName().equals("row") || row.getNodeName().equals("tr"); if (row.getNodeName().equals("row")) { final List<Node> entries = XMLUtilities.getDirectChildNodes(row, "entry...
java
public static List<StringToNodeCollection> getTranslatableStringsV3(final Document xml, final boolean allowDuplicates) { if (xml == null) return null; return getTranslatableStringsV3(xml.getDocumentElement(), allowDuplicates); }
java
public static List<StringToNodeCollection> getTranslatableStringsV3(final Node node, final boolean allowDuplicates) { if (node == null) return null; final List<StringToNodeCollection> retValue = new LinkedList<StringToNodeCollection>(); final NodeList nodes = node.getChildNodes(); for ...
java
private static String cleanTranslationText(final String input, final boolean removeWhitespaceFromStart, final boolean removeWhitespaceFromEnd) { String retValue = XMLUtilities.cleanText(input); retValue = retValue.trim(); /* * When presenting the contents of a childless XM...
java
public static Pair<String, String> wrapForValidation(final DocBookVersion docBookVersion, final String xml) { final String rootEleName = XMLUtilities.findRootElementName(xml); if (docBookVersion == DocBookVersion.DOCBOOK_50) { if (rootEleName.equals("abstract") || rootEleName.equals("legalno...
java
public static void wrapForRendering(final Document xmlDoc) { // Some topics need to be wrapped up to be rendered properly final String documentElementNodeName = xmlDoc.getDocumentElement().getNodeName(); if (documentElementNodeName.equals("authorgroup") || documentElementNodeName.equals("legalno...
java
public static boolean validateTables(final Document doc) { final NodeList tables = doc.getElementsByTagName("table"); for (int i = 0; i < tables.getLength(); i++) { final Element table = (Element) tables.item(i); if (!validateTableRows(table)) { return false; ...
java
public static boolean checkForInvalidInfoElements(final Document doc) { final List<Node> invalidElements = XMLUtilities.getDirectChildNodes(doc.getDocumentElement(), "title", "subtitle", "titleabbrev"); return invalidElements != null && !invalidElements.isEmpty(); }
java
public static String validateRevisionHistory(final Document doc, final String[] dateFormats) { final List<String> invalidRevNumbers = new ArrayList<String>(); // Find each <revnumber> element and make sure it matches the publican regex final NodeList revisions = doc.getElementsByTagName("revisi...
java
private static String cleanDate(final String dateString) { if (dateString == null) { return dateString; } String retValue = dateString; retValue = THURSDAY_DATE_RE.matcher(retValue).replaceAll("Thu"); retValue = TUESDAY_DATE_RE.matcher(retValue).replaceAll("Tue"); ...
java
public static Object get(final Object bean, final String property) { try { if (property.indexOf(".") >= 0) { final Object subBean = ClassMockUtils.get(bean, property.substring(0, property.indexOf("."))); if (subBean == null) { return null; ...
java
public static Object newInstance(final IClassWriter classMock) { try { final Class<?> clazz = classMock.build(); return clazz.newInstance(); } catch (final Exception e) { throw new RuntimeException("Can't intanciate class", e); } }
java
public LogWatchBuilder withDelayBetweenReads(final int length, final TimeUnit unit) { this.delayBetweenReads = LogWatchBuilder.getDelay(length, unit); return this; }
java
public LogWatchBuilder withDelayBetweenSweeps(final int length, final TimeUnit unit) { this.delayBetweenSweeps = LogWatchBuilder.getDelay(length, unit); return this; }
java
private Source register(Source source) { /** * As promised, the registrar simply abstracts away internal resolvers * by iterating over them during the registration process. */ for (Resolver resolver : resolvers) { resolver.register(source); } ...
java
private void checkForCycles( Class<?> target, Class<?> in, Stack<Class<?>> trace) { for (Field field : in.getDeclaredFields()) { if (field.getAnnotation(Autowired.class) != null) { Class<?> type = field.getType(); trace.push(type);...
java
public static SimpleModule getTupleMapperModule() { SimpleModule module = new SimpleModule("1", Version.unknownVersion()); SimpleAbstractTypeResolver resolver = getTupleTypeResolver(); module.setAbstractTypes(resolver); module.setKeyDeserializers(new SimpleKeyDeserializers()); r...
java
public void addSparseConstraint(int component, int index, double value) { constraints.add(new Constraint(component, index, value)); }
java
private static boolean isInheritIOBroken() { if (!System.getProperty("os.name", "none").toLowerCase().contains("windows")) { return false; } String runtime = System.getProperty("java.runtime.version"); if (!runtime.startsWith("1.7")) { return false; } ...
java
public synchronized static void setFormatter(Formatter formatter) { java.util.logging.Logger root = java.util.logging.LogManager.getLogManager().getLogger(StringUtils.EMPTY); for (Handler h : root.getHandlers()) { h.setFormatter(formatter); } }
java
public synchronized static void clearHandlers() { java.util.logging.Logger root = java.util.logging.LogManager.getLogManager().getLogger(StringUtils.EMPTY); Handler[] handlers = root.getHandlers(); for (Handler h : handlers) { root.removeHandler(h); } }
java
public synchronized static void addHandler(Handler handler) { java.util.logging.Logger root = java.util.logging.LogManager.getLogManager().getLogger(StringUtils.EMPTY); root.addHandler(handler); }
java
public Logger getLogger(Class<?> clazz) { if (clazz == null) { return getGlobalLogger(); } return getLogger(clazz.getName()); }
java
public Logger getGlobalLogger() { return new Logger(java.util.logging.Logger .getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME)); }
java
public List<String> getLoggerNames() { return Collections.list(java.util.logging.LogManager.getLogManager().getLoggerNames()); }
java
public void setLevel(String logger, Level level) { Logger log = getLogger(logger); log.setLevel(level); for (String loggerName : getLoggerNames()) { if (loggerName.startsWith(logger) && !loggerName.equals(logger)) { getLogger(loggerName).setLevel(level); } } }
java
public String renderServiceHtml(io.wcm.caravan.hal.docs.impl.model.Service service) throws IOException { Map<String, Object> model = ImmutableMap.<String, Object>builder() .put("service", service) .build(); return render(service, model, serviceTemplate); }
java
public String renderLinkRelationHtml(io.wcm.caravan.hal.docs.impl.model.Service service, LinkRelation linkRelation) throws IOException { Map<String, Object> model = ImmutableMap.<String, Object>builder() .put("service", service) .put("linkRelation", linkRelation) .build(); return r...
java
private String render(io.wcm.caravan.hal.docs.impl.model.Service service, Map<String, Object> model, Template template) throws IOException { Map<String, Object> mergedModel = ImmutableMap.<String, Object>builder() .putAll(model) .put("docsContext", ImmutableMap.<String, Object>builder() ...
java
public boolean start() { if (!this.isStarted.compareAndSet(false, true)) { return false; } final long delay = this.delayBetweenSweeps; this.timer.scheduleWithFixedDelay(this, delay, delay, TimeUnit.MILLISECONDS); LogWatchStorageSweeper.LOGGER.info( "Sc...
java
public boolean stop() { if (!this.isStarted.get() || !this.isStopped.compareAndSet(false, true)) { return false; } this.timer.shutdown(); LogWatchStorageSweeper.LOGGER.info("Cancelled automated unreachable message sweep in {}.", this.messaging.getLogWatch()); ...
java
private Properties copyProperties(Properties source) { Properties copy = new Properties(); if (source != null) { copy.putAll(source); } return copy; }
java
public void save(File file, String comment, boolean saveDefaults) throws IOException { save(file, comment, saveDefaults, null); }
java
public void save(File file, String comment, boolean saveDefaults, String propertyName) throws IOException { gatekeeper.lock(); try { File parent = file.getParentFile(); if (!parent.exists() && !parent.mkdi...
java
public String getProperty(String propertyName) { ChangeStack<String> stack = properties.get(propertyName); if (stack == null) { return null; } return stack.getCurrentValue(); }
java
public boolean setProperty(String propertyName, String value) throws NullPointerException { return setValue(propertyName, value, false); }
java
private boolean setValue(String propertyName, String value, boolean sync) throws NullPointerException { gatekeeper.signIn(); try { ChangeStack<String> stack = properties.get(propertyName); if (stack == null) { ChangeStack<String> newStack =...
java
public boolean resetToDefault(String propertyName) { gatekeeper.signIn(); try { /* * If this property was added with no default value, all we can do * is remove the property entirely. */ String defaultValue = getDefaultValue(prop...
java
public void resetToDefaults() { gatekeeper.signIn(); try { for (Iterator<Entry<String, ChangeStack<String>>> iter = properties.entrySet() .iterator(); iter.hasNext();) { Ent...
java
public boolean isModified(String propertyName) { gatekeeper.signIn(); try { ChangeStack<String> stack = properties.get(propertyName); if (stack == null) { return false; } return stack.isModified(); } ...
java
public boolean isModified() { gatekeeper.signIn(); try { for (ChangeStack<String> stack : properties.values()) { if (stack.isModified()) { return true; } } return false; ...
java
public static Resource from(String resource) { if (StringUtils.isNullOrBlank(resource)) { return new StringResource(); } Matcher matcher = protocolPattern.matcher(resource); if (matcher.find()) { String schema = matcher.group("PROTOCOL"); String options = matcher.group...
java
public static Resource temporaryDirectory() { File tempDir = new File(SystemInfo.JAVA_IO_TMPDIR); String baseName = System.currentTimeMillis() + "-"; for (int i = 0; i < 1_000_000; i++) { File tmp = new File(tempDir, baseName + i); if (tmp.mkdir()) { return new FileResour...
java
public static Resource temporaryFile(String name, String extension) throws IOException { return new FileResource(File.createTempFile(name, extension)); }
java
public synchronized Future<Message> setExpectation(final C condition, final MessageAction<P> action) { if (this.isStopped()) { throw new IllegalStateException("Already stopped."); } final AbstractExpectation<C, P> expectation = this.createExpectation(condition, action); final...
java
protected synchronized boolean unsetExpectation(final AbstractExpectation<C, P> expectation) { if (this.expectations.containsKey(expectation)) { this.expectations.remove(expectation); AbstractExpectationManager.LOGGER.info("Unregistered expectation {}.", expectation); return ...
java
@Api public <T> void setOption(GestureOption<T> option, T value) { if (value == null) { throw new IllegalArgumentException("Null value passed."); } if (value instanceof Boolean) { setOption(this, (Boolean) value, option.getName()); } else if (value instanceof Integer) { setOption(this, (Integer) valu...
java
static String toChars(String p) { if (p.length() >= 3 && p.charAt(0) == '[' && p.charAt(p.length() - 1) == ']') { return p.substring(1, p.length() - 1); } return p; }
java
public Regex then(Regex regex) { if (regex == null) { return this; } return re(this.pattern + regex.pattern); }
java
public Regex group(String name) { return re("(" + (StringUtils.isNotNullOrBlank(name) ? "?<" + name + ">" : StringUtils.EMPTY) + pattern + ")"); }
java
public Regex not() { if (this.pattern.length() > 0) { if (this.pattern.charAt(0) == '[' && this.pattern.length() > 1) { return re("[^" + this.pattern.substring(1)); } return re("^" + this.pattern); } return this; }
java
public Regex range(int min, int max) { return re(this.pattern + "{" + Integer.toString(min) + "," + Integer.toString(max) + "}"); }
java
public static ListMultimap<String, Link> getAllLinks(HalResource hal, Predicate<Pair<String, Link>> predicate) { return getAllLinks(hal, "self", predicate); }
java
public static List<Link> getAllLinksForRelation(HalResource hal, String relation) { List<Link> links = Lists.newArrayList(hal.getLinks(relation)); List<Link> embeddedLinks = hal.getEmbedded().values().stream() .flatMap(embedded -> getAllLinksForRelation(embedded, relation).stream()) .collect(Co...
java
private void cleanup(boolean atStartup) { boolean allTasksIdle = false; while (!allTasksIdle) { int activeCount = 0; for (Task task: taskDao.listTasks()) { if (!task.getState().equals(Task.IDLE)) { activeCount++; if (!task.g...
java
public static Pattern createFilePattern(String filePattern) { filePattern = StringUtils.isNullOrBlank(filePattern) ? "\\*" : filePattern; filePattern = filePattern.replaceAll("\\.", "\\."); filePattern = filePattern.replaceAll("\\*", ".*"); return Pattern.compile("^" + filePattern + "$"); }
java
public static boolean isCompressed(PushbackInputStream pushbackInputStream) throws IOException { if (pushbackInputStream == null) { return false; } byte[] buffer = new byte[2]; int read = pushbackInputStream.read(buffer); boolean isCompressed = false; if (read == 2) { ...
java
public static String toUnix(String spec) { if (spec == null) { return StringUtils.EMPTY; } return spec.replaceAll("\\\\+", "/"); }
java
public static String toWindows(String spec) { if (spec == null) { return StringUtils.EMPTY; } return spec.replaceAll("/+", "\\\\"); }
java
public static String addTrailingSlashIfNeeded(String directory) { if (StringUtils.isNullOrBlank(directory)) { return StringUtils.EMPTY; } int separator = indexOfLastSeparator(directory); String slash = SystemInfo.isUnix() ? Character.toString(UNIX_SEPARATOR) : Character.toString(WINDOWS...
java
public static String parent(String file) { if (StringUtils.isNullOrBlank(file)) { return StringUtils.EMPTY; } file = StringUtils.trim(file); String path = path(file); int index = indexOfLastSeparator(path); if (index <= 0) { return SystemInfo.isUnix() ? Character.to...
java
private static boolean openBrowserJava6(String url) throws Exception { final Class<?> desktopClass; try { desktopClass = Class.forName("java.awt.Desktop"); } catch (ClassNotFoundException e) { return false; } Boolean supported = (Boolean) desktopClass.getM...
java
private static String[] getOpenBrowserCommand(String url) throws IOException, InterruptedException { if (IS_WINDOWS) { return new String[]{"rundll32", "url.dll,FileProtocolHandler", url}; } else if (IS_MAC) { return new String[]{"/usr/bin/open", url}; } else if (IS_LINUX)...
java
public ParserToken lookAhead(int distance) { while (distance >= buffer.size() && tokenIterator.hasNext()) { buffer.addLast(tokenIterator.next()); } return buffer.size() > distance ? buffer.getLast() : null; }
java
public ParserTokenType lookAheadType(int distance) { ParserToken token = lookAhead(distance); return token == null ? null : token.type; }
java
public boolean nonConsumingMatch(ParserTokenType rhs) { ParserToken token = lookAhead(0); return token != null && token.type.isInstance(rhs); }
java
public boolean match(ParserTokenType expected) { ParserToken next = lookAhead(0); if (next == null || !next.type.isInstance(expected)) { return false; } consume(); return true; }
java
public static void main(String[] args) { JFrame frame; App biorhythm = new App(); try { frame = new JFrame("Biorhythm"); frame.addWindowListener(new AppCloser(frame, biorhythm)); } catch (java.lang.Throwable ivjExc) { frame = null; Syst...
java
public void init() { JPanel view = new JPanel(); view.setLayout(new BorderLayout()); label = new JLabel(INITIAL_TEXT); Font font = new Font(Font.SANS_SERIF, Font.BOLD, 32); label.setFont(font); view.add(BorderLayout.CENTER, label); this.getContentPane...
java
public String replicateTable(String tableName, boolean toCopyData) throws SQLException { String tempTableName = MySqlCommunication.getTempTableName(tableName); LOG.debug("Replicate table {} into {}", tableName, tempTableName); if (this.tableExists(tempTableName)) { this.truncateT...
java
public void restoreTable(String tableName, String tempTableName) throws SQLException { LOG.debug("Restore table {} from {}", tableName, tempTableName); try { this.setForeignKeyCheckEnabled(false); this.truncateTable(tableName); final String sql = "INSERT INTO " +...
java
public void removeTempTable(String tempTableName) throws SQLException { if (tempTableName == null) { return; } if (!tempTableName.contains(TEMP_TABLE_NAME_SUFFIX)) { throw new SQLException(tempTableName + " is not a valid temp table name"); } try (C...
java
public final void addParser(@NotNull final ParserConfig parser) { Contract.requireArgNotNull("parser", parser); if (list == null) { list = new ArrayList<>(); } list.add(parser); }
java
private String setXmlPreambleAndDTD(final String xml, final String dtdFileName, final String entities, final String dtdRootEleName) { // Check if the XML already has a DOCTYPE. If it does then replace the values and remove entities for processing final Matcher matcher = DOCTYPE_PATTERN.matcher(xml); ...
java
public int process() { // Calculate the result of the left operation if any if (leftOperation != null) { leftOperand = leftOperation.process(); } // Calculate the result of the right operation if any if (rightOperation != null) { rightOperand = rightOperation.process(); } // Process the operation ...
java
public void executeAction(ShanksSimulation simulation, ShanksAgent agent, List<NetworkElement> arguments) throws ShanksException { for (NetworkElement ne : arguments) { this.addAffectedElement(ne); } this.launchEvent(); }
java
@Override public synchronized boolean stopFollowing(final Follower follower) { if (!this.isFollowedBy(follower)) { return false; } this.stopConsuming(follower); DefaultLogWatch.LOGGER.info("Unregistered {} for {}.", follower, this); return true; }
java
public void progress() { count++; if (count % period == 0 && LOG.isInfoEnabled()) { final double percent = 100 * (count / (double) totalIterations); final long tock = System.currentTimeMillis(); final long timeInterval = tock - tick; final long linesPerSec = (count - prevCount) * 1000 / ...
java
public void writeEntries(JarFile jarFile) throws IOException { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( j...
java
@Override public void afterProjectsRead(final MavenSession session) throws MavenExecutionException { boolean anyProject = false; for (MavenProject project : session.getProjects()) { if (project.getPlugin("ceylon") != null || project.getPlugin("ceylon-maven-plugin") != n...
java
private boolean usesCeylonRepo(final MavenProject project) { for (Repository repo : project.getRepositories()) { if ("ceylon".equals(repo.getLayout())) { return true; } } for (Artifact ext : project.getPluginArtifacts()) { if (...
java
public void stream(InputStream inputStream, MediaType mediaType) { try { OutputStream outputStream = exchange.getOutputStream(); setResponseMediaType(mediaType); byte[] buffer = new byte[10240]; int len; while ((len = inputStream.read(buffer)) != -1) ...
java
public ServiceInformation get(String key) { ServiceInformation info = null; long hash = algorithm.hash(key); //Find the first server with a hash key after this one final SortedMap<Long, ServiceInformation> tailMap = ring.tailMap(hash); //Wrap around to the beginning of the ring, ...
java
public void addScenario(Class<? extends Scenario> scenarioClass, String scenarioID, String initialState, Properties properties, String gatewayDeviceID, String externalLinkID) throws ShanksException { // throws NonGatewayDeviceException, TooManyConnectionException, // ...
java
public void addPossiblesFailuresComplex() { Set<Scenario> scenarios = this.getScenarios(); for (Scenario s : scenarios) { for (Class<? extends Failure> c : s.getPossibleFailures().keySet()) { if (!this.getPossibleFailures().containsKey(c)) { this.addPossib...
java
public void addPossiblesEventsComplex() { Set<Scenario> scenarios = this.getScenarios(); for (Scenario s : scenarios) { for (Class<? extends Event> c : s.getPossibleEventsOfNE().keySet()) { if (!this.getPossibleEventsOfNE().containsKey(c)) { this.addPossib...
java
@Api public <T> void setOption(GestureOption<T> option, T value) { hammertime.setOption(option, value); }
java
@Api public void unregisterHandler(EventType eventType) { if (!jsHandlersMap.containsKey(eventType)) { return; } HammerGwt.off(hammertime, eventType, (NativeHammmerHandler) jsHandlersMap.remove(eventType)); }
java
private List<String> getChildrenList() { if (childrenList != null) return childrenList; SharedPreferences prefs = loadSharedPreferences("children"); String list = prefs.getString(getId(), null); childrenList = (list == null) ? new ArrayList<String>() : new ArrayList<>(Arrays.asList(li...
java
public void addChild(C child) { SharedPreferences prefs = loadSharedPreferences("children"); List<String> objects = getChildrenList(); Model toPut = (Model) child; if (objects.indexOf(toPut.getId()) != ArrayUtils.INDEX_NOT_FOUND) { return; } objects.add(to...
java
public boolean removeChild(String id) { SharedPreferences prefs = loadSharedPreferences("children"); List<String> objects = getChildrenList(); if (objects.indexOf(id) == ArrayUtils.INDEX_NOT_FOUND) { return false; } objects.remove(id); prefs.edit().putStrin...
java
public C findChild(String id) { int index = getChildrenList().indexOf(id); if (index == ArrayUtils.INDEX_NOT_FOUND) { return null; } C child = null; try { Model dummy = (Model) childClazz.newInstance(); dummy.setContext(context); ...
java