code
stringlengths
73
34.1k
label
stringclasses
1 value
protected static void appendNameAndParameters(StringBuilder sb, String name, List<Expression> parameters) { sb.append(name); sb.append("("); boolean first = true; for (Expression expr : parameters) { if (!first) { sb.append(", "); } fir...
java
public Expression getExpectedParam(int index) { if (parameters.size() <= index) { throw new IllegalArgumentException("Parameter index out of bounds: " + index + ". Function call: " + this); } return parameters.get(index); }
java
public Expression get(String name) { if (variables.containsKey(name)) { return variables.get(name); } if (parent == null) { return new Value(""); } return parent.get(name); }
java
public DuplicationReport monitorDuplication() { log.info("starting duplication monitor"); DuplicationReport report = new DuplicationReport(); for (String host : dupHosts.keySet()) { DuplicationInfo info = new DuplicationInfo(host); try { // Connect to sto...
java
public static int calculateThreads(final int executorThreads, final String name) { // For current standard 8 core machines this is 10 regardless. // On Java 10, you might get less than 8 core reported, but it will still size as if it's 8 // Beyond 8 core you MIGHT undersize if running on Docker,...
java
@SafeVarargs public final synchronized JaxRsClientFactory addFeatureToAllClients(Class<? extends Feature>... features) { return addFeatureToGroup(PrivateFeatureGroup.WILDCARD, features); }
java
public <T> T createClientProxy(Class<T> proxyClass, WebTarget baseTarget) { return factory(ctx).createClientProxy(proxyClass, baseTarget); }
java
public static boolean seemsToHaveSignature(Nanopub nanopub) { for (Statement st : nanopub.getPubinfo()) { if (st.getPredicate().equals(NanopubSignatureElement.HAS_SIGNATURE_ELEMENT)) return true; if (st.getPredicate().equals(NanopubSignatureElement.HAS_SIGNATURE_TARGET)) return true; if (st.getPredicate().eq...
java
private void workflowCuration(JsonSimple response, JsonSimple message) { String oid = message.getString(null, "oid"); if (!workflowCompleted(oid)) { return; } // Resolve relationships before we continue try { JSONArray relations = mapRelations(oid); // Unless there was an error, we should be good to...
java
private JSONArray mapRelations(String oid) { // We want our parsed data for reading JsonSimple formData = parsedFormData(oid); if (formData == null) { log.error("Error parsing form data"); return null; } // And raw data to see existing relations and write new ones JsonSimple rawData = getDataFromStor...
java
private boolean isKnownRelation(JSONArray relations, JsonObject newRelation) { // Does it have an OID? Highest priority. Avoids infinite loops // between ReDBox collections pointing at each other, so strict if (newRelation.containsKey("oid")) { for (Object relation : relations) { JsonObject json = (JsonObj...
java
private JsonSimple publish(JsonSimple message, String oid) throws TransactionException { log.debug("Publishing '{}'", oid); JsonSimple response = new JsonSimple(); try { DigitalObject object = storage.getObject(oid); Properties metadata = object.getMetadata(); // Already published? if (!metadata.co...
java
private void publishRelations(JsonSimple response, String oid) throws TransactionException { log.debug("Publishing Children of '{}'", oid); JsonSimple data = getDataFromStorage(oid); if (data == null) { log.error("Error accessing item data! '{}'", oid); emailObjectLink(response, oid, "An error occured...
java
private void reharvest(JsonSimple response, JsonSimple message) { String oid = message.getString(null, "oid"); try { if (oid != null) { setRenderFlag(oid); // Transformer config JsonSimple itemConfig = getConfigFromStorage(oid); if (itemConfig == null) { log.error("Error accessing item con...
java
private void emailObjectLink(JsonSimple response, String oid, String message) { String link = urlBase + "default/detail/" + oid; String text = "This is an automated message from the "; text += "ReDBox Curation Manager.\n\n" + message; text += "\n\nYou can find this object here:\n" + link; email(response, oid,...
java
private void email(JsonSimple response, String oid, String text) { JsonObject object = newMessage(response, EmailNotificationConsumer.LISTENER_ID); JsonObject message = (JsonObject) object.get("message"); message.put("to", emailAddress); message.put("body", text); message.put("oid", oid); }
java
private void audit(JsonSimple response, String oid, String message) { JsonObject order = newSubscription(response, oid); JsonObject messageObject = (JsonObject) order.get("message"); messageObject.put("eventType", message); }
java
private void scheduleTransformers(JsonSimple message, JsonSimple response) { String oid = message.getString(null, "oid"); List<String> list = message.getStringList("transformer", "metadata"); if (list != null && !list.isEmpty()) { for (String id : list) { JsonObject order = newTransform(response, id, oid);...
java
private void setRenderFlag(String oid) { try { DigitalObject object = storage.getObject(oid); Properties props = object.getMetadata(); props.setProperty("render-pending", "true"); storeProperties(object, props); } catch (StorageException ex) { log.error("Error accessing storage for '{}'", oid, ex); ...
java
private JsonObject createTask(JsonSimple response, String oid, String task) { return createTask(response, null, oid, task); }
java
private JsonObject createTask(JsonSimple response, String broker, String oid, String task) { JsonObject object = newMessage(response, TransactionManagerQueueConsumer.LISTENER_ID); if (broker != null) { object.put("broker", broker); } JsonObject message = (JsonObject) object.get("message"); message.p...
java
private JsonObject newIndex(JsonSimple response, String oid) { JsonObject order = createNewOrder(response, TransactionManagerQueueConsumer.OrderType.INDEXER.toString()); order.put("oid", oid); return order; }
java
private JsonSimple getConfigFromStorage(String oid) { String configOid = null; String configPid = null; // Get our object and look for its config info try { DigitalObject object = storage.getObject(oid); Properties metadata = object.getMetadata(); configOid = metadata.getProperty("jsonConfigOid"); ...
java
private JsonSimple parsedFormData(String oid) { // Get our data from Storage Payload payload = null; try { DigitalObject object = storage.getObject(oid); payload = getDataPayload(object); } catch (StorageException ex) { log.error("Error accessing object '{}' in storage: ", oid, ex); return null; }...
java
private Properties getObjectMetadata(String oid) { try { DigitalObject object = storage.getObject(oid); return object.getMetadata(); } catch (StorageException ex) { log.error("Error accessing object '{}' in storage: ", oid, ex); return null; } }
java
private void saveObjectData(JsonSimple data, String oid) throws TransactionException { // Get from storage DigitalObject object = null; try { object = storage.getObject(oid); getDataPayload(object); } catch (StorageException ex) { log.error("Error accessing object '{}' in storage: ", oid, ex); th...
java
public static JsonSimple parse(String input) throws IOException { ByteArrayInputStream bytes = new ByteArrayInputStream( input.getBytes("UTF-8")); return parse(bytes); }
java
public static JsonSimple parse(InputStream input) throws IOException { JsonSimple inputData = new JsonSimple(input); JsonSimple responseData = new JsonSimple(); // Go through every top level node JsonObject object = inputData.getJsonObject(); for (Object key : object.keySet()) {...
java
private static String validString(Object data) throws IOException { // Null is ok if (data == null) { return ""; } if (!(data instanceof String)) { throw new IOException("Invalid non-String value found!"); } return (String) data; }
java
private static void parseField(JsonSimple response, String field, String data) throws IOException { // Break it into pieces String [] fieldParts = field.split("\\."); // These are used as replacable pointers // to the last object used on the path JsonObject lastObjec...
java
private static JSONArray getArray(JsonObject object, String key) throws IOException { // Get the existing one if (object.containsKey(key)) { Object existing = object.get(key); if (!(existing instanceof JSONArray)) { throw new IOException("Invalid field...
java
private static JsonObject getObject(JsonObject object, String key) throws IOException { // Get the existing one if (object.containsKey(key)) { Object existing = object.get(key); if (!(existing instanceof JsonObject)) { throw new IOException("Invalid fi...
java
private static int parseInt(String integer) throws IOException { try { int value = Integer.parseInt(integer); if (value < 0) { throw new IOException("Invalid number in field name: '" + integer + "'"); } return value; ...
java
@Override public void init(String jsonString) throws TransformerException { try { setConfig(new JsonSimpleConfig(jsonString)); } catch (IOException e) { throw new TransformerException(e); } }
java
private DigitalObject process(DigitalObject in, String jsonConfig) throws TransformerException { String oid = in.getId(); // Workflow payload JsonSimple workflow = null; try { Payload workflowPayload = in.getPayload("workflow.metadata"); workflow = ne...
java
private DigitalObject processObject(DigitalObject object, JsonSimple workflow, Properties metadata) throws TransformerException { String oid = object.getId(); String title = workflow.getString(null, Strings.NODE_FORMDATA, "title"); FedoraClient fedora = null; try...
java
private String createNewObject(FedoraClient fedora, String oid) throws Exception { InputStream in = null; byte[] template = null; // Start by reading our FOXML template into memory try { if (foxmlTemplate != null) { // We have a user provided templ...
java
private void processDatastreams(FedoraClient fedora, DigitalObject object, String vitalPid) throws Exception { int sent = 0; // Each payload we care about needs to be sent for (String ourPid : pids.keySet()) { // Fascinator packages have unpredictable names, ...
java
private String getPackagePid(DigitalObject object) throws Exception { for (String pid : object.getPayloadIdList()) { if (pid.endsWith(".tfpackage")) { return pid; } } return null; }
java
private String[] resolveAltIds(String[] oldArray, String mimeType, int count) { // First, find the valid list we want String key = null; for (String mimeTest : attachAltIds.keySet()) { // Ignore 'default' if (mimeTest.equals(Strings.LITERAL_DEFAULT)) { ...
java
private String[] growArray(String[] oldArray, String newElement) { // Look for the element first for (String element : oldArray) { if (element.equals(newElement)) { // If it's already there, we're done return oldArray; } } log.debug...
java
private boolean datastreamExists(FedoraClient fedora, String vitalPid, String dsPid) { try { // Some options: // * getAPIA().listDatastreams... seems best // * getAPIM().getDatastream... causes Exceptions against new IDs // * getAPIM().getDatastreams.....
java
private String[] getAltIds(FedoraClient fedora, String vitalPid, String dsPid) { Datastream ds = getDatastream(fedora, vitalPid, dsPid); if (ds != null) { return ds.getAltIDs(); } return new String[]{}; }
java
private String fedoraLogEntry(DigitalObject object, String pid) { String message = fedoraMessageTemplate.replace("[[PID]]", pid); return message.replace("[[OID]]", object.getId()); }
java
private File getTempFile(DigitalObject object, String pid) throws Exception { // Create file in temp space, use OID in path for uniqueness File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.get...
java
private byte[] getBytes(DigitalObject object, String pid) throws Exception { // These can happily throw exceptions higher Payload payload = object.getPayload(pid); InputStream in = payload.open(); byte[] result = null; // But here, the payload must receive // a close bef...
java
public static HashMap<String, String> find(HashMap<String, String> props, String path) { // Kein Pfad angegeben. Also treffen alle. if (path == null || path.length() == 0) return props; // Die neue Map fuer die naechste Runde HashMap<String, String> next = new HashMap<>(); ...
java
public boolean run() { boolean passed; ExecutionToken t = createExecutionToken(); List<FeatureToken> features = getFeatureList(t); startTests(t, features); initializeInterpreter(); processFeatures(t, features); endTests(t, features); passed = t.getEndState...
java
public String getSuiteName() { return configReader.isSet(ChorusConfigProperty.SUITE_NAME) ? concatenateName(configReader.getValues(ChorusConfigProperty.SUITE_NAME)) : ""; }
java
private BigDecimal checkDebit(BigDecimal d, CreditDebitCode code) { if (d == null || code == null || code == CreditDebitCode.CRDT) return d; return BigDecimal.ZERO.subtract(d); }
java
@SuppressWarnings({"unchecked", "unused"}) public <T> T get(String key, Class<T> type) { try { return (T) state.get(key); } catch (ClassCastException cce) { return null; } }
java
protected String getResourceSuffix(String target) { int index = target.lastIndexOf('/'); if ( index > -1 ) { target = target.substring(index + 1); } return target; }
java
protected String trim(String s) { if (s == null || s.length() == 0) return s; return s.trim(); }
java
protected List<String> trim(List<String> list) { if (list == null || list.size() == 0) return list; List<String> result = new ArrayList<String>(); for (String s : list) { s = trim(s); if (s == null || s.length() == 0) continue; r...
java
public synchronized void startProcess(String configName, String processName, Properties processProperties) throws Exception { ProcessManagerConfig runtimeConfig = getProcessManagerConfig(configName, processProperties); if ( runtimeConfig.isEnabled()) { //could be disabled in some profiles ...
java
private void incrementPortsIfDuplicateName(String configName, ProcessConfigBean config) { int startedCount = getNumberOfInstancesStarted(configName); int debugPort = config.getDebugPort(); if ( debugPort != -1) { config.setDebugPort(debugPort + startedCount); } int ...
java
public StepEndState runSteps(ExecutionToken executionToken, StepInvokerProvider stepInvokerProvider, List<StepToken> stepList, StepCatalogue stepCatalogue, boolean skip) { for (StepToken step : stepList) { StepEndState endState = processStep(executionToken, stepInvokerProvider, step, stepCatalogue,...
java
private void sortInvokersByPattern(List<StepInvoker> stepInvokers) { Collections.sort(stepInvokers, new Comparator<StepInvoker>() { public int compare(StepInvoker o1, StepInvoker o2) { return o1.getStepPattern().toString().compareTo(o2.getStepPattern().toString()); } ...
java
public Map<String, Map<String, Set<String>>> getTargetLanguagesMap() { if (targetLanguagesMap == null) { assert false; return Collections.emptyMap(); } return Collections.unmodifiableMap(targetLanguagesMap); }
java
public String getSsf(Integer id) { if (id < 1 || id > 25) throw new IllegalStateException("Site specific factor must be between 1 and 25."); return getInput(INPUT_SSF_PREFIX + id); }
java
public void setSsf(Integer id, String ssf) { if (id < 1 || id > 25) throw new IllegalStateException("Site specific factor must be between 1 and 25."); setInput(INPUT_SSF_PREFIX + id, ssf); }
java
private void addStepInvoker(StepInvoker stepInvoker) { if ( connected.get() ) { throw new ChorusException("You cannot add more steps once the WebSocketStepPublisher is connected"); } stepInvokers.put(stepInvoker.getId(), stepInvoker); }
java
public WebSocketStepPublisher publish() { if (connected.getAndSet(true) == false) { try { log.info("Connecting"); boolean connected = chorusWebSocketClient.connectBlocking(); if ( ! connected) { throw new StepPublisherException("F...
java
static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) return; if (!(Math.abs(expected - actual) <= delta)) failNotEquals(message, new Float(expected), new Float(actual)); }
java
static public void assertEquals(String message, char expected, char actual) { assertEquals(message, new Character(expected), new Character(actual)); }
java
static public void assertEquals(String message, short expected, short actual) { assertEquals(message, new Short(expected), new Short(actual)); }
java
private Optional<Pattern> getDefaultValidationPattern(Class javaType) { return javaType.isEnum() ? Optional.of(createValidationPatternFromEnumType(javaType)) : getDefaultPatternIfPrimitive(javaType); }
java
private boolean containsOnly(String s, char c) { for (char c2 : s.toCharArray()) { if (c != c2) return false; } return true; }
java
protected final PainGeneratorIf getPainGenerator() { if (this.generator == null) { try { this.generator = PainGeneratorFactory.get(this, this.getPainVersion()); } catch (Exception e) { String msg = HBCIUtils.getLocMsg("EXCMSG_JOB_CREATE_ERR", this.getPainJ...
java
public int enumerateSegs(int startValue, boolean allowOverwrite) { int idx = startValue; for (MultipleSyntaxElements s : getChildContainers()) { if (s != null) idx = s.enumerateSegs(idx, allowOverwrite); } return idx; }
java
public void extractValues(HashMap<String, String> values) { for (MultipleSyntaxElements l : childContainers) { l.extractValues(values); } }
java
public void validate() { if (!needsRequestTag || haveRequestTag) { for (MultipleSyntaxElements l : childContainers) { l.validate(); } /* wenn keine exception geworfen wurde, dann ist das aktuelle element offensichtlich valid */ setV...
java
public Object invokeStep(String remoteStepInvokerId, String stepTokenId, List<String> params) throws Exception { try { //call the remote method Object[] args = {remoteStepInvokerId, stepTokenId, ChorusContext.getContext().getSnapshot(), params}; String[] signature = {"java.la...
java
public void processStartOfScope(Scope scopeStarting, Iterable<Object> handlerInstances) throws Exception { for (Object handler : handlerInstances) { Handler handlerAnnotation = handler.getClass().getAnnotation(Handler.class); Scope handlerScope = handlerAnnotation.scope(); i...
java
public void processEndOfScope(Scope scopeEnding, Iterable<Object> handlerInstances) throws Exception { for (Object handler : handlerInstances) { Handler handlerAnnotation = handler.getClass().getAnnotation(Handler.class); Scope scope = handlerAnnotation.scope(); runLifecycle...
java
private Scope getMethodScope(boolean isDestroy, Method method) { Scope methodScope; if ( isDestroy ) { Destroy annotation = method.getAnnotation(Destroy.class); methodScope = annotation != null ? annotation.scope() : null; } else { Initialize annotation = meth...
java
private void injectResourceFields(Object handler, Iterable<Object> handlerInstances, Scope... scopes) { Class<?> featureClass = handler.getClass(); List<Field> allFields = new ArrayList<>(); addAllPublicFields(featureClass, allFields); log.trace("Now examining handler fields for ChorusR...
java
public static SepaVersion byURN(String urn) { SepaVersion test = new SepaVersion(null, 0, urn, null, false); if (urn == null || urn.length() == 0) return test; for (List<SepaVersion> types : knownVersions.values()) { for (SepaVersion v : types) { if (v.e...
java
private static Type findType(String type, String value) throws IllegalArgumentException { if (type == null || type.length() == 0) throw new IllegalArgumentException("no SEPA type type given"); if (value == null || value.length() == 0) throw new IllegalArgumentException("no SEPA ...
java
public static SepaVersion autodetect(InputStream xml) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setValidating(false); factory.setNamespaceAware(true); DocumentBuilder buil...
java
public String getGeneratorClass(String jobName) { StringBuilder sb = new StringBuilder(); sb.append(PainGeneratorIf.class.getPackage().getName()); sb.append(".Gen"); sb.append(jobName); sb.append(this.type.getValue()); sb.append(new DecimalFormat(DF_MAJOR).format(this.maj...
java
public String getParserClass() { StringBuilder sb = new StringBuilder(); sb.append(ISEPAParser.class.getPackage().getName()); sb.append(".Parse"); sb.append(this.type.getType()); sb.append(this.type.getValue()); sb.append(new DecimalFormat(DF_MAJOR).format(this.major)); ...
java
public boolean canGenerate(String jobName) { try { Class.forName(this.getGeneratorClass(jobName)); return true; } catch (ClassNotFoundException e) { return false; } }
java
void runWithinPeriod(Runnable runnable, ExecuteStepMessage executeStepMessage, int timeout, TimeUnit unit) { if ( ! isRunningAStep.getAndSet(true)) { this.currentlyExecutingStep = executeStepMessage; Future<String> future = null; try { future = scheduledExecut...
java
private Runnable runStepAndResetIsRunning(Runnable runnable) { return () -> { try { runnable.run(); } catch (Throwable t) { //we're in control of the runnable and it should catch it's own execeptions, but just in case it doesn't log.error("...
java
private static StackTraceElement findStackTraceElement(Throwable t) { StackTraceElement element = t.getStackTrace().length > 0 ? t.getStackTrace()[0] : null; int index = 0; String chorusAssertClassName = ChorusAssert.class.getName(); String junitAssertClassName = "org.junit.Assert"; //jun...
java
public ChorusInterpreter buildAndConfigure(ConfigProperties config, SubsystemManager subsystemManager) { ChorusInterpreter chorusInterpreter = new ChorusInterpreter(listenerSupport); chorusInterpreter.setHandlerClassBasePackages(config.getValues(ChorusConfigProperty.HANDLER_PACKAGES)); chorusInt...
java
public static <T> T coerceType(ChorusLog log, String value, Class<T> requiredType) { T result = null; try { if ( "null".equals(value)) { result = null; } else if (isStringType(requiredType)) { result = (T) value; } else if (isStringBuf...
java
private static <T> T coerceObject(String value) { T result; //try boolean first if ("true".equals(value) || "false".equals(value)) { result = (T) (Boolean) Boolean.parseBoolean(value); } //then float numbers else if (floatPattern.matcher(value).matches()) { ...
java
private PropertyOperations mergeConfigurationAndProfileProperties(PropertyOperations props) { PropertyOperations result; result = mergeConfigurationProperties(props); result = mergeProfileProperties(result); return result; }
java
private PropertyOperations addPropertiesFromDatabase(PropertyOperations sourceProperties) { PropertyOperations dbPropsOnly = sourceProperties.filterByKeyPrefix(ChorusConstants.DATABASE_CONFIGS_PROPERTY_GROUP + ".") .removeKeyPrefix(ChorusConstants.DATABAS...
java
public boolean isFatal() { if (this.fatal) // dann brauchen wir den Cause nicht mehr checken return true; Throwable t = this.getCause(); if (t == this) return false; // sind wir selbst if (t instanceof HBCI_Exception) return ((HBCI_Exception) t).isFat...
java
public void setInput(String key, String value) { if (getAllowedKeys() != null && !getAllowedKeys().contains(key)) throw new IllegalStateException("The input key " + key + " is not allowed for lookups"); _inputs.put(key, value); }
java
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) { Statement stmt = createStatement(configName, connection); try { log.debug("Executing statement [" + description + "]"); List<String> stmtsToExecute =...
java
public final void stop() { if (this.thread != null) { try { if (this.thread != null) { this.thread.interrupt(); synchronized (this.thread) { this.thread.notifyAll(); } } } ...
java
public static String getNameForBLZ(String blz) { BankInfo info = getBankInfo(blz); if (info == null) return ""; return info.getName() != null ? info.getName() : ""; }
java
public static List<BankInfo> searchBankInfo(String query) { if (query != null) query = query.trim(); List<BankInfo> list = new LinkedList<BankInfo>(); if (query == null || query.length() < 3) return list; query = query.toLowerCase(); for (BankInfo info ...
java
public static String getIBANForKonto(Konto k) { String konto = k.number; // Die Unterkonto-Nummer muss mit eingerechnet werden. // Aber nur, wenn sie numerisch ist. Bei irgendeiner Bank wurde // "EUR" als Unterkontonummer verwendet. Das geht natuerlich nicht, // weil damit nicht...
java
public static String exception2StringShort(Exception e) { StringBuffer st = new StringBuffer(); Throwable e2 = e; while (e2 != null) { String exClass = e2.getClass().getName(); String msg = e2.getMessage(); if (msg != null) { st.setLength(0);...
java
public static String data2hex(byte[] data) { StringBuffer ret = new StringBuffer(); for (int i = 0; i < data.length; i++) { String st = Integer.toHexString(data[i]); if (st.length() == 1) { st = '0' + st; } st = st.substring(st.length() - ...
java