_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q176400
SQLiteAppender.computeReferenceMask
test
private static short computeReferenceMask(ILoggingEvent event) { short mask = 0; int mdcPropSize = 0; if (event.getMDCPropertyMap() != null) { mdcPropSize = event.getMDCPropertyMap().keySet().size(); } int contextPropSize = 0; if (event.getLoggerContextVO().getPropertyMap() != null) { contextPropSize = event.getLoggerContextVO().getPropertyMap().size(); } if (mdcPropSize > 0 || contextPropSize > 0) { mask = PROPERTIES_EXIST; } if (event.getThrowableProxy() != null) { mask |= EXCEPTION_EXISTS; } return mask; }
java
{ "resource": "" }
q176401
SQLiteAppender.mergePropertyMaps
test
private Map<String, String> mergePropertyMaps(ILoggingEvent event) { Map<String, String> mergedMap = new HashMap<String, String>(); // we add the context properties first, then the event properties, since // we consider that event-specific properties should have priority over // context-wide properties. Map<String, String> loggerContextMap = event.getLoggerContextVO().getPropertyMap(); if (loggerContextMap != null) { mergedMap.putAll(loggerContextMap); } Map<String, String> mdcMap = event.getMDCPropertyMap(); if (mdcMap != null) { mergedMap.putAll(mdcMap); } return mergedMap; }
java
{ "resource": "" }
q176402
SQLiteAppender.insertException
test
private void insertException(SQLiteStatement stmt, String txt, short i, long eventId) throws SQLException { stmt.bindLong(1, eventId); stmt.bindLong(2, i); stmt.bindString(3, txt); stmt.executeInsert(); }
java
{ "resource": "" }
q176403
ElementSelector.getPrefixMatchLength
test
public int getPrefixMatchLength(ElementPath p) { if (p == null) { return 0; } int lSize = this.partList.size(); int rSize = p.partList.size(); // no match possible for empty sets if ((lSize == 0) || (rSize == 0)) { return 0; } int minLen = (lSize <= rSize) ? lSize : rSize; int match = 0; for (int i = 0; i < minLen; i++) { String l = this.partList.get(i); String r = p.partList.get(i); if (equalityCheck(l, r)) { match++; } else { break; } } return match; }
java
{ "resource": "" }
q176404
StatusBase.getEffectiveLevel
test
public synchronized int getEffectiveLevel() { int result = level; int effLevel; Iterator it = iterator(); Status s; while (it.hasNext()) { s = (Status) it.next(); effLevel = s.getEffectiveLevel(); if (effLevel > result) { result = effLevel; } } return result; }
java
{ "resource": "" }
q176405
PropertySetter.setProperty
test
public void setProperty(String name, String value) { if (value == null) { return; } name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); if (prop == null) { addWarn("No such property [" + name + "] in " + objClass.getName() + "."); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); } } }
java
{ "resource": "" }
q176406
PropertySetter.isUnequivocallyInstantiable
test
private boolean isUnequivocallyInstantiable(Class<?> clazz) { if (clazz.isInterface()) { return false; } // checking for constructors would be more elegant, but in // classes without any declared constructors, Class.getConstructor() // returns null. Object o; try { o = clazz.getDeclaredConstructor().newInstance(); if (o != null) { return true; } else { return false; } } catch (InstantiationException e) { return false; } catch (IllegalAccessException e) { return false; } catch (NoSuchMethodException e) { return false; } catch (InvocationTargetException e) { return false; } }
java
{ "resource": "" }
q176407
CopyOnInheritThreadLocal.childValue
test
@Override protected HashMap<String, String> childValue( HashMap<String, String> parentValue) { if (parentValue == null) { return null; } else { return new HashMap<String, String>(parentValue); } }
java
{ "resource": "" }
q176408
IncludeAction.processInclude
test
@Override protected void processInclude(InterpretationContext ic, URL url) throws JoranException { InputStream in = openURL(url); try { if (in != null) { // add URL to watch list in case the "scan" flag is true, in // which case this URL is periodically checked for changes ConfigurationWatchListUtil.addToWatchList(getContext(), url); // parse the include SaxEventRecorder recorder = createRecorder(in, url); recorder.setContext(getContext()); recorder.recordEvents(in); // remove the leading/trailing tags (<included> or <configuration>) trimHeadAndTail(recorder); ic.getJoranInterpreter().getEventPlayer().addEventsDynamically(recorder.getSaxEventList(), this.eventOffset); } } catch (JoranException e) { optionalWarning("Failed processing [" + url.toString() + "]", e); } finally { close(in); } }
java
{ "resource": "" }
q176409
IncludeAction.openURL
test
private InputStream openURL(URL url) { try { return url.openStream(); } catch (IOException e) { optionalWarning("Failed to open [" + url.toString() + "]", e); return null; } }
java
{ "resource": "" }
q176410
IncludeAction.trimHeadAndTail
test
private void trimHeadAndTail(SaxEventRecorder recorder) { List<SaxEvent> saxEventList = recorder.getSaxEventList(); if (saxEventList.size() == 0) { return; } boolean includedTagFound = false; boolean configTagFound = false; // find opening element SaxEvent first = saxEventList.get(0); if (first != null) { String elemName = getEventName(first); includedTagFound = INCLUDED_TAG.equalsIgnoreCase(elemName); configTagFound = CONFIG_TAG.equalsIgnoreCase(elemName); } // if opening element found, remove it, and then remove the closing element if (includedTagFound || configTagFound) { saxEventList.remove(0); final int listSize = saxEventList.size(); if (listSize == 0) { return; } final int lastIndex = listSize - 1; SaxEvent last = saxEventList.get(lastIndex); if (last != null) { String elemName = getEventName(last); if ((includedTagFound && INCLUDED_TAG.equalsIgnoreCase(elemName)) || (configTagFound && CONFIG_TAG.equalsIgnoreCase(elemName))) { saxEventList.remove(lastIndex); } } } }
java
{ "resource": "" }
q176411
ServerSocketReceiver.shouldStart
test
protected boolean shouldStart() { ServerSocket serverSocket = null; try { serverSocket = getServerSocketFactory().createServerSocket( getPort(), getBacklog(), getInetAddress()); ServerListener<RemoteAppenderClient> listener = createServerListener(serverSocket); runner = createServerRunner(listener, getContext().getScheduledExecutorService()); runner.setContext(getContext()); return true; } catch (Exception ex) { addError("server startup error: " + ex, ex); CloseUtil.closeQuietly(serverSocket); return false; } }
java
{ "resource": "" }
q176412
AlgoliaException.isTransient
test
public boolean isTransient() { Throwable cause = getCause(); if (cause == null) { return isServerError(statusCode); } else if (cause instanceof AlgoliaException) { return ((AlgoliaException)cause).isTransient(); } else if (cause instanceof IOException) { return true; } else { return false; } }
java
{ "resource": "" }
q176413
PlacesClient.setDefaultHosts
test
private void setDefaultHosts() { List<String> fallbackHosts = Arrays.asList( "places-1.algolianet.com", "places-2.algolianet.com", "places-3.algolianet.com" ); Collections.shuffle(fallbackHosts); List<String> hosts = new ArrayList<>(fallbackHosts.size() + 1); hosts.add("places-dsn.algolia.net"); hosts.addAll(fallbackHosts); String[] hostsArray = hosts.toArray(new String[hosts.size()]); setReadHosts(hostsArray); setWriteHosts(hostsArray); }
java
{ "resource": "" }
q176414
MirroredIndex.ensureLocalIndex
test
private synchronized void ensureLocalIndex() { if (localIndex == null) { localIndex = new LocalIndex(getClient().getRootDataDir().getAbsolutePath(), getClient().getApplicationID(), getRawIndexName()); } }
java
{ "resource": "" }
q176415
MirroredIndex.sync
test
public void sync() { if (getDataSelectionQueries().length == 0) { throw new IllegalStateException("Cannot sync with empty data selection queries"); } synchronized (this) { if (syncing) return; syncing = true; } getClient().localBuildExecutorService.submit(new Runnable() { @Override public void run() { _sync(); } }); }
java
{ "resource": "" }
q176416
MirroredIndex.syncIfNeeded
test
public void syncIfNeeded() { long currentDate = System.currentTimeMillis(); if (currentDate - mirrorSettings.getLastSyncDate().getTime() > delayBetweenSyncs || mirrorSettings.getQueriesModificationDate().compareTo(mirrorSettings.getLastSyncDate()) > 0) { sync(); } }
java
{ "resource": "" }
q176417
Index.waitTask
test
public JSONObject waitTask(String taskID, long timeToWait) throws AlgoliaException { try { while (true) { JSONObject obj = client.getRequest("/1/indexes/" + encodedIndexName + "/task/" + URLEncoder.encode(taskID, "UTF-8"), /* urlParameters: */ null, false, /* requestOptions: */ null); if (obj.getString("status").equals("published")) { return obj; } try { Thread.sleep(timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait); } catch (InterruptedException e) { continue; } final long newTimeout = timeToWait * 2; timeToWait = (newTimeout <= 0 || newTimeout >= MAX_TIME_MS_TO_WAIT) ? MAX_TIME_MS_TO_WAIT : newTimeout; } } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q176418
OfflineClient.listIndexesOfflineSync
test
private JSONObject listIndexesOfflineSync() throws AlgoliaException { try { final String rootDataPath = getRootDataDir().getAbsolutePath(); final File appDir = getAppDir(); final File[] directories = appDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); JSONObject response = new JSONObject(); JSONArray items = new JSONArray(); if (directories != null) { for (File directory : directories) { final String name = directory.getName(); if (hasOfflineData(name)) { items.put(new JSONObject() .put("name", name) ); // TODO: Do we need other data as in the online API? } } } response.put("items", items); return response; } catch (JSONException e) { throw new RuntimeException(e); // should never happen } }
java
{ "resource": "" }
q176419
AbstractClient._toCharArray
test
private static String _toCharArray(InputStream stream) throws IOException { InputStreamReader is = new InputStreamReader(stream, "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[1000]; int l = 0; while (l >= 0) { builder.append(buf, 0, l); l = is.read(buf); } is.close(); return builder.toString(); }
java
{ "resource": "" }
q176420
AbstractClient._toByteArray
test
private static byte[] _toByteArray(InputStream stream) throws AlgoliaException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int read; byte[] buffer = new byte[1024]; try { while ((read = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); } out.flush(); return out.toByteArray(); } catch (IOException e) { throw new AlgoliaException("Error while reading stream: " + e.getMessage()); } }
java
{ "resource": "" }
q176421
AbstractClient.consumeQuietly
test
private static void consumeQuietly(final HttpURLConnection connection) { try { int read = 0; while (read != -1) { read = connection.getInputStream().read(); } connection.getInputStream().close(); read = 0; while (read != -1) { read = connection.getErrorStream().read(); } connection.getErrorStream().close(); connection.disconnect(); } catch (IOException e) { // no inputStream to close } }
java
{ "resource": "" }
q176422
AbstractClient.hostsThatAreUp
test
private List<String> hostsThatAreUp(List<String> hosts) { List<String> upHosts = new ArrayList<>(); for (String host : hosts) { if (isUpOrCouldBeRetried(host)) { upHosts.add(host); } } return upHosts.isEmpty() ? hosts : upHosts; }
java
{ "resource": "" }
q176423
PlacesQuery.setType
test
public @NonNull PlacesQuery setType(Type type) { if (type == null) { set(KEY_TYPE, null); } else { switch (type) { case CITY: set(KEY_TYPE, "city"); break; case COUNTRY: set(KEY_TYPE, "country"); break; case ADDRESS: set(KEY_TYPE, "address"); break; case BUS_STOP: set(KEY_TYPE, "busStop"); break; case TRAIN_STATION: set(KEY_TYPE, "trainStation"); break; case TOWN_HALL: set(KEY_TYPE, "townhall"); break; case AIRPORT: set(KEY_TYPE, "airport"); break; } } return this; }
java
{ "resource": "" }
q176424
BrowseIterator.start
test
public void start() { if (started) { throw new IllegalStateException(); } started = true; request = index.browseAsync(query, requestOptions, completionHandler); }
java
{ "resource": "" }
q176425
ExpiringCache.put
test
public V put(K key, V value) { V previous = null; synchronized (this) { long timeout = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(expirationTimeout, expirationTimeUnit); final Pair<V, Long> previousPair = lruCache.put(key, new Pair<>(value, timeout)); if (previousPair != null) { previous = previousPair.first; } } return previous; }
java
{ "resource": "" }
q176426
ExpiringCache.get
test
synchronized public V get(K key) { final Pair<V, Long> cachePair = lruCache.get(key); if (cachePair != null && cachePair.first != null) { if (cachePair.second > System.currentTimeMillis()) { return cachePair.first; } else { lruCache.remove(key); } } return null; }
java
{ "resource": "" }
q176427
ThreadSpawner.awaitCompletion
test
public void awaitCompletion() { for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { throw rethrow(e); } } if (caughtException != null) { throw rethrow(caughtException); } }
java
{ "resource": "" }
q176428
VersionUtils.versionCompare
test
public static int versionCompare(String firstVersionString, String secondVersionString) { String[] firstVersion = parseVersionString(firstVersionString); String[] secondVersion = parseVersionString(secondVersionString); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < firstVersion.length && i < secondVersion.length && firstVersion[i].equals(secondVersion[i])) { i++; } if (i < firstVersion.length && i < secondVersion.length) { // compare first non-equal ordinal number int diff = Integer.valueOf(firstVersion[i]).compareTo(Integer.valueOf(secondVersion[i])); return Integer.signum(diff); } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer.signum(firstVersion.length - secondVersion.length); } }
java
{ "resource": "" }
q176429
ExceptionReporter.report
test
public static void report(String testId, Throwable cause) { if (cause == null) { LOGGER.fatal("Can't call report with a null exception"); return; } long exceptionCount = FAILURE_ID.incrementAndGet(); if (exceptionCount > MAX_EXCEPTION_COUNT) { LOGGER.warn("Exception #" + exceptionCount + " detected. The maximum number of exceptions has been exceeded, so it" + " won't be reported to the Agent.", cause); return; } LOGGER.warn("Exception #" + exceptionCount + " detected", cause); String targetFileName = exceptionCount + ".exception"; File dir = getUserDir(); File tmpFile = new File(dir, targetFileName + ".tmp"); try { if (!tmpFile.createNewFile()) { throw new IOException("Could not create tmp file: " + tmpFile.getAbsolutePath()); } } catch (IOException e) { LOGGER.fatal("Could not report exception; this means that this exception is not visible to the coordinator", e); return; } writeText(testId + NEW_LINE + throwableToString(cause), tmpFile); File file = new File(dir, targetFileName); LOGGER.info(file.getAbsolutePath()); rename(tmpFile, file); }
java
{ "resource": "" }
q176430
FileUtils.copyDirectory
test
public static void copyDirectory(File src, File target) { checkNotNull(src, "src can't be null"); checkNotNull(target, "target can't be null"); File[] files = src.listFiles(); if (files == null) { return; } for (File srcFile : files) { if (srcFile.isDirectory()) { File targetChild = new File(target, srcFile.getName()); ensureExistingDirectory(targetChild); copyDirectory(srcFile, targetChild); } else { copyFileToDirectory(srcFile, target); } } }
java
{ "resource": "" }
q176431
SimulatorProperties.init
test
public SimulatorProperties init(File file) { if (file == null) { // if no file is explicitly given, we look in the working directory file = new File(getUserDir(), PROPERTIES_FILE_NAME); if (!file.exists()) { LOGGER.info(format("Found no %s in working directory, relying on default properties", PROPERTIES_FILE_NAME)); return null; } } LOGGER.info(format("Loading additional %s: %s", PROPERTIES_FILE_NAME, file.getAbsolutePath())); check(file); load(file, false); return this; }
java
{ "resource": "" }
q176432
ReflectionUtils.getStaticFieldValue
test
public static <E> E getStaticFieldValue(Class clazz, String fieldName, Class fieldType) { Field field = getField(clazz, fieldName, fieldType); if (field == null) { throw new ReflectionException(format("Field %s.%s is not found", clazz.getName(), fieldName)); } field.setAccessible(true); return getFieldValue0(null, field, clazz.getName(), fieldName); }
java
{ "resource": "" }
q176433
ReflectionUtils.getMethodByName
test
public static Method getMethodByName(Class clazz, String methodName) { for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals(methodName)) { return method; } } return null; }
java
{ "resource": "" }
q176434
FormatUtils.formatPercentage
test
public static String formatPercentage(long value, long baseValue) { double percentage = (baseValue > 0 ? (ONE_HUNDRED * value) / baseValue : 0); return formatDouble(percentage, PERCENTAGE_FORMAT_LENGTH); }
java
{ "resource": "" }
q176435
FormatUtils.formatDouble
test
public static String formatDouble(double number, int length) { return padLeft(format(Locale.US, "%,.2f", number), length); }
java
{ "resource": "" }
q176436
FormatUtils.formatLong
test
public static String formatLong(long number, int length) { return padLeft(format(Locale.US, "%,d", number), length); }
java
{ "resource": "" }
q176437
JsonProtocol.readJsonSyntaxChar
test
protected void readJsonSyntaxChar(byte[] b) throws IOException { byte ch = reader.read(); if (ch != b[0]) { throw new ProtocolException("Unexpected character:" + (char) ch); } }
java
{ "resource": "" }
q176438
JsonProtocol.hexVal
test
private static byte hexVal(byte ch) throws IOException { if ((ch >= '0') && (ch <= '9')) { return (byte) ((char) ch - '0'); } else if ((ch >= 'a') && (ch <= 'f')) { return (byte) ((char) ch - 'a' + 10); } else { throw new ProtocolException("Expected hex character"); } }
java
{ "resource": "" }
q176439
JsonProtocol.writeJsonString
test
private void writeJsonString(byte[] b) throws IOException { context.write(); transport.write(QUOTE); int len = b.length; for (int i = 0; i < len; i++) { if ((b[i] & 0x00FF) >= 0x30) { if (b[i] == BACKSLASH[0]) { transport.write(BACKSLASH); transport.write(BACKSLASH); } else { transport.write(b, i, 1); } } else { tmpbuf[0] = JSON_CHAR_TABLE[b[i]]; if (tmpbuf[0] == 1) { transport.write(b, i, 1); } else if (tmpbuf[0] > 1) { transport.write(BACKSLASH); transport.write(tmpbuf, 0, 1); } else { transport.write(ESCSEQ); tmpbuf[0] = hexChar((byte) (b[i] >> 4)); tmpbuf[1] = hexChar(b[i]); transport.write(tmpbuf, 0, 2); } } } transport.write(QUOTE); }
java
{ "resource": "" }
q176440
JsonProtocol.writeJsonInteger
test
private void writeJsonInteger(long num) throws IOException { context.write(); String str = Long.toString(num); boolean escapeNum = context.escapeNum(); if (escapeNum) { transport.write(QUOTE); } try { byte[] buf = str.getBytes("UTF-8"); transport.write(buf); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } if (escapeNum) { transport.write(QUOTE); } }
java
{ "resource": "" }
q176441
JsonProtocol.writeJsonDouble
test
private void writeJsonDouble(double num) throws IOException { context.write(); String str = Double.toString(num); boolean special = false; switch (str.charAt(0)) { case 'N': // NaN case 'I': // Infinity special = true; break; case '-': if (str.charAt(1) == 'I') { // -Infinity special = true; } break; default: break; } boolean escapeNum = special || context.escapeNum(); if (escapeNum) { transport.write(QUOTE); } try { byte[] b = str.getBytes("UTF-8"); transport.write(b, 0, b.length); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } if (escapeNum) { transport.write(QUOTE); } }
java
{ "resource": "" }
q176442
JsonProtocol.readJsonString
test
private ByteString readJsonString(boolean skipContext) throws IOException { Buffer buffer = new Buffer(); ArrayList<Character> codeunits = new ArrayList<>(); if (!skipContext) { context.read(); } readJsonSyntaxChar(QUOTE); while (true) { byte ch = reader.read(); if (ch == QUOTE[0]) { break; } if (ch == ESCSEQ[0]) { ch = reader.read(); if (ch == ESCSEQ[1]) { transport.read(tmpbuf, 0, 4); short cu = (short) ( ((short) hexVal(tmpbuf[0]) << 12) + ((short) hexVal(tmpbuf[1]) << 8) + ((short) hexVal(tmpbuf[2]) << 4) + (short) hexVal(tmpbuf[3])); try { if (Character.isHighSurrogate((char) cu)) { if (codeunits.size() > 0) { throw new ProtocolException("Expected low surrogate char"); } codeunits.add((char) cu); } else if (Character.isLowSurrogate((char) cu)) { if (codeunits.size() == 0) { throw new ProtocolException("Expected high surrogate char"); } codeunits.add((char) cu); buffer.write(new String(new int[]{codeunits.get(0), codeunits.get(1)}, 0, 2) .getBytes("UTF-8")); codeunits.clear(); } else { buffer.write(new String(new int[]{cu}, 0, 1).getBytes("UTF-8")); } continue; } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } catch (IOException ex) { throw new ProtocolException("Invalid unicode sequence"); } } else { int off = ESCAPE_CHARS.indexOf(ch); if (off == -1) { throw new ProtocolException("Expected control char"); } ch = ESCAPE_CHAR_VALS[off]; } } buffer.write(new byte[]{ch}); } return buffer.readByteString(); }
java
{ "resource": "" }
q176443
JsonProtocol.readJsonNumericChars
test
private String readJsonNumericChars() throws IOException { StringBuilder strbld = new StringBuilder(); while (true) { byte ch = reader.peek(); if (!isJsonNumeric(ch)) { break; } strbld.append((char) reader.read()); } return strbld.toString(); }
java
{ "resource": "" }
q176444
JsonProtocol.readJsonInteger
test
private long readJsonInteger() throws IOException { context.read(); if (context.escapeNum()) { readJsonSyntaxChar(QUOTE); } String str = readJsonNumericChars(); if (context.escapeNum()) { readJsonSyntaxChar(QUOTE); } try { return Long.valueOf(str); } catch (NumberFormatException ex) { throw new ProtocolException("Bad data encountered in numeric data"); } }
java
{ "resource": "" }
q176445
JsonProtocol.readJsonDouble
test
private double readJsonDouble() throws IOException { context.read(); if (reader.peek() == QUOTE[0]) { ByteString str = readJsonString(true); double dub = Double.valueOf(str.utf8()); if (!context.escapeNum() && !Double.isNaN(dub) && !Double.isInfinite(dub)) { // Throw exception -- we should not be in a string in this case throw new ProtocolException("Numeric data unexpectedly quoted"); } return dub; } else { if (context.escapeNum()) { // This will throw - we should have had a quote if escapeNum == true readJsonSyntaxChar(QUOTE); } try { return Double.valueOf(readJsonNumericChars()); } catch (NumberFormatException ex) { throw new ProtocolException("Bad data encountered in numeric data"); } } }
java
{ "resource": "" }
q176446
JsonProtocol.readJsonBase64
test
private ByteString readJsonBase64() throws IOException { ByteString str = readJsonString(false); return ByteString.decodeBase64(str.utf8()); }
java
{ "resource": "" }
q176447
ClientBase.execute
test
protected final Object execute(MethodCall<?> methodCall) throws Exception { if (!running.get()) { throw new IllegalStateException("Cannot write to a closed service client"); } try { return invokeRequest(methodCall); } catch (ServerException e) { throw e.thriftException; } }
java
{ "resource": "" }
q176448
ClientBase.invokeRequest
test
final Object invokeRequest(MethodCall<?> call) throws Exception { boolean isOneWay = call.callTypeId == TMessageType.ONEWAY; int sid = seqId.incrementAndGet(); protocol.writeMessageBegin(call.name, call.callTypeId, sid); call.send(protocol); protocol.writeMessageEnd(); protocol.flush(); if (isOneWay) { // No response will be received return null; } MessageMetadata metadata = protocol.readMessageBegin(); if (metadata.seqId != sid) { throw new ThriftException( ThriftException.Kind.BAD_SEQUENCE_ID, "Unrecognized sequence ID"); } if (metadata.type == TMessageType.EXCEPTION) { ThriftException e = ThriftException.read(protocol); protocol.readMessageEnd(); throw new ServerException(e); } else if (metadata.type != TMessageType.REPLY) { throw new ThriftException( ThriftException.Kind.INVALID_MESSAGE_TYPE, "Invalid message type: " + metadata.type); } if (metadata.seqId != seqId.get()) { throw new ThriftException( ThriftException.Kind.BAD_SEQUENCE_ID, "Out-of-order response"); } if (!metadata.name.equals(call.name)) { throw new ThriftException( ThriftException.Kind.WRONG_METHOD_NAME, "Unexpected method name in reply; expected " + call.name + " but received " + metadata.name); } try { Object result = call.receive(protocol, metadata); protocol.readMessageEnd(); return result; } catch (Exception e) { if (e instanceof Struct) { // Business as usual protocol.readMessageEnd(); } throw e; } }
java
{ "resource": "" }
q176449
AsyncClientBase.enqueue
test
protected void enqueue(MethodCall<?> methodCall) { if (!running.get()) { throw new IllegalStateException("Cannot write to a closed service client"); } if (!pendingCalls.offer(methodCall)) { // This should never happen with an unbounded queue throw new IllegalStateException("Call queue is full"); } }
java
{ "resource": "" }
q176450
PlatformUtils.getResourceFromFSPath
test
public static IFile getResourceFromFSPath(String location) { return Activator.getDefault().getWorkspace(). getRoot().getFileForLocation(new Path(location)); }
java
{ "resource": "" }
q176451
PlatformUtils.updateDecoration
test
public static void updateDecoration() { final IWorkbench workbench = Activator.getDefault().getWorkbench(); workbench.getDisplay().syncExec(new Runnable() { public void run() { IDecoratorManager manager = workbench.getDecoratorManager(); manager.update(GuvnorDecorator.DECORATOR_ID); } }); }
java
{ "resource": "" }
q176452
PlatformUtils.refreshRepositoryView
test
public static void refreshRepositoryView() { IWorkbenchWindow activeWindow = Activator.getDefault(). getWorkbench().getActiveWorkbenchWindow(); // If there is no active workbench window, then there can be no Repository view if (activeWindow == null) { return; } // If there is no active workbench page, then there can be no Repository view IWorkbenchPage page = activeWindow.getActivePage(); if (page == null) { return; } RepositoryView view = (RepositoryView)page.findView(IGuvnorConstants.REPVIEW_ID); if (view != null) { view.refresh(); } }
java
{ "resource": "" }
q176453
PlatformUtils.getResourceHistoryView
test
public static ResourceHistoryView getResourceHistoryView() throws Exception { IWorkbenchWindow activeWindow = Activator.getDefault(). getWorkbench().getActiveWorkbenchWindow(); // If there is no active workbench window, then there can be no Repository History view if (activeWindow == null) { return null; } // If there is no active workbench page, then there can be no Repository History view IWorkbenchPage page = activeWindow.getActivePage(); if (page == null) { return null; } return (ResourceHistoryView)page.showView(IGuvnorConstants.RESHISTORYVIEW_ID); }
java
{ "resource": "" }
q176454
PlatformUtils.openEditor
test
public static void openEditor(String contents, String name) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IStorage storage = new StringStorage(contents, name); IStorageEditorInput input = new StringInput(storage); IWorkbenchPage page = window.getActivePage(); IEditorDescriptor desc = PlatformUI.getWorkbench(). getEditorRegistry().getDefaultEditor(name); // If there is no editor associated with the given file name, we'll just // use the eclipse text editor as a default String editorId = desc != null?desc.getId():"org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$ try { if (page != null) { page.openEditor(input, editorId); } } catch (Exception e) { Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true); } }
java
{ "resource": "" }
q176455
PlatformUtils.reportAuthenticationFailure
test
public static void reportAuthenticationFailure() { Display display = PlatformUI.getWorkbench().getDisplay(); display.asyncExec(new Runnable() { public void run() { Display display = Display.getCurrent(); Shell shell = display.getActiveShell(); MessageDialog.openError(shell, Messages.getString("login.failure.dialog.caption"), //$NON-NLS-1$ Messages.getString("login.failure.dialog.message")); //$NON-NLS-1$ } }); }
java
{ "resource": "" }
q176456
PlatformUtils.promptForAuthentication
test
public AuthPromptResults promptForAuthentication(final String server) { Display display = PlatformUI.getWorkbench().getDisplay(); AuthPromptRunnable op = new AuthPromptRunnable(server); display.syncExec(op); return op.getResults(); }
java
{ "resource": "" }
q176457
KieNavigatorView.createDefaultPage
test
private Control createDefaultPage(FormToolkit kit) { Form form = kit.createForm(book); Composite body = form.getBody(); GridLayout layout = new GridLayout(2, false); body.setLayout(layout); Link hlink = new Link(body, SWT.NONE); hlink.setText("<a>Use the Servers View to create a new server...</a>"); hlink.setBackground(book.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); GridData gd = new GridData(SWT.LEFT, SWT.FILL, true, false); hlink.setLayoutData(gd); hlink.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // show Servers View ViewUtils.showServersView(); } }); // Create the context menu for the default page final CommonViewer commonViewer = this.getCommonViewer(); if (commonViewer != null) { ICommonViewerSite commonViewerSite = CommonViewerSiteFactory.createCommonViewerSite(this.getViewSite()); if (commonViewerSite != null) { // Note: actionService cannot be null final NavigatorActionService actionService = new NavigatorActionService(commonViewerSite, commonViewer, commonViewer.getNavigatorContentService()); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { ISelection selection = commonViewer.getSelection(); actionService.setContext(new ActionContext(selection)); actionService.fillContextMenu(mgr); } }); Menu menu = menuManager.createContextMenu(body); // It is necessary to set the menu in two places: // 1. The white space in the server view // 2. The text and link in the server view. If this menu is not // set, if the // user right clicks on the text or uses shortcut keys to open // the context menu, // the context menu will not come up body.setMenu(menu); hlink.setMenu(menu); } else { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, // "The commonViewerSite is null"); // } } } else { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, "The commonViewer is null"); // } } return form; }
java
{ "resource": "" }
q176458
KieNavigatorView.startThread
test
protected void startThread() { if (animationActive) return; stopAnimation = false; final Display display = treeViewer == null ? Display.getDefault() : treeViewer.getControl().getDisplay(); final int SLEEP = 200; final Runnable[] animator = new Runnable[1]; animator[0] = new Runnable() { public void run() { if (!stopAnimation) { try { int size = 0; String[] servers; synchronized (starting) { size = starting.size(); servers = new String[size]; starting.toArray(servers); } for (int i = 0; i < size; i++) { IServer server = ServerCore.findServer(servers[i]); if (server != null) { // ServerDecorator.animate(); treeViewer.update(server, new String[] { "ICON" }); } } } catch (Exception e) { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, // "Error in Servers view animation", e); // } } display.timerExec(SLEEP, animator[0]); } } }; Display.getDefault().asyncExec(new Runnable() { public void run() { display.timerExec(SLEEP, animator[0]); } }); }
java
{ "resource": "" }
q176459
PropertyBehavior.setIsKeepAllAlive
test
public void setIsKeepAllAlive(boolean isKeepAllAlive) { Element child = getFirstChild(root, childNames); boolean isAlreadyKeepAllAlive = false; if (isDAVElement(child, "keepalive")) //$NON-NLS-1$ isAlreadyKeepAllAlive = "*".equals(getFirstText(child)); //$NON-NLS-1$ if (isKeepAllAlive) { if (!isAlreadyKeepAllAlive) { if (child != null) root.removeChild(child); appendChild(root, "keepalive", "*"); //$NON-NLS-1$ //$NON-NLS-2$ } } else if (isAlreadyKeepAllAlive) root.removeChild(child); }
java
{ "resource": "" }
q176460
PropertyBehavior.setIsOmit
test
public void setIsOmit(boolean isOmit) { Element child = getFirstChild(root, childNames); boolean isAlreadyOmit = isDAVElement(child, "omit"); //$NON-NLS-1$ if (isOmit) { if (!isAlreadyOmit) { if (child != null) root.removeChild(child); appendChild(root, "omit"); //$NON-NLS-1$ } } else if (isAlreadyOmit) root.removeChild(child); }
java
{ "resource": "" }
q176461
ActiveLock.setOwner
test
public Owner setOwner() { Element owner = setChild(root, "owner", childNames, false); //$NON-NLS-1$ Owner result = null; try { result = new Owner(owner); } catch (MalformedElementException e) { Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$ } return result; }
java
{ "resource": "" }
q176462
ConditionTerm.addConditionFactor
test
public void addConditionFactor(ConditionFactor factor) throws WebDAVException { if (conditionFactors.contains(factor)) throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseDuplicateEntry")); //$NON-NLS-1$ conditionFactors.addElement(factor); }
java
{ "resource": "" }
q176463
ConditionTerm.create
test
public static ConditionTerm create(StreamTokenizer tokenizer) throws WebDAVException { ConditionTerm term = new ConditionTerm(); try { int token = tokenizer.ttype; if (token == '(') token = tokenizer.nextToken(); else throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), "(")); //$NON-NLS-1$ //$NON-NLS-2$ while (token == StreamTokenizer.TT_WORD || token == '<' || token == '[') { term.addConditionFactor(ConditionFactor.create(tokenizer)); token = tokenizer.ttype; } if (token == ')') token = tokenizer.nextToken(); else throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), ")")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException exc) { // ignore or log? } if (!term.getConditionFactors().hasMoreElements()) throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissingStateOrEntity")); //$NON-NLS-1$ return term; }
java
{ "resource": "" }
q176464
ConditionTerm.matches
test
public boolean matches(ConditionTerm conditionTerm) { int numberOfItemsToMatch = 0; boolean match = true; Enumeration factors = getConditionFactors(); while (match && factors.hasMoreElements()) { ConditionFactor factor = (ConditionFactor) factors.nextElement(); if (factor.not()) { match = !conditionTerm.contains(factor); } else { match = conditionTerm.contains(factor); numberOfItemsToMatch++; } } match = match && numberOfItemsToMatch == conditionTerm.numberOfFactors(); return match; }
java
{ "resource": "" }
q176465
DSLAdapter.getDSLContent
test
public static Reader getDSLContent(String ruleSource, IResource input) throws CoreException { String dslFileName = findDSLConfigName( ruleSource, input ); if (dslFileName == null) { return null; } IResource res = findDSLResource( input, dslFileName ); if (res instanceof IFile) { IFile dslConf = (IFile) res; if (dslConf.exists()) { return new InputStreamReader(dslConf.getContents()); } } return null; }
java
{ "resource": "" }
q176466
DSLAdapter.loadConfig
test
private void loadConfig(IFile input) { IResource res = findDSLResource( input, dslConfigName ); if (res instanceof IFile) { IFile dslConf = (IFile) res; if (dslConf.exists()) { InputStream stream = null; try { stream = dslConf.getContents(); readConfig( stream ); valid = true; } catch ( Exception e ) { throw new IllegalStateException("Unable to open DSL config file. (Exception: " + e.getMessage() + ")"); } finally { closeStream( stream ); } } } }
java
{ "resource": "" }
q176467
DSLAdapter.readConfig
test
void readConfig(InputStream stream) throws IOException, CoreException { DSLTokenizedMappingFile file = new DSLTokenizedMappingFile(); file.parseAndLoad(new InputStreamReader(stream)); DSLMapping grammar = file.getMapping(); List<DSLMappingEntry> conditions = grammar.getEntries( DSLMappingEntry.CONDITION ); List<DSLMappingEntry> consequences = grammar.getEntries( DSLMappingEntry.CONSEQUENCE ); conditionProposals = buildProposals(conditions); consequenceProposals = buildProposals(consequences); dslTree.buildTree(grammar); }
java
{ "resource": "" }
q176468
RuleHelperActionDelegate.getMenu
test
public Menu getMenu(Control parent) { setMenu( new Menu( parent ) ); final Shell shell = parent.getShell(); addProjectWizard( menu, shell ); addRuleWizard( menu, shell ); addDSLWizard( menu, shell ); addDTWizard( menu, shell ); return menu; }
java
{ "resource": "" }
q176469
MultiStatus.addResponse
test
public ResponseBody addResponse() { Element response = addChild(root, "response", childNames, true); //$NON-NLS-1$ try { return new ResponseBody(response); } catch (MalformedElementException e) { Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$ return null; // Never reached. } }
java
{ "resource": "" }
q176470
HrefSet.addHref
test
public void addHref(String href) { String encodedHref = encodeHref(href); if (isDuplicate(encodedHref)) return; appendChild(root, "href", encodedHref); //$NON-NLS-1$ }
java
{ "resource": "" }
q176471
HrefSet.insertHrefBefore
test
public void insertHrefBefore(String newHref, String refHref) { String refHrefEncoded = encodeHref(refHref); String newHrefEncoded = encodeHref(newHref); if (isDuplicate(newHrefEncoded)) return; Element child = getFirstChild(root, "href"); //$NON-NLS-1$ while (child != null) { if (refHrefEncoded.equals(getFirstText(child))) { insertBefore(child, "href", newHrefEncoded); //$NON-NLS-1$ return; } child = getNextSibling(child, "href"); //$NON-NLS-1$ } Assert.isTrue(false, Policy.bind("assert.noHrefRef")); //$NON-NLS-1$ }
java
{ "resource": "" }
q176472
HrefSet.removeHref
test
public void removeHref(String href) { String encodedHref = encodeHref(href); Element child = getFirstChild(root, "href"); //$NON-NLS-1$ while (child != null) { if (encodedHref.equals(getFirstText(child))) { root.removeChild(child); return; } child = getNextSibling(child, "href"); //$NON-NLS-1$ } }
java
{ "resource": "" }
q176473
ResponseBody.addPropStat
test
public PropStat addPropStat() { Element firstHref = getFirstChild(root, "href"); //$NON-NLS-1$ Assert.isTrue(firstHref == null || getNextSibling(firstHref, new String[] {"href", "status"}) == null); //$NON-NLS-1$ //$NON-NLS-2$ Element element = addChild(root, "propstat", fgNamesPropStat, false); //$NON-NLS-1$ try { return new PropStat(element); } catch (MalformedElementException e) { Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$ return null; // Never reached. } }
java
{ "resource": "" }
q176474
ResponseBody.getHref
test
public String getHref() throws MalformedElementException { String href = getChildText(root, "href", true); //$NON-NLS-1$ ensureNotNull(Policy.bind("ensure.missingHrefElmt"), href); //$NON-NLS-1$ return decodeHref(href); }
java
{ "resource": "" }
q176475
ResponseBody.getStatus
test
public String getStatus() throws MalformedElementException { Element status = getFirstChild(root, "status"); //$NON-NLS-1$ ensureNotNull(Policy.bind("ensure.missingStatusElmt"), status); //$NON-NLS-1$ return getFirstText(status); }
java
{ "resource": "" }
q176476
DebugUtil.getStackFrame
test
public static IJavaStackFrame getStackFrame(IValue value) throws CoreException { IStatusHandler handler = getStackFrameProvider(); if (handler != null) { IJavaStackFrame stackFrame = (IJavaStackFrame) handler .handleStatus(fgNeedStackFrame, value); if (stackFrame != null) { return stackFrame; } } IDebugTarget target = value.getDebugTarget(); IJavaDebugTarget javaTarget = (IJavaDebugTarget) target .getAdapter(IJavaDebugTarget.class); if (javaTarget != null) { IThread[] threads = javaTarget.getThreads(); for (int i = 0; i < threads.length; i++) { IThread thread = threads[i]; if (thread.isSuspended()) { return (IJavaStackFrame) thread.getTopStackFrame(); } } } return null; }
java
{ "resource": "" }
q176477
RuleCompletionProcessor.isSubtypeOf
test
private boolean isSubtypeOf(String class1, String class2) { if (class1 == null || class2 == null) { return false; } class1 = convertToNonPrimitiveClass(class1); class2 = convertToNonPrimitiveClass(class2); // TODO add code to take primitive types into account ClassTypeResolver resolver = new ClassTypeResolver(getUniqueImports(), ProjectClassLoader.getProjectClassLoader(getEditor())); try { Class<?> clazz1 = resolver.resolveType(class1); Class<?> clazz2 = resolver.resolveType(class2); if (clazz1 == null || clazz2 == null) { return false; } return clazz2.isAssignableFrom(clazz1); } catch (ClassNotFoundException exc) { return false; } }
java
{ "resource": "" }
q176478
RuleCompletionProcessor.containsProposal
test
public static boolean containsProposal(final Collection<ICompletionProposal> proposals, String newProposal) { for (ICompletionProposal prop : proposals) { String displayString = prop.getDisplayString(); String[] existings = displayString.split(" "); if (existings.length == 0) { continue; } String[] newProposals = newProposal.split(" "); if (newProposals.length == 0) { continue; } if (existings[0].equals(newProposals[0])) { return true; } } return false; }
java
{ "resource": "" }
q176479
ElementEditor.cloneNode
test
public static Node cloneNode(Document document, Node node) { Node nodeClone = null; switch (node.getNodeType()) { case Node.ELEMENT_NODE : { nodeClone = document.createElement(((Element) node).getTagName()); NamedNodeMap namedNodeMap = node.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); ++i) { Attr attr = (Attr) namedNodeMap.item(i); Attr attrClone = document.createAttribute(attr.getName()); attrClone.setValue(attr.getValue()); ((Element) nodeClone).setAttributeNode(attrClone); } } break; case Node.TEXT_NODE : nodeClone = document.createTextNode(((CharacterData) node).getData()); break; case Node.CDATA_SECTION_NODE : nodeClone = document.createCDATASection(((CharacterData) node).getData()); break; case Node.ENTITY_REFERENCE_NODE : nodeClone = document.createEntityReference(node.getNodeName()); break; case Node.PROCESSING_INSTRUCTION_NODE : nodeClone = document.createProcessingInstruction(((ProcessingInstruction) node).getTarget(), ((ProcessingInstruction) node).getData()); break; case Node.COMMENT_NODE : nodeClone = document.createComment(((CharacterData) node).getData()); break; case Node.DOCUMENT_FRAGMENT_NODE : nodeClone = document.createDocumentFragment(); break; case Node.DOCUMENT_NODE : case Node.DOCUMENT_TYPE_NODE : case Node.NOTATION_NODE : case Node.ATTRIBUTE_NODE : case Node.ENTITY_NODE : Assert.isTrue(false, Policy.bind("assert.notSupported")); //$NON-NLS-1$ break; default : Assert.isTrue(false, Policy.bind("assert.unknownNodeType")); //$NON-NLS-1$ } return nodeClone; }
java
{ "resource": "" }
q176480
RequestInputStream.reset
test
public void reset() throws IOException { if (file == null) { ((ByteArrayInputStream) is).reset(); } else { if (fos != null) { while (skip(4096) > 0); fos.close(); fos = null; if (length == -1) { length = totalBytesRead; } } is.close(); is = new FileInputStream(file); } totalBytesRead = 0; }
java
{ "resource": "" }
q176481
AbstractRuleEditor.createActions
test
protected void createActions() { super.createActions(); IAction a = new TextOperationAction(RuleEditorMessages .getResourceBundle(), "ContentAssistProposal.", this, ISourceViewer.CONTENTASSIST_PROPOSALS); a .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", a); a = new TextOperationAction( RuleEditorMessages.getResourceBundle(), "ContentAssistTip.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ a .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistTip", a); a = new ToggleBreakpointAction(getSite().getPart() , null, getVerticalRuler()); setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, a); }
java
{ "resource": "" }
q176482
GraphicalVertex.addConnection
test
public void addConnection(Connection conn) { if ( conn == null || conn.getSource() == conn.getTarget() ) { throw new IllegalArgumentException(); } if ( conn.getSource() == this ) { sourceConnections.add( conn ); firePropertyChange( SOURCE_CONNECTIONS_PROP, null, conn ); } else if ( conn.getTarget() == this ) { targetConnections.add( conn ); firePropertyChange( TARGET_CONNECTIONS_PROP, null, conn ); } }
java
{ "resource": "" }
q176483
GraphicalVertex.getPropertyValue
test
public Object getPropertyValue(Object propertyId) { if ( XPOS_PROP.equals( propertyId ) ) { return Integer.toString( location.x ); } if ( YPOS_PROP.equals( propertyId ) ) { return Integer.toString( location.y ); } if ( HEIGHT_PROP.equals( propertyId ) ) { return Integer.toString( size.height ); } if ( WIDTH_PROP.equals( propertyId ) ) { return Integer.toString( size.width ); } return null; }
java
{ "resource": "" }
q176484
GraphicalVertex.removeConnection
test
public void removeConnection(Connection conn) { if ( conn == null ) { throw new IllegalArgumentException(); } if ( conn.getSource() == this ) { sourceConnections.remove( conn ); firePropertyChange( SOURCE_CONNECTIONS_PROP, null, conn ); } else if ( conn.getTarget() == this ) { targetConnections.remove( conn ); firePropertyChange( TARGET_CONNECTIONS_PROP, null, conn ); } }
java
{ "resource": "" }
q176485
GraphicalVertex.setLocation
test
public void setLocation(Point newLocation) { if ( newLocation == null ) { throw new IllegalArgumentException(); } location.setLocation( newLocation ); firePropertyChange( LOCATION_PROP, null, location ); }
java
{ "resource": "" }
q176486
GraphicalVertex.setPropertyValue
test
public void setPropertyValue(Object propertyId, Object value) { if ( XPOS_PROP.equals( propertyId ) ) { int x = Integer.parseInt( (String) value ); setLocation( new Point( x, location.y ) ); } else if ( YPOS_PROP.equals( propertyId ) ) { int y = Integer.parseInt( (String) value ); setLocation( new Point( location.x, y ) ); } else if ( HEIGHT_PROP.equals( propertyId ) ) { int height = Integer.parseInt( (String) value ); setSize( new Dimension( size.width, height ) ); } else if ( WIDTH_PROP.equals( propertyId ) ) { int width = Integer.parseInt( (String) value ); setSize( new Dimension( width, size.height ) ); } }
java
{ "resource": "" }
q176487
GraphicalVertex.setSize
test
public void setSize(Dimension newSize) { if ( newSize != null ) { size.setSize( newSize ); firePropertyChange( SIZE_PROP, null, size ); } }
java
{ "resource": "" }
q176488
GraphicalVertex.dumpConstraints
test
public static String dumpConstraints(final Constraint[] constraints) { if ( constraints == null ) { return null; } final StringBuffer buffer = new StringBuffer(); for ( int i = 0, length = constraints.length; i < length; i++ ) { buffer.append( constraints[i].toString() + "<br>" ); } return buffer.toString(); }
java
{ "resource": "" }
q176489
SupportedLock.addLockEntry
test
public LockEntry addLockEntry() { Element lockentry = addChild(root, "lockentry", childNames, false); //$NON-NLS-1$ Element locktype = appendChild(lockentry, "locktype"); //$NON-NLS-1$ appendChild(locktype, "write"); //$NON-NLS-1$ LockEntry result = null; try { result = new LockEntry(lockentry); } catch (MalformedElementException e) { Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$ } return result; }
java
{ "resource": "" }
q176490
ReteGraph.addChild
test
public boolean addChild(BaseVertex vertex) { if ( vertex != null && vertices.add( vertex ) ) { firePropertyChange( PROP_CHILD_ADDED, null, vertex ); return true; } return false; }
java
{ "resource": "" }
q176491
ReteGraph.removeChild
test
public boolean removeChild(BaseVertex vertex) { if ( vertex != null && vertices.remove( vertex ) ) { firePropertyChange( PROP_CHILD_REMOVED, null, vertex ); return true; } return false; }
java
{ "resource": "" }
q176492
DroolsEclipsePlugin.start
test
public void start(BundleContext context) throws Exception { super.start( context ); IPreferenceStore preferenceStore = getPreferenceStore(); useCachePreference = preferenceStore.getBoolean( IDroolsConstants.CACHE_PARSED_RULES ); preferenceStore.addPropertyChangeListener( new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if ( IDroolsConstants.CACHE_PARSED_RULES.equals( event.getProperty() ) ) { useCachePreference = ((Boolean) event.getNewValue()).booleanValue(); if ( !useCachePreference ) { clearCache(); } } } } ); }
java
{ "resource": "" }
q176493
DroolsEclipsePlugin.stop
test
public void stop(BundleContext context) throws Exception { super.stop( context ); plugin = null; resourceBundle = null; parsedRules = null; compiledRules = null; processInfos = null; processInfosById = null; for (Color color: colors.values()) { color.dispose(); } }
java
{ "resource": "" }
q176494
DroolsEclipsePlugin.getResourceString
test
public static String getResourceString(String key) { ResourceBundle bundle = DroolsEclipsePlugin.getDefault().getResourceBundle(); try { return (bundle != null) ? bundle.getString( key ) : key; } catch ( MissingResourceException e ) { return key; } }
java
{ "resource": "" }
q176495
DroolsEclipsePlugin.getResourceBundle
test
public ResourceBundle getResourceBundle() { try { if ( resourceBundle == null ) resourceBundle = ResourceBundle.getBundle( "droolsIDE.DroolsIDEPluginResources" ); } catch ( MissingResourceException x ) { resourceBundle = null; } return resourceBundle; }
java
{ "resource": "" }
q176496
DroolsEclipsePlugin.getRuleBuilderFormColors
test
public FormColors getRuleBuilderFormColors(Display display) { if ( ruleBuilderFormColors == null ) { ruleBuilderFormColors = new FormColors( display ); ruleBuilderFormColors.markShared(); } return ruleBuilderFormColors; }
java
{ "resource": "" }
q176497
DateTime.setDateTime
test
public void setDateTime(String date) { String[] patterns = {RFC_1123_PATTERN, ISO_8601_UTC_PATTERN, ISO_8601_UTC_MILLIS_PATTERN, ISO_8601_PATTERN, ISO_8601_MILLIS_PATTERN, RFC_850_PATTERN, ASCTIME_PATTERN}; for (int i = 0; i < patterns.length; i++) { if (setDateTime(date, patterns[i])) break; } }
java
{ "resource": "" }
q176498
DateTime.setDateTime
test
protected boolean setDateTime(String date, String pattern) { boolean dateChanged = true; dateFormat.applyPattern(pattern); try { setDateTime(dateFormat.parse(date)); } catch (ParseException e) { dateChanged = false; } return dateChanged; }
java
{ "resource": "" }
q176499
Activator.error
test
public static IStatus error(final String message, final Throwable thr) { return new Status(IStatus.ERROR, PLUGIN_ID, 0, message, thr); }
java
{ "resource": "" }