code
stringlengths
73
34.1k
label
stringclasses
1 value
public Reflect create() throws ReflectionException { try { return on(clazz.getConstructor(), accessAll); } catch (NoSuchMethodException e) { if (accessAll) { try { return on(clazz.getDeclaredConstructor(), accessAll); } catch (NoSuchMethodException e2...
java
public Reflect create(Object... args) throws ReflectionException { return create(ReflectionUtils.getTypes(args), args); }
java
public Reflect create(Class[] types, Object... args) throws ReflectionException { try { return on(clazz.getConstructor(types), accessAll, args); } catch (NoSuchMethodException e) { for (Constructor constructor : getConstructors()) { if (ReflectionUtils.typesMatch(constructor.ge...
java
public Method getMethod(final String name) { if (StringUtils.isNullOrBlank(name)) { return null; } return getMethods().stream().filter(method -> method.getName().equals(name)).findFirst().orElse(null); }
java
public boolean containsMethod(final String name) { if (StringUtils.isNullOrBlank(name)) { return false; } return ClassDescriptorCache.getInstance() .getClassDescriptor(clazz) .getMethods(accessAll) ...
java
public Reflect invoke(String methodName, Object... args) throws ReflectionException { Class[] types = ReflectionUtils.getTypes(args); try { return on(clazz.getMethod(methodName, types), object, accessAll, args); } catch (NoSuchMethodException e) { Method method = ReflectionUtils.best...
java
public Reflect set(String fieldName, Object value) throws ReflectionException { Field field = null; boolean isAccessible = false; try { if (hasField(fieldName)) { field = getField(fieldName); isAccessible = field.isAccessible(); field.setAccessible(accessAl...
java
public TypedQuery<Long> count(Filter filter) { CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<T> from = query.from(getEntityClass()); if (filter != null) { Predicate where = new CriteriaMapper(from, cb).create(filter); query.where(where); } ...
java
public static String generateMD5(final String input) { try { return generateMD5(input.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.debug("An error occurred generating the MD5 Hash of the input string", e); return null; } }
java
public static Properties loadClasspath(String path) throws IOException { InputStream input = PropUtils.class.getClassLoader().getResourceAsStream(path); Properties prop = null; try { prop = load(input); } finally { IOUtils.close(input); } return prop; }
java
public Tuple shiftLeft() { if (degree() < 2) { return Tuple0.INSTANCE; } Object[] copy = new Object[degree() - 1]; System.arraycopy(array(), 1, copy, 0, copy.length); return NTuple.of(copy); }
java
public Tuple slice(int start, int end) { Preconditions.checkArgument(start >= 0, "Start index must be >= 0"); Preconditions.checkArgument(start < end, "Start index must be < end index"); if (start >= degree()) { return Tuple0.INSTANCE; } return new NTuple(Arrays.copyOfRange(array(...
java
public <T> Tuple appendLeft(T object) { if (degree() == 0) { return Tuple1.of(object); } Object[] copy = new Object[degree() + 1]; System.arraycopy(array(), 0, copy, 1, degree()); copy[0] = object; return NTuple.of(copy); }
java
private boolean isIncluded(String className) { if (includes == null || includes.size() == 0) { // generate nothing if no include defined - it makes no sense to generate for all classes from classpath return false; } return includes.stream() .filter(pattern -> SelectorUtils.matchPath(patt...
java
private boolean isExcluded(String className) { if (excludes == null || excludes.size() == 0) { return false; } return excludes.stream() .filter(pattern -> SelectorUtils.matchPath(pattern, className, ".", true)) .count() == 0; }
java
private void generateSchema(Class clazz) { try { File targetFile = new File(getGeneratedResourcesDirectory(), clazz.getName() + ".json"); getLog().info("Generate JSON schema: " + targetFile.getName()); SchemaFactoryWrapper schemaFactory = new SchemaFactoryWrapper(); OBJECT_MAPPER.acceptJsonF...
java
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (LaunchedURLClassLoader.LOCK_PROVIDER.getLock(this, name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass == null) { Handler....
java
@SuppressWarnings("unchecked") public static int compare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } return Cast.<Comparable>as(o1).compareTo(o2); }
java
public static <T> SerializableComparator<T> hashCodeComparator() { return (o1, o2) -> { if (o1 == o2) { return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } return Integer.compare(o1.hashCode(), o2.hashC...
java
public final void addFolder(@NotNull final Folder folder) { Contract.requireArgNotNull("folder", folder); if (folders == null) { folders = new ArrayList<>(); } folders.add(folder); }
java
public Iterator<int[]> fastPassByReferenceIterator() { final int[] assignments = new int[dimensions.length]; if (dimensions.length > 0) assignments[0] = -1; return new Iterator<int[]>() { @Override public boolean hasNext() { for (int i = 0; i < assignment...
java
private int getTableAccessOffset(int[] assignment) { assert(assignment.length == dimensions.length); int offset = 0; for (int i = 0; i < assignment.length; i++) { assert(assignment[i] < dimensions[i]); offset = (offset*dimensions[i]) + assignment[i]; } ret...
java
public static String center(String s, int length) { if (s == null) { return null; } int start = (int) Math.floor(Math.max(0, (length - s.length()) / 2d)); return padEnd(repeat(' ', start) + s, length, ' '); }
java
public static int compare(String s1, String s2, boolean ignoreCase) { if (s1 == null && s2 == null) { return 0; } else if (s1 == null) { return -1; } else if (s2 == null) { return 1; } return ignoreCase ? s1.compareToIgnoreCase(s2) : s1.compareTo(s2); }
java
public static String firstNonNullOrBlank(String... strings) { if (strings == null || strings.length == 0) { return null; } for (String s : strings) { if (isNotNullOrBlank(s)) { return s; } } return null; }
java
public static String leftTrim(CharSequence input) { if (input == null) { return null; } return StringFunctions.LEFT_TRIM.apply(input.toString()); }
java
public static String removeDiacritics(CharSequence input) { if (input == null) { return null; } return StringFunctions.DIACRITICS_NORMALIZATION.apply(input.toString()); }
java
public static String rightTrim(CharSequence input) { if (input == null) { return null; } return StringFunctions.RIGHT_TRIM.apply(input.toString()); }
java
public static boolean safeEquals(String s1, String s2, boolean caseSensitive) { if (s1 == s2) { return true; } else if (s1 == null || s2 == null) { return false; } else if (caseSensitive) { return s1.equals(s2); } return s1.equalsIgnoreCase(s2); }
java
@SneakyThrows public static List<String> split(CharSequence input, char separator) { if (input == null) { return new ArrayList<>(); } Preconditions.checkArgument(separator != '"', "Separator cannot be a quote"); try (CSVReader reader = CSV.builder().delimiter(separator).reader(new St...
java
public static String toCanonicalForm(CharSequence input) { if (input == null) { return null; } return StringFunctions.CANONICAL_NORMALIZATION.apply(input.toString()); }
java
public static String toTitleCase(CharSequence input) { if (input == null) { return null; } return StringFunctions.TITLE_CASE.apply(input.toString()); }
java
public static String trim(CharSequence input) { if (input == null) { return null; } return StringFunctions.TRIM.apply(input.toString()); }
java
public static String unescape(String input, char escapeCharacter) { if (input == null) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < input.length(); ) { if (input.charAt(i) == escapeCharacter) { builder.append(input.charAt(i + 1))...
java
public static void validateAddress(String address) { // Check for improperly formatted addresses Matcher matcher = ADDRESS_PATTERN.matcher(address); if(!matcher.matches()) { String message = "The address must have the format X.X.X.X"; throw new IllegalArgumentException(message); } // Check for out of r...
java
public static void validatePeriod(Duration period) { if(period.equals(Duration.ZERO)) { String message = "The period must be nonzero"; throw new IllegalArgumentException(message); } }
java
public static void validateTimeout(Duration timeout) { if(timeout.equals(Duration.ZERO)) { String message = "The timeout must be nonzero"; throw new IllegalArgumentException(message); } }
java
@Override public boolean setProperties(Dictionary<String, String> properties) { this.properties = properties; if (this.properties != null) { if (properties.get("debug") != null) debug = Integer.parseInt(properties.get("debug")); if (properties.get("in...
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public boolean setDocBase(String basePath) { proxyDirContext = null; if (basePath == null) return false; Hashtable env = new Hashtable(); File file = new File(basePath); if (!file.exists()) ...
java
public static Properties loadProperties(final Class<?> clasz, final String filename) { checkNotNull("clasz", clasz); checkNotNull("filename", filename); final String path = getPackagePath(clasz); final String resPath = path + "/" + filename; return loadProperties(clasz.getClassL...
java
public static Properties loadProperties(final ClassLoader loader, final String resource) { checkNotNull("loader", loader); checkNotNull("resource", resource); final Properties props = new Properties(); try (final InputStream inStream = loader.getResourceAsStream(resource)) { ...
java
public static Properties loadProperties(final URL baseUrl, final String filename) { return loadProperties(createUrl(baseUrl, "", filename)); }
java
public static Properties loadProperties(final URL fileURL) { checkNotNull("fileURL", fileURL); final Properties props = new Properties(); try (final InputStream inStream = fileURL.openStream()) { props.load(inStream); } catch (final IOException ex) { throw new Run...
java
private ScenarioManager createScenarioManager( Class<? extends Scenario> scenarioClass, String scenarioID, String initialState, Properties properties) throws ShanksException { // throws UnsupportedNetworkElementFieldException, // TooManyConnectionException, UnsupportedScena...
java
public void startSimulation() throws ShanksException { schedule.scheduleRepeating(Schedule.EPOCH, 0, this.scenarioManager, 2); schedule.scheduleRepeating(Schedule.EPOCH, 1, this.notificationManager, 1); this.addAgents(); this.addSteppables(); }
java
private void addAgents() throws ShanksException { for (Entry<String, ShanksAgent> agentEntry : this.agents.entrySet()) { stoppables.put(agentEntry.getKey(), schedule.scheduleRepeating(Schedule.EPOCH, 2, agentEntry.getValue(), 1)); } }
java
public void registerShanksAgent(ShanksAgent agent) throws ShanksException { if (!this.agents.containsKey(agent.getID())) { this.agents.put(agent.getID(), agent); } else { throw new DuplicatedAgentIDException(agent.getID()); } }
java
public void unregisterShanksAgent(String agentID){ if (this.agents.containsKey(agentID)) { // this.agents.get(agentID).stop(); if (stoppables.containsKey(agentID)) { this.agents.remove(agentID); this.stoppables.remove(agentID).stop(); } else {...
java
public boolean containsStartTag(@NotNull @FileExists @IsFile final File file, @NotNull final String tagName) { Contract.requireArgNotNull("file", file); FileExistsValidator.requireArgValid("file", file); IsFileValidator.requireArgValid("file", file); Contract.requireArgNotNull("tagNa...
java
@SuppressWarnings("unchecked") @NotNull public <TYPE> TYPE create(@NotNull final Reader reader, @NotNull final JAXBContext jaxbContext) throws UnmarshalObjectException { Contract.requireArgNotNull("reader", reader); Contract.requireArgNotNull("jaxbContext", jaxbContext); try { ...
java
@SuppressWarnings("unchecked") @NotNull public <TYPE> TYPE create(@NotNull @FileExists @IsFile final File file, @NotNull final JAXBContext jaxbContext) throws UnmarshalObjectException { Contract.requireArgNotNull("file", file); FileExistsValidator.requireArgValid("file", file); ...
java
@SuppressWarnings("unchecked") @NotNull public <TYPE> TYPE create(@NotNull final String xml, @NotNull final JAXBContext jaxbContext) throws UnmarshalObjectException { Contract.requireArgNotNull("xml", xml); Contract.requireArgNotNull("jaxbContext", jaxbContext); return (TYPE) cr...
java
public <TYPE> void write(@NotNull final TYPE obj, @NotNull final File file, @NotNull final JAXBContext jaxbContext) throws MarshalObjectException { Contract.requireArgNotNull("obj", obj); Contract.requireArgNotNull("file", file); Contract.requireArgNotNull("jaxbContext", jaxbCo...
java
public <TYPE> String write(@NotNull final TYPE obj, @NotNull final JAXBContext jaxbContext) throws MarshalObjectException { Contract.requireArgNotNull("obj", obj); Contract.requireArgNotNull("jaxbContext", jaxbContext); final StringWriter writer = new StringWriter(); write(obj, w...
java
public <TYPE> void write(@NotNull final TYPE obj, @NotNull final Writer writer, @NotNull final JAXBContext jaxbContext) throws MarshalObjectException { Contract.requireArgNotNull("obj", obj); Contract.requireArgNotNull("writer", writer); Contract.requireArgNotNull("jaxbContext"...
java
public boolean shouldConfigureVirtualenv() { if(this.configureVirtualenv == ConfigureVirtualenv.NO) { return false; } else if(this.configureVirtualenv == ConfigureVirtualenv.YES) { return true; } else { final Optional<File> whichVirtualenv = this.which("virtualenv"); return whichVirt...
java
public boolean isPre20141006Release(File galaxyRoot) { if (galaxyRoot == null) { throw new IllegalArgumentException("galaxyRoot is null"); } else if (!galaxyRoot.exists()) { throw new IllegalArgumentException("galaxyRoot=" + galaxyRoot.getAbsolutePath() + " does not exist"); } File conf...
java
private File getConfigSampleIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini.sample"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini.sample"); } }
java
private File getConfigIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini"); } }
java
@SuppressWarnings("unchecked") public void init(ServletConfig config) throws ServletException { super.init(config); // Move init params to my properties Enumeration<String> paramNames = this.getInitParameterNames(); while (paramNames.hasMoreElements()) { Strin...
java
public String getRequestParam(HttpServletRequest request, String param, String defaultValue) { String value = request.getParameter(servicePid + '.' + param); if ((value == null) && (properties != null)) value = properties.get(servicePid + '.' + param); if (value == null) ...
java
private static Map<String, Object> readMap(StreamingInput input) throws IOException { boolean readEnd = false; if(input.peek() == Token.OBJECT_START) { // Check if the object is wrapped readEnd = true; input.next(); } Token t; Map<String, Object> result = new HashMap<String, Object>(); while(...
java
private static List<Object> readList(StreamingInput input) throws IOException { input.next(Token.LIST_START); List<Object> result = new ArrayList<Object>(); while(input.peek() != Token.LIST_END) { // Read the value Object value = readDynamic(input); result.add(value); } input.next(Token.LIST_E...
java
private static Object readDynamic(StreamingInput input) throws IOException { switch(input.peek()) { case VALUE: input.next(); return input.getValue(); case NULL: input.next(); return input.getValue(); case LIST_START: return readList(input); case OBJECT_START: return readMap(i...
java
public void execute() throws MojoExecutionException { try { repositoryPath = findRepoPath(this.ceylonRepository); ArtifactRepositoryLayout layout = new CeylonRepoLayout(); getLog().debug("Layout: " + layout.getClass()); localRepository = ne...
java
private void installProject(final MavenProject mavenProject) throws MojoExecutionException { Artifact artifact = mavenProject.getArtifact(); String packaging = mavenProject.getPackaging(); boolean isPomArtifact = "pom".equals(packaging); try { // skip copying pom to ...
java
void install(final File file, final Artifact artifact, final ArtifactRepository repo) throws MojoExecutionException { File destFile = new File(repo.getBasedir() + File.separator + repo.getLayout().pathOf(artifact)); destFile.getParentFile().mkdirs(); try { ...
java
String calculateDependencies(final MavenProject proj) throws MojoExecutionException { Module module = new Module( new ModuleIdentifier(CeylonUtil.ceylonModuleBaseName(proj.getGroupId(), proj.getArtifactId()), proj.getVersion(), false, false)); for (De...
java
File findRepoPath(final String repoAlias) { if ("user".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/repo"); } else if ("cache".equals(repoAlias)) { return new File(System.getPro...
java
void installAdditional(final File installedFile, final String fileExt, final String payload, final boolean chop) throws MojoExecutionException { File additionalFile = null; if (chop) { String path = installedFile.getAbsolutePath(); additionalFile = new File(path....
java
public boolean complete(Number value) { return root.complete(new Tree((Tree) null, null, value)); }
java
public boolean complete(String value) { return root.complete(new Tree((Tree) null, null, value)); }
java
public boolean complete(Date value) { return root.complete(new Tree((Tree) null, null, value)); }
java
public boolean complete(UUID value) { return root.complete(new Tree((Tree) null, null, value)); }
java
public boolean complete(InetAddress value) { return root.complete(new Tree((Tree) null, null, value)); }
java
public static final Promise race(Promise... promises) { if (promises == null || promises.length == 0) { return Promise.resolve(); } @SuppressWarnings("unchecked") CompletableFuture<Tree>[] futures = new CompletableFuture[promises.length]; for (int i = 0; i < promises.length; i++) { futures[i] =...
java
@SuppressWarnings("unchecked") protected static final Tree toTree(Object object) { if (object == null) { return new Tree((Tree) null, null, null); } if (object instanceof Tree) { return (Tree) object; } if (object instanceof Map) { return new Tree((Map<String, Object>) object); } retu...
java
public Object addingService(ServiceReference reference) { HttpService httpService = (HttpService) context.getService(reference); this.properties = this.updateDictionaryConfig(this.properties, true); try { String alias = this.getAlias(); String servicePid = this.prope...
java
public Servlet makeServlet(String alias, Dictionary<String, String> dictionary) { String servletClass = dictionary.get(BundleConstants.SERVICE_CLASS); return (Servlet)ClassServiceUtility.getClassService().makeObjectFromClassName(servletClass); }
java
public void removeService(ServiceReference reference, Object service) { if (serviceRegistration != null) { serviceRegistration.unregister(); serviceRegistration = null; } String alias = this.getAlias(); ((HttpService) service).unregister(alias); if (servl...
java
public String getAlias() { String alias = this.properties.get(BaseWebappServlet.ALIAS); if (alias == null) alias = this.properties.get(BaseWebappServlet.ALIAS.substring(BaseWebappServlet.PROPERTY_PREFIX.length())); return HttpServiceTracker.addURLPath(null, alias); }
java
public String calculateWebAlias(Dictionary<String, String> dictionary) { String alias = dictionary.get(BaseWebappServlet.ALIAS); if (alias == null) alias = dictionary.get(BaseWebappServlet.ALIAS.substring(BaseWebappServlet.PROPERTY_PREFIX.length())); if (alias == null) ...
java
public void configPropertiesUpdated(Dictionary<String, String> properties) { if (HttpServiceTracker.propertiesEqual(properties, configProperties)) return; configProperties = properties; ServiceReference reference = context.getServiceReference(HttpService.class.getName()); ...
java
public boolean changeServletProperties(Servlet servlet, Dictionary<String, String> properties) { if (servlet instanceof WebappServlet) { Dictionary<String, String> dictionary = ((WebappServlet)servlet).getProperties(); properties = BaseBundleActivator.putAll(properties, dicti...
java
public boolean setServletProperties(Servlet servlet, Dictionary<String, String> properties) { this.properties = properties; if (servlet instanceof WebappServlet) return ((WebappServlet)servlet).setProperties(properties); return true; // Success }
java
public static boolean propertiesEqual(Dictionary<String, String> properties, Dictionary<String, String> dictionary) { Enumeration<String> props = properties.keys(); while (props.hasMoreElements()) { String key = props.nextElement(); if (!properties.get(key).equals(dic...
java
private String buildLogPath(File bootstrapLogDir, String logFileName) { return new File(bootstrapLogDir, logFileName).getAbsolutePath(); }
java
private void executeGalaxyScript(final String scriptName) { final String bashScript = String.format("cd %s; if [ -d .venv ]; then . .venv/bin/activate; fi; %s", getPath(), scriptName); IoUtils.executeAndWait("bash", "-c", bashScript); }
java
public void stateMachine(ShanksSimulation sim) throws Exception{ logger.fine("Using default state machine for ScenarioManager"); // switch (this.simulationStateMachineStatus) { // case CHECK_FAILURES: // this.checkFailures(sim); // this.simulationStateMachineStatus = GENERATE...
java
public EmbedVaadinComponent withTheme(String theme) { assertNotNull(theme, "theme could not be null."); getConfig().setTheme(theme); return self(); }
java
public synchronized static void enableLogging() { if (SplitlogLoggerFactory.state == SplitlogLoggingState.ON) { return; } SplitlogLoggerFactory.messageCounter.set(0); SplitlogLoggerFactory.state = SplitlogLoggingState.ON; /* * intentionally using the original...
java
public synchronized static boolean isLoggingEnabled() { switch (SplitlogLoggerFactory.state) { case ON: return true; case OFF: return false; default: final String propertyValue = System.getProperty(SplitlogLoggerFactory.LOGGING_...
java
public synchronized static void silenceLogging() { if (SplitlogLoggerFactory.state == SplitlogLoggingState.OFF) { return; } SplitlogLoggerFactory.state = SplitlogLoggingState.OFF; SplitlogLoggerFactory.messageCounter.set(0); /* * intentionally using the origi...
java
public static void add() { String current = System.getProperties().getProperty(HANDLER_PKGS, ""); if (current.length() > 0) { if (current.contains(PKG)) { return; } current = current + "|"; } System.getProperties().put(HANDLER_PKGS, cu...
java
public static void remove() { final String current = System.getProperties().getProperty(HANDLER_PKGS, ""); // Only one if (current.equals(PKG)) { System.getProperties().put(HANDLER_PKGS, ""); return; } // Middle String token = "|" + PKG + "|"; ...
java
public boolean pauseQuartzJob(String jobName, String jobGroupName) { try { this.scheduler.pauseJob(new JobKey(jobName, jobGroupName)); return true; } catch (SchedulerException e) { logger.error("error pausing job: " + jobName + " in group: " + jobGroupName, e); ...
java
public boolean pauseQuartzScheduler() { try { this.scheduler.standby(); return true; } catch (SchedulerException e) { logger.error("error pausing quartz scheduler", e); } return false; }
java
public Boolean isSchedulerPaused() { try { return this.scheduler.isInStandbyMode(); } catch (SchedulerException e) { logger.error("error retrieveing scheduler condition", e); } return null; }
java
public boolean executeJob(String jobName, String jobGroupName) { try { this.scheduler.triggerJob(new JobKey(jobName, jobGroupName)); return true; } catch (SchedulerException e) { logger.error("error executing job: " + jobName + " in group: " + jobGroupName, e); ...
java
public void log(Level level, String message, Object... args) { if (logger.isLoggable(level)) { String errorMessage = ""; Throwable thrown = null; Object[] params = null; if (args == null || args.length == 0) { errorMessage = message; } else if (args[0] ins...
java