code
stringlengths
73
34.1k
label
stringclasses
1 value
static boolean isCOctetStringValid(String value, int maxLength) { if (value == null) return true; if (value.length() >= maxLength) return false; return true; }
java
static boolean isCOctetStringNullOrNValValid(String value, int length) { if (value == null) { return true; } if (value.length() == 0) { return true; } if (value.length() == length - 1) { return true; } ...
java
static boolean isOctetStringValid(String value, int maxLength) { if (value == null) return true; if (value.length() > maxLength) return false; return true; }
java
public String format(Calendar calendar, Calendar smscCalendar) { if (calendar == null || smscCalendar == null) { return null; } long diffTimeInMillis = calendar.getTimeInMillis() - smscCalendar.getTimeInMillis(); if (diffTimeInMillis < 0) { throw new IllegalArgumentException("The requested ...
java
public int append(byte[] b, int offset, int length) { int oldLength = bytesLength; bytesLength += length; int newCapacity = capacityPolicy.ensureCapacity(bytesLength, bytes.length); if (newCapacity > bytes.length) { byte[] newB = new byte[newCapacity]; System.arra...
java
public int appendAll(OptionalParameter[] optionalParameters) { int length = 0; for (OptionalParameter optionalParamameter : optionalParameters) { length += append(optionalParamameter); } return length; }
java
public void setSourceArchiveUrls(List<String> sourceArchiveUrls) { if (sourceArchiveUrls == null) throw new IllegalArgumentException(); this.sourceArchiveUrls = new ArrayList<String>(sourceArchiveUrls); }
java
public void setCompilerOptionsProviders(List<CompilerOptionsProvider> compilerOptionsProviders) { if (compilerOptionsProviders == null) throw new NullPointerException(); this.compilerOptionsProviders = new ArrayList<CompilerOptionsProvider>(compilerOptionsProviders); }
java
private void doHousekeeping() { logger.info("started"); while (!shutdown) { try { List<EarlyResponse> removedEarlyResponses = new ArrayList<>(); synchronized (responseMap) { Iterator<List<EarlyResponse>> responseMapIterator = response...
java
public void asynchLog(final AuditTrailEvent e, final AuditTrailCallback cb) { CommandCallback<BatchInsertIntoAutoTrail.Command> callback = new CommandCallback<BatchInsertIntoAutoTrail.Command>() { @Override public void commandCompleted() { cb.done(); } ...
java
public static void closeConnection(Connection con) { if (con != null) { try { con.close(); } catch (SQLException ex) { logger.debug("Could not close JDBC Connection", ex); } catch (Throwable ex) { logger.debug("Unexpected...
java
public synchronized void release(int count) { used -= count; if (used < 0) used = 0; // no negative number of ticket! if (logger.isDebugEnabled()) logger.debug("Released " + count + " tickets! (Now " + this.toString() + ")"); notifyAll(); }
java
public String obtainAndReturnTicketPoolId(Workflow<?> wf) { TicketPool tp = findPool(wf.getClass().getName()); tp.obtain(); return tp.getId(); }
java
protected String classnameReplacement(String classname) { if (classname.startsWith(COPPER_2X_PACKAGE_PREFIX)) { String className3x = classname.replace(COPPER_2X_PACKAGE_PREFIX, COPPER_3_PACKAGE_PREFIX); if ((COPPER_3_PACKAGE_PREFIX + COPPER_2X_INTERRUPT_NAME).equals(className3x)) { ...
java
public void addCurrentEntity(Object entity) { Object identifier = identifier(entity); Object o = memento.get(identifier); if (o == null) { inserted.add(entity); } else { potentiallyChanged.put(identifier, entity); } }
java
public void putResponse(Response<?> r) { synchronized (responseMap) { List<Response<?>> l = responseMap.get(r.getCorrelationId()); if (l == null) { l = new SortedResponseList(); responseMap.put(r.getCorrelationId(), l); } l.a...
java
protected final void resubmit() throws Interrupt { final String cid = engine.createUUID(); engine.registerCallbacks(this, WaitMode.ALL, 0, cid); Acknowledge ack = createCheckpointAcknowledge(); engine.notify(new Response<Object>(cid, null, null), ack); registerCheckpointAckn...
java
@Override public int countWorkflowInstances(WorkflowInstanceFilter filter) throws Exception { final StringBuilder query = new StringBuilder(); final List<Object> values = new ArrayList<>(); query.append("SELECT COUNT(*) AS COUNT_NUMBER FROM COP_WORKFLOW_INSTANCE"); appendQueryBase(qu...
java
private String getAuthHash(WebContext ctx) { Value authorizationHeaderValue = ctx.getHeaderValue(HttpHeaderNames.AUTHORIZATION); if (!authorizationHeaderValue.isFilled()) { return ctx.get("Signature").asString(ctx.get("X-Amz-Signature").asString()); } String authentication = ...
java
private void signalObjectError(WebContext ctx, HttpResponseStatus status, String message) { if (ctx.getRequest().method() == HEAD) { ctx.respondWith().status(status); } else { ctx.respondWith().error(status, message); } log.log(ctx.getRequest().method().name(), ...
java
private void signalObjectSuccess(WebContext ctx) { log.log(ctx.getRequest().method().name(), ctx.getRequestedURI(), APILog.Result.OK, CallContext.getCurrent().getWatch()); }
java
private void listBuckets(WebContext ctx) { HttpMethod method = ctx.getRequest().method(); if (GET == method) { List<Bucket> buckets = storage.getBuckets(); Response response = ctx.respondWith(); response.setHeader(HTTP_HEADER_NAME_CONTENT_TYPE, CONTENT_TYPE_XML); ...
java
private void readObject(WebContext ctx, String bucketName, String objectId) throws IOException { Bucket bucket = storage.getBucket(bucketName); String id = objectId.replace('/', '_'); String uploadId = ctx.get("uploadId").asString(); if (!checkObjectRequest(ctx, bucket, id)) { ...
java
public boolean supports(final WebContext ctx) { return AWS_AUTH4_PATTERN.matcher(ctx.getHeaderValue("Authorization").asString("")).matches() || X_AMZ_CREDENTIAL_PATTERN.matcher(ctx.get("X-Amz-Credential").asString("")).matches(); }
java
public String getBasePath() { StringBuilder sb = new StringBuilder(getBaseDirUnchecked().getAbsolutePath()); if (!getBaseDirUnchecked().exists()) { sb.append(" (non-existent!)"); } else if (!getBaseDirUnchecked().isDirectory()) { sb.append(" (no directory!)"); } e...
java
public List<Bucket> getBuckets() { List<Bucket> result = Lists.newArrayList(); for (File file : getBaseDir().listFiles()) { if (file.isDirectory()) { result.add(new Bucket(file)); } } return result; }
java
public Bucket getBucket(String bucket) { if (bucket.contains("..") || bucket.contains("/") || bucket.contains("\\")) { throw Exceptions.createHandled() .withSystemErrorMessage( "Invalid bucket name: %s. A bucket name must not contain '....
java
public void delete() { if (!file.delete()) { Storage.LOG.WARN("Failed to delete data file for object %s (%s).", getName(), file.getAbsolutePath()); } if (!getPropertiesFile().delete()) { Storage.LOG.WARN("Failed to delete properties file for object %s (%s).", ...
java
public void storeProperties(Map<String, String> properties) throws IOException { Properties props = new Properties(); properties.forEach(props::setProperty); try (FileOutputStream out = new FileOutputStream(getPropertiesFile())) { props.store(out, ""); } }
java
public boolean delete() { boolean deleted = false; for (File child : file.listFiles()) { deleted = child.delete() || deleted; } deleted = file.delete() || deleted; return deleted; }
java
public void makePrivate() { if (getPublicMarkerFile().exists()) { if (getPublicMarkerFile().delete()) { publicAccessCache.put(getName(), false); } else { Storage.LOG.WARN("Failed to delete public marker for bucket %s - it remains public!", getName()); ...
java
public void makePublic() { if (!getPublicMarkerFile().exists()) { try { new FileOutputStream(getPublicMarkerFile()).close(); } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } publicAccessCache.put(getName(),...
java
public StoredObject getObject(String id) { if (id.contains("..") || id.contains("/") || id.contains("\\")) { throw Exceptions.createHandled() .withSystemErrorMessage( "Invalid object name: %s. A object name must not contain '..' '/' or ...
java
@Override public void start() { if(layout == null) { initializationFailed = true; addError("Invalid configuration - No layout for appender: " + name); return; } if(streamName == null) { initializationFailed = true; addError("Invalid configuration - streamName cannot be null ...
java
@Override public void stop() { threadPoolExecutor.shutdown(); BlockingQueue<Runnable> taskQueue = threadPoolExecutor.getQueue(); int bufferSizeBeforeShutdown = threadPoolExecutor.getQueue().size(); boolean gracefulShutdown = true; try { gracefulShutdown = threadPoolExecutor.awaitTermination(...
java
private Region findRegion() { boolean regionProvided = !Validator.isBlank(this.region); if(!regionProvided) { // Determine region from where application is running, or fall back to default region Region currentRegion = Regions.getCurrentRegion(); if(currentRegion != null) { return curr...
java
public void setStreamName(String streamName) { Validator.validate(!Validator.isBlank(streamName), "streamName cannot be blank"); this.streamName = streamName.trim(); }
java
public void setEncoding(String charset) { Validator.validate(!Validator.isBlank(charset), "encoding cannot be blank"); this.encoding = charset.trim(); }
java
@SuppressWarnings("unchecked") public <T> T getProperty(String key, Class<T> cls) { if (properties != null) { if (cls != null && cls != Object.class && cls != String.class && !cls.isInterface() && !cls.isArray()) { // engine.getProperty("loaders", ClasspathLoa...
java
public Map<String, Object> createContext(final Map<String, Object> parent, Map<String, Object> current) { return new DelegateMap<String, Object>(parent, current) { private static final long serialVersionUID = 1L; @Override public Object get(Object key) { Obje...
java
public Template parseTemplate(String source, Object parameterTypes) throws ParseException { String name = "/$" + Digest.getMD5(source); if (!hasResource(name)) { stringLoader.add(name, source); } try { return getTemplate(name, parameterTypes); } catch (IOE...
java
public Resource getResource(String name, Locale locale, String encoding) throws IOException { name = UrlUtils.cleanName(name); locale = cleanLocale(locale); return loadResource(name, locale, encoding); }
java
public boolean hasResource(String name, Locale locale) { name = UrlUtils.cleanName(name); locale = cleanLocale(locale); return stringLoader.exists(name, locale) || loader.exists(name, locale); }
java
public void init() { if (logger != null && StringUtils.isNotEmpty(name)) { if (logger.isWarnEnabled() && !ConfigUtils.isFilePath(name)) { try { List<String> realPaths = new ArrayList<String>(); Enumeration<URL> e = Thread.currentThread().getCon...
java
public void inited() { if (preload) { try { int count = 0; if (templateSuffix == null) { templateSuffix = new String[]{".httl"}; } for (String suffix : templateSuffix) { List<String> list = loader...
java
public JSONWriter objectBegin() throws IOException { beforeValue(); writer.write(JSON.LBRACE); stack.push(state); state = new State(OBJECT); return this; }
java
public JSONWriter objectEnd() throws IOException { writer.write(JSON.RBRACE); state = stack.pop(); return this; }
java
public JSONWriter objectItem(String name) throws IOException { beforeObjectItem(); writer.write(JSON.QUOTE); writer.write(escape(name)); writer.write(JSON.QUOTE); writer.write(JSON.COLON); return this; }
java
public JSONWriter arrayBegin() throws IOException { beforeValue(); writer.write(JSON.LSQUARE); stack.push(state); state = new State(ARRAY); return this; }
java
public JSONWriter arrayEnd() throws IOException { writer.write(JSON.RSQUARE); state = stack.pop(); return this; }
java
public MultiFormatter add(Formatter<?>... formatters) { if (formatter != null) { MultiFormatter copy = new MultiFormatter(); copy.formatters.putAll(this.formatters); copy.setFormatters(formatters); return copy; } return this; }
java
public MultiFormatter remove(Formatter<?>... formatters) { if (formatter != null) { MultiFormatter copy = new MultiFormatter(); copy.formatters.putAll(this.formatters); if (formatters != null && formatters.length > 0) { for (Formatter<?> formatter : formatters...
java
public static Properties loadProperties(String path, boolean required) { Properties properties = new Properties(); return loadProperties(properties, path, required); }
java
public static String json(Object obj, boolean writeClass, Converter<Object, Map<String, Object>> mc) throws IOException { if (obj == null) return NULL; StringWriter sw = new StringWriter(); try { json(obj, sw, writeClass, mc); ret...
java
void tryToDrainBuffers() { if (evictionLock.tryLock()) { try { drainStatus.set(PROCESSING); drainBuffers(); } finally { drainStatus.compareAndSet(PROCESSING, IDLE); evictionLock.unlock(); } } }
java
void drainBuffers() { // A mostly strict ordering is achieved by observing that each buffer // contains tasks in a weakly sorted order starting from the last drain. // The buffers can be merged into a sorted array in O(n) time by using // counting sort and chaining on a collision. ...
java
int moveTasksFromBuffers(Task[] tasks) { int maxTaskIndex = -1; for (int i = 0; i < buffers.length; i++) { int maxIndex = moveTasksFromBuffer(tasks, i); maxTaskIndex = Math.max(maxIndex, maxTaskIndex); } return maxTaskIndex; }
java
int moveTasksFromBuffer(Task[] tasks, int bufferIndex) { // While a buffer is being drained it may be concurrently appended to. // The // number of tasks removed are tracked so that the length can be // decremented // by the delta rather than set to zero. Queue<Task> buff...
java
void addTaskToChain(Task[] tasks, Task task, int index) { task.setNext(tasks[index]); tasks[index] = task; }
java
void updateDrainedOrder(Task[] tasks, int maxTaskIndex) { if (maxTaskIndex >= 0) { Task task = tasks[maxTaskIndex]; drainedOrder = task.getOrder() + 1; } }
java
V put(K key, V value, boolean onlyIfAbsent) { checkNotNull(key); checkNotNull(value); final int weight = weigher.weightOf(key, value); final WeightedValue<V> weightedValue = new WeightedValue<V>(value, weight); final Node node = new Node(key, weightedValue); ...
java
public static Engine getEngine(String configPath, Properties configProperties) { if (StringUtils.isEmpty(configPath)) { configPath = HTTL_PROPERTIES; } VolatileReference<Engine> reference = ENGINES.get(configPath); if (reference == null) { reference = new Volatile...
java
public String getProperty(String key, String defaultValue) { String value = getProperty(key, String.class); return StringUtils.isEmpty(value) ? defaultValue : value; }
java
public int getProperty(String key, int defaultValue) { String value = getProperty(key, String.class); return StringUtils.isEmpty(value) ? defaultValue : Integer.parseInt(value); }
java
public boolean getProperty(String key, boolean defaultValue) { String value = getProperty(key, String.class); return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); }
java
private void processInput(boolean endOfInput) throws IOException { // Prepare decoderIn for reading decoderIn.flip(); CoderResult coderResult; while (true) { coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); if (coderResult.isOverflow()) { ...
java
private void flushOutput() throws IOException { if (decoderOut.position() > 0) { writer.write(decoderOut.array(), 0, decoderOut.position()); decoderOut.rewind(); } }
java
public static Context getContext() { Context context = LOCAL.get(); if (context == null) { context = new Context(null, null); LOCAL.set(context); } return context; }
java
public static Context pushContext(Map<String, Object> current) { Context context = new Context(getContext(), current); LOCAL.set(context); return context; }
java
public static void popContext() { Context context = LOCAL.get(); if (context != null) { Context parent = context.getParent(); if (parent != null) { LOCAL.set(parent); } else { LOCAL.remove(); } } }
java
private void checkThread() { if (Thread.currentThread() != thread) { throw new IllegalStateException("Don't cross-thread using the " + Context.class.getName() + " object, it's thread-local only. context thread: " + thread.getName() + ", current thread: " + Thr...
java
private void setCurrent(Map<String, Object> current) { if (current instanceof Context) { throw new IllegalArgumentException("Don't using the " + Context.class.getName() + " object as a parameters, it's implicitly delivery by thread-local. parameter context: " ...
java
public Context setTemplate(Template template) { checkThread(); if (template != null) { setEngine(template.getEngine()); } this.template = template; return this; }
java
public Context setEngine(Engine engine) { checkThread(); if (engine != null) { if (template != null && template.getEngine() != engine) { throw new IllegalStateException("Failed to set the context engine, because is not the same to template engine. template engine: " ...
java
public Object get(String key, Object defaultValue) { Object value = get(key); return value == null ? defaultValue : value; }
java
public static boolean showRateDialogIfNeeded(final Context context, int themeId) { if (shouldShowRateDialog()) { showRateDialog(context, themeId); return true; } else { return false; } }
java
public static boolean shouldShowRateDialog() { if (mOptOut) { return false; } else { if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) { return true; } long threshold = TimeUnit.DAYS.toMillis(sConfig.mCriteriaInstallDays); // msec ...
java
public static void showRateDialog(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); showRateDialog(context, builder); }
java
public static int getLaunchCount(final Context context){ SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); return pref.getInt(KEY_LAUNCH_TIMES, 0); }
java
private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) { Date installDate = new Date(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { PackageManager packMan = context.getPackageManager(); try { PackageInfo pk...
java
private static void storeAskLaterDate(final Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis()); editor.apply(); }
java
public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); }
java
public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title,...
java
public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); ...
java
public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); }
java
public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); }
java
public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, ...
java
public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); }
java
public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); }
java
public static String capitalise(String text) { if (empty(text)) { return ""; } return text.substring(0, 1).toUpperCase() + text.substring(1); }
java
public void startAsync() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { start(); } catch (Exception e) { LOG.error("Failed to connect to kubernetes: " + e, e); } ...
java
public void start() { doClose(); Watcher<PipelineActivity> listener = new Watcher<PipelineActivity>() { @Override public void eventReceived(Action action, PipelineActivity pipelineActivity) { onEventReceived(action, pipelineActivity); } @...
java
public static boolean isNewer(HasMetadata newer, HasMetadata older) { long n1 = parseResourceVersion(newer); long n2 = parseResourceVersion(older); return n1 >= n2; }
java
public static long parseResourceVersion(HasMetadata obj) { ObjectMeta metadata = obj.getMetadata(); if (metadata != null) { String resourceVersion = metadata.getResourceVersion(); if (notEmpty(resourceVersion)) { try { return Long.parseLong(res...
java
public static String getPullRequestName(String prUrl) { if (notEmpty(prUrl)) { int idx = prUrl.lastIndexOf("/"); if (idx > 0) { return " #" + prUrl.substring(idx + 1); } } return ""; }
java
public static String convertToKubernetesName(String text, boolean allowDots) { String lower = text.toLowerCase(); StringBuilder builder = new StringBuilder(); boolean started = false; char lastCh = ' '; for (int i = 0, last = lower.length() - 1; i <= last; i++) { char...
java
protected final SerializerFactory findSerializerFactory() { SerializerFactory factory = _serializerFactory; if (factory == null) { factory = SerializerFactory.createDefault(); _defaultSerializerFactory = factory; _serializerFactory = factory; } r...
java
public Object readObject() throws IOException { _is.startPacket(); Object obj = _in.readStreamingObject(); _is.endPacket(); return obj; }
java
public void init(OutputStream os) { this.os = os; _refs = null; if (_serializerFactory == null) _serializerFactory = new SerializerFactory(); }
java
public void writeRemote(String type, String url) throws IOException { os.write('r'); os.write('t'); printLenString(type); os.write('S'); printLenString(url); }
java