_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8000 | CouchDbClient.execute | train | public HttpConnection execute(HttpConnection connection) {
//set our HttpUrlFactory on the connection
connection.connectionFactory = factory;
// all CouchClient requests want to receive application/json responses
connection.requestProperties.put("Accept", "application/json");
connection.responseInterceptors.addAll(this.responseInterceptors);
connection.requestInterceptors.addAll(this.requestInterceptors);
InputStream es = null; // error stream - response from server for a 500 etc
// first try to execute our request and get the input stream with the server's response
// we want to catch IOException because HttpUrlConnection throws these for non-success
// responses (eg 404 throws a FileNotFoundException) but we need to map to our own
// specific exceptions
try {
try {
connection = connection.execute();
} catch (HttpConnectionInterceptorException e) {
CouchDbException exception = new CouchDbException(connection.getConnection()
.getResponseMessage(), connection.getConnection().getResponseCode());
if (e.deserialize) {
try {
JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject
.class);
exception.error = getAsString(errorResponse, "error");
exception.reason = getAsString(errorResponse, "reason");
} catch (JsonParseException jpe) {
exception.error = e.error;
}
} else {
exception.error = e.error;
exception.reason = e.reason;
}
throw exception;
}
int code = connection.getConnection().getResponseCode();
String response = connection.getConnection().getResponseMessage();
// everything ok? return the stream
if (code / 100 == 2) { // success [200,299]
return connection;
} else {
final CouchDbException ex;
switch (code) {
case HttpURLConnection.HTTP_NOT_FOUND: //404
ex = new NoDocumentException(response);
break;
case HttpURLConnection.HTTP_CONFLICT: //409
ex = new DocumentConflictException(response);
break;
case HttpURLConnection.HTTP_PRECON_FAILED: //412
ex = new PreconditionFailedException(response);
break;
case 429:
// If a Replay429Interceptor is present it will check for 429 and retry at
// intervals. If the retries do not succeed or no 429 replay was configured
// we end up here and throw a TooManyRequestsException.
ex = new TooManyRequestsException(response);
break;
default:
ex = new CouchDbException(response, code);
break;
}
es = connection.getConnection().getErrorStream();
//if there is an error stream try to deserialize into the typed exception
if (es != null) {
try {
//read the error stream into memory
byte[] errorResponse = IOUtils.toByteArray(es);
Class<? extends CouchDbException> exceptionClass = ex.getClass();
//treat the error as JSON and try to deserialize
try {
// Register an InstanceCreator that returns the existing exception so
// we can just populate the fields, but not ignore the constructor.
// Uses a new Gson so we don't accidentally recycle an exception.
Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new
CouchDbExceptionInstanceCreator(ex)).create();
// Now populate the exception with the error/reason other info from JSON
g.fromJson(new InputStreamReader(new ByteArrayInputStream
(errorResponse),
"UTF-8"), exceptionClass);
} catch (JsonParseException e) {
// The error stream was not JSON so just set the string content as the
// error field on ex before we throw it
ex.error = new String(errorResponse, "UTF-8");
}
} finally {
close(es);
}
}
ex.setUrl(connection.url.toString());
throw ex;
}
} catch (IOException ioe) {
CouchDbException ex = new CouchDbException("Error retrieving server response", ioe);
ex.setUrl(connection.url.toString());
throw ex;
}
} | java | {
"resource": ""
} |
q8001 | UserAgentInterceptor.loadUA | train | private static String loadUA(ClassLoader loader, String filename){
String ua = "cloudant-http";
String version = "unknown";
final InputStream propStream = loader.getResourceAsStream(filename);
final Properties properties = new Properties();
try {
if (propStream != null) {
try {
properties.load(propStream);
} finally {
propStream.close();
}
}
ua = properties.getProperty("user.agent.name", ua);
version = properties.getProperty("user.agent.version", version);
} catch (IOException e) {
// Swallow exception and use default values.
}
return String.format(Locale.ENGLISH, "%s/%s", ua,version);
} | java | {
"resource": ""
} |
q8002 | IamCookieInterceptor.getBearerToken | train | private String getBearerToken(HttpConnectionInterceptorContext context) {
final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();
boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,
"application/x-www-form-urlencoded", "application/json",
new StoreBearerCallable(iamTokenResponse));
if (result) {
return iamTokenResponse.get();
} else {
return null;
}
} | java | {
"resource": ""
} |
q8003 | QueryBuilder.useIndex | train | public QueryBuilder useIndex(String designDocument, String indexName) {
useIndex = new String[]{designDocument, indexName};
return this;
} | java | {
"resource": ""
} |
q8004 | QueryBuilder.quoteSort | train | private static String quoteSort(Sort[] sort) {
LinkedList<String> sorts = new LinkedList<String>();
for (Sort pair : sort) {
sorts.add(String.format("{%s: %s}", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));
}
return sorts.toString();
} | java | {
"resource": ""
} |
q8005 | ViewRequestBuilder.newMultipleRequest | train | public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,
Class<V> valueType) {
return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),
valueType));
} | java | {
"resource": ""
} |
q8006 | CouchDatabaseBase.find | train | public <T> T find(Class<T> classType, String id, String rev) {
assertNotEmpty(classType, "Class");
assertNotEmpty(id, "id");
assertNotEmpty(id, "rev");
final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, "rev", rev);
return couchDbClient.get(uri, classType);
} | java | {
"resource": ""
} |
q8007 | CouchDatabaseBase.contains | train | public boolean contains(String id) {
assertNotEmpty(id, "id");
InputStream response = null;
try {
response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id));
} catch (NoDocumentException e) {
return false;
} finally {
close(response);
}
return true;
} | java | {
"resource": ""
} |
q8008 | CouchDatabaseBase.bulk | train | public List<Response> bulk(List<?> objects, boolean allOrNothing) {
assertNotEmpty(objects, "objects");
InputStream responseStream = null;
HttpConnection connection;
try {
final JsonObject jsonObject = new JsonObject();
if(allOrNothing) {
jsonObject.addProperty("all_or_nothing", true);
}
final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();
jsonObject.add("docs", getGson().toJsonTree(objects));
connection = Http.POST(uri, "application/json");
if (jsonObject.toString().length() != 0) {
connection.setRequestBody(jsonObject.toString());
}
couchDbClient.execute(connection);
responseStream = connection.responseAsInputStream();
List<Response> bulkResponses = getResponseList(responseStream, getGson(),
DeserializationTypes.LC_RESPONSES);
for(Response response : bulkResponses) {
response.setStatusCode(connection.getConnection().getResponseCode());
}
return bulkResponses;
}
catch (IOException e) {
throw new CouchDbException("Error retrieving response input stream.", e);
} finally {
close(responseStream);
}
} | java | {
"resource": ""
} |
q8009 | Search.query | train | public <T> List<T> query(String query, Class<T> classOfT) {
InputStream instream = null;
List<T> result = new ArrayList<T>();
try {
Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
if (json.has("rows")) {
if (!includeDocs) {
log.warning("includeDocs set to false and attempting to retrieve doc. " +
"null object will be returned");
}
for (JsonElement e : json.getAsJsonArray("rows")) {
result.add(jsonToObject(client.getGson(), e, "doc", classOfT));
}
} else {
log.warning("No ungrouped result available. Use queryGroups() if grouping set");
}
return result;
} catch (UnsupportedEncodingException e1) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(e1);
} finally {
close(instream);
}
} | java | {
"resource": ""
} |
q8010 | Search.queryGroups | train | public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {
InputStream instream = null;
try {
Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();
if (json.has("groups")) {
for (JsonElement e : json.getAsJsonArray("groups")) {
String groupName = e.getAsJsonObject().get("by").getAsString();
List<T> orows = new ArrayList<T>();
if (!includeDocs) {
log.warning("includeDocs set to false and attempting to retrieve doc. " +
"null object will be returned");
}
for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) {
orows.add(jsonToObject(client.getGson(), rows, "doc", classOfT));
}
result.put(groupName, orows);
}// end for(groups)
}// end hasgroups
else {
log.warning("No grouped results available. Use query() if non grouped query");
}
return result;
} catch (UnsupportedEncodingException e1) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(e1);
} finally {
close(instream);
}
} | java | {
"resource": ""
} |
q8011 | Search.groupField | train | public Search groupField(String fieldName, boolean isNumber) {
assertNotEmpty(fieldName, "fieldName");
if (isNumber) {
databaseHelper.query("group_field", fieldName + "<number>");
} else {
databaseHelper.query("group_field", fieldName);
}
return this;
} | java | {
"resource": ""
} |
q8012 | Search.counts | train | public Search counts(String[] countsfields) {
assert (countsfields.length > 0);
JsonArray countsJsonArray = new JsonArray();
for(String countsfield : countsfields) {
JsonPrimitive element = new JsonPrimitive(countsfield);
countsJsonArray.add(element);
}
databaseHelper.query("counts", countsJsonArray);
return this;
} | java | {
"resource": ""
} |
q8013 | Indexes.allIndexes | train | public List<Index<Field>> allIndexes() {
List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();
indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));
return indexesOfAnyType;
} | java | {
"resource": ""
} |
q8014 | Indexes.listIndexType | train | private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {
List<T> indexesOfType = new ArrayList<T>();
Gson g = new Gson();
for (JsonElement index : indexes) {
if (index.isJsonObject()) {
JsonObject indexDefinition = index.getAsJsonObject();
JsonElement indexType = indexDefinition.get("type");
if (indexType != null && indexType.isJsonPrimitive()) {
JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();
if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive
.getAsString().equals(type))) {
indexesOfType.add(g.fromJson(indexDefinition, modelType));
}
}
}
}
return indexesOfType;
} | java | {
"resource": ""
} |
q8015 | URIBaseMethods.encodePath | train | String encodePath(String in) {
try {
String encodedString = HierarchicalUriComponents.encodeUriComponent(in, "UTF-8",
HierarchicalUriComponents.Type.PATH_SEGMENT);
if (encodedString.startsWith(_design_prefix_encoded) ||
encodedString.startsWith(_local_prefix_encoded)) {
// we replaced the first slash in the design or local doc URL, which we shouldn't
// so let's put it back
return encodedString.replaceFirst("%2F", "/");
} else {
return encodedString;
}
} catch (UnsupportedEncodingException uee) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(
"Couldn't encode ID " + in,
uee);
}
} | java | {
"resource": ""
} |
q8016 | URIBaseMethods.build | train | public URI build() {
try {
String uriString = String.format("%s%s", baseUri.toASCIIString(),
(path.isEmpty() ? "" : path));
if(qParams != null && qParams.size() > 0) {
//Add queries together if both exist
if(!completeQuery.isEmpty()) {
uriString = String.format("%s?%s&%s", uriString,
getJoinedQuery(qParams.getParams()),
completeQuery);
} else {
uriString = String.format("%s?%s", uriString,
getJoinedQuery(qParams.getParams()));
}
} else if(!completeQuery.isEmpty()) {
uriString = String.format("%s?%s", uriString, completeQuery);
}
return new URI(uriString);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
} | java | {
"resource": ""
} |
q8017 | ClientBuilder.account | train | public static ClientBuilder account(String account) {
logger.config("Account: " + account);
return ClientBuilder.url(
convertStringToURL(String.format("https://%s.cloudant.com", account)));
} | java | {
"resource": ""
} |
q8018 | HttpConnection.setRequestBody | train | public HttpConnection setRequestBody(final String input) {
try {
final byte[] inputBytes = input.getBytes("UTF-8");
return setRequestBody(inputBytes);
} catch (UnsupportedEncodingException e) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q8019 | HttpConnection.setRequestBody | train | public HttpConnection setRequestBody(final InputStream input, final long inputLength) {
try {
return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),
inputLength);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error copying input stream for request body", e);
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q8020 | HttpConnection.getLogRequestIdentifier | train | private String getLogRequestIdentifier() {
if (logIdentifier == null) {
logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()),
numberOfRetries, connection.getRequestMethod(), connection.getURL());
}
return logIdentifier;
} | java | {
"resource": ""
} |
q8021 | PGPSigner.getSecretKey | train | private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {
PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());
Iterator rIt = keyrings.getKeyRings();
while (rIt.hasNext()) {
PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();
Iterator kIt = kRing.getSecretKeys();
while (kIt.hasNext()) {
PGPSecretKey key = (PGPSecretKey) kIt.next();
if (key.isSigningKey() && String.format("%08x", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {
return key;
}
}
}
return null;
} | java | {
"resource": ""
} |
q8022 | PGPSigner.trim | train | private String trim(String line) {
char[] chars = line.toCharArray();
int len = chars.length;
while (len > 0) {
if (!Character.isWhitespace(chars[len - 1])) {
break;
}
len--;
}
return line.substring(0, len);
} | java | {
"resource": ""
} |
q8023 | DebMaker.validate | train | public void validate() throws PackagingException {
if (control == null || !control.isDirectory()) {
throw new PackagingException("The 'control' attribute doesn't point to a directory. " + control);
}
if (changesIn != null) {
if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {
throw new PackagingException("The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable.");
}
if (changesOut != null && !isWritableFile(changesOut)) {
throw new PackagingException("Cannot write the output for 'changesOut' to " + changesOut);
}
if (changesSave != null && !isWritableFile(changesSave)) {
throw new PackagingException("Cannot write the output for 'changesSave' to " + changesSave);
}
} else {
if (changesOut != null || changesSave != null) {
throw new PackagingException("The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.");
}
}
if (Compression.toEnum(compression) == null) {
throw new PackagingException("The compression method '" + compression + "' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')");
}
if (deb == null) {
throw new PackagingException("You need to specify where the deb file is supposed to be created.");
}
getDigestCode(digest);
} | java | {
"resource": ""
} |
q8024 | ControlFile.getUserDefinedFieldName | train | protected String getUserDefinedFieldName(String field) {
int index = field.indexOf('-');
char letter = getUserDefinedFieldLetter();
for (int i = 0; i < index; ++i) {
if (field.charAt(i) == letter) {
return field.substring(index + 1);
}
}
return null;
} | java | {
"resource": ""
} |
q8025 | Utils.replaceVariables | train | public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) {
final char[] open = pOpen.toCharArray();
final char[] close = pClose.toCharArray();
final StringBuilder out = new StringBuilder();
StringBuilder sb = new StringBuilder();
char[] last = null;
int wo = 0;
int wc = 0;
int level = 0;
for (char c : pExpression.toCharArray()) {
if (c == open[wo]) {
if (wc > 0) {
sb.append(close, 0, wc);
}
wc = 0;
wo++;
if (open.length == wo) {
// found open
if (last == open) {
out.append(open);
}
level++;
out.append(sb);
sb = new StringBuilder();
wo = 0;
last = open;
}
} else if (c == close[wc]) {
if (wo > 0) {
sb.append(open, 0, wo);
}
wo = 0;
wc++;
if (close.length == wc) {
// found close
if (last == open) {
final String variable = pResolver.get(sb.toString());
if (variable != null) {
out.append(variable);
} else {
out.append(open);
out.append(sb);
out.append(close);
}
} else {
out.append(sb);
out.append(close);
}
sb = new StringBuilder();
level--;
wc = 0;
last = close;
}
} else {
if (wo > 0) {
sb.append(open, 0, wo);
}
if (wc > 0) {
sb.append(close, 0, wc);
}
sb.append(c);
wo = wc = 0;
}
}
if (wo > 0) {
sb.append(open, 0, wo);
}
if (wc > 0) {
sb.append(close, 0, wc);
}
if (level > 0) {
out.append(open);
}
out.append(sb);
return out.toString();
} | java | {
"resource": ""
} |
q8026 | Utils.toUnixLineEndings | train | public static byte[] toUnixLineEndings( InputStream input ) throws IOException {
String encoding = "ISO-8859-1";
FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));
filter.setEol(FixCrLfFilter.CrLf.newInstance("unix"));
ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();
Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);
return filteredFile.toByteArray();
} | java | {
"resource": ""
} |
q8027 | Utils.movePath | train | public static String movePath( final String file,
final String target ) {
final String name = new File(file).getName();
return target.endsWith("/") ? target + name : target + '/' + name;
} | java | {
"resource": ""
} |
q8028 | Utils.lookupIfEmpty | train | public static String lookupIfEmpty( final String value,
final Map<String, String> props,
final String key ) {
return value != null ? value : props.get(key);
} | java | {
"resource": ""
} |
q8029 | Utils.getKnownPGPSecureRingLocations | train | public static Collection<String> getKnownPGPSecureRingLocations() {
final LinkedHashSet<String> locations = new LinkedHashSet<String>();
final String os = System.getProperty("os.name");
final boolean runOnWindows = os == null || os.toLowerCase().contains("win");
if (runOnWindows) {
// The user's roaming profile on Windows, via environment
final String windowsRoaming = System.getenv("APPDATA");
if (windowsRoaming != null) {
locations.add(joinLocalPath(windowsRoaming, "gnupg", "secring.gpg"));
}
// The user's local profile on Windows, via environment
final String windowsLocal = System.getenv("LOCALAPPDATA");
if (windowsLocal != null) {
locations.add(joinLocalPath(windowsLocal, "gnupg", "secring.gpg"));
}
// The Windows installation directory
final String windir = System.getProperty("WINDIR");
if (windir != null) {
// Local Profile on Windows 98 and ME
locations.add(joinLocalPath(windir, "Application Data", "gnupg", "secring.gpg"));
}
}
final String home = System.getProperty("user.home");
if (home != null && runOnWindows) {
// These are for various flavours of Windows
// if the environment variables above have failed
// Roaming profile on Vista and later
locations.add(joinLocalPath(home, "AppData", "Roaming", "gnupg", "secring.gpg"));
// Local profile on Vista and later
locations.add(joinLocalPath(home, "AppData", "Local", "gnupg", "secring.gpg"));
// Roaming profile on 2000 and XP
locations.add(joinLocalPath(home, "Application Data", "gnupg", "secring.gpg"));
// Local profile on 2000 and XP
locations.add(joinLocalPath(home, "Local Settings", "Application Data", "gnupg", "secring.gpg"));
}
// *nix, including OS X
if (home != null) {
locations.add(joinLocalPath(home, ".gnupg", "secring.gpg"));
}
return locations;
} | java | {
"resource": ""
} |
q8030 | Utils.guessKeyRingFile | train | public static File guessKeyRingFile() throws FileNotFoundException {
final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();
for (final String location : possibleLocations) {
final File candidate = new File(location);
if (candidate.exists()) {
return candidate;
}
}
final StringBuilder message = new StringBuilder("Could not locate secure keyring, locations tried: ");
final Iterator<String> it = possibleLocations.iterator();
while (it.hasNext()) {
message.append(it.next());
if (it.hasNext()) {
message.append(", ");
}
}
throw new FileNotFoundException(message.toString());
} | java | {
"resource": ""
} |
q8031 | Utils.defaultString | train | public static String defaultString(final String str, final String fallback) {
return isNullOrEmpty(str) ? fallback : str;
} | java | {
"resource": ""
} |
q8032 | Producers.defaultFileEntryWithName | train | static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {
TarArchiveEntry entry = new TarArchiveEntry(fileName, true);
entry.setUserId(ROOT_UID);
entry.setUserName(ROOT_NAME);
entry.setGroupId(ROOT_UID);
entry.setGroupName(ROOT_NAME);
entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
return entry;
} | java | {
"resource": ""
} |
q8033 | Producers.defaultDirEntryWithName | train | static TarArchiveEntry defaultDirEntryWithName( final String dirName ) {
TarArchiveEntry entry = new TarArchiveEntry(dirName, true);
entry.setUserId(ROOT_UID);
entry.setUserName(ROOT_NAME);
entry.setGroupId(ROOT_UID);
entry.setGroupName(ROOT_NAME);
entry.setMode(TarArchiveEntry.DEFAULT_DIR_MODE);
return entry;
} | java | {
"resource": ""
} |
q8034 | Producers.produceInputStreamWithEntry | train | static void produceInputStreamWithEntry( final DataConsumer consumer,
final InputStream inputStream,
final TarArchiveEntry entry ) throws IOException {
try {
consumer.onEachFile(inputStream, entry);
} finally {
IOUtils.closeQuietly(inputStream);
}
} | java | {
"resource": ""
} |
q8035 | ControlField.format | train | public String format(String value) {
StringBuilder s = new StringBuilder();
if (value != null && value.trim().length() > 0) {
boolean continuationLine = false;
s.append(getName()).append(":");
if (isFirstLineEmpty()) {
s.append("\n");
continuationLine = true;
}
try {
BufferedReader reader = new BufferedReader(new StringReader(value));
String line;
while ((line = reader.readLine()) != null) {
if (continuationLine && line.trim().length() == 0) {
// put a dot on the empty continuation lines
s.append(" .\n");
} else {
s.append(" ").append(line).append("\n");
}
continuationLine = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return s.toString();
} | java | {
"resource": ""
} |
q8036 | ChangesFile.initialize | train | public void initialize(BinaryPackageControlFile packageControlFile) {
set("Binary", packageControlFile.get("Package"));
set("Source", Utils.defaultString(packageControlFile.get("Source"), packageControlFile.get("Package")));
set("Architecture", packageControlFile.get("Architecture"));
set("Version", packageControlFile.get("Version"));
set("Maintainer", packageControlFile.get("Maintainer"));
set("Changed-By", packageControlFile.get("Maintainer"));
set("Distribution", packageControlFile.get("Distribution"));
for (Entry<String, String> entry : packageControlFile.getUserDefinedFields().entrySet()) {
set(entry.getKey(), entry.getValue());
}
StringBuilder description = new StringBuilder();
description.append(packageControlFile.get("Package"));
if (packageControlFile.get("Description") != null) {
description.append(" - ");
description.append(packageControlFile.getShortDescription());
}
set("Description", description.toString());
} | java | {
"resource": ""
} |
q8037 | DebMojo.initializeSignProperties | train | private void initializeSignProperties() {
if (!signPackage && !signChanges) {
return;
}
if (key != null && keyring != null && passphrase != null) {
return;
}
Map<String, String> properties =
readPropertiesFromActiveProfiles(signCfgPrefix, KEY, KEYRING, PASSPHRASE);
key = lookupIfEmpty(key, properties, KEY);
keyring = lookupIfEmpty(keyring, properties, KEYRING);
passphrase = decrypt(lookupIfEmpty(passphrase, properties, PASSPHRASE));
if (keyring == null) {
try {
keyring = Utils.guessKeyRingFile().getAbsolutePath();
console.info("Located keyring at " + keyring);
} catch (FileNotFoundException e) {
console.warn(e.getMessage());
}
}
} | java | {
"resource": ""
} |
q8038 | DebMojo.readPropertiesFromActiveProfiles | train | public Map<String, String> readPropertiesFromActiveProfiles( final String prefix,
final String... properties ) {
if (settings == null) {
console.debug("No maven setting injected");
return Collections.emptyMap();
}
final List<String> activeProfilesList = settings.getActiveProfiles();
if (activeProfilesList.isEmpty()) {
console.debug("No active profiles found");
return Collections.emptyMap();
}
final Map<String, String> map = new HashMap<String, String>();
final Set<String> activeProfiles = new HashSet<String>(activeProfilesList);
// Iterate over all active profiles in order
for (final Profile profile : settings.getProfiles()) {
// Check if the profile is active
final String profileId = profile.getId();
if (activeProfiles.contains(profileId)) {
console.debug("Trying active profile " + profileId);
for (final String property : properties) {
final String propKey = prefix != null ? prefix + property : property;
final String value = profile.getProperties().getProperty(propKey);
if (value != null) {
console.debug("Found property " + property + " in profile " + profileId);
map.put(property, value);
}
}
}
}
return map;
} | java | {
"resource": ""
} |
q8039 | ControlBuilder.buildControl | train | void buildControl(BinaryPackageControlFile packageControlFile, File[] controlFiles, List<String> conffiles, StringBuilder checksums, File output) throws IOException, ParseException {
final File dir = output.getParentFile();
if (dir != null && (!dir.exists() || !dir.isDirectory())) {
throw new IOException("Cannot write control file at '" + output.getAbsolutePath() + "'");
}
final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)));
outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
boolean foundConffiles = false;
// create the final package control file out of the "control" file, copy all other files, ignore the directories
for (File file : controlFiles) {
if (file.isDirectory()) {
// warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)
if (!isDefaultExcludes(file)) {
console.warn("Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?");
}
continue;
}
if ("conffiles".equals(file.getName())) {
foundConffiles = true;
}
if (CONFIGURATION_FILENAMES.contains(file.getName()) || MAINTAINER_SCRIPTS.contains(file.getName())) {
FilteredFile configurationFile = new FilteredFile(new FileInputStream(file), resolver);
configurationFile.setOpenToken(openReplaceToken);
configurationFile.setCloseToken(closeReplaceToken);
addControlEntry(file.getName(), configurationFile.toString(), outputStream);
} else if (!"control".equals(file.getName())) {
// initialize the information stream to guess the type of the file
InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));
Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
infoStream.close();
// fix line endings for shell scripts
InputStream in = new FileInputStream(file);
if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {
byte[] buf = Utils.toUnixLineEndings(in);
in = new ByteArrayInputStream(buf);
}
addControlEntry(file.getName(), IOUtils.toString(in), outputStream);
in.close();
}
}
if (foundConffiles) {
console.info("Found file 'conffiles' in the control directory. Skipping conffiles generation.");
} else if ((conffiles != null) && (conffiles.size() > 0)) {
addControlEntry("conffiles", createPackageConffilesFile(conffiles), outputStream);
} else {
console.info("Skipping 'conffiles' generation. No entries defined in maven/pom or ant/build.xml.");
}
if (packageControlFile == null) {
throw new FileNotFoundException("No 'control' file found in " + controlFiles.toString());
}
addControlEntry("control", packageControlFile.toString(), outputStream);
addControlEntry("md5sums", checksums.toString(), outputStream);
outputStream.close();
} | java | {
"resource": ""
} |
q8040 | HttpUtils.get | train | public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {
LOGGER.log(Level.INFO, "Sending GET request to the url {0}", url);
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> param : params.entrySet()) {
uriBuilder.setParameter(param.getKey(), param.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
populateHeaders(httpGet, customHeaders);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (isErrorStatus(statusCode)) {
String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);
}
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} | java | {
"resource": ""
} |
q8041 | HttpUtils.post | train | public static String post(String url, Map<String, String> customHeaders, Map<String, String> params) throws IOException, HTTPException {
LOGGER.log(Level.INFO, "Sending POST request to the url {0}", url);
HttpPost httpPost = new HttpPost(url);
populateHeaders(httpPost, customHeaders);
if (params != null && params.size() > 0) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
for (Map.Entry<String, String> param : params.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (isErrorStatus(statusCode)) {
String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);
}
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
} | java | {
"resource": ""
} |
q8042 | TransitionController.reverse | train | public T reverse() {
String id = getId();
String REVERSE = "_REVERSE";
if (id.endsWith(REVERSE)) {
setId(id.substring(0, id.length() - REVERSE.length()));
}
float start = mStart;
float end = mEnd;
mStart = end;
mEnd = start;
mReverse = !mReverse;
return self();
} | java | {
"resource": ""
} |
q8043 | AbstractTransitionBuilder.transitFloat | train | public T transitFloat(int propertyId, float... vals) {
String property = getPropertyName(propertyId);
mHolders.put(propertyId, PropertyValuesHolder.ofFloat(property, vals));
mShadowHolders.put(propertyId, ShadowValuesHolder.ofFloat(property, vals));
return self();
} | java | {
"resource": ""
} |
q8044 | AbstractTransitionBuilder.transitInt | train | public T transitInt(int propertyId, int... vals) {
String property = getPropertyName(propertyId);
mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));
mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));
return self();
} | java | {
"resource": ""
} |
q8045 | AbstractTransition.isCompatible | train | @CheckResult
public boolean isCompatible(AbstractTransition another) {
if (getClass().equals(another.getClass()) && mTarget == another.mTarget && mReverse == another.mReverse && ((mInterpolator == null && another.mInterpolator == null) ||
mInterpolator.getClass().equals(another.mInterpolator.getClass()))) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q8046 | AbstractTransition.merge | train | public boolean merge(AbstractTransition another) {
if (!isCompatible(another)) {
return false;
}
if (another.mId != null) {
if (mId == null) {
mId = another.mId;
} else {
StringBuilder sb = new StringBuilder(mId.length() + another.mId.length());
sb.append(mId);
sb.append("_MERGED_");
sb.append(another.mId);
mId = sb.toString();
}
}
mUpdateStateAfterUpdateProgress |= another.mUpdateStateAfterUpdateProgress;
mSetupList.addAll(another.mSetupList);
Collections.sort(mSetupList, new Comparator<S>() {
@Override
public int compare(S lhs, S rhs) {
if (lhs instanceof AbstractTransitionBuilder && rhs instanceof AbstractTransitionBuilder) {
AbstractTransitionBuilder left = (AbstractTransitionBuilder) lhs;
AbstractTransitionBuilder right = (AbstractTransitionBuilder) rhs;
float startLeft = left.mReverse ? left.mEnd : left.mStart;
float startRight = right.mReverse ? right.mEnd : right.mStart;
return (int) ((startRight - startLeft) * 1000);
}
return 0;
}
});
return true;
} | java | {
"resource": ""
} |
q8047 | AnimationManager.removeAllAnimations | train | public void removeAllAnimations() {
for (int i = 0, size = mAnimationList.size(); i < size; i++) {
mAnimationList.get(i).removeAnimationListener(mAnimationListener);
}
mAnimationList.clear();
} | java | {
"resource": ""
} |
q8048 | DefaultTransitionManager.stopTransition | train | @Override
public void stopTransition() {
//call listeners so they can perform their actions first, like modifying this adapter's transitions
for (int i = 0, size = mListenerList.size(); i < size; i++) {
mListenerList.get(i).onTransitionEnd(this);
}
for (int i = 0, size = mTransitionList.size(); i < size; i++) {
mTransitionList.get(i).stopTransition();
}
} | java | {
"resource": ""
} |
q8049 | TransitionControllerManager.start | train | public void start() {
if (TransitionConfig.isDebug()) {
getTransitionStateHolder().start();
}
mLastProgress = Float.MIN_VALUE;
TransitionController transitionController;
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
transitionController = mTransitionControls.get(i);
if (mInterpolator != null) {
transitionController.setInterpolator(mInterpolator);
}
//required for ViewPager transitions to work
if (mTarget != null) {
transitionController.setTarget(mTarget);
}
transitionController.setUpdateStateAfterUpdateProgress(mUpdateStateAfterUpdateProgress);
transitionController.start();
}
} | java | {
"resource": ""
} |
q8050 | TransitionControllerManager.end | train | public void end() {
if (TransitionConfig.isPrintDebug()) {
getTransitionStateHolder().end();
getTransitionStateHolder().print();
}
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).end();
}
} | java | {
"resource": ""
} |
q8051 | TransitionControllerManager.reverse | train | public void reverse() {
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).reverse();
}
} | java | {
"resource": ""
} |
q8052 | LoginContextBuilder.getClientLoginContext | train | private LoginContext getClientLoginContext() throws LoginException {
Configuration config = new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<String, String>();
options.put("multi-threaded", "true");
options.put("restore-login-identity", "true");
AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
return new AppConfigurationEntry[] { clmEntry };
}
};
return getLoginContext(config);
} | java | {
"resource": ""
} |
q8053 | Main.mainInternal | train | public static void mainInternal(String[] args) throws Exception {
Options options = new Options();
CmdLineParser parser = new CmdLineParser(options);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
helpScreen(parser);
return;
}
try {
List<String> configs = new ArrayList<>();
if (options.configs != null) {
configs.addAll(Arrays.asList(options.configs.split(",")));
}
ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);
} catch (ConfigException ex) {
ConfigLogger.error(ex);
throw ex;
} catch (Throwable th) {
ConfigLogger.error(th);
throw th;
}
} | java | {
"resource": ""
} |
q8054 | IllegalStateAssertion.assertNull | train | public static <T> T assertNull(T value, String message) {
if (value != null)
throw new IllegalStateException(message);
return value;
} | java | {
"resource": ""
} |
q8055 | IllegalStateAssertion.assertNotNull | train | public static <T> T assertNotNull(T value, String message) {
if (value == null)
throw new IllegalStateException(message);
return value;
} | java | {
"resource": ""
} |
q8056 | IllegalStateAssertion.assertTrue | train | public static Boolean assertTrue(Boolean value, String message) {
if (!Boolean.valueOf(value))
throw new IllegalStateException(message);
return value;
} | java | {
"resource": ""
} |
q8057 | IllegalStateAssertion.assertFalse | train | public static Boolean assertFalse(Boolean value, String message) {
if (Boolean.valueOf(value))
throw new IllegalStateException(message);
return value;
} | java | {
"resource": ""
} |
q8058 | IllegalArgumentAssertion.assertNotNull | train | public static <T> T assertNotNull(T value, String name) {
if (value == null)
throw new IllegalArgumentException("Null " + name);
return value;
} | java | {
"resource": ""
} |
q8059 | IllegalArgumentAssertion.assertTrue | train | public static Boolean assertTrue(Boolean value, String message) {
if (!Boolean.valueOf(value))
throw new IllegalArgumentException(message);
return value;
} | java | {
"resource": ""
} |
q8060 | IllegalArgumentAssertion.assertFalse | train | public static Boolean assertFalse(Boolean value, String message) {
if (Boolean.valueOf(value))
throw new IllegalArgumentException(message);
return value;
} | java | {
"resource": ""
} |
q8061 | UndertowHTTPDestination.retrieveEngine | train | public void retrieveEngine() throws GeneralSecurityException, IOException {
if (serverEngineFactory == null) {
return;
}
engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());
if (engine == null) {
engine = serverEngineFactory.getHTTPServerEngine(nurl.getHost(), nurl.getPort(), nurl.getProtocol());
}
assert engine != null;
TLSServerParameters serverParameters = engine.getTlsServerParameters();
if (serverParameters != null && serverParameters.getCertConstraints() != null) {
CertificateConstraintsType constraints = serverParameters.getCertConstraints();
if (constraints != null) {
certConstraints = CertConstraintsJaxBUtils.createCertConstraints(constraints);
}
}
// When configuring for "http", however, it is still possible that
// Spring configuration has configured the port for https.
if (!nurl.getProtocol().equals(engine.getProtocol())) {
throw new IllegalStateException("Port " + engine.getPort() + " is configured with wrong protocol \"" + engine.getProtocol() + "\" for \"" + nurl + "\"");
}
} | java | {
"resource": ""
} |
q8062 | UndertowHTTPDestination.finalizeConfig | train | public void finalizeConfig() {
assert !configFinalized;
try {
retrieveEngine();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
configFinalized = true;
} | java | {
"resource": ""
} |
q8063 | ReportMetadata.getStylesheetPath | train | public File getStylesheetPath()
{
String path = System.getProperty(STYLESHEET_KEY);
return path == null ? null : new File(path);
} | java | {
"resource": ""
} |
q8064 | JUnitXMLReporter.flattenResults | train | private Collection<TestClassResults> flattenResults(List<ISuite> suites)
{
Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();
for (ISuite suite : suites)
{
for (ISuiteResult suiteResult : suite.getResults().values())
{
// Failed and skipped configuration methods are treated as test failures.
organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);
// Successful configuration methods are not included.
organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);
}
}
return flattenedResults.values();
} | java | {
"resource": ""
} |
q8065 | JUnitXMLReporter.getResultsForClass | train | private TestClassResults getResultsForClass(Map<IClass, TestClassResults> flattenedResults,
ITestResult testResult)
{
TestClassResults resultsForClass = flattenedResults.get(testResult.getTestClass());
if (resultsForClass == null)
{
resultsForClass = new TestClassResults(testResult.getTestClass());
flattenedResults.put(testResult.getTestClass(), resultsForClass);
}
return resultsForClass;
} | java | {
"resource": ""
} |
q8066 | AbstractReporter.createContext | train | protected VelocityContext createContext()
{
VelocityContext context = new VelocityContext();
context.put(META_KEY, META);
context.put(UTILS_KEY, UTILS);
context.put(MESSAGES_KEY, MESSAGES);
return context;
} | java | {
"resource": ""
} |
q8067 | AbstractReporter.generateFile | train | protected void generateFile(File file,
String templateName,
VelocityContext context) throws Exception
{
Writer writer = new BufferedWriter(new FileWriter(file));
try
{
Velocity.mergeTemplate(classpathPrefix + templateName,
ENCODING,
context,
writer);
writer.flush();
}
finally
{
writer.close();
}
} | java | {
"resource": ""
} |
q8068 | AbstractReporter.copyClasspathResource | train | protected void copyClasspathResource(File outputDirectory,
String resourceName,
String targetFileName) throws IOException
{
String resourcePath = classpathPrefix + resourceName;
InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
copyStream(outputDirectory, resourceStream, targetFileName);
} | java | {
"resource": ""
} |
q8069 | AbstractReporter.copyFile | train | protected void copyFile(File outputDirectory,
File sourceFile,
String targetFileName) throws IOException
{
InputStream fileStream = new FileInputStream(sourceFile);
try
{
copyStream(outputDirectory, fileStream, targetFileName);
}
finally
{
fileStream.close();
}
} | java | {
"resource": ""
} |
q8070 | AbstractReporter.copyStream | train | protected void copyStream(File outputDirectory,
InputStream stream,
String targetFileName) throws IOException
{
File resourceFile = new File(outputDirectory, targetFileName);
BufferedReader reader = null;
Writer writer = null;
try
{
reader = new BufferedReader(new InputStreamReader(stream, ENCODING));
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));
String line = reader.readLine();
while (line != null)
{
writer.write(line);
writer.write('\n');
line = reader.readLine();
}
writer.flush();
}
finally
{
if (reader != null)
{
reader.close();
}
if (writer != null)
{
writer.close();
}
}
} | java | {
"resource": ""
} |
q8071 | AbstractReporter.removeEmptyDirectories | train | protected void removeEmptyDirectories(File outputDirectory)
{
if (outputDirectory.exists())
{
for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter()))
{
file.delete();
}
}
} | java | {
"resource": ""
} |
q8072 | HTMLReporter.generateReport | train | public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
boolean useFrames = System.getProperty(FRAMES_PROPERTY, "true").equals("true");
boolean onlyFailures = System.getProperty(ONLY_FAILURES_PROPERTY, "false").equals("true");
File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
outputDirectory.mkdirs();
try
{
if (useFrames)
{
createFrameset(outputDirectory);
}
createOverview(suites, outputDirectory, !useFrames, onlyFailures);
createSuiteList(suites, outputDirectory, onlyFailures);
createGroups(suites, outputDirectory);
createResults(suites, outputDirectory, onlyFailures);
createLog(outputDirectory, onlyFailures);
copyResources(outputDirectory);
}
catch (Exception ex)
{
throw new ReportNGException("Failed generating HTML report.", ex);
}
} | java | {
"resource": ""
} |
q8073 | HTMLReporter.createFrameset | train | private void createFrameset(File outputDirectory) throws Exception
{
VelocityContext context = createContext();
generateFile(new File(outputDirectory, INDEX_FILE),
INDEX_FILE + TEMPLATE_EXTENSION,
context);
} | java | {
"resource": ""
} |
q8074 | HTMLReporter.createSuiteList | train | private void createSuiteList(List<ISuite> suites,
File outputDirectory,
boolean onlyFailures) throws Exception
{
VelocityContext context = createContext();
context.put(SUITES_KEY, suites);
context.put(ONLY_FAILURES_KEY, onlyFailures);
generateFile(new File(outputDirectory, SUITES_FILE),
SUITES_FILE + TEMPLATE_EXTENSION,
context);
} | java | {
"resource": ""
} |
q8075 | HTMLReporter.createResults | train | private void createResults(List<ISuite> suites,
File outputDirectory,
boolean onlyShowFailures) throws Exception
{
int index = 1;
for (ISuite suite : suites)
{
int index2 = 1;
for (ISuiteResult result : suite.getResults().values())
{
boolean failuresExist = result.getTestContext().getFailedTests().size() > 0
|| result.getTestContext().getFailedConfigurations().size() > 0;
if (!onlyShowFailures || failuresExist)
{
VelocityContext context = createContext();
context.put(RESULT_KEY, result);
context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));
context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));
context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));
context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));
context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));
String fileName = String.format("suite%d_test%d_%s", index, index2, RESULTS_FILE);
generateFile(new File(outputDirectory, fileName),
RESULTS_FILE + TEMPLATE_EXTENSION,
context);
}
++index2;
}
++index;
}
} | java | {
"resource": ""
} |
q8076 | HTMLReporter.copyResources | train | private void copyResources(File outputDirectory) throws IOException
{
copyClasspathResource(outputDirectory, "reportng.css", "reportng.css");
copyClasspathResource(outputDirectory, "reportng.js", "reportng.js");
// If there is a custom stylesheet, copy that.
File customStylesheet = META.getStylesheetPath();
if (customStylesheet != null)
{
if (customStylesheet.exists())
{
copyFile(outputDirectory, customStylesheet, CUSTOM_STYLE_FILE);
}
else
{
// If not found, try to read the file as a resource on the classpath
// useful when reportng is called by a jarred up library
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(customStylesheet.getPath());
if (stream != null)
{
copyStream(outputDirectory, stream, CUSTOM_STYLE_FILE);
}
}
}
} | java | {
"resource": ""
} |
q8077 | ReportNGUtils.getCauses | train | public List<Throwable> getCauses(Throwable t)
{
List<Throwable> causes = new LinkedList<Throwable>();
Throwable next = t;
while (next.getCause() != null)
{
next = next.getCause();
causes.add(next);
}
return causes;
} | java | {
"resource": ""
} |
q8078 | ReportNGUtils.commaSeparate | train | private String commaSeparate(Collection<String> strings)
{
StringBuilder buffer = new StringBuilder();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext())
{
String string = iterator.next();
buffer.append(string);
if (iterator.hasNext())
{
buffer.append(", ");
}
}
return buffer.toString();
} | java | {
"resource": ""
} |
q8079 | ReportNGUtils.stripThreadName | train | public String stripThreadName(String threadId)
{
if (threadId == null)
{
return null;
}
else
{
int index = threadId.lastIndexOf('@');
return index >= 0 ? threadId.substring(0, index) : threadId;
}
} | java | {
"resource": ""
} |
q8080 | ReportNGUtils.getStartTime | train | public long getStartTime(List<IInvokedMethod> methods)
{
long startTime = System.currentTimeMillis();
for (IInvokedMethod method : methods)
{
startTime = Math.min(startTime, method.getDate());
}
return startTime;
} | java | {
"resource": ""
} |
q8081 | ReportNGUtils.getEndTime | train | private long getEndTime(ISuite suite, IInvokedMethod method)
{
// Find the latest end time for all tests in the suite.
for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())
{
ITestContext testContext = entry.getValue().getTestContext();
for (ITestNGMethod m : testContext.getAllTestMethods())
{
if (method == m)
{
return testContext.getEndDate().getTime();
}
}
// If we can't find a matching test method it must be a configuration method.
for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods())
{
if (method == m)
{
return testContext.getEndDate().getTime();
}
}
for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods())
{
if (method == m)
{
return testContext.getEndDate().getTime();
}
}
}
throw new IllegalStateException("Could not find matching end time.");
} | java | {
"resource": ""
} |
q8082 | PollingConsumer.waitForBuffer | train | public void waitForBuffer(long timeoutMilli) {
//assert(callerProcessing.booleanValue() == false);
synchronized(buffer) {
if( dirtyBuffer )
return;
if( !foundEOF() ) {
logger.trace("Waiting for things to come in, or until timeout");
try {
if( timeoutMilli > 0 )
buffer.wait(timeoutMilli);
else
buffer.wait();
} catch(InterruptedException ie) {
logger.trace("Woken up, while waiting for buffer");
}
// this might went early, but running the processing again isn't a big deal
logger.trace("Waited");
}
}
} | java | {
"resource": ""
} |
q8083 | PollingConsumer.main | train | public static void main(String args[]) throws Exception {
final StringBuffer buffer = new StringBuffer("The lazy fox");
Thread t1 = new Thread() {
public void run() {
synchronized(buffer) {
buffer.delete(0,4);
buffer.append(" in the middle");
System.err.println("Middle");
try { Thread.sleep(4000); } catch(Exception e) {}
buffer.append(" of fall");
System.err.println("Fall");
}
}
};
Thread t2 = new Thread() {
public void run() {
try { Thread.sleep(1000); } catch(Exception e) {}
buffer.append(" jump over the fence");
System.err.println("Fence");
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.err.println(buffer);
} | java | {
"resource": ""
} |
q8084 | ConsumerImpl.notifyBufferChange | train | protected void notifyBufferChange(char[] newData, int numChars) {
synchronized(bufferChangeLoggers) {
Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();
while (iterator.hasNext()) {
iterator.next().bufferChanged(newData, numChars);
}
}
} | java | {
"resource": ""
} |
q8085 | Expect4j.expect | train | public int expect(String pattern) throws MalformedPatternException, Exception {
logger.trace("Searching for '" + pattern + "' in the reader stream");
return expect(pattern, null);
} | java | {
"resource": ""
} |
q8086 | Expect4j.prepareClosure | train | protected ExpectState prepareClosure(int pairIndex, MatchResult result) {
/* TODO: potentially remove this?
{
System.out.println( "Begin: " + result.beginOffset(0) );
System.out.println( "Length: " + result.length() );
System.out.println( "Current: " + input.getCurrentOffset() );
System.out.println( "Begin: " + input.getMatchBeginOffset() );
System.out.println( "End: " + input.getMatchEndOffset() );
//System.out.println( "Match: " + input.match() );
//System.out.println( "Pre: >" + input.preMatch() + "<");
//System.out.println( "Post: " + input.postMatch() );
}
*/
// Prepare Closure environment
ExpectState state;
Map<String, Object> prevMap = null;
if (g_state != null) {
prevMap = g_state.getVars();
}
int matchedWhere = result.beginOffset(0);
String matchedText = result.toString(); // expect_out(0,string)
// Unmatched upto end of match
// expect_out(buffer)
char[] chBuffer = input.getBuffer();
String copyBuffer = new String(chBuffer, 0, result.endOffset(0) );
List<String> groups = new ArrayList<>();
for (int j = 1; j <= result.groups(); j++) {
String group = result.group(j);
groups.add( group );
}
state = new ExpectState(copyBuffer.toString(), matchedWhere, matchedText, pairIndex, groups, prevMap);
return state;
} | java | {
"resource": ""
} |
q8087 | SubstCrCommand.cmdProc | train | public void cmdProc(Interp interp, TclObject argv[])
throws TclException {
int currentObjIndex, len, i;
int objc = argv.length - 1;
boolean doBackslashes = true;
boolean doCmds = true;
boolean doVars = true;
StringBuffer result = new StringBuffer();
String s;
char c;
for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) {
if (!argv[currentObjIndex].toString().startsWith("-")) {
break;
}
int opt = TclIndex.get(interp, argv[currentObjIndex],
validCmds, "switch", 0);
switch (opt) {
case OPT_NOBACKSLASHES:
doBackslashes = false;
break;
case OPT_NOCOMMANDS:
doCmds = false;
break;
case OPT_NOVARS:
doVars = false;
break;
default:
throw new TclException(interp,
"SubstCrCmd.cmdProc: bad option " + opt
+ " index to cmds");
}
}
if (currentObjIndex != objc) {
throw new TclNumArgsException(interp, currentObjIndex, argv,
"?-nobackslashes? ?-nocommands? ?-novariables? string");
}
/*
* Scan through the string one character at a time, performing
* command, variable, and backslash substitutions.
*/
s = argv[currentObjIndex].toString();
len = s.length();
i = 0;
while (i < len) {
c = s.charAt(i);
if ((c == '[') && doCmds) {
ParseResult res;
try {
interp.evalFlags = Parser.TCL_BRACKET_TERM;
interp.eval(s.substring(i + 1, len));
TclObject interp_result = interp.getResult();
interp_result.preserve();
res = new ParseResult(interp_result,
i + interp.termOffset);
} catch (TclException e) {
i = e.errIndex + 1;
throw e;
}
i = res.nextIndex + 2;
result.append( res.value.toString() );
res.release();
/**
* Removed
(ToDo) may not be portable on Mac
} else if (c == '\r') {
i++;
*/
} else if ((c == '$') && doVars) {
ParseResult vres = Parser.parseVar(interp,
s.substring(i, len));
i += vres.nextIndex;
result.append( vres.value.toString() );
vres.release();
} else if ((c == '\\') && doBackslashes) {
BackSlashResult bs = Interp.backslash(s, i, len);
i = bs.nextIndex;
if (bs.isWordSep) {
break;
} else {
result.append( bs.c );
}
} else {
result.append( c );
i++;
}
}
interp.setResult(result.toString());
} | java | {
"resource": ""
} |
q8088 | JaCoCoReportMerger.mergeReports | train | public static void mergeReports(File reportOverall, File... reports) {
SessionInfoStore infoStore = new SessionInfoStore();
ExecutionDataStore dataStore = new ExecutionDataStore();
boolean isCurrentVersionFormat = loadSourceFiles(infoStore, dataStore, reports);
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(reportOverall))) {
Object visitor;
if (isCurrentVersionFormat) {
visitor = new ExecutionDataWriter(outputStream);
} else {
visitor = new org.jacoco.previous.core.data.ExecutionDataWriter(outputStream);
}
infoStore.accept((ISessionInfoVisitor) visitor);
dataStore.accept((IExecutionDataVisitor) visitor);
} catch (IOException e) {
throw new IllegalStateException(String.format("Unable to write overall coverage report %s", reportOverall.getAbsolutePath()), e);
}
} | java | {
"resource": ""
} |
q8089 | JaCoCoReportReader.readJacocoReport | train | public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) {
if (jacocoExecutionData == null) {
return this;
}
JaCoCoExtensions.logger().info("Analysing {}", jacocoExecutionData);
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) {
if (useCurrentBinaryFormat) {
ExecutionDataReader reader = new ExecutionDataReader(inputStream);
reader.setSessionInfoVisitor(sessionInfoStore);
reader.setExecutionDataVisitor(executionDataVisitor);
reader.read();
} else {
org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream);
reader.setSessionInfoVisitor(sessionInfoStore);
reader.setExecutionDataVisitor(executionDataVisitor);
reader.read();
}
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Unable to read %s", jacocoExecutionData.getAbsolutePath()), e);
}
return this;
} | java | {
"resource": ""
} |
q8090 | ArtifactNameBuilder.build | train | public ArtifactName build() {
String groupId = this.groupId;
String artifactId = this.artifactId;
String classifier = this.classifier;
String packaging = this.packaging;
String version = this.version;
if (artifact != null && !artifact.isEmpty()) {
final String[] artifactSegments = artifact.split(":");
// groupId:artifactId:version[:packaging][:classifier].
String value;
switch (artifactSegments.length) {
case 5:
value = artifactSegments[4].trim();
if (!value.isEmpty()) {
classifier = value;
}
case 4:
value = artifactSegments[3].trim();
if (!value.isEmpty()) {
packaging = value;
}
case 3:
value = artifactSegments[2].trim();
if (!value.isEmpty()) {
version = value;
}
case 2:
value = artifactSegments[1].trim();
if (!value.isEmpty()) {
artifactId = value;
}
case 1:
value = artifactSegments[0].trim();
if (!value.isEmpty()) {
groupId = value;
}
}
}
return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version);
} | java | {
"resource": ""
} |
q8091 | Deployment.of | train | public static Deployment of(final File content) {
final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("content", content).toPath());
return new Deployment(deploymentContent, null);
} | java | {
"resource": ""
} |
q8092 | Deployment.of | train | public static Deployment of(final Path content) {
final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("content", content));
return new Deployment(deploymentContent, null);
} | java | {
"resource": ""
} |
q8093 | Deployment.of | train | public static Deployment of(final URL url) {
final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam("url", url));
return new Deployment(deploymentContent, null);
} | java | {
"resource": ""
} |
q8094 | Deployment.setServerGroups | train | public Deployment setServerGroups(final Collection<String> serverGroups) {
this.serverGroups.clear();
this.serverGroups.addAll(serverGroups);
return this;
} | java | {
"resource": ""
} |
q8095 | AbstractDeployment.validate | train | protected void validate(final boolean isDomain) throws MojoDeploymentException {
final boolean hasServerGroups = hasServerGroups();
if (isDomain) {
if (!hasServerGroups) {
throw new MojoDeploymentException(
"Server is running in domain mode, but no server groups have been defined.");
}
} else if (hasServerGroups) {
throw new MojoDeploymentException("Server is running in standalone mode, but server groups have been defined.");
}
} | java | {
"resource": ""
} |
q8096 | AddResourceMojo.buildAddOperation | train | private ModelNode buildAddOperation(final ModelNode address, final Map<String, String> properties) {
final ModelNode op = ServerOperations.createAddOperation(address);
for (Map.Entry<String, String> prop : properties.entrySet()) {
final String[] props = prop.getKey().split(",");
if (props.length == 0) {
throw new RuntimeException("Invalid property " + prop);
}
ModelNode node = op;
for (int i = 0; i < props.length - 1; ++i) {
node = node.get(props[i]);
}
final String value = prop.getValue() == null ? "" : prop.getValue();
if (value.startsWith("!!")) {
handleDmrString(node, props[props.length - 1], value);
} else {
node.get(props[props.length - 1]).set(value);
}
}
return op;
} | java | {
"resource": ""
} |
q8097 | AddResourceMojo.handleDmrString | train | private void handleDmrString(final ModelNode node, final String name, final String value) {
final String realValue = value.substring(2);
node.get(name).set(ModelNode.fromString(realValue));
} | java | {
"resource": ""
} |
q8098 | AddResourceMojo.parseAddress | train | private ModelNode parseAddress(final String profileName, final String inputAddress) {
final ModelNode result = new ModelNode();
if (profileName != null) {
result.add(ServerOperations.PROFILE, profileName);
}
String[] parts = inputAddress.split(",");
for (String part : parts) {
String[] address = part.split("=");
if (address.length != 2) {
throw new RuntimeException(part + " is not a valid address segment");
}
result.add(address[0], address[1]);
}
return result;
} | java | {
"resource": ""
} |
q8099 | ServerHelper.getContainerDescription | train | public static ContainerDescription getContainerDescription(final ModelControllerClient client) throws IOException, OperationExecutionException {
return DefaultContainerDescription.lookup(Assert.checkNotNullParam("client", client));
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.