_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q4300
BlobVault.getStringContent
train
@Nullable public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException { String result; result = stringContentCache.tryKey(this, blobHandle); if (result == null) { final InputStream content = getContent(blobHandle, txn); if (content == null) { logger.error("Blob string not found: " + getBlobLocation(blobHandle), new FileNotFoundException()); } result = content == null ? null : UTFUtil.readUTF(content); if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) { if (stringContentCache.getObject(this, blobHandle) == null) { stringContentCache.cacheObject(this, blobHandle, result); } } } return result; }
java
{ "resource": "" }
q4301
JobProcessorAdapter.queueIn
train
@Override public final Job queueIn(final Job job, final long millis) { return pushAt(job, System.currentTimeMillis() + millis); }
java
{ "resource": "" }
q4302
BlobsTable.put
train
public void put(@NotNull final Transaction txn, final long localId, final int blobId, @NotNull final ByteIterable value) { primaryStore.put(txn, PropertyKey.propertyKeyToEntry(new PropertyKey(localId, blobId)), value); allBlobsIndex.put(txn, IntegerBinding.intToCompressedEntry(blobId), LongBinding.longToCompressedEntry(localId)); }
java
{ "resource": "" }
q4303
PropertiesTable.put
train
public void put(@NotNull final PersistentStoreTransaction txn, final long localId, @NotNull final ByteIterable value, @Nullable final ByteIterable oldValue, final int propertyId, @NotNull final ComparableValueType type) { final Store valueIdx = getOrCreateValueIndex(txn, propertyId); final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId)); final Transaction envTxn = txn.getEnvironmentTransaction(); primaryStore.put(envTxn, key, value); final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId); boolean success; if (oldValue == null) { success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue); } else { success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type)); } if (success) { for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) { valueIdx.put(envTxn, secondaryKey, secondaryValue); } } checkStatus(success, "Failed to put"); }
java
{ "resource": "" }
q4304
AbstractPersistent23Tree.tailIterator
train
public Iterator<K> tailIterator(@NotNull final K key) { return new Iterator<K>() { private Stack<TreePos<K>> stack; private boolean hasNext; private boolean hasNextValid; @Override public boolean hasNext() { if (hasNextValid) { return hasNext; } hasNextValid = true; if (stack == null) { Node<K> root = getRoot(); if (root == null) { hasNext = false; return hasNext; } stack = new Stack<>(); if (!root.getLess(key, stack)) { stack.push(new TreePos<>(root)); } } TreePos<K> treePos = stack.peek(); if (treePos.node.isLeaf()) { while (treePos.pos >= (treePos.node.isTernary() ? 2 : 1)) { stack.pop(); if (stack.isEmpty()) { hasNext = false; return hasNext; } treePos = stack.peek(); } } else { if (treePos.pos == 0) { treePos = new TreePos<>(treePos.node.getFirstChild()); } else if (treePos.pos == 1) { treePos = new TreePos<>(treePos.node.getSecondChild()); } else { treePos = new TreePos<>(treePos.node.getThirdChild()); } stack.push(treePos); while (!treePos.node.isLeaf()) { treePos = new TreePos<>(treePos.node.getFirstChild()); stack.push(treePos); } } treePos.pos++; hasNext = true; return hasNext; } @Override public K next() { if (!hasNext()) { throw new NoSuchElementException(); } hasNextValid = false; TreePos<K> treePos = stack.peek(); // treePos.pos must be 1 or 2 here return treePos.pos == 1 ? treePos.node.getFirstKey() : treePos.node.getSecondKey(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
java
{ "resource": "" }
q4305
TwoColumnTable.get
train
@Nullable public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable first) { return this.first.get(txn, first); }
java
{ "resource": "" }
q4306
TwoColumnTable.get2
train
@Nullable public ByteIterable get2(@NotNull final Transaction txn, @NotNull final ByteIterable second) { return this.second.get(txn, second); }
java
{ "resource": "" }
q4307
TcpChannelHub.close
train
@Override public void close() { if (closed) return; closed = true; tcpSocketConsumer.prepareToShutdown(); if (shouldSendCloseMessage) eventLoop.addHandler(new EventHandler() { @Override public boolean action() throws InvalidEventHandlerException { try { TcpChannelHub.this.sendCloseMessage(); tcpSocketConsumer.stop(); closed = true; if (LOG.isDebugEnabled()) Jvm.debug().on(getClass(), "closing connection to " + socketAddressSupplier); while (clientChannel != null) { if (LOG.isDebugEnabled()) Jvm.debug().on(getClass(), "waiting for disconnect to " + socketAddressSupplier); } } catch (ConnectionDroppedException e) { throw new InvalidEventHandlerException(e); } // we just want this to run once throw new InvalidEventHandlerException(); } @NotNull @Override public String toString() { return TcpChannelHub.class.getSimpleName() + "..close()"; } }); }
java
{ "resource": "" }
q4308
TcpChannelHub.sendCloseMessage
train
private void sendCloseMessage() { this.lock(() -> { TcpChannelHub.this.writeMetaDataForKnownTID(0, outWire, null, 0); TcpChannelHub.this.outWire.writeDocument(false, w -> w.writeEventName(EventId.onClientClosing).text("")); }, TryLock.LOCK); // wait up to 1 seconds to receive an close request acknowledgment from the server try { final boolean await = receivedClosedAcknowledgement.await(1, TimeUnit.SECONDS); if (!await) if (Jvm.isDebugEnabled(getClass())) Jvm.debug().on(getClass(), "SERVER IGNORED CLOSE REQUEST: shutting down the client anyway as the " + "server did not respond to the close() request."); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } }
java
{ "resource": "" }
q4309
TcpChannelHub.nextUniqueTransaction
train
public long nextUniqueTransaction(long timeMs) { long id = timeMs; for (; ; ) { long old = transactionID.get(); if (old >= id) id = old + 1; if (transactionID.compareAndSet(old, id)) break; } return id; }
java
{ "resource": "" }
q4310
TcpChannelHub.checkConnection
train
public void checkConnection() { long start = Time.currentTimeMillis(); while (clientChannel == null) { tcpSocketConsumer.checkNotShutdown(); if (start + timeoutMs > Time.currentTimeMillis()) try { condition.await(1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new IORuntimeException("Interrupted"); } else throw new IORuntimeException("Not connected to " + socketAddressSupplier); } if (clientChannel == null) throw new IORuntimeException("Not connected to " + socketAddressSupplier); }
java
{ "resource": "" }
q4311
VanillaNetworkContext.closeAtomically
train
protected boolean closeAtomically() { if (isClosed.compareAndSet(false, true)) { Closeable.closeQuietly(networkStatsListener); return true; } else { //was already closed. return false; } }
java
{ "resource": "" }
q4312
WireTcpHandler.onRead0
train
private void onRead0() { assert inWire.startUse(); ensureCapacity(); try { while (!inWire.bytes().isEmpty()) { try (DocumentContext dc = inWire.readingDocument()) { if (!dc.isPresent()) return; try { if (YamlLogging.showServerReads()) logYaml(dc); onRead(dc, outWire); onWrite(outWire); } catch (Exception e) { Jvm.warn().on(getClass(), "inWire=" + inWire.getClass() + ",yaml=" + Wires.fromSizePrefixedBlobs(dc), e); } } } } finally { assert inWire.endUse(); } }
java
{ "resource": "" }
q4313
HeartbeatHandler.hasReceivedHeartbeat
train
private boolean hasReceivedHeartbeat() { long currentTimeMillis = System.currentTimeMillis(); boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis; if (!result) Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + " missed heartbeat, lastTimeMessageReceived=" + lastTimeMessageReceived + ", currentTimeMillis=" + currentTimeMillis); return result; }
java
{ "resource": "" }
q4314
Mapper.mapsCell
train
public boolean mapsCell(String cell) { return mappedCells.stream().anyMatch(x -> x.equals(cell)); }
java
{ "resource": "" }
q4315
GeoDistance.getDegrees
train
public double getDegrees() { double kms = getValue(GeoDistanceUnit.KILOMETRES); return DistanceUtils.dist2Degrees(kms, DistanceUtils.EARTH_MEAN_RADIUS_KM); }
java
{ "resource": "" }
q4316
DateRangeMapper.makeShape
train
public NRShape makeShape(Date from, Date to) { UnitNRShape fromShape = tree.toUnitShape(from); UnitNRShape toShape = tree.toUnitShape(to); return tree.toRangeShape(fromShape, toShape); }
java
{ "resource": "" }
q4317
GeospatialUtils.validateGeohashMaxLevels
train
public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) { int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels; if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) { throw new IndexException("max_levels must be in range [1, {}], but found {}", GeohashPrefixTree.getMaxLevelsPossible(), maxLevels); } return maxLevels; }
java
{ "resource": "" }
q4318
GeospatialUtils.checkLatitude
train
public static Double checkLatitude(String name, Double latitude) { if (latitude == null) { throw new IndexException("{} required", name); } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) { throw new IndexException("{} must be in range [{}, {}], but found {}", name, MIN_LATITUDE, MAX_LATITUDE, latitude); } return latitude; }
java
{ "resource": "" }
q4319
GeospatialUtils.checkLongitude
train
public static Double checkLongitude(String name, Double longitude) { if (longitude == null) { throw new IndexException("{} required", name); } else if (longitude < MIN_LONGITUDE || longitude > MAX_LONGITUDE) { throw new IndexException("{} must be in range [{}, {}], but found {}", name, MIN_LONGITUDE, MAX_LONGITUDE, longitude); } return longitude; }
java
{ "resource": "" }
q4320
Search.postProcessingFields
train
public Set<String> postProcessingFields() { Set<String> fields = new LinkedHashSet<>(); query.forEach(condition -> fields.addAll(condition.postProcessingFields())); sort.forEach(condition -> fields.addAll(condition.postProcessingFields())); return fields; }
java
{ "resource": "" }
q4321
Builder.index
train
public static Index index(String keyspace, String table, String name) { return new Index(table, name).keyspace(keyspace); }
java
{ "resource": "" }
q4322
GeoShapeMapper.transform
train
public GeoShapeMapper transform(GeoTransformation... transformations) { if (this.transformations == null) { this.transformations = Arrays.asList(transformations); } else { this.transformations.addAll(Arrays.asList(transformations)); } return this; }
java
{ "resource": "" }
q4323
SearchBuilderLegacy.paging
train
@JsonProperty("paging") void paging(String paging) { builder.paging(IndexPagingState.fromByteBuffer(ByteBufferUtils.byteBuffer(paging))); }
java
{ "resource": "" }
q4324
Schema.mapsCell
train
public boolean mapsCell(String cell) { return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell)); }
java
{ "resource": "" }
q4325
ResUtils.convertPathToResource
train
private static String convertPathToResource(String path) { File file = new File(path); List<String> parts = new ArrayList<String>(); do { parts.add(file.getName()); file = file.getParentFile(); } while (file != null); StringBuffer sb = new StringBuffer(); int size = parts.size(); for (int a = size - 1; a >= 0; a--) { if (sb.length() > 0) { sb.append("_"); } sb.append(parts.get(a)); } // TODO: Better regex replacement return sb.toString().replace('-', '_').replace("+", "plus").toLowerCase(Locale.US); }
java
{ "resource": "" }
q4326
DateUtils.formatDateTime
train
public static String formatDateTime(Context context, ReadablePartial time, int flags) { return android.text.format.DateUtils.formatDateTime(context, toMillis(time), flags | FORMAT_UTC); }
java
{ "resource": "" }
q4327
DateUtils.formatDateRange
train
public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) { return formatDateRange(context, toMillis(start), toMillis(end), flags); }
java
{ "resource": "" }
q4328
DateUtils.getRelativeTimeSpanString
train
public static CharSequence getRelativeTimeSpanString(Context context, ReadableInstant time, int flags) { boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0; // We set the millis to 0 so we aren't off by a fraction of a second when counting intervals DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0); DateTime timeDt = new DateTime(time).withMillisOfSecond(0); boolean past = !now.isBefore(timeDt); Interval interval = past ? new Interval(timeDt, now) : new Interval(now, timeDt); int resId; long count; if (Minutes.minutesIn(interval).isLessThan(Minutes.ONE)) { count = Seconds.secondsIn(interval).getSeconds(); if (past) { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_num_seconds_ago; } else { resId = R.plurals.joda_time_android_num_seconds_ago; } } else { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_in_num_seconds; } else { resId = R.plurals.joda_time_android_in_num_seconds; } } } else if (Hours.hoursIn(interval).isLessThan(Hours.ONE)) { count = Minutes.minutesIn(interval).getMinutes(); if (past) { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_num_minutes_ago; } else { resId = R.plurals.joda_time_android_num_minutes_ago; } } else { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_in_num_minutes; } else { resId = R.plurals.joda_time_android_in_num_minutes; } } } else if (Days.daysIn(interval).isLessThan(Days.ONE)) { count = Hours.hoursIn(interval).getHours(); if (past) { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_num_hours_ago; } else { resId = R.plurals.joda_time_android_num_hours_ago; } } else { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_in_num_hours; } else { resId = R.plurals.joda_time_android_in_num_hours; } } } else if (Weeks.weeksIn(interval).isLessThan(Weeks.ONE)) { count = Days.daysIn(interval).getDays(); if (past) { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_num_days_ago; } else { resId = R.plurals.joda_time_android_num_days_ago; } } else { if (abbrevRelative) { resId = R.plurals.joda_time_android_abbrev_in_num_days; } else { resId = R.plurals.joda_time_android_in_num_days; } } } else { return formatDateRange(context, time, time, flags); } String format = context.getResources().getQuantityString(resId, (int) count); return String.format(format, count); }
java
{ "resource": "" }
q4329
DateUtils.formatDuration
train
public static CharSequence formatDuration(Context context, ReadableDuration readableDuration) { Resources res = context.getResources(); Duration duration = readableDuration.toDuration(); final int hours = (int) duration.getStandardHours(); if (hours != 0) { return res.getQuantityString(R.plurals.joda_time_android_duration_hours, hours, hours); } final int minutes = (int) duration.getStandardMinutes(); if (minutes != 0) { return res.getQuantityString(R.plurals.joda_time_android_duration_minutes, minutes, minutes); } final int seconds = (int) duration.getStandardSeconds(); return res.getQuantityString(R.plurals.joda_time_android_duration_seconds, seconds, seconds); }
java
{ "resource": "" }
q4330
ResourceZoneInfoProvider.getZone
train
public DateTimeZone getZone(String id) { if (id == null) { return null; } Object obj = iZoneInfoMap.get(id); if (obj == null) { return null; } if (id.equals(obj)) { // Load zone data for the first time. return loadZoneData(id); } if (obj instanceof SoftReference<?>) { @SuppressWarnings("unchecked") SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj; DateTimeZone tz = ref.get(); if (tz != null) { return tz; } // Reference cleared; load data again. return loadZoneData(id); } // If this point is reached, mapping must link to another. return getZone((String) obj); }
java
{ "resource": "" }
q4331
DesignerNotificationPopupsManager.addNotification
train
public void addNotification(@Observes final DesignerNotificationEvent event) { if (user.getIdentifier().equals(event.getUserId())) { if (event.getNotification() != null && !event.getNotification().equals("openinxmleditor")) { final NotificationPopupView view = new NotificationPopupView(); activeNotifications.add(view); view.setPopupPosition(getMargin(), activeNotifications.size() * SPACING); view.setNotification(event.getNotification()); view.setType(event.getType()); view.setNotificationWidth(getWidth() + "px"); view.show(new Command() { @Override public void execute() { //The notification has been shown and can now be removed deactiveNotifications.add(view); remove(); } }); } } }
java
{ "resource": "" }
q4332
DesignerNotificationPopupsManager.remove
train
private void remove() { if (removing) { return; } if (deactiveNotifications.size() == 0) { return; } removing = true; final NotificationPopupView view = deactiveNotifications.get(0); final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) { @Override public void onUpdate(double progress) { super.onUpdate(progress); for (int i = 0; i < activeNotifications.size(); i++) { NotificationPopupView v = activeNotifications.get(i); final int left = v.getPopupLeft(); final int top = (int) (((i + 1) * SPACING) - (progress * SPACING)); v.setPopupPosition(left, top); } } @Override public void onComplete() { super.onComplete(); view.hide(); deactiveNotifications.remove(view); activeNotifications.remove(view); removing = false; remove(); } }; fadeOutAnimation.run(500); }
java
{ "resource": "" }
q4333
EditorHandler.readDesignerVersion
train
public static String readDesignerVersion(ServletContext context) { String retStr = ""; BufferedReader br = null; try { InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF"); br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.startsWith(BUNDLE_VERSION)) { retStr = line.substring(BUNDLE_VERSION.length() + 1); retStr = retStr.trim(); } } inputStream.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (br != null) { IOUtils.closeQuietly(br); } } return retStr; }
java
{ "resource": "" }
q4334
ActivityDataIOEditorWidget.isDuplicateName
train
public boolean isDuplicateName(String name) { if (name == null || name.trim().isEmpty()) { return false; } List<AssignmentRow> as = view.getAssignmentRows(); if (as != null && !as.isEmpty()) { int nameCount = 0; for (AssignmentRow row : as) { if (name.trim().compareTo(row.getName()) == 0) { nameCount++; if (nameCount > 1) { return true; } } } } return false; }
java
{ "resource": "" }
q4335
ListBoxValues.getValueForDisplayValue
train
public String getValueForDisplayValue(final String key) { if (mapDisplayValuesToValues.containsKey(key)) { return mapDisplayValuesToValues.get(key); } return key; }
java
{ "resource": "" }
q4336
AssignmentData.getAssignmentRows
train
public List<AssignmentRow> getAssignmentRows(VariableType varType) { List<AssignmentRow> rows = new ArrayList<AssignmentRow>(); List<Variable> handledVariables = new ArrayList<Variable>(); // Create an AssignmentRow for each Assignment for (Assignment assignment : assignments) { if (assignment.getVariableType() == varType) { String dataType = getDisplayNameFromDataType(assignment.getDataType()); AssignmentRow row = new AssignmentRow(assignment.getName(), assignment.getVariableType(), dataType, assignment.getCustomDataType(), assignment.getProcessVarName(), assignment.getConstant()); rows.add(row); handledVariables.add(assignment.getVariable()); } } List<Variable> vars = null; if (varType == VariableType.INPUT) { vars = inputVariables; } else { vars = outputVariables; } // Create an AssignmentRow for each Variable that doesn't have an Assignment for (Variable var : vars) { if (!handledVariables.contains(var)) { AssignmentRow row = new AssignmentRow(var.getName(), var.getVariableType(), var.getDataType(), var.getCustomDataType(), null, null); rows.add(row); } } return rows; }
java
{ "resource": "" }
q4337
DiagramBuilder.parseJson
train
public static Diagram parseJson(String json, Boolean keepGlossaryLink) throws JSONException { JSONObject modelJSON = new JSONObject(json); return parseJson(modelJSON, keepGlossaryLink); }
java
{ "resource": "" }
q4338
DiagramBuilder.parseJson
train
public static Diagram parseJson(JSONObject json, Boolean keepGlossaryLink) throws JSONException { ArrayList<Shape> shapes = new ArrayList<Shape>(); HashMap<String, JSONObject> flatJSON = flatRessources(json); for (String resourceId : flatJSON.keySet()) { parseRessource(shapes, flatJSON, resourceId, keepGlossaryLink); } String id = "canvas"; if (json.has("resourceId")) { id = json.getString("resourceId"); shapes.remove(new Shape(id)); } ; Diagram diagram = new Diagram(id); // remove Diagram // (Diagram)getShapeWithId(json.getString("resourceId"), shapes); parseStencilSet(json, diagram); parseSsextensions(json, diagram); parseStencil(json, diagram); parseProperties(json, diagram, keepGlossaryLink); parseChildShapes(shapes, json, diagram); parseBounds(json, diagram); diagram.setShapes(shapes); return diagram; }
java
{ "resource": "" }
q4339
DiagramBuilder.parseRessource
train
private static void parseRessource(ArrayList<Shape> shapes, HashMap<String, JSONObject> flatJSON, String resourceId, Boolean keepGlossaryLink) throws JSONException { JSONObject modelJSON = flatJSON.get(resourceId); Shape current = getShapeWithId(modelJSON.getString("resourceId"), shapes); parseStencil(modelJSON, current); parseProperties(modelJSON, current, keepGlossaryLink); parseOutgoings(shapes, modelJSON, current); parseChildShapes(shapes, modelJSON, current); parseDockers(modelJSON, current); parseBounds(modelJSON, current); parseTarget(shapes, modelJSON, current); }
java
{ "resource": "" }
q4340
DiagramBuilder.parseStencil
train
private static void parseStencil(JSONObject modelJSON, Shape current) throws JSONException { // get stencil type if (modelJSON.has("stencil")) { JSONObject stencil = modelJSON.getJSONObject("stencil"); // TODO other attributes of stencil String stencilString = ""; if (stencil.has("id")) { stencilString = stencil.getString("id"); } current.setStencil(new StencilType(stencilString)); } }
java
{ "resource": "" }
q4341
DiagramBuilder.parseStencilSet
train
private static void parseStencilSet(JSONObject modelJSON, Diagram current) throws JSONException { // get stencil type if (modelJSON.has("stencilset")) { JSONObject object = modelJSON.getJSONObject("stencilset"); String url = null; String namespace = null; if (object.has("url")) { url = object.getString("url"); } if (object.has("namespace")) { namespace = object.getString("namespace"); } current.setStencilset(new StencilSet(url, namespace)); } }
java
{ "resource": "" }
q4342
DiagramBuilder.parseProperties
train
@SuppressWarnings("unchecked") private static void parseProperties(JSONObject modelJSON, Shape current, Boolean keepGlossaryLink) throws JSONException { if (modelJSON.has("properties")) { JSONObject propsObject = modelJSON.getJSONObject("properties"); Iterator<String> keys = propsObject.keys(); Pattern pattern = Pattern.compile(jsonPattern); while (keys.hasNext()) { StringBuilder result = new StringBuilder(); int lastIndex = 0; String key = keys.next(); String value = propsObject.getString(key); if (!keepGlossaryLink) { Matcher matcher = pattern.matcher(value); while (matcher.find()) { String id = matcher.group(1); current.addGlossaryIds(id); String text = matcher.group(2); result.append(text); lastIndex = matcher.end(); } result.append(value.substring(lastIndex)); value = result.toString(); } current.putProperty(key, value); } } }
java
{ "resource": "" }
q4343
DiagramBuilder.parseSsextensions
train
private static void parseSsextensions(JSONObject modelJSON, Diagram current) throws JSONException { if (modelJSON.has("ssextensions")) { JSONArray array = modelJSON.getJSONArray("ssextensions"); for (int i = 0; i < array.length(); i++) { current.addSsextension(array.getString(i)); } } }
java
{ "resource": "" }
q4344
DiagramBuilder.parseOutgoings
train
private static void parseOutgoings(ArrayList<Shape> shapes, JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("outgoing")) { ArrayList<Shape> outgoings = new ArrayList<Shape>(); JSONArray outgoingObject = modelJSON.getJSONArray("outgoing"); for (int i = 0; i < outgoingObject.length(); i++) { Shape out = getShapeWithId(outgoingObject.getJSONObject(i).getString("resourceId"), shapes); outgoings.add(out); out.addIncoming(current); } if (outgoings.size() > 0) { current.setOutgoings(outgoings); } } }
java
{ "resource": "" }
q4345
DiagramBuilder.parseChildShapes
train
private static void parseChildShapes(ArrayList<Shape> shapes, JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("childShapes")) { ArrayList<Shape> childShapes = new ArrayList<Shape>(); JSONArray childShapeObject = modelJSON.getJSONArray("childShapes"); for (int i = 0; i < childShapeObject.length(); i++) { childShapes.add(getShapeWithId(childShapeObject.getJSONObject(i).getString("resourceId"), shapes)); } if (childShapes.size() > 0) { for (Shape each : childShapes) { each.setParent(current); } current.setChildShapes(childShapes); } ; } }
java
{ "resource": "" }
q4346
DiagramBuilder.parseDockers
train
private static void parseDockers(JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("dockers")) { ArrayList<Point> dockers = new ArrayList<Point>(); JSONArray dockersObject = modelJSON.getJSONArray("dockers"); for (int i = 0; i < dockersObject.length(); i++) { Double x = dockersObject.getJSONObject(i).getDouble("x"); Double y = dockersObject.getJSONObject(i).getDouble("y"); dockers.add(new Point(x, y)); } if (dockers.size() > 0) { current.setDockers(dockers); } } }
java
{ "resource": "" }
q4347
DiagramBuilder.parseBounds
train
private static void parseBounds(JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("bounds")) { JSONObject boundsObject = modelJSON.getJSONObject("bounds"); current.setBounds(new Bounds(new Point(boundsObject.getJSONObject("lowerRight").getDouble("x"), boundsObject.getJSONObject("lowerRight").getDouble( "y")), new Point(boundsObject.getJSONObject("upperLeft").getDouble("x"), boundsObject.getJSONObject("upperLeft").getDouble("y")))); } }
java
{ "resource": "" }
q4348
DiagramBuilder.parseTarget
train
private static void parseTarget(ArrayList<Shape> shapes, JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("target")) { JSONObject targetObject = modelJSON.getJSONObject("target"); if (targetObject.has("resourceId")) { current.setTarget(getShapeWithId(targetObject.getString("resourceId"), shapes)); } } }
java
{ "resource": "" }
q4349
DiagramBuilder.flatRessources
train
public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException { HashMap<String, JSONObject> result = new HashMap<String, JSONObject>(); // no cycle in hierarchies!! if (object.has("resourceId") && object.has("childShapes")) { result.put(object.getString("resourceId"), object); JSONArray childShapes = object.getJSONArray("childShapes"); for (int i = 0; i < childShapes.length(); i++) { result.putAll(flatRessources(childShapes.getJSONObject(i))); } } ; return result; }
java
{ "resource": "" }
q4350
DataIOEditorNameTextBox.setInvalidValues
train
public void setInvalidValues(final Set<String> invalidValues, final boolean isCaseSensitive, final String invalidValueErrorMessage) { if (isCaseSensitive) { this.invalidValues = invalidValues; } else { this.invalidValues = new HashSet<String>(); for (String value : invalidValues) { this.invalidValues.add(value.toLowerCase()); } } this.isCaseSensitive = isCaseSensitive; this.invalidValueErrorMessage = invalidValueErrorMessage; }
java
{ "resource": "" }
q4351
DataIOEditorNameTextBox.setRegExp
train
public void setRegExp(final String pattern, final String invalidCharactersInNameErrorMessage, final String invalidCharacterTypedMessage) { regExp = RegExp.compile(pattern); this.invalidCharactersInNameErrorMessage = invalidCharactersInNameErrorMessage; this.invalidCharacterTypedMessage = invalidCharacterTypedMessage; }
java
{ "resource": "" }
q4352
Shape.getProperties
train
public HashMap<String, String> getProperties() { if (this.properties == null) { this.properties = new HashMap<String, String>(); } return properties; }
java
{ "resource": "" }
q4353
Shape.putProperty
train
public String putProperty(String key, String value) { return this.getProperties().put(key, value); }
java
{ "resource": "" }
q4354
CalledElementServlet.getRuleFlowNames
train
List<String> getRuleFlowNames(HttpServletRequest req) { final String[] projectAndBranch = getProjectAndBranchNames(req); // Query RuleFlowGroups for asset project and branch List<RefactoringPageRow> results = queryService.query( DesignerFindRuleFlowNamesQuery.NAME, new HashSet<ValueIndexTerm>() {{ add(new ValueSharedPartIndexTerm("*", PartType.RULEFLOW_GROUP, TermSearchType.WILDCARD)); add(new ValueModuleNameIndexTerm(projectAndBranch[0])); if (projectAndBranch[1] != null) { add(new ValueBranchNameIndexTerm(projectAndBranch[1])); } }}); final List<String> ruleFlowGroupNames = new ArrayList<String>(); for (RefactoringPageRow row : results) { ruleFlowGroupNames.add((String) row.getValue()); } Collections.sort(ruleFlowGroupNames); // Query RuleFlowGroups for all projects and branches results = queryService.query( DesignerFindRuleFlowNamesQuery.NAME, new HashSet<ValueIndexTerm>() {{ add(new ValueSharedPartIndexTerm("*", PartType.RULEFLOW_GROUP, TermSearchType.WILDCARD)); }}); final List<String> otherRuleFlowGroupNames = new LinkedList<String>(); for (RefactoringPageRow row : results) { String ruleFlowGroupName = (String) row.getValue(); if (!ruleFlowGroupNames.contains(ruleFlowGroupName)) { // but only add the new ones otherRuleFlowGroupNames.add(ruleFlowGroupName); } } Collections.sort(otherRuleFlowGroupNames); ruleFlowGroupNames.addAll(otherRuleFlowGroupNames); return ruleFlowGroupNames; }
java
{ "resource": "" }
q4355
PluginServiceImpl.getLocalPluginsRegistry
train
public static Map<String, IDiagramPlugin> getLocalPluginsRegistry(ServletContext context) { if (LOCAL == null) { LOCAL = initializeLocalPlugins(context); } return LOCAL; }
java
{ "resource": "" }
q4356
Diagram.addSsextension
train
public boolean addSsextension(String ssExt) { if (this.ssextensions == null) { this.ssextensions = new ArrayList<String>(); } return this.ssextensions.add(ssExt); }
java
{ "resource": "" }
q4357
JSONBuilder.parseStencil
train
private static JSONObject parseStencil(String stencilId) throws JSONException { JSONObject stencilObject = new JSONObject(); stencilObject.put("id", stencilId.toString()); return stencilObject; }
java
{ "resource": "" }
q4358
JSONBuilder.parseChildShapesRecursive
train
private static JSONArray parseChildShapesRecursive(ArrayList<Shape> childShapes) throws JSONException { if (childShapes != null) { JSONArray childShapesArray = new JSONArray(); for (Shape childShape : childShapes) { JSONObject childShapeObject = new JSONObject(); childShapeObject.put("resourceId", childShape.getResourceId().toString()); childShapeObject.put("properties", parseProperties(childShape.getProperties())); childShapeObject.put("stencil", parseStencil(childShape.getStencilId())); childShapeObject.put("childShapes", parseChildShapesRecursive(childShape.getChildShapes())); childShapeObject.put("outgoing", parseOutgoings(childShape.getOutgoings())); childShapeObject.put("bounds", parseBounds(childShape.getBounds())); childShapeObject.put("dockers", parseDockers(childShape.getDockers())); if (childShape.getTarget() != null) { childShapeObject.put("target", parseTarget(childShape.getTarget())); } childShapesArray.put(childShapeObject); } return childShapesArray; } return new JSONArray(); }
java
{ "resource": "" }
q4359
JSONBuilder.parseTarget
train
private static JSONObject parseTarget(Shape target) throws JSONException { JSONObject targetObject = new JSONObject(); targetObject.put("resourceId", target.getResourceId().toString()); return targetObject; }
java
{ "resource": "" }
q4360
JSONBuilder.parseDockers
train
private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException { if (dockers != null) { JSONArray dockersArray = new JSONArray(); for (Point docker : dockers) { JSONObject dockerObject = new JSONObject(); dockerObject.put("x", docker.getX().doubleValue()); dockerObject.put("y", docker.getY().doubleValue()); dockersArray.put(dockerObject); } return dockersArray; } return new JSONArray(); }
java
{ "resource": "" }
q4361
JSONBuilder.parseOutgoings
train
private static JSONArray parseOutgoings(ArrayList<Shape> outgoings) throws JSONException { if (outgoings != null) { JSONArray outgoingsArray = new JSONArray(); for (Shape outgoing : outgoings) { JSONObject outgoingObject = new JSONObject(); outgoingObject.put("resourceId", outgoing.getResourceId().toString()); outgoingsArray.put(outgoingObject); } return outgoingsArray; } return new JSONArray(); }
java
{ "resource": "" }
q4362
JSONBuilder.parseProperties
train
private static JSONObject parseProperties(HashMap<String, String> properties) throws JSONException { if (properties != null) { JSONObject propertiesObject = new JSONObject(); for (String key : properties.keySet()) { String propertyValue = properties.get(key); /* * if(propertyValue.matches("true|false")) { * * propertiesObject.put(key, propertyValue.equals("true")); * * } else if(propertyValue.matches("[0-9]+")) { * * Integer value = Integer.parseInt(propertyValue); * propertiesObject.put(key, value); * * } else */ if (propertyValue.startsWith("{") && propertyValue.endsWith("}")) { propertiesObject.put(key, new JSONObject(propertyValue)); } else { propertiesObject.put(key, propertyValue.toString()); } } return propertiesObject; } return new JSONObject(); }
java
{ "resource": "" }
q4363
JSONBuilder.parseStencilSetExtensions
train
private static JSONArray parseStencilSetExtensions(ArrayList<String> extensions) { if (extensions != null) { JSONArray extensionsArray = new JSONArray(); for (String extension : extensions) { extensionsArray.put(extension.toString()); } return extensionsArray; } return new JSONArray(); }
java
{ "resource": "" }
q4364
JSONBuilder.parseStencilSet
train
private static JSONObject parseStencilSet(StencilSet stencilSet) throws JSONException { if (stencilSet != null) { JSONObject stencilSetObject = new JSONObject(); stencilSetObject.put("url", stencilSet.getUrl().toString()); stencilSetObject.put("namespace", stencilSet.getNamespace().toString()); return stencilSetObject; } return new JSONObject(); }
java
{ "resource": "" }
q4365
JSONBuilder.parseBounds
train
private static JSONObject parseBounds(Bounds bounds) throws JSONException { if (bounds != null) { JSONObject boundsObject = new JSONObject(); JSONObject lowerRight = new JSONObject(); JSONObject upperLeft = new JSONObject(); lowerRight.put("x", bounds.getLowerRight().getX().doubleValue()); lowerRight.put("y", bounds.getLowerRight().getY().doubleValue()); upperLeft.put("x", bounds.getUpperLeft().getX().doubleValue()); upperLeft.put("y", bounds.getUpperLeft().getY().doubleValue()); boundsObject.put("lowerRight", lowerRight); boundsObject.put("upperLeft", upperLeft); return boundsObject; } return new JSONObject(); }
java
{ "resource": "" }
q4366
StringUtils.createQuotedConstant
train
public static String createQuotedConstant(String str) { if (str == null || str.isEmpty()) { return str; } try { Double.parseDouble(str); } catch (NumberFormatException nfe) { return "\"" + str + "\""; } return str; }
java
{ "resource": "" }
q4367
StringUtils.createUnquotedConstant
train
public static String createUnquotedConstant(String str) { if (str == null || str.isEmpty()) { return str; } if (str.startsWith("\"")) { str = str.substring(1); } if (str.endsWith("\"")) { str = str.substring(0, str.length() - 1); } return str; }
java
{ "resource": "" }
q4368
StringUtils.isQuotedConstant
train
public static boolean isQuotedConstant(String str) { if (str == null || str.isEmpty()) { return false; } return (str.startsWith("\"") && str.endsWith("\"")); }
java
{ "resource": "" }
q4369
StringUtils.urlEncode
train
public String urlEncode(String s) { if (s == null || s.isEmpty()) { return s; } return URL.encodeQueryString(s); }
java
{ "resource": "" }
q4370
StringUtils.urlDecode
train
public String urlDecode(String s) { if (s == null || s.isEmpty()) { return s; } return URL.decodeQueryString(s); }
java
{ "resource": "" }
q4371
Bpmn2JsonUnmarshaller.unmarshall
train
private Bpmn2Resource unmarshall(JsonParser parser, String preProcessingData) throws IOException { try { parser.nextToken(); // open the object ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2); _currentResource = bpmn2; if (preProcessingData == null || preProcessingData.length() < 1) { preProcessingData = "ReadOnlyService"; } // do the unmarshalling now: Definitions def = (Definitions) unmarshallItem(parser, preProcessingData); def.setExporter(exporterName); def.setExporterVersion(exporterVersion); revisitUserTasks(def); revisitServiceTasks(def); revisitMessages(def); revisitCatchEvents(def); revisitThrowEvents(def); revisitLanes(def); revisitSubProcessItemDefs(def); revisitArtifacts(def); revisitGroups(def); revisitTaskAssociations(def); revisitTaskIoSpecification(def); revisitSendReceiveTasks(def); reconnectFlows(); revisitGateways(def); revisitCatchEventsConvertToBoundary(def); revisitBoundaryEventsPositions(def); createDiagram(def); updateIDs(def); revisitDataObjects(def); revisitAssociationsIoSpec(def); revisitWsdlImports(def); revisitMultiInstanceTasks(def); addSimulation(def); revisitItemDefinitions(def); revisitProcessDoc(def); revisitDI(def); revisitSignalRef(def); orderDiagramElements(def); // return def; _currentResource.getContents().add(def); return _currentResource; } catch (Exception e) { _logger.error(e.getMessage()); return _currentResource; } finally { parser.close(); _objMap.clear(); _idMap.clear(); _outgoingFlows.clear(); _sequenceFlowTargets.clear(); _bounds.clear(); _currentResource = null; } }
java
{ "resource": "" }
q4372
Bpmn2JsonUnmarshaller.revisitThrowEvents
train
public void revisitThrowEvents(Definitions def) { List<RootElement> rootElements = def.getRootElements(); List<Signal> toAddSignals = new ArrayList<Signal>(); Set<Error> toAddErrors = new HashSet<Error>(); Set<Escalation> toAddEscalations = new HashSet<Escalation>(); Set<Message> toAddMessages = new HashSet<Message>(); Set<ItemDefinition> toAddItemDefinitions = new HashSet<ItemDefinition>(); for (RootElement root : rootElements) { if (root instanceof Process) { setThrowEventsInfo((Process) root, def, rootElements, toAddSignals, toAddErrors, toAddEscalations, toAddMessages, toAddItemDefinitions); } } for (Lane lane : _lanes) { setThrowEventsInfoForLanes(lane, def, rootElements, toAddSignals, toAddErrors, toAddEscalations, toAddMessages, toAddItemDefinitions); } for (Signal s : toAddSignals) { def.getRootElements().add(s); } for (Error er : toAddErrors) { def.getRootElements().add(er); } for (Escalation es : toAddEscalations) { def.getRootElements().add(es); } for (ItemDefinition idef : toAddItemDefinitions) { def.getRootElements().add(idef); } for (Message msg : toAddMessages) { def.getRootElements().add(msg); } }
java
{ "resource": "" }
q4373
Bpmn2JsonUnmarshaller.revisitGateways
train
private void revisitGateways(Definitions def) { List<RootElement> rootElements = def.getRootElements(); for (RootElement root : rootElements) { if (root instanceof Process) { setGatewayInfo((Process) root); } } }
java
{ "resource": "" }
q4374
Bpmn2JsonUnmarshaller.revisitMessages
train
private void revisitMessages(Definitions def) { List<RootElement> rootElements = def.getRootElements(); List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>(); for (RootElement root : rootElements) { if (root instanceof Message) { if (!existsMessageItemDefinition(rootElements, root.getId())) { ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition(); itemdef.setId(root.getId() + "Type"); toAddDefinitions.add(itemdef); ((Message) root).setItemRef(itemdef); } } } for (ItemDefinition id : toAddDefinitions) { def.getRootElements().add(id); } }
java
{ "resource": "" }
q4375
Bpmn2JsonUnmarshaller.reconnectFlows
train
private void reconnectFlows() { // create the reverse id map: for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) { for (String flowId : entry.getValue()) { if (entry.getKey() instanceof SequenceFlow) { // if it is a sequence flow, we can tell its targets if (_idMap.get(flowId) instanceof FlowNode) { ((SequenceFlow) entry.getKey()).setTargetRef((FlowNode) _idMap.get(flowId)); } if (_idMap.get(flowId) instanceof Association) { ((Association) _idMap.get(flowId)).setTargetRef((SequenceFlow) entry.getKey()); } } else if (entry.getKey() instanceof Association) { ((Association) entry.getKey()).setTargetRef((BaseElement) _idMap.get(flowId)); } else { // if it is a node, we can map it to its outgoing sequence flows if (_idMap.get(flowId) instanceof SequenceFlow) { ((FlowNode) entry.getKey()).getOutgoing().add((SequenceFlow) _idMap.get(flowId)); } else if (_idMap.get(flowId) instanceof Association) { ((Association) _idMap.get(flowId)).setSourceRef((BaseElement) entry.getKey()); } } } } }
java
{ "resource": "" }
q4376
AbstractConnectorServlet.parseRequest
train
protected void parseRequest(HttpServletRequest request, HttpServletResponse response) { requestParams = new HashMap<String, Object>(); listFiles = new ArrayList<FileItemStream>(); listFileStreams = new ArrayList<ByteArrayOutputStream>(); // Parse the request if (ServletFileUpload.isMultipartContent(request)) { // multipart request try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { listFiles.add(item); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); listFileStreams.add(os); } } } } catch (Exception e) { logger.error("Unexpected error parsing multipart content", e); } } else { // not a multipart for (Object mapKey : request.getParameterMap().keySet()) { String mapKeyString = (String) mapKey; if (mapKeyString.endsWith("[]")) { // multiple values String values[] = request.getParameterValues(mapKeyString); List<String> listeValues = new ArrayList<String>(); for (String value : values) { listeValues.add(value); } requestParams.put(mapKeyString, listeValues); } else { // single value String value = request.getParameter(mapKeyString); requestParams.put(mapKeyString, value); } } } }
java
{ "resource": "" }
q4377
AbstractConnectorServlet.putResponse
train
protected void putResponse(JSONObject json, String param, Object value) { try { json.put(param, value); } catch (JSONException e) { logger.error("json write error", e); } }
java
{ "resource": "" }
q4378
Variable.deserialize
train
public static Variable deserialize(String s, VariableType variableType, List<String> dataTypes) { Variable var = new Variable(variableType); String[] varParts = s.split(":"); if (varParts.length > 0) { String name = varParts[0]; if (!name.isEmpty()) { var.setName(name); if (varParts.length == 2) { String dataType = varParts[1]; if (!dataType.isEmpty()) { if (dataTypes != null && dataTypes.contains(dataType)) { var.setDataType(dataType); } else { var.setCustomDataType(dataType); } } } } } return var; }
java
{ "resource": "" }
q4379
Variable.deserialize
train
public static Variable deserialize(String s, VariableType variableType) { return deserialize(s, variableType, null); }
java
{ "resource": "" }
q4380
SvgInline.processStencilSet
train
public void processStencilSet() throws IOException { StringBuilder stencilSetFileContents = new StringBuilder(); Scanner scanner = null; try { scanner = new Scanner(new File(ssInFile), "UTF-8"); String currentLine = ""; String prevLine = ""; while (scanner.hasNextLine()) { prevLine = currentLine; currentLine = scanner.nextLine(); String trimmedPrevLine = prevLine.trim(); String trimmedCurrentLine = currentLine.trim(); // First time processing - replace view="<file>.svg" with _view_file="<file>.svg" + view="<svg_xml>" if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) { String newLines = processViewPropertySvgReference(currentLine); stencilSetFileContents.append(newLines); } // Second time processing - replace view="<svg_xml>" with refreshed contents of file referenced by previous line else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX) && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) { String newLines = processViewFilePropertySvgReference(prevLine, currentLine); stencilSetFileContents.append(newLines); } else { stencilSetFileContents.append(currentLine + LINE_SEPARATOR); } } } finally { if (scanner != null) { scanner.close(); } } Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile), "UTF-8")); out.write(stencilSetFileContents.toString()); } catch (FileNotFoundException e) { } catch (UnsupportedEncodingException e) { } catch (IOException e) { } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } System.out.println("SVG files referenced more than once:"); for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) { if (stringIntegerEntry.getValue() > 1) { System.out.println("\t" + stringIntegerEntry.getKey() + "\t = " + stringIntegerEntry.getValue()); } } }
java
{ "resource": "" }
q4381
ProfileServiceImpl.init
train
public void init(ServletContext context) { if (profiles != null) { for (IDiagramProfile profile : profiles) { profile.init(context); _registry.put(profile.getName(), profile); } } }
java
{ "resource": "" }
q4382
ReflectUtils.getPropertyName
train
public static String getPropertyName(String name) { if(name != null && (name.startsWith("get") || name.startsWith("set"))) { StringBuilder b = new StringBuilder(name); b.delete(0, 3); b.setCharAt(0, Character.toLowerCase(b.charAt(0))); return b.toString(); } else { return name; } }
java
{ "resource": "" }
q4383
ReflectUtils.loadClass
train
public static Class<?> loadClass(String className) { try { return Class.forName(className); } catch(ClassNotFoundException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q4384
ReflectUtils.loadClass
train
public static Class<?> loadClass(String className, ClassLoader cl) { try { return Class.forName(className, false, cl); } catch(ClassNotFoundException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q4385
ReflectUtils.callConstructor
train
public static <T> T callConstructor(Class<T> klass) { return callConstructor(klass, new Class<?>[0], new Object[0]); }
java
{ "resource": "" }
q4386
ReflectUtils.callConstructor
train
public static <T> T callConstructor(Class<T> klass, Object[] args) { Class<?>[] klasses = new Class[args.length]; for(int i = 0; i < args.length; i++) klasses[i] = args[i].getClass(); return callConstructor(klass, klasses, args); }
java
{ "resource": "" }
q4387
ReflectUtils.callMethod
train
public static <T> Object callMethod(Object obj, Class<T> c, String name, Class<?>[] classes, Object[] args) { try { Method m = getMethod(c, name, classes); return m.invoke(obj, args); } catch(InvocationTargetException e) { throw getCause(e); } catch(IllegalAccessException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q4388
ReflectUtils.getMethod
train
public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) { try { return c.getMethod(name, argTypes); } catch(NoSuchMethodException e) { throw new IllegalArgumentException(e); } }
java
{ "resource": "" }
q4389
VersionedPutPruneJob.pruneNonReplicaEntries
train
public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals, List<Integer> keyReplicas, MutableBoolean didPrune) { List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size()); for(Versioned<byte[]> val: vals) { VectorClock clock = (VectorClock) val.getVersion(); List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(); for(ClockEntry clockEntry: clock.getEntries()) { if(keyReplicas.contains((int) clockEntry.getNodeId())) { clockEntries.add(clockEntry); } else { didPrune.setValue(true); } } prunedVals.add(new Versioned<byte[]>(val.getValue(), new VectorClock(clockEntries, clock.getTimestamp()))); } return prunedVals; }
java
{ "resource": "" }
q4390
ObjectSerializer.toBytes
train
public byte[] toBytes(T object) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(stream); out.writeObject(object); return stream.toByteArray(); } catch(IOException e) { throw new SerializationException(e); } }
java
{ "resource": "" }
q4391
ObjectSerializer.toObject
train
@SuppressWarnings("unchecked") public T toObject(byte[] bytes) { try { return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); } catch(IOException e) { throw new SerializationException(e); } catch(ClassNotFoundException c) { throw new SerializationException(c); } }
java
{ "resource": "" }
q4392
VoldemortNativeRequestHandler.isCompleteRequest
train
@Override public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException { DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer)); try { byte opCode = inputStream.readByte(); // Store Name inputStream.readUTF(); // Store routing type getRoutingType(inputStream); switch(opCode) { case VoldemortOpCode.GET_VERSION_OP_CODE: if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer)) return false; break; case VoldemortOpCode.GET_OP_CODE: if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; case VoldemortOpCode.GET_ALL_OP_CODE: if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; case VoldemortOpCode.PUT_OP_CODE: { if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion)) return false; break; } case VoldemortOpCode.DELETE_OP_CODE: { if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer)) return false; break; } default: throw new VoldemortException(" Unrecognized Voldemort OpCode " + opCode); } // This should not happen, if we reach here and if buffer has more // data, there is something wrong. if(buffer.hasRemaining()) { logger.info("Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode: " + opCode + ", remaining bytes: " + buffer.remaining()); } return true; } catch(IOException e) { // This could also occur if the various methods we call into // re-throw a corrupted value error as some other type of exception. // For example, updating the position on a buffer past its limit // throws an InvalidArgumentException. if(logger.isDebugEnabled()) logger.debug("Probable partial read occurred causing exception", e); return false; } }
java
{ "resource": "" }
q4393
WriteThroughCache.put
train
@Override synchronized public V put(K key, V value) { V oldValue = this.get(key); try { super.put(key, value); writeBack(key, value); return oldValue; } catch(Exception e) { super.put(key, oldValue); writeBack(key, oldValue); throw new VoldemortException("Failed to put(" + key + ", " + value + ") in write through cache", e); } }
java
{ "resource": "" }
q4394
CheckSum.update
train
public void update(int number) { byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_INT]; ByteUtils.writeInt(numberInBytes, number, 0); update(numberInBytes); }
java
{ "resource": "" }
q4395
CheckSum.update
train
public void update(short number) { byte[] numberInBytes = new byte[ByteUtils.SIZE_OF_SHORT]; ByteUtils.writeShort(numberInBytes, number, 0); update(numberInBytes); }
java
{ "resource": "" }
q4396
AsyncPutSynchronizer.tryDelegateSlop
train
public synchronized boolean tryDelegateSlop(Node node) { if(asyncCallbackShouldSendhint) { return false; } else { slopDestinations.put(node, true); return true; } }
java
{ "resource": "" }
q4397
AsyncPutSynchronizer.tryDelegateResponseHandling
train
public synchronized boolean tryDelegateResponseHandling(Response<ByteArray, Object> response) { if(responseHandlingCutoff) { return false; } else { responseQueue.offer(response); this.notifyAll(); return true; } }
java
{ "resource": "" }
q4398
AsyncPutSynchronizer.responseQueuePoll
train
public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout, TimeUnit timeUnit) throws InterruptedException { long timeoutMs = timeUnit.toMillis(timeout); long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs; while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) { long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis()); if(logger.isDebugEnabled()) { logger.debug("Start waiting for response queue with timeoutMs: " + timeoutMs); } this.wait(remainingMs); if(logger.isDebugEnabled()) { logger.debug("End waiting for response queue with timeoutMs: " + timeoutMs); } } return responseQueue.poll(); }
java
{ "resource": "" }
q4399
RESTClientConfig.setProperties
train
private void setProperties(Properties properties) { Props props = new Props(properties); if(props.containsKey(ClientConfig.ENABLE_JMX_PROPERTY)) { this.setEnableJmx(props.getBoolean(ClientConfig.ENABLE_JMX_PROPERTY)); } if(props.containsKey(ClientConfig.BOOTSTRAP_URLS_PROPERTY)) { List<String> urls = props.getList(ClientConfig.BOOTSTRAP_URLS_PROPERTY); if(urls.size() > 0) { setHttpBootstrapURL(urls.get(0)); } } if(props.containsKey(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY)) { setMaxR2ConnectionPoolSize(props.getInt(ClientConfig.MAX_TOTAL_CONNECTIONS_PROPERTY, maxR2ConnectionPoolSize)); } if(props.containsKey(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY)) this.setTimeoutMs(props.getLong(ClientConfig.ROUTING_TIMEOUT_MS_PROPERTY, timeoutMs), TimeUnit.MILLISECONDS); // By default, make all the timeouts equal to routing timeout timeoutConfig = new TimeoutConfig(timeoutMs, false); if(props.containsKey(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY)) timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE, props.getInt(ClientConfig.GETALL_ROUTING_TIMEOUT_MS_PROPERTY)); if(props.containsKey(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY)) timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_OP_CODE, props.getInt(ClientConfig.GET_ROUTING_TIMEOUT_MS_PROPERTY)); if(props.containsKey(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY)) { long putTimeoutMs = props.getInt(ClientConfig.PUT_ROUTING_TIMEOUT_MS_PROPERTY); timeoutConfig.setOperationTimeout(VoldemortOpCode.PUT_OP_CODE, putTimeoutMs); // By default, use the same thing for getVersions() also timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, putTimeoutMs); } // of course, if someone overrides it, we will respect that if(props.containsKey(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY)) timeoutConfig.setOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE, props.getInt(ClientConfig.GET_VERSIONS_ROUTING_TIMEOUT_MS_PROPERTY)); if(props.containsKey(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY)) timeoutConfig.setOperationTimeout(VoldemortOpCode.DELETE_OP_CODE, props.getInt(ClientConfig.DELETE_ROUTING_TIMEOUT_MS_PROPERTY)); if(props.containsKey(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY)) timeoutConfig.setPartialGetAllAllowed(props.getBoolean(ClientConfig.ALLOW_PARTIAL_GETALLS_PROPERTY)); }
java
{ "resource": "" }