code
stringlengths
73
34.1k
label
stringclasses
1 value
public Response remove(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.remove(ensureDesignPrefix(id), rev); }
java
public Response remove(DesignDocument designDocument) { assertNotEmpty(designDocument, "DesignDocument"); ensureDesignPrefixObject(designDocument); return db.remove(designDocument); }
java
public List<DesignDocument> list() throws IOException { return db.getAllDocsRequestBuilder() .startKey("_design/") .endKey("_design0") .inclusiveEnd(false) .includeDocs(true) .build() .getResponse().getDocsAs(DesignDocument.class); }
java
public static List<DesignDocument> fromDirectory(File directory) throws FileNotFoundException { List<DesignDocument> designDocuments = new ArrayList<DesignDocument>(); if (directory.isDirectory()) { Collection<File> files = FileUtils.listFiles(directory, null, true); for (File designDocFile : files) { designDocuments.add(fromFile(designDocFile)); } } else { designDocuments.add(fromFile(directory)); } return designDocuments; }
java
public static DesignDocument fromFile(File file) throws FileNotFoundException { assertNotEmpty(file, "Design js file"); DesignDocument designDocument; Gson gson = new Gson(); InputStreamReader reader = null; try { reader = new InputStreamReader(new FileInputStream(file),"UTF-8"); //Deserialize JS file contents into DesignDocument object designDocument = gson.fromJson(reader, DesignDocument.class); return designDocument; } catch (UnsupportedEncodingException e) { //UTF-8 should be supported on all JVMs throw new RuntimeException(e); } finally { IOUtils.closeQuietly(reader); } }
java
static <K, V> ViewQueryParameters<K, V> forwardPaginationQueryParameters (ViewQueryParameters<K, V> initialQueryParameters, K startkey, String startkey_docid) { // Copy the initial query parameters ViewQueryParameters<K, V> pageParameters = initialQueryParameters.copy(); // Now override with the start keys provided pageParameters.setStartKey(startkey); pageParameters.setStartKeyDocId(startkey_docid); return pageParameters; }
java
public static HttpConnection connect(String requestMethod, URL url, String contentType) { return new HttpConnection(requestMethod, url, contentType); }
java
public B partialFilterSelector(Selector selector) { instance.def.selector = Helpers.getJsonObjectFromSelector(selector); return returnThis(); }
java
protected B fields(List<F> fields) { if (instance.def.fields == null) { instance.def.fields = new ArrayList<F>(fields.size()); } instance.def.fields.addAll(fields); return returnThis(); }
java
public SchedulerDocsResponse.Doc schedulerDoc(String docId) { assertNotEmpty(docId, "docId"); return this.get(new DatabaseURIHelper(getBaseUri()). path("_scheduler").path("docs").path("_replicator").path(docId).build(), SchedulerDocsResponse.Doc.class); }
java
public List<String> uuids(long count) { final URI uri = new URIBase(clientUri).path("_uuids").query("count", count).build(); final JsonObject json = get(uri, JsonObject.class); return getGson().fromJson(json.get("uuids").toString(), DeserializationTypes.STRINGS); }
java
public Response executeToResponse(HttpConnection connection) { InputStream is = null; try { is = this.executeToInputStream(connection); Response response = getResponse(is, Response.class, getGson()); response.setStatusCode(connection.getConnection().getResponseCode()); response.setReason(connection.getConnection().getResponseMessage()); return response; } catch (IOException e) { throw new CouchDbException("Error retrieving response code or message.", e); } finally { close(is); } }
java
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
java
public <T> T get(URI uri, Class<T> classType) { HttpConnection connection = Http.GET(uri); InputStream response = executeToInputStream(connection); try { return getResponse(response, classType, getGson()); } finally { close(response); } }
java
Response put(URI uri, InputStream instream, String contentType) { HttpConnection connection = Http.PUT(uri, contentType); connection.setRequestBody(instream); return executeToResponse(connection); }
java
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
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
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
public QueryBuilder useIndex(String designDocument, String indexName) { useIndex = new String[]{designDocument, indexName}; return this; }
java
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
public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType, Class<V> valueType) { return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(), valueType)); }
java
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
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
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
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
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
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
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
public List<Index<Field>> allIndexes() { List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>(); indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class)); return indexesOfAnyType; }
java
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
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
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
public static ClientBuilder account(String account) { logger.config("Account: " + account); return ClientBuilder.url( convertStringToURL(String.format("https://%s.cloudant.com", account))); }
java
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
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
private String getLogRequestIdentifier() { if (logIdentifier == null) { logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()), numberOfRetries, connection.getRequestMethod(), connection.getURL()); } return logIdentifier; }
java
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
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
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
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
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
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
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
public static String lookupIfEmpty( final String value, final Map<String, String> props, final String key ) { return value != null ? value : props.get(key); }
java
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
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
public static String defaultString(final String str, final String fallback) { return isNullOrEmpty(str) ? fallback : str; }
java
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
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
static void produceInputStreamWithEntry( final DataConsumer consumer, final InputStream inputStream, final TarArchiveEntry entry ) throws IOException { try { consumer.onEachFile(inputStream, entry); } finally { IOUtils.closeQuietly(inputStream); } }
java
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
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
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
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
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
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
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
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
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
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
@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
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
public void removeAllAnimations() { for (int i = 0, size = mAnimationList.size(); i < size; i++) { mAnimationList.get(i).removeAnimationListener(mAnimationListener); } mAnimationList.clear(); }
java
@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
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
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
public void reverse() { for (int i = 0, size = mTransitionControls.size(); i < size; i++) { mTransitionControls.get(i).reverse(); } }
java
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
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
public static <T> T assertNull(T value, String message) { if (value != null) throw new IllegalStateException(message); return value; }
java
public static <T> T assertNotNull(T value, String message) { if (value == null) throw new IllegalStateException(message); return value; }
java
public static Boolean assertTrue(Boolean value, String message) { if (!Boolean.valueOf(value)) throw new IllegalStateException(message); return value; }
java
public static Boolean assertFalse(Boolean value, String message) { if (Boolean.valueOf(value)) throw new IllegalStateException(message); return value; }
java
public static <T> T assertNotNull(T value, String name) { if (value == null) throw new IllegalArgumentException("Null " + name); return value; }
java
public static Boolean assertTrue(Boolean value, String message) { if (!Boolean.valueOf(value)) throw new IllegalArgumentException(message); return value; }
java
public static Boolean assertFalse(Boolean value, String message) { if (Boolean.valueOf(value)) throw new IllegalArgumentException(message); return value; }
java
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
public void finalizeConfig() { assert !configFinalized; try { retrieveEngine(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } configFinalized = true; }
java
public File getStylesheetPath() { String path = System.getProperty(STYLESHEET_KEY); return path == null ? null : new File(path); }
java
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
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
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
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
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
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
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
protected void removeEmptyDirectories(File outputDirectory) { if (outputDirectory.exists()) { for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter())) { file.delete(); } } }
java
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
private void createFrameset(File outputDirectory) throws Exception { VelocityContext context = createContext(); generateFile(new File(outputDirectory, INDEX_FILE), INDEX_FILE + TEMPLATE_EXTENSION, context); }
java
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
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
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
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
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
public String stripThreadName(String threadId) { if (threadId == null) { return null; } else { int index = threadId.lastIndexOf('@'); return index >= 0 ? threadId.substring(0, index) : threadId; } }
java
public long getStartTime(List<IInvokedMethod> methods) { long startTime = System.currentTimeMillis(); for (IInvokedMethod method : methods) { startTime = Math.min(startTime, method.getDate()); } return startTime; }
java
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
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
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
protected void notifyBufferChange(char[] newData, int numChars) { synchronized(bufferChangeLoggers) { Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator(); while (iterator.hasNext()) { iterator.next().bufferChanged(newData, numChars); } } }
java