code
stringlengths
73
34.1k
label
stringclasses
1 value
public void sendMessage(String channel, Message message) { ensureChannel(channel); admin.getRabbitTemplate().convertAndSend(exchange.getName(), channel, message); }
java
protected boolean putToQueue(IQueueMessage<ID, DATA> msg) { try { BytesMessage message = getProducerSession().createBytesMessage(); message.writeBytes(serialize(msg)); getMessageProducer().send(message); return true; } catch (Exception e) { thr...
java
public boolean hasException(Class<? extends Throwable> type) { for (Throwable exception : exceptions) { if (type.isInstance(exception)) { return true; } } return false; }
java
@Override public StackTraceElement[] getStackTrace() { ArrayList<StackTraceElement> stackTrace = new ArrayList<>(); for (Throwable exception : exceptions) { stackTrace.addAll(Arrays.asList(exception.getStackTrace())); } return stackTrace.toArray(new Stac...
java
public int dot(int[] other) { int dot = 0; for (int c = 0; c < used && indices[c] < other.length; c++) { if (indices[c] > Integer.MAX_VALUE) { break; } dot += values[c] * other[SafeCast.safeLongToInt(indices[c])]; } return dot; }
java
public int dot(int[][] matrix, int col) { int ret = 0; for (int c = 0; c < used && indices[c] < matrix.length; c++) { if (indices[c] > Integer.MAX_VALUE) { break; } ret += values[c] * matrix[SafeCast.safeLongToInt(indices[c])][col]; } r...
java
public static void copyResourceToFile(String resourceAbsoluteClassPath, File targetFile) throws IOException { InputStream is = ResourceUtil.class.getResourceAsStream(resourceAbsoluteClassPath); if (is == null) { throw new IOException("Resource not found! " + resourceAbsoluteClassPath); ...
java
public static String getAbsolutePath(String classPath) { URL configUrl = Thread.currentThread().getContextClassLoader().getResource(classPath.substring(1)); if (configUrl == null) { configUrl = ResourceUtil.class.getResource(classPath); } if (configUrl == null) { ...
java
@Override public void setFocus() { Radiobutton radio = editor.getSelected(); if (radio == null) { radio = (Radiobutton) editor.getChildren().get(0); } radio.setFocus(true); }
java
public static DesignContextMenu getInstance() { Page page = ExecutionContext.getPage(); DesignContextMenu contextMenu = page.getAttribute(DesignConstants.ATTR_DESIGN_MENU, DesignContextMenu.class); if (contextMenu == null) { contextMenu = create(); page.setAttribute(Desi...
java
public static DesignContextMenu create() { return PageUtil.createPage(DesignConstants.RESOURCE_PREFIX + "designContextMenu.fsp", ExecutionContext.getPage()) .get(0).getAttribute("controller", DesignContextMenu.class); }
java
private void disable(IDisable comp, boolean disabled) { if (comp != null) { comp.setDisabled(disabled); if (comp instanceof BaseUIComponent) { ((BaseUIComponent) comp).addStyle("opacity", disabled ? ".2" : "1"); } } }
java
public static double logAdd(double x, double y) { if (FastMath.useLogAddTable) { return SmoothedLogAddTable.logAdd(x,y); } else { return FastMath.logAddExact(x,y); } }
java
public static int mod(int val, int mod) { val = val % mod; if (val < 0) { val += mod; } return val; }
java
protected void prepareXMLReader() throws VerifierConfigurationException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); reader = factory.newSAXParser().getXMLReader(); } catch( SAXException e ) { throw new VerifierConfigurationException(e); } ...
java
private Mode makeBuiltinMode(String name, Class cls) { // lookup/create a mode with the given name. Mode mode = lookupCreateMode(name); // Init the element action set for this mode. ActionSet actions = new ActionSet(); // from the current mode we will use further the built in mode. ModeUsage mod...
java
SchemaFuture installHandlers(XMLReader in, SchemaReceiverImpl sr) { Handler h = new Handler(sr); in.setContentHandler(h); return h; }
java
private Mode getModeAttribute(Attributes attributes, String localName) { return lookupCreateMode(attributes.getValue("", localName)); }
java
private Mode lookupCreateMode(String name) { if (name == null) return null; name = name.trim(); Mode mode = (Mode)modeMap.get(name); if (mode == null) { mode = new Mode(name, defaultBaseMode); modeMap.put(name, mode); } return mode; }
java
private Date _advanceToNextDayOfWeekIfNecessary (final Date aFireTime, final boolean forceToAdvanceNextDay) { // a. Advance or adjust to next dayOfWeek if need to first, starting next // day with startTimeOfDay. Date fireTime = aFireTime; final TimeOfDay sTimeOfDay = getStartTimeOfDay (); final Da...
java
@Nonnull public static IScheduler getScheduler (final boolean bStartAutomatically) { try { // Don't try to use a name - results in NPE final IScheduler aScheduler = s_aSchedulerFactory.getScheduler (); if (bStartAutomatically && !aScheduler.isStarted ()) aScheduler.start (); ...
java
@Nonnull public static SchedulerMetaData getSchedulerMetaData () { try { // Get the scheduler without starting it return s_aSchedulerFactory.getScheduler ().getMetaData (); } catch (final SchedulerException ex) { throw new IllegalStateException ("Failed to get scheduler metadat...
java
public void setCronExpression (@Nonnull final String expression) throws ParseException { final CronExpression newExp = new CronExpression (expression); setCronExpression (newExp); }
java
public static <T extends Key <T>> GroupMatcher <T> groupEquals (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.EQUALS); }
java
public static <T extends Key <T>> GroupMatcher <T> groupStartsWith (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.STARTS_WITH); }
java
public static <T extends Key <T>> GroupMatcher <T> groupEndsWith (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.ENDS_WITH); }
java
public static <T extends Key <T>> GroupMatcher <T> groupContains (final String compareTo) { return new GroupMatcher <> (compareTo, StringOperatorName.CONTAINS); }
java
public static <U extends Key <U>> KeyMatcher <U> keyEquals (final U compareTo) { return new KeyMatcher <> (compareTo); }
java
public static <T> T instantiate(Class<T> clazz, CRestConfig crestConfig) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException { try { return accessible(clazz.getDeclaredConstructor(CRestConfig.class)).newInstance(crestConfig); } catch (NoSuc...
java
public Object doReverseOne( JTransfo jTransfo, Object domainObject, SyntheticField toField, Class<?> toType, String... tags) throws JTransfoException { return jTransfo.convertTo(domainObject, jTransfo.getToSubType(toType, domainObject), tags); }
java
public void addJobChainLink (final JobKey firstJob, final JobKey secondJob) { ValueEnforcer.notNull (firstJob, "FirstJob"); ValueEnforcer.notNull (firstJob.getName (), "FirstJob.Name"); ValueEnforcer.notNull (secondJob, "SecondJob"); ValueEnforcer.notNull (secondJob.getName (), "SecondJob.Name"); ...
java
private void checkM() throws DatatypeException, IOException { if (context.length() == 0) { appendToContext(current); } current = reader.read(); appendToContext(current); skipSpaces(); checkArg('M', "x coordinate"); skipCommaSpaces(); checkArg(...
java
private void checkC() throws DatatypeException, IOException { if (context.length() == 0) { appendToContext(current); } current = reader.read(); appendToContext(current); skipSpaces(); boolean expectNumber = true; for (;;) { switch (current...
java
public boolean before (final TimeOfDay timeOfDay) { if (timeOfDay.m_nHour > m_nHour) return true; if (timeOfDay.m_nHour < m_nHour) return false; if (timeOfDay.m_nMinute > m_nMinute) return true; if (timeOfDay.m_nMinute < m_nMinute) return false; if (timeOfDay.m_nSecond > ...
java
@Nullable public Date getTimeOfDayForDate (final Date dateTime) { if (dateTime == null) return null; final Calendar cal = PDTFactory.createCalendar (); cal.setTime (dateTime); cal.set (Calendar.HOUR_OF_DAY, m_nHour); cal.set (Calendar.MINUTE, m_nMinute); cal.set (Calendar.SECOND, m_nSe...
java
public Document parse(InputSource inputsource) throws SAXException, IOException { return verify(_WrappedBuilder.parse(inputsource)); }
java
public Document parse(File file) throws SAXException, IOException { return verify(_WrappedBuilder.parse(file)); }
java
public Document parse(InputStream strm) throws SAXException, IOException { return verify(_WrappedBuilder.parse(strm)); }
java
public Document parse(String url) throws SAXException, IOException { return verify(_WrappedBuilder.parse(url)); }
java
private int convertNonNegativeInteger(String str) { str = str.trim(); DecimalDatatype decimal = new DecimalDatatype(); if (!decimal.lexicallyAllows(str)) return -1; // Canonicalize the value str = decimal.getValue(str, null).toString(); // Reject negative and fractional numbers if (str...
java
private void checkItem(Element root, Deque<Element> parents) throws SAXException { Deque<Element> pending = new ArrayDeque<Element>(); Set<Element> memory = new HashSet<Element>(); memory.add(root); for (Element child : root.children) { pending.push(child); } ...
java
public static <T> ContractCondition<T> condition( final Predicate<T> condition, final Function<T, String> describer) { return ContractCondition.of(condition, describer); }
java
static int compare (final Date nextFireTime1, final int priority1, final TriggerKey key1, final Date nextFireTime2, final int priority2, final TriggerKey key2) { if (nextFireTime1 != null ||...
java
@Override public List<Connector> getSipConnectors() { List<Connector> connectors = new ArrayList<Connector>(); Connector[] conns = service.findConnectors(); for (Connector conn : conns) { if (conn.getProtocolHandler() instanceof SipProtocolHandler){ connectors.add(conn); } } return connect...
java
void perform(SectionState state) throws SAXException { final ModeUsage modeUsage = getModeUsage(); state.reject(); state.addChildMode(modeUsage, null); state.addAttributeValidationModeUsage(modeUsage); }
java
public Object getAttribute(String key) { Object result; if (attributes == null) { result = null; } else { result = attributes.get(key); } return result; }
java
private int reverseIndex(int k) { if (reverseIndexMap == null) { reverseIndexMap = new int[attributes.getLength()]; for (int i = 0, len = indexSet.size(); i < len; i++) reverseIndexMap[indexSet.get(i)] = i + 1; } return reverseIndexMap[k] - 1; }
java
public String getURI(int index) { if (index < 0 || index >= indexSet.size()) return null; return attributes.getURI(indexSet.get(index)); }
java
public String getLocalName(int index) { if (index < 0 || index >= indexSet.size()) return null; return attributes.getLocalName(indexSet.get(index)); }
java
public String getQName(int index) { if (index < 0 || index >= indexSet.size()) return null; return attributes.getQName(indexSet.get(index)); }
java
public String getType(int index) { if (index < 0 || index >= indexSet.size()) return null; return attributes.getType(indexSet.get(index)); }
java
public String getValue(int index) { if (index < 0 || index >= indexSet.size()) return null; return attributes.getValue(indexSet.get(index)); }
java
public String getType(String uri, String localName) { return attributes.getType(getRealIndex(uri, localName)); }
java
public String getValue(String uri, String localName) { return attributes.getValue(getRealIndex(uri, localName)); }
java
void perform(SectionState state) { state.addChildMode(getModeUsage(), null); state.addAttributeValidationModeUsage(getModeUsage()); }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInSeconds (final int intervalInSeconds) { _validateInterval (intervalInSeconds); m_nInterval = intervalInSeconds; m_eIntervalUnit = EIntervalUnit.SECOND; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInMinutes (final int intervalInMinutes) { _validateInterval (intervalInMinutes); m_nInterval = intervalInMinutes; m_eIntervalUnit = EIntervalUnit.MINUTE; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInHours (final int intervalInHours) { _validateInterval (intervalInHours); m_nInterval = intervalInHours; m_eIntervalUnit = EIntervalUnit.HOUR; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInDays (final int intervalInDays) { _validateInterval (intervalInDays); m_nInterval = intervalInDays; m_eIntervalUnit = EIntervalUnit.DAY; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInWeeks (final int intervalInWeeks) { _validateInterval (intervalInWeeks); m_nInterval = intervalInWeeks; m_eIntervalUnit = EIntervalUnit.WEEK; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInMonths (final int intervalInMonths) { _validateInterval (intervalInMonths); m_nInterval = intervalInMonths; m_eIntervalUnit = EIntervalUnit.MONTH; return this; }
java
@Nonnull public CalendarIntervalScheduleBuilder withIntervalInYears (final int intervalInYears) { _validateInterval (intervalInYears); m_nInterval = intervalInYears; m_eIntervalUnit = EIntervalUnit.YEAR; return this; }
java
static int checkResult(int result) { if (exceptionsEnabled && result != cusolverStatus.CUSOLVER_STATUS_SUCCESS) { throw new CudaException(cusolverStatus.stringFor(result)); } return result; }
java
public NonBlockingProperties getPropertyGroup (final String sPrefix, final boolean bStripPrefix, final String [] excludedPrefixes) { final NonBlockingProperties group = new NonBlockingProperties (); String prefi...
java
public void partialDeserialize(TBase<?,?> base, DBObject dbObject, TFieldIdEnum... fieldIds) throws TException { try { protocol_.setDBOject(dbObject); protocol_.setBaseObject( base ); protocol_.setFieldIdsFilter(base, fieldIds); base.read(protocol_); } finally { protocol_.reset();...
java
public Verifier newVerifier(String uri) throws VerifierConfigurationException, SAXException, IOException { return compileSchema(uri).newVerifier(); }
java
public Verifier newVerifier(File file) throws VerifierConfigurationException, SAXException, IOException { return compileSchema(file).newVerifier(); }
java
public Verifier newVerifier(InputSource source) throws VerifierConfigurationException, SAXException, IOException { return compileSchema(source).newVerifier(); }
java
public static VerifierFactory newInstance(String language,ClassLoader classLoader) throws VerifierConfigurationException { Iterator itr = providers( VerifierFactoryLoader.class, classLoader ); while(itr.hasNext()) { VerifierFactoryLoader loader = (VerifierFactoryLoader)itr.next(); try { VerifierFac...
java
@Override public void deleteUnpackedWAR(StandardContext standardContext) { File unpackDir = new File(standardHost.getAppBase(), standardContext.getPath().substring(1)); if (unpackDir.exists()) { ExpandWar.deleteDir(unpackDir); } }
java
public boolean sameValue(Object value1, Object value2) { return ((BigDecimal)value1).compareTo((BigDecimal)value2) == 0; }
java
public void addSchema( String uri, IslandSchema s ) { if( schemata.containsKey(uri) ) throw new IllegalArgumentException(); schemata.put( uri, s ); }
java
public String generateNonce() { // Get the time of day and run MD5 over it. Date date = new Date(); long time = date.getTime(); Random rand = new Random(); long pad = rand.nextLong(); String nonceString = (Long.valueOf(time)).toString() + (Long.valueOf(pad)).toString(); byte mdbytes[] = messageDigest....
java
public static String formatException(final Exception e) { final StringBuilder sb = new StringBuilder(); Throwable t = e; while (t != null) { sb.append(t.getMessage()).append("\n"); t = t.getCause(); } return sb.toString(); }
java
public DailyTimeIntervalScheduleBuilder onDaysOfTheWeek (final Set <DayOfWeek> onDaysOfWeek) { ValueEnforcer.notEmpty (onDaysOfWeek, "OnDaysOfWeek"); m_aDaysOfWeek = onDaysOfWeek; return this; }
java
public DailyTimeIntervalScheduleBuilder endingDailyAfterCount (final int count) { ValueEnforcer.isGT0 (count, "Count"); if (m_aStartTimeOfDay == null) throw new IllegalArgumentException ("You must set the startDailyAt() before calling this endingDailyAfterCount()!"); final Date today = new Date ()...
java
protected void onValidMarkup(AppendingStringBuffer responseBuffer, ValidationReport report) { IRequestablePage responsePage = getResponsePage(); DocType doctype = getDocType(responseBuffer); log.info("Markup for {} is valid {}", responsePage != null ? responsePage.getClass().getName() : "<unable to ...
java
protected void onInvalidMarkup(AppendingStringBuffer responseBuffer, ValidationReport report) { String head = report.getHeadMarkup(); String body = report.getBodyMarkup(); int indexOfHeadClose = responseBuffer.lastIndexOf("</head>"); responseBuffer.insert(indexOfHeadClose, head); int indexOfBodyClose = r...
java
<T> Class<T> loadClass(String name) throws ClassNotFoundException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (null == cl) { cl = ToHelper.class.getClassLoader(); } return (Class<T>) cl.loadClass(name); }
java
List<Field> getFields(Class<?> clazz) { List<Field> result = new ArrayList<>(); Set<String> fieldNames = new HashSet<>(); Class<?> searchType = clazz; while (!Object.class.equals(searchType) && searchType != null) { Field[] fields = searchType.getDeclaredFields(); ...
java
Method getMethod(Class<?> type, Class<?> returnType, String name, Class<?>... parameters) { Method method = null; try { // first try for public methods method = type.getMethod(name, parameters); if (null != returnType && !returnType.isAssignableFrom(method.getReturnTy...
java
protected static void triggerCustomExceptionHandler (@Nonnull final Throwable t, @Nullable final String sJobClassName, @Nonnull final IJob aJob) { exceptionCallbacks ().forEach (x -> x.onScheduledJobExcep...
java
public static Response toResponse(Response.Status status, String wwwAuthHeader) { Response.ResponseBuilder rb = Response.status(status); if (wwwAuthHeader != null) { rb.header("WWW-Authenticate", wwwAuthHeader); } return rb.build(); }
java
public void execute(final FifoTask<E> task) throws InterruptedException { final int id; synchronized (this) { id = idCounter++; taskMap.put(id, task); while (activeCounter >= maxThreads) { wait(); } activeCounter++; } ...
java
public static String executeProcess(Map<String, String> env, File workingFolder, String... command) throws ProcessException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(command); if (workingFolder != null) { pb.directory(workingFolder); } if (env != nul...
java
public static int cusolverRfGetMatrixFormat( cusolverRfHandle handle, int[] format, int[] diag) { return checkResult(cusolverRfGetMatrixFormatNative(handle, format, diag)); }
java
public static int cusolverRfSetNumericProperties( cusolverRfHandle handle, double zero, double boost) { return checkResult(cusolverRfSetNumericPropertiesNative(handle, zero, boost)); }
java
public static int cusolverRfSetAlgs( cusolverRfHandle handle, int factAlg, int solveAlg) { return checkResult(cusolverRfSetAlgsNative(handle, factAlg, solveAlg)); }
java
public static int cusolverRfSetupHost( int n, int nnzA, Pointer h_csrRowPtrA, Pointer h_csrColIndA, Pointer h_csrValA, int nnzL, Pointer h_csrRowPtrL, Pointer h_csrColIndL, Pointer h_csrValL, int nnzU, Pointer h...
java
public static int cusolverRfBatchSetupHost( int batchSize, int n, int nnzA, Pointer h_csrRowPtrA, Pointer h_csrColIndA, Pointer h_csrValA_array, int nnzL, Pointer h_csrRowPtrL, Pointer h_csrColIndL, Pointer h_csrValL, ...
java
public static RegexPathTemplate create(String urlTemplate) { StringBuffer baseUrl = new StringBuffer(); Map<String, PathTemplate> templates = new HashMap<String, PathTemplate>(); CurlyBraceTokenizer t = new CurlyBraceTokenizer(urlTemplate); while (t.hasNext()) { String tok = ...
java
public void addValidator(Schema schema, ModeUsage modeUsage) { // adds the schema to this section schemas schemas.addElement(schema); // creates the validator Validator validator = createValidator(schema); // adds the validator to this section validators validators.addElement(validat...
java
public static void writeStringToFile(File file, String data, String charset) throws IOException { FileOutputStream fos = openOutputStream(file, false); fos.write(data.getBytes(charset)); fos.close(); }
java
public static Thread pipeAsynchronously(final InputStream is, final ErrorHandler errorHandler, final boolean closeResources, final OutputStream... os) { Thread t = new Thread() { @Override public void run() { try { pipeSynchronously(is, closeResou...
java
public static File createFile(String filePath) throws IOException { boolean isDirectory = filePath.endsWith("/") || filePath.endsWith("\\"); String formattedFilePath = formatFilePath(filePath); File f = new File(formattedFilePath); if (f.exists()) { return f; ...
java
public boolean compete(NamespaceSpecification other) { // if no wildcard for other then we check coverage if ("".equals(other.wildcard)) { return covers(other.ns); } // split the namespaces at wildcards String[] otherParts = split(other.ns, other.wildcard); // if the given nameps...
java
static private boolean matchPrefix(String s1, String s2) { return s1.startsWith(s2) || s2.startsWith(s1); }
java
public boolean covers(String uri) { // any namspace covers only the any namespace uri // no wildcard ("") requires equality between namespaces. if (ANY_NAMESPACE.equals(ns) || "".equals(wildcard)) { return ns.equals(uri); } String[] parts = split(ns, wildcard); // no wildcard if (p...
java
@Override public void reloadContext() throws DeploymentException { Archive<?> archive = mssContainer.getArchive(); deployableContainer.undeploy(archive); deployableContainer.deploy(archive); }
java
private Mode resolve(Mode mode) { if (mode == Mode.CURRENT) { return currentMode; } // For an action that does not specify the useMode attribute // we create an anonymous next mode that becomes defined if we // have a nested mode element inside the action. // If we do not have a nested mo...
java