code
stringlengths
73
34.1k
label
stringclasses
1 value
public ComponentFactory<T, E> toConfigure(BiConsumer<Context, Annotation> consumer) { return new ComponentFactory<>(this.annotationType, this.classElement, consumer, this.createFunction); }
java
public List<E> createAll(AnnotatedElement element) { List<E> result = new ArrayList<>(); for (Annotation annotation : element.getAnnotations()) { create(annotation).ifPresent(result::add); } return result; }
java
public static String getVersion() { String version = null; // try to load from maven properties first try { Properties p = new Properties(); InputStream is = VersionHelper.class.getResourceAsStream("/META-INF/maven/io.redlink/redlink-sdk-java/pom.properties"); ...
java
protected static String formatApiVersion(String version) { if (StringUtils.isBlank(version)) { return VERSION; } else { final Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) { return String.format("%s.%s", matcher.group(1), m...
java
@Override public int numSheets() { int ret = -1; if(workbook != null) ret = workbook.getNumberOfSheets(); else if(writableWorkbook != null) ret = writableWorkbook.getNumberOfSheets(); return ret; }
java
@Override public String[] getSheetNames() { String[] ret = null; if(workbook != null) ret = workbook.getSheetNames(); else if(writableWorkbook != null) ret = writableWorkbook.getSheetNames(); return ret; }
java
@Override public XlsWorksheet getSheet(String name) { XlsWorksheet ret = null; if(workbook != null) { Sheet sheet = workbook.getSheet(name); if(sheet != null) ret = new XlsWorksheet(sheet); } else if(writableWorkbook != null) ...
java
@Override public XlsWorksheet createSheet(FileColumn[] columns, List<String[]> lines, String sheetName) throws IOException { // Create the worksheet and add the cells WritableSheet sheet = writableWorkbook.createSheet(sheetName, 9999); // Append sheet try { a...
java
@Override public void appendToSheet(FileColumn[] columns, List<String[]> lines, String sheetName) throws IOException { try { XlsWorksheet sheet = getSheet(sheetName); if(sheet != null) appendRows((WritableSheet)sheet.getSheet(), columns, lines, she...
java
private void appendRows(WritableSheet sheet, FileColumn[] columns, List<String[]> lines, String sheetName) throws WriteException { WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD); WritableCellFormat headerFormat = new WritableCellFormat(headerF...
java
public void setCellFormatAttributes(WritableCellFormat cellFormat, FileColumn column) { try { if(cellFormat != null && column != null) { Alignment a = Alignment.GENERAL; short align = column.getAlign(); if(align == FileColumn.AL...
java
@Override public void close() { if(workbook != null) workbook.close(); try { if(writableWorkbook != null) writableWorkbook.close(); } catch(IOException e) { } catch(WriteException e) { } ...
java
public static List<Range<Date>> getDateRanges(Date from, Date to, final Period periodGranulation) throws InvalidRangeException { if (from.after(to)) { throw buildInvalidRangeException(from, to); } if (periodGranulation == Period.SINGLE) { @SuppressWarnings("unchecked") ArrayList<Range<Dat...
java
public static Range<Date> getDatePeriod(final Date date, final Period period) { Calendar calendar = buildCalendar(date); Range<Date> dateRange = null; Date startDate = calendar.getTime(); Date endDate = calendar.getTime(); if (period != Period.DAY) { for (; period.getValue(date) == period.get...
java
private static Calendar buildCalendar(final Date date) { Calendar calendar = buildCalendar(); calendar.setTime(date); return calendar; }
java
public synchronized void execute(Runnable command) { if (active.get()) { stop(); this.command = command; start(); } else { this.command = command; } }
java
public boolean startsWith(Name prefix) { byte[] thisBytes = this.getByteArray(); int thisOffset = this.getByteOffset(); int thisLength = this.getByteLength(); byte[] prefixBytes = prefix.getByteArray(); int prefixOffset = prefix.getByteOffset(); int prefixLength =...
java
@Programmatic public DocumentTemplate createBlob( final DocumentType type, final LocalDate date, final String atPath, final String fileSuffix, final boolean previewOnly, final Blob blob, final RenderingStrategy contentRenderingStrat...
java
@Programmatic public List<DocumentTemplate> findByType(final DocumentType documentType) { return repositoryService.allMatches( new QueryDefault<>(DocumentTemplate.class, "findByType", "type", documentType)); }
java
@Programmatic public List<DocumentTemplate> findByApplicableToAtPathAndCurrent(final String atPath) { final LocalDate now = clockService.now(); return repositoryService.allMatches( new QueryDefault<>(DocumentTemplate.class, "findByApplicableToAtPathAndCurrent"...
java
@Programmatic public TranslatableString validateApplicationTenancyAndDate( final DocumentType proposedType, final String proposedAtPath, final LocalDate proposedDate, final DocumentTemplate ignore) { final List<DocumentTemplate> existingTemplates = ...
java
public synchronized int numActiveSubTasks() { int c = 0; for (Future<?> f : subTasks) { if (!f.isDone() && !f.isCancelled()) { c++; } } return c; }
java
public synchronized void use() { assert(!inUse); inUse = true; compiler = com.sun.tools.javac.api.JavacTool.create(); fileManager = compiler.getStandardFileManager(null, null, null); fileManagerBase = (BaseFileManager)fileManager; smartFileManager = new SmartFileManager(f...
java
public synchronized void unuse() { assert(inUse); inUse = false; compiler = null; fileManager = null; fileManagerBase = null; smartFileManager = null; context = null; subTasks = null; }
java
private static boolean expect(BufferedReader in, String key) throws IOException { String s = in.readLine(); if (s != null && s.equals(key)) { return true; } return false; }
java
public ParametricStatement set(String sql) throws IllegalArgumentException { if (_env != null) { try { sql = Macro.expand(sql, _env.call()); } catch (Exception x) { throw new IllegalArgumentException(x.getMessage(), x); } } if (_params != null) { int count = 0; int qmark ...
java
public int executeUpdate(Connection conn, DataObject object) throws SQLException { PreparedStatement statement = conn.prepareStatement(_sql); try { load(statement, object); return statement.executeUpdate(); } finally { statement.close(); } }
java
public int executeUpdate(Connection conn, DataObject[] objects) throws SQLException { PreparedStatement statement = conn.prepareStatement(_sql); try { for (DataObject object: objects) { load(statement, object); statement.addBatch(); } i...
java
public long[] executeInsert(Connection conn, DataObject object, boolean generatedKeys) throws SQLException { PreparedStatement statement = conn.prepareStatement(_sql, generatedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); try { load(statement, object); lo...
java
public int executeProcedure(Connection conn, DataObject object) throws SQLException { CallableStatement statement = conn.prepareCall(_sql); try { for (int i = 0; i < _params.length; ++i) { if ((_params[i].direction & Param.OUT) == 0) continue; statement.regist...
java
public void add(T closeable, Future<?> future) { _pairs.add(new Pair<T, Future<?>>(closeable, future)); }
java
public boolean isDone() { int count = 0; for (Pair<T, Future<?>> pair: _pairs) { if (pair.second.isDone()) ++count; } return count == _pairs.size(); }
java
@Override public void close() { // waiting phase int count = 0, last = 0; do { last = count; try { Thread.sleep(500); } catch (Exception x) {} count = 0; for (Pair<T, Future<?>> pair: _pairs) { if (pair.second.isDone()) ++count;...
java
public static Contract load(File idlJson) throws IOException { FileInputStream fis = new FileInputStream(idlJson); Contract c = load(fis); fis.close(); return c; }
java
@SuppressWarnings("unchecked") public static Contract load(InputStream idlJson, Serializer ser) throws IOException { return new Contract(ser.readList(idlJson)); }
java
public Function getFunction(String iface, String func) throws RpcException { Interface i = interfaces.get(iface); if (i == null) { String msg = "Interface '" + iface + "' not found"; throw RpcException.Error.METHOD_NOT_FOUND.exc(msg); } Function f = i.getFunction...
java
private String getName(String s1, String s2) { if (s1 == null || "".equals(s1)) return s2; else return s1; }
java
private void write(String s) throws SAXException { try { out.write(s); out.flush(); } catch (IOException ioException) { throw new SAXParseException("I/O error", documentLocator, ioException); } ...
java
void printSaxException(String message, SAXException e) { System.err.println(); System.err.println("*** SAX Exception -- " + message); System.err.println(" SystemId = \"" + documentLocator.getSystemId() + "\""); e.printStackTrace(System.err); }
java
void printSaxParseException(String message, SAXParseException e) { System.err.println(); System.err.println("*** SAX Parse Exception -- " + message); System.err.println(" SystemId = \"" + e.getSystemId() + "\""); System.err.println(" PublicI...
java
public void call(final T request, final Functor<String, RemoteService.Response> process, final Functor<Void, RemoteService.Response> confirm) { try { String message = process.invoke(RemoteService.call(location, endpoint, true, request)); if (message != null) { // clean fa...
java
public void execute() throws MojoExecutionException, MojoFailureException { if(preverifyPath == null) { getLog().debug("skip native preverification"); return; } getLog().debug("start native preverification"); final File preverifyCmd= getAbsolutePreverify...
java
public static boolean isDisplayable(Class<?> type) { return Enum.class.isAssignableFrom(type) || type == java.net.URL.class || type == java.io.File.class || java.math.BigInteger.class.isAssignableFrom(type) || java.math.BigDecimal.class.isAssignableFrom(type) || j...
java
public static Class<?> classForName(String name) throws ClassNotFoundException { if ("void".equals(name)) return void.class; if ("char".equals(name)) return char.class; if ("boolean".equals(name)) return boolean.class; if ("byte".equals(name)) return byte.class; if ("short".equal...
java
public static Class<?> toPrimitive(Class<?> type) { if (type.isPrimitive()) { return type; } else if (type == Boolean.class) { return Boolean.TYPE; } else if (type == Character.class) { return Character.TYPE; } else if (type == Byte.class) { ...
java
public static Class<?>[] boxPrimitives(Class<?>[] types) { for (int i = 0; i < types.length; ++i) { types[i] = boxPrimitive(types[i]); } return types; }
java
public static Field getKnownField(Class<?> type, String name) throws NoSuchFieldException { NoSuchFieldException last = null; do { try { Field field = type.getDeclaredField(name); field.setAccessible(true); return field; } catch (No...
java
public static <T extends AccessibleObject> T accessible(T object) throws SecurityException { object.setAccessible(true); return object; }
java
@SuppressWarnings("unchecked") public static void setValue(Object object, Field field, Object value) throws IllegalArgumentException, IllegalAccessException { if (value == null) { //if (Number.class.isAssignableFrom(field.getType())) { //value = java.math.BigDecimal.ZERO; ...
java
public static <T> T fill(T destination, Object source) { if (destination != source) { Class<?> stype = source.getClass(); for (Field field: destination.getClass().getFields()) { try { Object value = field.get(destination); if (value...
java
public static <T, V> T update(T object, Class<V> type, String pattern, Bifunctor<V, String, V> updater) { if (type.isPrimitive()) { throw new IllegalArgumentException("Primitive type must be boxed"); } Pattern regex = pattern != null ? Pattern.compile(pattern) : null; for (Fi...
java
public static StringBuilder print(StringBuilder sb, Object bean, int level) throws IntrospectionException { return print(sb, Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()), bean, level); }
java
public static <E> E get(Class<E> type) { ServiceLoader<E> loader = ServiceLoader.load(type); Iterator<E> iterator = loader.iterator(); if (iterator.hasNext()) { return iterator.next(); // only one is expected } try { //loads the default implementation return (E) Class.forName(getDe...
java
@Nonnull public static IMutablePriceGraduation createSimple (@Nonnull final IMutablePrice aPrice) { final PriceGraduation ret = new PriceGraduation (aPrice.getCurrency ()); ret.addItem (new PriceGraduationItem (1, aPrice.getNetAmount ().getValue ())); return ret; }
java
@Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); _dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class); _packaged = _context.getResourcePaths("/WEB-INF/lib/"); _extended = discover(System.getProperty("xillium.servi...
java
public void realize(ApplicationContext wac, ConfigurableApplicationContext child) { if (WebApplicationContextUtils.getWebApplicationContext(_context) == null) { _context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); } else { _logger.warning("Alr...
java
public void destroy() { XmlWebApplicationContext wac = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(_context); if (wac != null) { _context.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } else { _logger.warn...
java
private ApplicationContext install(ApplicationContext wac, ModuleSorter.Sorted sorted, ServiceModuleInfo info) { // scan special modules, configuring and initializing PlatformAware objects as each module is loaded wac = install(wac, sorted.specials(), info, true); // scan regular modules, colle...
java
public <T, F> T doReadOnly(F facility, Task<T, F> task) { return doTransaction(facility, task, _readonly); }
java
public <T, F> T doReadWrite(F facility, Task<T, F> task) { return doTransaction(facility, task, null); }
java
public ParametricStatement getParametricStatement(String name) { ParametricStatement statement = _statements.get(name); if (statement != null) { return statement; } else { throw new RuntimeException("ParametricStatement '" + name + "' not found"); } }
java
public <T> T executeSelect(String name, DataObject object, ResultSetWorker<T> worker) throws Exception { ParametricQuery statement = (ParametricQuery)_statements.get(name); if (statement != null) { return statement.executeSelect(DataSourceUtils.getConnection(_dataSource), object, worker);...
java
public <T extends DataObject> List<T> getResults(String name, DataObject object) throws Exception { @SuppressWarnings("unchecked") ObjectMappedQuery<T> statement = (ObjectMappedQuery<T>)_statements.get(name); if (statement != null) { return statement.getResults(DataSourceUtils.ge...
java
public int compile() throws SQLException { int count = 0; for (Map.Entry<String, ParametricStatement> entry: _statements.entrySet()) { try { ParametricStatement statement = entry.getValue(); Connection connection = DataSourceUtils.getConnection(_dataSourc...
java
public void addPackageDeprecationInfo(Content li, PackageDoc pkg) { Tag[] deprs; if (Util.isDeprecated(pkg)) { deprs = pkg.tags("deprecated"); HtmlTree deprDiv = new HtmlTree(HtmlTag.DIV); deprDiv.addStyle(HtmlStyle.deprecatedContent); Content deprPhrase =...
java
public Content getNavLinkPrevious() { Content li; if (prevProfile == null) { li = HtmlTree.LI(prevprofileLabel); } else { li = HtmlTree.LI(getHyperLink(pathToRoot.resolve(DocPaths.profileSummary( prevProfile.name)), prevprofileLabel, "", "")); ...
java
public Content getNavLinkNext() { Content li; if (nextProfile == null) { li = HtmlTree.LI(nextprofileLabel); } else { li = HtmlTree.LI(getHyperLink(pathToRoot.resolve(DocPaths.profileSummary( nextProfile.name)), nextprofileLabel, "", "")); } ...
java
public ProgramElementDoc owner() { Symbol osym = type.tsym.owner; if ((osym.kind & Kinds.TYP) != 0) { return env.getClassDoc((ClassSymbol)osym); } Names names = osym.name.table.names; if (osym.name == names.init) { return env.getConstructorDoc((MethodSymbo...
java
protected void activate(final ComponentContext context) throws InvalidSyntaxException { log.info("activate"); bundleContext = context.getBundleContext(); sl = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.UNREGISTERING) { cache.unregi...
java
protected void deactivate(ComponentContext context) { log.info("deactivate"); bundleContext = context.getBundleContext(); bundleContext.removeServiceListener(sl); log.info("Deactivate successful"); }
java
protected void reloadCache() { log.info("reloadCache"); cache.clear(); try { ServiceReference[] references = bundleContext .getAllServiceReferences( ComponentBindingsProvider.class.getCanonicalName(), null); if (references != null) { for (ServiceReference reference : references) { ...
java
private boolean htmlSentenceTerminatorFound(String str, int index) { for (int i = 0; i < sentenceTerminators.length; i++) { String terminator = sentenceTerminators[i]; if (str.regionMatches(true, index, terminator, 0, terminator.length())) { ...
java
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) { if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) { return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType(); } return com.sun.tools.javac.code.Type.noType; }
java
private static MimeBodyPart createBodyPart(byte[] data, String type, String filename) throws MessagingException { final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(filename); ByteArrayDataSource source = new ByteArrayDataSource(data, type); attachmentPart...
java
public T getObject(Connection conn, DataObject object) throws Exception { return executeSelect(conn, object, new ResultSetMapper<SingleObjectCollector<T>>(new SingleObjectCollector<T>())).value; }
java
public Collector<T> getResults(Connection conn, DataObject object, Collector<T> collector) throws Exception { return executeSelect(conn, object, new ResultSetMapper<Collector<T>>(collector)); }
java
public static void preRegister(Context context) { context.put(FSInfo.class, new Context.Factory<FSInfo>() { public FSInfo make(Context c) { FSInfo instance = new CacheFSInfo(); c.put(FSInfo.class, instance); return instance; } }); ...
java
public MediaType getContentType() { if (isNull(this.contentType)) { contentType = getHeader(HeaderName.CONTENT_TYPE) .map(MediaType::of) .orElse(WILDCARD); } return contentType; }
java
public List<MediaType> getAccept() { if (isNull(accept)) { List<MediaType> accepts = getHeader(HeaderName.ACCEPT) .map(MediaType::list) .get(); this.accept = nonEmpty(accepts) ? accepts : singletonList(WILDCARD); } return accept; }
java
public int verify(Request request, Response response) { String authValue = request.getHeaders().getValues("Authorization"); log.debug("Auth header value is: "+ authValue); if (authValue == null) { return Verifier.RESULT_MISSING; } String[] tokenValues = authValue.split(" "); if (tokenValues.length < 2) {...
java
public void organizeTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) { annotate.afterRepeated( new Worker() { @Override public void run() { JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile); try { ...
java
public static Class<?> classForNameWithException(final String name, final ClassLoader cl) throws ClassNotFoundException { if (cl != null) { try { return Class.forName(name, false, cl); } catch (final ClassNotFoundException | NoClassDefFoundError e) { ...
java
public static ClassLoader getContextClassLoader() { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClass...
java
@Override public void sendMessage(String subject, String message) { first.sendMessage(subject, message); second.sendMessage(subject, message); }
java
private short getCellType(String value) { short ret = STRING_TYPE; if(value.equals("number")) ret = NUMBER_TYPE; else if(value.equals("datetime")) ret = DATETIME_TYPE; else if(value.equals("boolean")) ret = BOOLEAN_TYPE; return ret; }
java
private short getDataType(String value) { short ret = STRING_TYPE; if(value.equals("number")) ret = NUMBER_TYPE; else if(value.equals("integer")) ret = INTEGER_TYPE; else if(value.equals("decimal")) ret = DECIMAL_TYPE; else if(value.equals...
java
private short getAlignment(String value) { short ret = ALIGN_LEFT; if(value.equals("centre")) ret = ALIGN_CENTRE; else if(value.equals("left")) ret = ALIGN_LEFT; else if(value.equals("right")) ret = ALIGN_RIGHT; else if(value.equals("justi...
java
public WritableCellFormat getCellFormat(boolean create) { WritableCellFormat ret = null; if(cellFormat != null) ret = cellFormat; else if(create) ret = new WritableCellFormat(NumberFormats.TEXT); return ret; }
java
private String convert(String str, String dateFormat) { String ret = str; // Carry out the required string conversion long longValue = 0L; double doubleValue = 0.0d; // Convert the input value to a number if(str.length() > 0) { if(inputType == IN...
java
private long parseDateTime(String str, String format) { return FormatUtilities.getDateTime(str, format, false, true); }
java
private String convertDateTime(long dt, String format) { if(format.length() == 0) format = Formats.DATETIME_FORMAT; return FormatUtilities.getFormattedDateTime(dt, format, false, 0L); }
java
private String convertDecimal(double d, String format) { String ret = ""; if(format.length() > 0) { DecimalFormat f = new DecimalFormat(format); ret = f.format(d); } else { ret = Double.toString(d); } return ret; ...
java
private String convertString(String str, String format, String expr) { String ret = str; String[] params = null; if(format.length() > 0) { ret = ""; if(expr.length() > 0) // Indicates a format using regex { Pattern pattern = getPa...
java
private Pattern getPattern(String expr) { Pattern pattern = patterns.get(expr); if(pattern == null) { pattern = Pattern.compile(expr); patterns.put(expr, pattern); } return pattern; }
java
public LanguageVersion languageVersion() { try { Object retVal; String methodName = "languageVersion"; Class<?>[] paramTypes = new Class<?>[0]; Object[] params = new Object[0]; try { retVal = invoke(methodName, JAVA_1_1, paramTypes, par...
java
private Object invoke(String methodName, Object returnValueIfNonExistent, Class<?>[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchM...
java
public synchronized List<ZipFileIndex> getZipFileIndexes(boolean openedOnly) { List<ZipFileIndex> zipFileIndexes = new ArrayList<ZipFileIndex>(); zipFileIndexes.addAll(map.values()); if (openedOnly) { for(ZipFileIndex elem : zipFileIndexes) { if (!elem.isOpen()) { ...
java
public synchronized void setOpenedIndexes(List<ZipFileIndex>indexes) throws IllegalStateException { if (map.isEmpty()) { String msg = "Setting opened indexes should be called only when the ZipFileCache is empty. " + "Call JavacFileManager.flush() before callin...
java
public void close() throws IOException, QdbException { this.compoundRegistry.close(); this.propertyRegistry.close(); this.descriptorRegistry.close(); this.modelRegistry.close(); this.predictionRegistry.close(); try { this.storage.close(); } finally { this.storage = null; } try { if(this.tem...
java
public static ExceptionThrower instance(Class<? extends RuntimeException> classType) { iae.throwIfNull(classType, "The parameter of exception type can not be null."); if (classType.equals(IllegalArgumentException.class)) { return iae; } else { iae.throwIfTrue(true, "Not ...
java