repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.remove
public Response remove(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.remove(ensureDesignPrefix(id), rev); }
java
public Response remove(String id, String rev) { assertNotEmpty(id, "id"); assertNotEmpty(id, "rev"); return db.remove(ensureDesignPrefix(id), rev); }
[ "public", "Response", "remove", "(", "String", "id", ",", "String", "rev", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"rev\"", ")", ";", "return", "db", ".", "remove", "(", "ensureDesignPrefix", "(...
Removes a design document using the id and rev from the database. @param id the document id (optionally prefixed with "_design/") @param rev the document revision @return {@link DesignDocument}
[ "Removes", "a", "design", "document", "using", "the", "id", "and", "rev", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L195-L200
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.remove
public Response remove(DesignDocument designDocument) { assertNotEmpty(designDocument, "DesignDocument"); ensureDesignPrefixObject(designDocument); return db.remove(designDocument); }
java
public Response remove(DesignDocument designDocument) { assertNotEmpty(designDocument, "DesignDocument"); ensureDesignPrefixObject(designDocument); return db.remove(designDocument); }
[ "public", "Response", "remove", "(", "DesignDocument", "designDocument", ")", "{", "assertNotEmpty", "(", "designDocument", ",", "\"DesignDocument\"", ")", ";", "ensureDesignPrefixObject", "(", "designDocument", ")", ";", "return", "db", ".", "remove", "(", "designD...
Removes a design document using DesignDocument object from the database. @param designDocument the design document object to be removed @return {@link DesignDocument}
[ "Removes", "a", "design", "document", "using", "DesignDocument", "object", "from", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L208-L212
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.list
public List<DesignDocument> list() throws IOException { return db.getAllDocsRequestBuilder() .startKey("_design/") .endKey("_design0") .inclusiveEnd(false) .includeDocs(true) .build() .getResponse().getDocsAs(DesignDocument.class); }
java
public List<DesignDocument> list() throws IOException { return db.getAllDocsRequestBuilder() .startKey("_design/") .endKey("_design0") .inclusiveEnd(false) .includeDocs(true) .build() .getResponse().getDocsAs(DesignDocument.class); }
[ "public", "List", "<", "DesignDocument", ">", "list", "(", ")", "throws", "IOException", "{", "return", "db", ".", "getAllDocsRequestBuilder", "(", ")", ".", "startKey", "(", "\"_design/\"", ")", ".", "endKey", "(", "\"_design0\"", ")", ".", "inclusiveEnd", ...
Performs a query to retrieve all the design documents defined in the database. @return a list of the design documents from the database @throws IOException if there was an error communicating with the server @since 2.5.0
[ "Performs", "a", "query", "to", "retrieve", "all", "the", "design", "documents", "defined", "in", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L221-L229
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.fromDirectory
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 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; }
[ "public", "static", "List", "<", "DesignDocument", ">", "fromDirectory", "(", "File", "directory", ")", "throws", "FileNotFoundException", "{", "List", "<", "DesignDocument", ">", "designDocuments", "=", "new", "ArrayList", "<", "DesignDocument", ">", "(", ")", ...
Deserialize a directory of javascript design documents to a List of DesignDocument objects. @param directory the directory containing javascript files @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "Deserialize", "a", "directory", "of", "javascript", "design", "documents", "to", "a", "List", "of", "DesignDocument", "objects", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L238-L249
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java
DesignDocumentManager.fromFile
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
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); } }
[ "public", "static", "DesignDocument", "fromFile", "(", "File", "file", ")", "throws", "FileNotFoundException", "{", "assertNotEmpty", "(", "file", ",", "\"Design js file\"", ")", ";", "DesignDocument", "designDocument", ";", "Gson", "gson", "=", "new", "Gson", "("...
Deserialize a javascript design document file to a DesignDocument object. @param file the design document javascript file (UTF-8 encoded) @return {@link DesignDocument} @throws FileNotFoundException if the file does not exist or cannot be read
[ "Deserialize", "a", "javascript", "design", "document", "file", "to", "a", "DesignDocument", "object", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/DesignDocumentManager.java#L258-L274
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/views/PageMetadata.java
PageMetadata.forwardPaginationQueryParameters
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
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; }
[ "static", "<", "K", ",", "V", ">", "ViewQueryParameters", "<", "K", ",", "V", ">", "forwardPaginationQueryParameters", "(", "ViewQueryParameters", "<", "K", ",", "V", ">", "initialQueryParameters", ",", "K", "startkey", ",", "String", "startkey_docid", ")", "{...
Generate query parameters for a forward page with the specified start key. @param initialQueryParameters page 1 query parameters @param startkey the startkey for the forward page @param startkey_docid the doc id for the startkey (in case of duplicate keys) @param <K> the view key type @param <V> the view value type @return the query parameters for the forward page
[ "Generate", "query", "parameters", "for", "a", "forward", "page", "with", "the", "specified", "start", "key", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/views/PageMetadata.java#L78-L89
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/Http.java
Http.connect
public static HttpConnection connect(String requestMethod, URL url, String contentType) { return new HttpConnection(requestMethod, url, contentType); }
java
public static HttpConnection connect(String requestMethod, URL url, String contentType) { return new HttpConnection(requestMethod, url, contentType); }
[ "public", "static", "HttpConnection", "connect", "(", "String", "requestMethod", ",", "URL", "url", ",", "String", "contentType", ")", "{", "return", "new", "HttpConnection", "(", "requestMethod", ",", "url", ",", "contentType", ")", ";", "}" ]
low level http operations
[ "low", "level", "http", "operations" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/Http.java#L87-L91
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java
Builder.partialFilterSelector
public B partialFilterSelector(Selector selector) { instance.def.selector = Helpers.getJsonObjectFromSelector(selector); return returnThis(); }
java
public B partialFilterSelector(Selector selector) { instance.def.selector = Helpers.getJsonObjectFromSelector(selector); return returnThis(); }
[ "public", "B", "partialFilterSelector", "(", "Selector", "selector", ")", "{", "instance", ".", "def", ".", "selector", "=", "Helpers", ".", "getJsonObjectFromSelector", "(", "selector", ")", ";", "return", "returnThis", "(", ")", ";", "}" ]
Configure a selector to choose documents that should be added to the index.
[ "Configure", "a", "selector", "to", "choose", "documents", "that", "should", "be", "added", "to", "the", "index", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java#L69-L72
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java
Builder.fields
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
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(); }
[ "protected", "B", "fields", "(", "List", "<", "F", ">", "fields", ")", "{", "if", "(", "instance", ".", "def", ".", "fields", "==", "null", ")", "{", "instance", ".", "def", ".", "fields", "=", "new", "ArrayList", "<", "F", ">", "(", "fields", "....
Add fields to the text index configuration. @param fields the {@link TextIndex.Field} configurations to add @return the builder for chaining
[ "Add", "fields", "to", "the", "text", "index", "configuration", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/query/Builder.java#L80-L86
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.schedulerDoc
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 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); }
[ "public", "SchedulerDocsResponse", ".", "Doc", "schedulerDoc", "(", "String", "docId", ")", "{", "assertNotEmpty", "(", "docId", ",", "\"docId\"", ")", ";", "return", "this", ".", "get", "(", "new", "DatabaseURIHelper", "(", "getBaseUri", "(", ")", ")", ".",...
Get replication document state for a given replication document ID. @param docId The replication document ID @return Replication document for {@code docId}
[ "Get", "replication", "document", "state", "for", "a", "given", "replication", "document", "ID", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L332-L337
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.uuids
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 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); }
[ "public", "List", "<", "String", ">", "uuids", "(", "long", "count", ")", "{", "final", "URI", "uri", "=", "new", "URIBase", "(", "clientUri", ")", ".", "path", "(", "\"_uuids\"", ")", ".", "query", "(", "\"count\"", ",", "count", ")", ".", "build", ...
Request a database sends a list of UUIDs. @param count The count of UUIDs.
[ "Request", "a", "database", "sends", "a", "list", "of", "UUIDs", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L344-L348
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.executeToResponse
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
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); } }
[ "public", "Response", "executeToResponse", "(", "HttpConnection", "connection", ")", "{", "InputStream", "is", "=", "null", ";", "try", "{", "is", "=", "this", ".", "executeToInputStream", "(", "connection", ")", ";", "Response", "response", "=", "getResponse", ...
Executes a HTTP request and parses the JSON response into a Response instance. @param connection The HTTP request to execute. @return Response object of the deserialized JSON response
[ "Executes", "a", "HTTP", "request", "and", "parses", "the", "JSON", "response", "into", "a", "Response", "instance", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L356-L369
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.delete
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
java
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
[ "Response", "delete", "(", "URI", "uri", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "DELETE", "(", "uri", ")", ";", "return", "executeToResponse", "(", "connection", ")", ";", "}" ]
Performs a HTTP DELETE request. @return {@link Response}
[ "Performs", "a", "HTTP", "DELETE", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L376-L379
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.get
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
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); } }
[ "public", "<", "T", ">", "T", "get", "(", "URI", "uri", ",", "Class", "<", "T", ">", "classType", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "GET", "(", "uri", ")", ";", "InputStream", "response", "=", "executeToInputStream", "(", "con...
Performs a HTTP GET request. @return Class type of object T (i.e. {@link Response}
[ "Performs", "a", "HTTP", "GET", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L397-L405
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.put
Response put(URI uri, InputStream instream, String contentType) { HttpConnection connection = Http.PUT(uri, contentType); connection.setRequestBody(instream); return executeToResponse(connection); }
java
Response put(URI uri, InputStream instream, String contentType) { HttpConnection connection = Http.PUT(uri, contentType); connection.setRequestBody(instream); return executeToResponse(connection); }
[ "Response", "put", "(", "URI", "uri", ",", "InputStream", "instream", ",", "String", "contentType", ")", "{", "HttpConnection", "connection", "=", "Http", ".", "PUT", "(", "uri", ",", "contentType", ")", ";", "connection", ".", "setRequestBody", "(", "instre...
Performs a HTTP PUT request, saves an attachment. @return {@link Response}
[ "Performs", "a", "HTTP", "PUT", "request", "saves", "an", "attachment", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L445-L451
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java
CouchDbClient.execute
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
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; } }
[ "public", "HttpConnection", "execute", "(", "HttpConnection", "connection", ")", "{", "//set our HttpUrlFactory on the connection", "connection", ".", "connectionFactory", "=", "factory", ";", "// all CouchClient requests want to receive application/json responses", "connection", "...
Execute a HTTP request and handle common error cases. @param connection the HttpConnection request to execute @return the executed HttpConnection @throws CouchDbException for HTTP error codes or if an IOException was thrown
[ "Execute", "a", "HTTP", "request", "and", "handle", "common", "error", "cases", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L535-L634
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/UserAgentInterceptor.java
UserAgentInterceptor.loadUA
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 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); }
[ "private", "static", "String", "loadUA", "(", "ClassLoader", "loader", ",", "String", "filename", ")", "{", "String", "ua", "=", "\"cloudant-http\"", ";", "String", "version", "=", "\"unknown\"", ";", "final", "InputStream", "propStream", "=", "loader", ".", "...
Loads the properties file using the classloader provided. Creating a string from the properties "user.agent.name" and "user.agent.version". @param loader The class loader to use to load the resource. @param filename The name of the file to load. @return A string that represents the first part of the UA string eg java-cloudant/2.6.1
[ "Loads", "the", "properties", "file", "using", "the", "classloader", "provided", ".", "Creating", "a", "string", "from", "the", "properties", "user", ".", "agent", ".", "name", "and", "user", ".", "agent", ".", "version", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/UserAgentInterceptor.java#L73-L93
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/IamCookieInterceptor.java
IamCookieInterceptor.getBearerToken
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
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; } }
[ "private", "String", "getBearerToken", "(", "HttpConnectionInterceptorContext", "context", ")", "{", "final", "AtomicReference", "<", "String", ">", "iamTokenResponse", "=", "new", "AtomicReference", "<", "String", ">", "(", ")", ";", "boolean", "result", "=", "su...
get bearer token returned by IAM in JSON format
[ "get", "bearer", "token", "returned", "by", "IAM", "in", "JSON", "format" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/internal/interceptors/IamCookieInterceptor.java#L90-L100
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java
QueryBuilder.useIndex
public QueryBuilder useIndex(String designDocument, String indexName) { useIndex = new String[]{designDocument, indexName}; return this; }
java
public QueryBuilder useIndex(String designDocument, String indexName) { useIndex = new String[]{designDocument, indexName}; return this; }
[ "public", "QueryBuilder", "useIndex", "(", "String", "designDocument", ",", "String", "indexName", ")", "{", "useIndex", "=", "new", "String", "[", "]", "{", "designDocument", ",", "indexName", "}", ";", "return", "this", ";", "}" ]
Instruct a query to use a specific index. @param designDocument Design document to use. @param indexName Index name to use. @return {@code QueryBuilder} object for method chaining.
[ "Instruct", "a", "query", "to", "use", "a", "specific", "index", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java#L183-L186
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java
QueryBuilder.quoteSort
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
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(); }
[ "private", "static", "String", "quoteSort", "(", "Sort", "[", "]", "sort", ")", "{", "LinkedList", "<", "String", ">", "sorts", "=", "new", "LinkedList", "<", "String", ">", "(", ")", ";", "for", "(", "Sort", "pair", ":", "sort", ")", "{", "sorts", ...
sorts are a bit more awkward and need a helper...
[ "sorts", "are", "a", "bit", "more", "awkward", "and", "need", "a", "helper", "..." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/QueryBuilder.java#L240-L246
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/views/ViewRequestBuilder.java
ViewRequestBuilder.newMultipleRequest
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 <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType, Class<V> valueType) { return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(), valueType)); }
[ "public", "<", "K", ",", "V", ">", "MultipleRequestBuilder", "<", "K", ",", "V", ">", "newMultipleRequest", "(", "Key", ".", "Type", "<", "K", ">", "keyType", ",", "Class", "<", "V", ">", "valueType", ")", "{", "return", "new", "MultipleRequestBuilderImp...
Create a new builder for multiple unpaginated requests on the view. @param keyType {@link com.cloudant.client.api.views.Key.Type} of the key emitted by the view @param valueType class of the type of value emitted by the view @param <K> type of key emitted by the view @param <V> type of value emitted by the view @return a new {@link MultipleRequestBuilder} for the database view specified by this ViewRequestBuilder
[ "Create", "a", "new", "builder", "for", "multiple", "unpaginated", "requests", "on", "the", "view", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/views/ViewRequestBuilder.java#L118-L122
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.find
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 <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); }
[ "public", "<", "T", ">", "T", "find", "(", "Class", "<", "T", ">", "classType", ",", "String", "id", ",", "String", "rev", ")", "{", "assertNotEmpty", "(", "classType", ",", "\"Class\"", ")", ";", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";",...
Finds an Object of the specified type. @param <T> Object type. @param classType The class of type T. @param id The document _id field. @param rev The document _rev field. @return An object of type T. @throws NoDocumentException If the document is not found in the database.
[ "Finds", "an", "Object", "of", "the", "specified", "type", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L115-L121
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.contains
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 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; }
[ "public", "boolean", "contains", "(", "String", "id", ")", "{", "assertNotEmpty", "(", "id", ",", "\"id\"", ")", ";", "InputStream", "response", "=", "null", ";", "try", "{", "response", "=", "couchDbClient", ".", "head", "(", "new", "DatabaseURIHelper", "...
Checks if a document exist in the database. @param id The document _id field. @return true If the document is found, false otherwise.
[ "Checks", "if", "a", "document", "exist", "in", "the", "database", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L173-L184
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java
CouchDatabaseBase.bulk
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 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); } }
[ "public", "List", "<", "Response", ">", "bulk", "(", "List", "<", "?", ">", "objects", ",", "boolean", "allOrNothing", ")", "{", "assertNotEmpty", "(", "objects", ",", "\"objects\"", ")", ";", "InputStream", "responseStream", "=", "null", ";", "HttpConnectio...
Performs a Bulk Documents insert request. @param objects The {@link List} of objects. @param allOrNothing Indicates whether the request has <tt>all-or-nothing</tt> semantics. @return {@code List<Response>} Containing the resulted entries.
[ "Performs", "a", "Bulk", "Documents", "insert", "request", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDatabaseBase.java#L269-L298
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.query
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> 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); } }
[ "public", "<", "T", ">", "List", "<", "T", ">", "query", "(", "String", "query", ",", "Class", "<", "T", ">", "classOfT", ")", "{", "InputStream", "instream", "=", "null", ";", "List", "<", "T", ">", "result", "=", "new", "ArrayList", "<", "T", "...
Queries a Search Index and returns ungrouped results. In case the query used grouping, an empty list is returned @param <T> Object type T @param query the Lucene query to be passed to the Search index @param classOfT The class of type T @return The result of the search query as a {@code List<T> }
[ "Queries", "a", "Search", "Index", "and", "returns", "ungrouped", "results", ".", "In", "case", "the", "query", "used", "grouping", "an", "empty", "list", "is", "returned" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L141-L166
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.queryGroups
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 <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); } }
[ "public", "<", "T", ">", "Map", "<", "String", ",", "List", "<", "T", ">", ">", "queryGroups", "(", "String", "query", ",", "Class", "<", "T", ">", "classOfT", ")", "{", "InputStream", "instream", "=", "null", ";", "try", "{", "Reader", "reader", "...
Queries a Search Index and returns grouped results in a map where key of the map is the groupName. In case the query didnt use grouping, an empty map is returned @param <T> Object type T @param query the Lucene query to be passed to the Search index @param classOfT The class of type T @return The result of the grouped search query as a ordered {@code Map<String,T> }
[ "Queries", "a", "Search", "Index", "and", "returns", "grouped", "results", "in", "a", "map", "where", "key", "of", "the", "map", "is", "the", "groupName", ".", "In", "case", "the", "query", "didnt", "use", "grouping", "an", "empty", "map", "is", "returne...
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L178-L209
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.groupField
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 groupField(String fieldName, boolean isNumber) { assertNotEmpty(fieldName, "fieldName"); if (isNumber) { databaseHelper.query("group_field", fieldName + "<number>"); } else { databaseHelper.query("group_field", fieldName); } return this; }
[ "public", "Search", "groupField", "(", "String", "fieldName", ",", "boolean", "isNumber", ")", "{", "assertNotEmpty", "(", "fieldName", ",", "\"fieldName\"", ")", ";", "if", "(", "isNumber", ")", "{", "databaseHelper", ".", "query", "(", "\"group_field\"", ","...
Group results by the specified field. @param fieldName by which to group results @param isNumber whether field isNumeric. @return this for additional parameter setting or to query
[ "Group", "results", "by", "the", "specified", "field", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L301-L309
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Search.java
Search.counts
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 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; }
[ "public", "Search", "counts", "(", "String", "[", "]", "countsfields", ")", "{", "assert", "(", "countsfields", ".", "length", ">", "0", ")", ";", "JsonArray", "countsJsonArray", "=", "new", "JsonArray", "(", ")", ";", "for", "(", "String", "countsfield", ...
Array of fieldNames for which counts should be produced @param countsfields array of the field names @return this for additional parameter setting or to query
[ "Array", "of", "fieldNames", "for", "which", "counts", "should", "be", "produced" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Search.java#L358-L367
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java
Indexes.allIndexes
public List<Index<Field>> allIndexes() { List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>(); indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class)); return indexesOfAnyType; }
java
public List<Index<Field>> allIndexes() { List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>(); indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class)); return indexesOfAnyType; }
[ "public", "List", "<", "Index", "<", "Field", ">", ">", "allIndexes", "(", ")", "{", "List", "<", "Index", "<", "Field", ">>", "indexesOfAnyType", "=", "new", "ArrayList", "<", "Index", "<", "Field", ">", ">", "(", ")", ";", "indexesOfAnyType", ".", ...
All the indexes defined in the database. Type widening means that the returned Index objects are limited to the name, design document and type of the index and the names of the fields. @return a list of defined indexes with name, design document, type and field names.
[ "All", "the", "indexes", "defined", "in", "the", "database", ".", "Type", "widening", "means", "that", "the", "returned", "Index", "objects", "are", "limited", "to", "the", "name", "design", "document", "and", "type", "of", "the", "index", "and", "the", "n...
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java#L53-L57
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java
Indexes.listIndexType
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
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; }
[ "private", "<", "T", "extends", "Index", ">", "List", "<", "T", ">", "listIndexType", "(", "String", "type", ",", "Class", "<", "T", ">", "modelType", ")", "{", "List", "<", "T", ">", "indexesOfType", "=", "new", "ArrayList", "<", "T", ">", "(", ")...
Utility to list indexes of a given type. @param type the type of index to list, null means all types @param modelType the class to deserialize the index into @param <T> the type of the index @return the list of indexes of the specified type
[ "Utility", "to", "list", "indexes", "of", "a", "given", "type", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/query/Indexes.java#L67-L84
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java
URIBaseMethods.encodePath
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
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); } }
[ "String", "encodePath", "(", "String", "in", ")", "{", "try", "{", "String", "encodedString", "=", "HierarchicalUriComponents", ".", "encodeUriComponent", "(", "in", ",", "\"UTF-8\"", ",", "HierarchicalUriComponents", ".", "Type", ".", "PATH_SEGMENT", ")", ";", ...
Encode a path in a manner suitable for a GET request @param in The path to encode, eg "a/document" @return The encoded path eg "a%2Fdocument"
[ "Encode", "a", "path", "in", "a", "manner", "suitable", "for", "a", "GET", "request" ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java#L92-L111
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java
URIBaseMethods.build
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 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); } }
[ "public", "URI", "build", "(", ")", "{", "try", "{", "String", "uriString", "=", "String", ".", "format", "(", "\"%s%s\"", ",", "baseUri", ".", "toASCIIString", "(", ")", ",", "(", "path", ".", "isEmpty", "(", ")", "?", "\"\"", ":", "path", ")", ")...
Build and return the complete URI containing values such as the document ID, attachment ID, and query syntax.
[ "Build", "and", "return", "the", "complete", "URI", "containing", "values", "such", "as", "the", "document", "ID", "attachment", "ID", "and", "query", "syntax", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/URIBaseMethods.java#L117-L139
train
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/ClientBuilder.java
ClientBuilder.account
public static ClientBuilder account(String account) { logger.config("Account: " + account); return ClientBuilder.url( convertStringToURL(String.format("https://%s.cloudant.com", account))); }
java
public static ClientBuilder account(String account) { logger.config("Account: " + account); return ClientBuilder.url( convertStringToURL(String.format("https://%s.cloudant.com", account))); }
[ "public", "static", "ClientBuilder", "account", "(", "String", "account", ")", "{", "logger", ".", "config", "(", "\"Account: \"", "+", "account", ")", ";", "return", "ClientBuilder", ".", "url", "(", "convertStringToURL", "(", "String", ".", "format", "(", ...
Constructs a new ClientBuilder for building a CloudantClient instance to connect to the Cloudant server with the specified account. @param account the Cloudant account name to connect to e.g. "example" is the account name for the "example.cloudant.com" endpoint @return a new ClientBuilder for the account @throws IllegalArgumentException if the specified account name forms an invalid endpoint URL
[ "Constructs", "a", "new", "ClientBuilder", "for", "building", "a", "CloudantClient", "instance", "to", "connect", "to", "the", "Cloudant", "server", "with", "the", "specified", "account", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/ClientBuilder.java#L184-L188
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.setRequestBody
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 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); } }
[ "public", "HttpConnection", "setRequestBody", "(", "final", "String", "input", ")", "{", "try", "{", "final", "byte", "[", "]", "inputBytes", "=", "input", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "return", "setRequestBody", "(", "inputBytes", ")", ";", ...
Set the String of request body data to be sent to the server. @param input String of request body data to be sent to the server @return an {@link HttpConnection} for method chaining
[ "Set", "the", "String", "of", "request", "body", "data", "to", "be", "sent", "to", "the", "server", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L156-L165
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.setRequestBody
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
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); } }
[ "public", "HttpConnection", "setRequestBody", "(", "final", "InputStream", "input", ",", "final", "long", "inputLength", ")", "{", "try", "{", "return", "setRequestBody", "(", "new", "InputStreamWrappingGenerator", "(", "input", ",", "inputLength", ")", ",", "inpu...
Set the InputStream of request body data, of known length, to be sent to the server. @param input InputStream of request body data to be sent to the server @param inputLength Length of request body data to be sent to the server, in bytes @return an {@link HttpConnection} for method chaining @deprecated Use {@link #setRequestBody(InputStreamGenerator, long)}
[ "Set", "the", "InputStream", "of", "request", "body", "data", "of", "known", "length", "to", "be", "sent", "to", "the", "server", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L197-L205
train
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.getLogRequestIdentifier
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 String getLogRequestIdentifier() { if (logIdentifier == null) { logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()), numberOfRetries, connection.getRequestMethod(), connection.getURL()); } return logIdentifier; }
[ "private", "String", "getLogRequestIdentifier", "(", ")", "{", "if", "(", "logIdentifier", "==", "null", ")", "{", "logIdentifier", "=", "String", ".", "format", "(", "\"%s-%s %s %s\"", ",", "Integer", ".", "toHexString", "(", "hashCode", "(", ")", ")", ",",...
Get a prefix for the log message to help identify which request is which and which responses belong to which requests.
[ "Get", "a", "prefix", "for", "the", "log", "message", "to", "help", "identify", "which", "request", "is", "which", "and", "which", "responses", "belong", "to", "which", "requests", "." ]
42c438654945361bded2cc0827afc046d535b31b
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L548-L554
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/signing/PGPSigner.java
PGPSigner.getSecretKey
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 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; }
[ "private", "PGPSecretKey", "getSecretKey", "(", "InputStream", "input", ",", "String", "keyId", ")", "throws", "IOException", ",", "PGPException", "{", "PGPSecretKeyRingCollection", "keyrings", "=", "new", "PGPSecretKeyRingCollection", "(", "PGPUtil", ".", "getDecoderSt...
Returns the secret key matching the specified identifier. @param input the input stream containing the keyring collection @param keyId the 4 bytes identifier of the key
[ "Returns", "the", "secret", "key", "matching", "the", "specified", "identifier", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/signing/PGPSigner.java#L136-L155
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/signing/PGPSigner.java
PGPSigner.trim
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
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); }
[ "private", "String", "trim", "(", "String", "line", ")", "{", "char", "[", "]", "chars", "=", "line", ".", "toCharArray", "(", ")", ";", "int", "len", "=", "chars", ".", "length", ";", "while", "(", "len", ">", "0", ")", "{", "if", "(", "!", "C...
Trim the trailing spaces. @param line
[ "Trim", "the", "trailing", "spaces", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/signing/PGPSigner.java#L162-L174
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/DebMaker.java
DebMaker.validate
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
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); }
[ "public", "void", "validate", "(", ")", "throws", "PackagingException", "{", "if", "(", "control", "==", "null", "||", "!", "control", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "PackagingException", "(", "\"The 'control' attribute doesn't point to a ...
Validates the input parameters.
[ "Validates", "the", "input", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/DebMaker.java#L248-L282
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/debian/ControlFile.java
ControlFile.getUserDefinedFieldName
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
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; }
[ "protected", "String", "getUserDefinedFieldName", "(", "String", "field", ")", "{", "int", "index", "=", "field", ".", "indexOf", "(", "'", "'", ")", ";", "char", "letter", "=", "getUserDefinedFieldLetter", "(", ")", ";", "for", "(", "int", "i", "=", "0"...
Returns the user defined field without its prefix. @param field the name of the user defined field @return the user defined field without the prefix, or null if the fields doesn't apply to this control file. @since 1.1
[ "Returns", "the", "user", "defined", "field", "without", "its", "prefix", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/debian/ControlFile.java#L216-L227
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.replaceVariables
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 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(); }
[ "public", "static", "String", "replaceVariables", "(", "final", "VariableResolver", "pResolver", ",", "final", "String", "pExpression", ",", "final", "String", "pOpen", ",", "final", "String", "pClose", ")", "{", "final", "char", "[", "]", "open", "=", "pOpen"...
Substitute the variables in the given expression with the values from the resolver @param pResolver @param pExpression
[ "Substitute", "the", "variables", "in", "the", "given", "expression", "with", "the", "values", "from", "the", "resolver" ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L129-L213
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.toUnixLineEndings
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 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(); }
[ "public", "static", "byte", "[", "]", "toUnixLineEndings", "(", "InputStream", "input", ")", "throws", "IOException", "{", "String", "encoding", "=", "\"ISO-8859-1\"", ";", "FixCrLfFilter", "filter", "=", "new", "FixCrLfFilter", "(", "new", "InputStreamReader", "(...
Replaces new line delimiters in the input stream with the Unix line feed. @param input
[ "Replaces", "new", "line", "delimiters", "in", "the", "input", "stream", "with", "the", "Unix", "line", "feed", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L220-L229
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.movePath
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 movePath( final String file, final String target ) { final String name = new File(file).getName(); return target.endsWith("/") ? target + name : target + '/' + name; }
[ "public", "static", "String", "movePath", "(", "final", "String", "file", ",", "final", "String", "target", ")", "{", "final", "String", "name", "=", "new", "File", "(", "file", ")", ".", "getName", "(", ")", ";", "return", "target", ".", "endsWith", "...
Construct new path by replacing file directory part. No files are actually modified. @param file path to move @param target new path directory
[ "Construct", "new", "path", "by", "replacing", "file", "directory", "part", ".", "No", "files", "are", "actually", "modified", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L299-L303
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.lookupIfEmpty
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 String lookupIfEmpty( final String value, final Map<String, String> props, final String key ) { return value != null ? value : props.get(key); }
[ "public", "static", "String", "lookupIfEmpty", "(", "final", "String", "value", ",", "final", "Map", "<", "String", ",", "String", ">", "props", ",", "final", "String", "key", ")", "{", "return", "value", "!=", "null", "?", "value", ":", "props", ".", ...
Extracts value from map if given value is null. @param value current value @param props properties to extract value from @param key property name to extract @return initial value or value extracted from map
[ "Extracts", "value", "from", "map", "if", "given", "value", "is", "null", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L312-L316
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.getKnownPGPSecureRingLocations
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 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; }
[ "public", "static", "Collection", "<", "String", ">", "getKnownPGPSecureRingLocations", "(", ")", "{", "final", "LinkedHashSet", "<", "String", ">", "locations", "=", "new", "LinkedHashSet", "<", "String", ">", "(", ")", ";", "final", "String", "os", "=", "S...
Get the known locations where the secure keyring can be located. Looks through known locations of the GNU PG secure keyring. @return The location of the PGP secure keyring if it was found, null otherwise
[ "Get", "the", "known", "locations", "where", "the", "secure", "keyring", "can", "be", "located", ".", "Looks", "through", "known", "locations", "of", "the", "GNU", "PG", "secure", "keyring", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L325-L374
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.guessKeyRingFile
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 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()); }
[ "public", "static", "File", "guessKeyRingFile", "(", ")", "throws", "FileNotFoundException", "{", "final", "Collection", "<", "String", ">", "possibleLocations", "=", "getKnownPGPSecureRingLocations", "(", ")", ";", "for", "(", "final", "String", "location", ":", ...
Tries to guess location of the user secure keyring using various heuristics. @return path to the keyring file @throws FileNotFoundException if no keyring file found
[ "Tries", "to", "guess", "location", "of", "the", "user", "secure", "keyring", "using", "various", "heuristics", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L383-L400
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/utils/Utils.java
Utils.defaultString
public static String defaultString(final String str, final String fallback) { return isNullOrEmpty(str) ? fallback : str; }
java
public static String defaultString(final String str, final String fallback) { return isNullOrEmpty(str) ? fallback : str; }
[ "public", "static", "String", "defaultString", "(", "final", "String", "str", ",", "final", "String", "fallback", ")", "{", "return", "isNullOrEmpty", "(", "str", ")", "?", "fallback", ":", "str", ";", "}" ]
Return fallback if first string is null or empty
[ "Return", "fallback", "if", "first", "string", "is", "null", "or", "empty" ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/utils/Utils.java#L412-L414
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/producers/Producers.java
Producers.defaultFileEntryWithName
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 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; }
[ "static", "TarArchiveEntry", "defaultFileEntryWithName", "(", "final", "String", "fileName", ")", "{", "TarArchiveEntry", "entry", "=", "new", "TarArchiveEntry", "(", "fileName", ",", "true", ")", ";", "entry", ".", "setUserId", "(", "ROOT_UID", ")", ";", "entry...
Creates a tar file entry with defaults parameters. @param fileName the entry name @return file entry with reasonable defaults
[ "Creates", "a", "tar", "file", "entry", "with", "defaults", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/producers/Producers.java#L42-L50
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/producers/Producers.java
Producers.defaultDirEntryWithName
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 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; }
[ "static", "TarArchiveEntry", "defaultDirEntryWithName", "(", "final", "String", "dirName", ")", "{", "TarArchiveEntry", "entry", "=", "new", "TarArchiveEntry", "(", "dirName", ",", "true", ")", ";", "entry", ".", "setUserId", "(", "ROOT_UID", ")", ";", "entry", ...
Creates a tar directory entry with defaults parameters. @param dirName the directory name @return dir entry with reasonable defaults
[ "Creates", "a", "tar", "directory", "entry", "with", "defaults", "parameters", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/producers/Producers.java#L57-L65
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/producers/Producers.java
Producers.produceInputStreamWithEntry
static void produceInputStreamWithEntry( final DataConsumer consumer, final InputStream inputStream, final TarArchiveEntry entry ) throws IOException { try { consumer.onEachFile(inputStream, entry); } finally { IOUtils.closeQuietly(inputStream); } }
java
static void produceInputStreamWithEntry( final DataConsumer consumer, final InputStream inputStream, final TarArchiveEntry entry ) throws IOException { try { consumer.onEachFile(inputStream, entry); } finally { IOUtils.closeQuietly(inputStream); } }
[ "static", "void", "produceInputStreamWithEntry", "(", "final", "DataConsumer", "consumer", ",", "final", "InputStream", "inputStream", ",", "final", "TarArchiveEntry", "entry", ")", "throws", "IOException", "{", "try", "{", "consumer", ".", "onEachFile", "(", "input...
Feeds input stream to data consumer using metadata from tar entry. @param consumer the consumer @param inputStream the stream to feed @param entry the entry to use for metadata @throws IOException on consume error
[ "Feeds", "input", "stream", "to", "data", "consumer", "using", "metadata", "from", "tar", "entry", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/producers/Producers.java#L86-L94
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/debian/ControlField.java
ControlField.format
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 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(); }
[ "public", "String", "format", "(", "String", "value", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "value", "!=", "null", "&&", "value", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", ...
Returns the field with the specified value properly formatted. Multiline values are automatically indented, and dots are added on the empty lines. <pre> Field-Name: value </pre>
[ "Returns", "the", "field", "with", "the", "specified", "value", "properly", "formatted", ".", "Multiline", "values", "are", "automatically", "indented", "and", "dots", "are", "added", "on", "the", "empty", "lines", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/debian/ControlField.java#L96-L127
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/debian/ChangesFile.java
ChangesFile.initialize
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
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()); }
[ "public", "void", "initialize", "(", "BinaryPackageControlFile", "packageControlFile", ")", "{", "set", "(", "\"Binary\"", ",", "packageControlFile", ".", "get", "(", "\"Package\"", ")", ")", ";", "set", "(", "\"Source\"", ",", "Utils", ".", "defaultString", "("...
Initializes the fields on the changes file with the values of the specified binary package control file. @param packageControlFile
[ "Initializes", "the", "fields", "on", "the", "changes", "file", "with", "the", "values", "of", "the", "specified", "binary", "package", "control", "file", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/debian/ChangesFile.java#L66-L86
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/maven/DebMojo.java
DebMojo.initializeSignProperties
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
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()); } } }
[ "private", "void", "initializeSignProperties", "(", ")", "{", "if", "(", "!", "signPackage", "&&", "!", "signChanges", ")", "{", "return", ";", "}", "if", "(", "key", "!=", "null", "&&", "keyring", "!=", "null", "&&", "passphrase", "!=", "null", ")", "...
Initializes unspecified sign properties using available defaults and global settings.
[ "Initializes", "unspecified", "sign", "properties", "using", "available", "defaults", "and", "global", "settings", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/maven/DebMojo.java#L623-L647
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/maven/DebMojo.java
DebMojo.readPropertiesFromActiveProfiles
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
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; }
[ "public", "Map", "<", "String", ",", "String", ">", "readPropertiesFromActiveProfiles", "(", "final", "String", "prefix", ",", "final", "String", "...", "properties", ")", "{", "if", "(", "settings", "==", "null", ")", "{", "console", ".", "debug", "(", "\...
Read properties from the active profiles. Goes through all active profiles (in the order the profiles are defined in settings.xml) and extracts the desired properties (if present). The prefix is used when looking up properties in the profile but not in the returned map. @param prefix The prefix to use or null if no prefix should be used @param properties The properties to read @return A map containing the values for the properties that were found
[ "Read", "properties", "from", "the", "active", "profiles", "." ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/maven/DebMojo.java#L704-L738
train
tcurdt/jdeb
src/main/java/org/vafer/jdeb/ControlBuilder.java
ControlBuilder.buildControl
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
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(); }
[ "void", "buildControl", "(", "BinaryPackageControlFile", "packageControlFile", ",", "File", "[", "]", "controlFiles", ",", "List", "<", "String", ">", "conffiles", ",", "StringBuilder", "checksums", ",", "File", "output", ")", "throws", "IOException", ",", "ParseE...
Build control archive of the deb @param packageControlFile the package control file @param controlFiles the other control information files (maintainer scripts, etc) @param dataSize the size of the installed package @param checksums the md5 checksums of the files in the data archive @param output @return @throws java.io.FileNotFoundException @throws java.io.IOException @throws java.text.ParseException
[ "Build", "control", "archive", "of", "the", "deb" ]
b899a7b1b3391356aafc491ab601f258961f67f0
https://github.com/tcurdt/jdeb/blob/b899a7b1b3391356aafc491ab601f258961f67f0/src/main/java/org/vafer/jdeb/ControlBuilder.java#L82-L148
train
Instamojo/instamojo-java
src/main/java/com/instamojo/wrapper/util/HttpUtils.java
HttpUtils.get
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 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); }
[ "public", "static", "String", "get", "(", "String", "url", ",", "Map", "<", "String", ",", "String", ">", "customHeaders", ",", "Map", "<", "String", ",", "String", ">", "params", ")", "throws", "URISyntaxException", ",", "IOException", ",", "HTTPException",...
Send get request. @param url the url @param customHeaders the customHeaders @param params the params @return the string @throws URISyntaxException the uri syntax exception @throws IOException the io exception
[ "Send", "get", "request", "." ]
7b1bf5edb6ade1f1b816a7db1262ef09f7d5273a
https://github.com/Instamojo/instamojo-java/blob/7b1bf5edb6ade1f1b816a7db1262ef09f7d5273a/src/main/java/com/instamojo/wrapper/util/HttpUtils.java#L54-L80
train
Instamojo/instamojo-java
src/main/java/com/instamojo/wrapper/util/HttpUtils.java
HttpUtils.post
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 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); }
[ "public", "static", "String", "post", "(", "String", "url", ",", "Map", "<", "String", ",", "String", ">", "customHeaders", ",", "Map", "<", "String", ",", "String", ">", "params", ")", "throws", "IOException", ",", "HTTPException", "{", "LOGGER", ".", "...
Send post request. @param url the url @param customHeaders the customHeaders @param params the params @return the string @throws IOException the io exception
[ "Send", "post", "request", "." ]
7b1bf5edb6ade1f1b816a7db1262ef09f7d5273a
https://github.com/Instamojo/instamojo-java/blob/7b1bf5edb6ade1f1b816a7db1262ef09f7d5273a/src/main/java/com/instamojo/wrapper/util/HttpUtils.java#L91-L117
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/internal/TransitionController.java
TransitionController.reverse
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 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(); }
[ "public", "T", "reverse", "(", ")", "{", "String", "id", "=", "getId", "(", ")", ";", "String", "REVERSE", "=", "\"_REVERSE\"", ";", "if", "(", "id", ".", "endsWith", "(", "REVERSE", ")", ")", "{", "setId", "(", "id", ".", "substring", "(", "0", ...
Reverse how the transition is applied, such that the transition previously performed when progress=start of range is only performed when progress=end of range @return
[ "Reverse", "how", "the", "transition", "is", "applied", "such", "that", "the", "transition", "previously", "performed", "when", "progress", "=", "start", "of", "range", "is", "only", "performed", "when", "progress", "=", "end", "of", "range" ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/internal/TransitionController.java#L125-L138
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/AbstractTransitionBuilder.java
AbstractTransitionBuilder.transitFloat
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 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(); }
[ "public", "T", "transitFloat", "(", "int", "propertyId", ",", "float", "...", "vals", ")", "{", "String", "property", "=", "getPropertyName", "(", "propertyId", ")", ";", "mHolders", ".", "put", "(", "propertyId", ",", "PropertyValuesHolder", ".", "ofFloat", ...
Transits a float propertyId from the start value to the end value. @param propertyId @param vals @return self
[ "Transits", "a", "float", "propertyId", "from", "the", "start", "value", "to", "the", "end", "value", "." ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/AbstractTransitionBuilder.java#L642-L647
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/AbstractTransitionBuilder.java
AbstractTransitionBuilder.transitInt
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
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(); }
[ "public", "T", "transitInt", "(", "int", "propertyId", ",", "int", "...", "vals", ")", "{", "String", "property", "=", "getPropertyName", "(", "propertyId", ")", ";", "mHolders", ".", "put", "(", "propertyId", ",", "PropertyValuesHolder", ".", "ofInt", "(", ...
Transits a float property from the start value to the end value. @param propertyId @param vals @return self
[ "Transits", "a", "float", "property", "from", "the", "start", "value", "to", "the", "end", "value", "." ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/AbstractTransitionBuilder.java#L656-L661
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/AbstractTransition.java
AbstractTransition.isCompatible
@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
@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; }
[ "@", "CheckResult", "public", "boolean", "isCompatible", "(", "AbstractTransition", "another", ")", "{", "if", "(", "getClass", "(", ")", ".", "equals", "(", "another", ".", "getClass", "(", ")", ")", "&&", "mTarget", "==", "another", ".", "mTarget", "&&",...
Checks to see if another AbstractTransition's states is isCompatible for merging. @param another @return
[ "Checks", "to", "see", "if", "another", "AbstractTransition", "s", "states", "is", "isCompatible", "for", "merging", "." ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/AbstractTransition.java#L140-L147
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/AbstractTransition.java
AbstractTransition.merge
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 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; }
[ "public", "boolean", "merge", "(", "AbstractTransition", "another", ")", "{", "if", "(", "!", "isCompatible", "(", "another", ")", ")", "{", "return", "false", ";", "}", "if", "(", "another", ".", "mId", "!=", "null", ")", "{", "if", "(", "mId", "=="...
Merge another AbstractTransition's states into this object, such that the other AbstractTransition can be discarded. @param another @return true if the merge is successful.
[ "Merge", "another", "AbstractTransition", "s", "states", "into", "this", "object", "such", "that", "the", "other", "AbstractTransition", "can", "be", "discarded", "." ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/AbstractTransition.java#L156-L188
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/animation/AnimationManager.java
AnimationManager.removeAllAnimations
public void removeAllAnimations() { for (int i = 0, size = mAnimationList.size(); i < size; i++) { mAnimationList.get(i).removeAnimationListener(mAnimationListener); } mAnimationList.clear(); }
java
public void removeAllAnimations() { for (int i = 0, size = mAnimationList.size(); i < size; i++) { mAnimationList.get(i).removeAnimationListener(mAnimationListener); } mAnimationList.clear(); }
[ "public", "void", "removeAllAnimations", "(", ")", "{", "for", "(", "int", "i", "=", "0", ",", "size", "=", "mAnimationList", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "mAnimationList", ".", "get", "(", "i", ")", "."...
Stops and clears all transitions
[ "Stops", "and", "clears", "all", "transitions" ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/animation/AnimationManager.java#L123-L128
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/DefaultTransitionManager.java
DefaultTransitionManager.stopTransition
@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
@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(); } }
[ "@", "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", "(", ")", ";", ...
Stops all transitions.
[ "Stops", "all", "transitions", "." ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/DefaultTransitionManager.java#L137-L147
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java
TransitionControllerManager.start
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 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(); } }
[ "public", "void", "start", "(", ")", "{", "if", "(", "TransitionConfig", ".", "isDebug", "(", ")", ")", "{", "getTransitionStateHolder", "(", ")", ".", "start", "(", ")", ";", "}", "mLastProgress", "=", "Float", ".", "MIN_VALUE", ";", "TransitionController...
Starts the transition
[ "Starts", "the", "transition" ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java#L100-L120
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java
TransitionControllerManager.end
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 end() { if (TransitionConfig.isPrintDebug()) { getTransitionStateHolder().end(); getTransitionStateHolder().print(); } for (int i = 0, size = mTransitionControls.size(); i < size; i++) { mTransitionControls.get(i).end(); } }
[ "public", "void", "end", "(", ")", "{", "if", "(", "TransitionConfig", ".", "isPrintDebug", "(", ")", ")", "{", "getTransitionStateHolder", "(", ")", ".", "end", "(", ")", ";", "getTransitionStateHolder", "(", ")", ".", "print", "(", ")", ";", "}", "fo...
Ends the transition
[ "Ends", "the", "transition" ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java#L133-L142
train
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java
TransitionControllerManager.reverse
public void reverse() { for (int i = 0, size = mTransitionControls.size(); i < size; i++) { mTransitionControls.get(i).reverse(); } }
java
public void reverse() { for (int i = 0, size = mTransitionControls.size(); i < size; i++) { mTransitionControls.get(i).reverse(); } }
[ "public", "void", "reverse", "(", ")", "{", "for", "(", "int", "i", "=", "0", ",", "size", "=", "mTransitionControls", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "mTransitionControls", ".", "get", "(", "i", ")", ".", ...
Reverses all the TransitionControllers managed by this TransitionManager
[ "Reverses", "all", "the", "TransitionControllers", "managed", "by", "this", "TransitionManager" ]
7b53074206622f5cf5d82091d891a7ed8b9f06cd
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java#L206-L210
train
wildfly-extras/wildfly-camel
subsystem/security/src/main/java/org/wildfly/extension/camel/security/LoginContextBuilder.java
LoginContextBuilder.getClientLoginContext
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
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); }
[ "private", "LoginContext", "getClientLoginContext", "(", ")", "throws", "LoginException", "{", "Configuration", "config", "=", "new", "Configuration", "(", ")", "{", "@", "Override", "public", "AppConfigurationEntry", "[", "]", "getAppConfigurationEntry", "(", "String...
Provides a RunAs client login context
[ "Provides", "a", "RunAs", "client", "login", "context" ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/subsystem/security/src/main/java/org/wildfly/extension/camel/security/LoginContextBuilder.java#L101-L114
train
wildfly-extras/wildfly-camel
config/src/main/java/org/wildfly/extras/config/internal/Main.java
Main.mainInternal
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 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; } }
[ "public", "static", "void", "mainInternal", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "Options", "options", "=", "new", "Options", "(", ")", ";", "CmdLineParser", "parser", "=", "new", "CmdLineParser", "(", "options", ")", ";", "try...
Entry point with no system exit
[ "Entry", "point", "with", "no", "system", "exit" ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/config/src/main/java/org/wildfly/extras/config/internal/Main.java#L42-L66
train
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertNull
public static <T> T assertNull(T value, String message) { if (value != null) throw new IllegalStateException(message); return value; }
java
public static <T> T assertNull(T value, String message) { if (value != null) throw new IllegalStateException(message); return value; }
[ "public", "static", "<", "T", ">", "T", "assertNull", "(", "T", "value", ",", "String", "message", ")", "{", "if", "(", "value", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "message", ")", ";", "return", "value", ";", "}" ]
Throws an IllegalStateException when the given value is not null. @return the value
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "value", "is", "not", "null", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L38-L42
train
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertNotNull
public static <T> T assertNotNull(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; }
[ "public", "static", "<", "T", ">", "T", "assertNotNull", "(", "T", "value", ",", "String", "message", ")", "{", "if", "(", "value", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "message", ")", ";", "return", "value", ";", "}" ]
Throws an IllegalStateException when the given value is null. @return the value
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "value", "is", "null", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L48-L52
train
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertTrue
public static Boolean assertTrue(Boolean value, String message) { if (!Boolean.valueOf(value)) 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; }
[ "public", "static", "Boolean", "assertTrue", "(", "Boolean", "value", ",", "String", "message", ")", "{", "if", "(", "!", "Boolean", ".", "valueOf", "(", "value", ")", ")", "throw", "new", "IllegalStateException", "(", "message", ")", ";", "return", "value...
Throws an IllegalStateException when the given value is not true.
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "value", "is", "not", "true", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L57-L62
train
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertFalse
public static Boolean assertFalse(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; }
[ "public", "static", "Boolean", "assertFalse", "(", "Boolean", "value", ",", "String", "message", ")", "{", "if", "(", "Boolean", ".", "valueOf", "(", "value", ")", ")", "throw", "new", "IllegalStateException", "(", "message", ")", ";", "return", "value", "...
Throws an IllegalStateException when the given value is not false.
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "value", "is", "not", "false", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L67-L71
train
wildfly-extras/wildfly-camel
config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java
IllegalArgumentAssertion.assertNotNull
public static <T> T assertNotNull(T value, String name) { if (value == null) throw new IllegalArgumentException("Null " + name); return value; }
java
public static <T> T assertNotNull(T value, String name) { if (value == null) throw new IllegalArgumentException("Null " + name); return value; }
[ "public", "static", "<", "T", ">", "T", "assertNotNull", "(", "T", "value", ",", "String", "name", ")", "{", "if", "(", "value", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Null \"", "+", "name", ")", ";", "return", "value", ...
Throws an IllegalArgumentException when the given value is null. @param value the value to assert if not null @param name the name of the argument @param <T> The generic type of the value to assert if not null @return the value
[ "Throws", "an", "IllegalArgumentException", "when", "the", "given", "value", "is", "null", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java#L41-L46
train
wildfly-extras/wildfly-camel
config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java
IllegalArgumentAssertion.assertTrue
public static Boolean assertTrue(Boolean value, String message) { if (!Boolean.valueOf(value)) throw new IllegalArgumentException(message); return value; }
java
public static Boolean assertTrue(Boolean value, String message) { if (!Boolean.valueOf(value)) throw new IllegalArgumentException(message); return value; }
[ "public", "static", "Boolean", "assertTrue", "(", "Boolean", "value", ",", "String", "message", ")", "{", "if", "(", "!", "Boolean", ".", "valueOf", "(", "value", ")", ")", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "return", "va...
Throws an IllegalArgumentException when the given value is not true. @param value the value to assert if true @param message the message to display if the value is false @return the value
[ "Throws", "an", "IllegalArgumentException", "when", "the", "given", "value", "is", "not", "true", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java#L54-L58
train
wildfly-extras/wildfly-camel
config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java
IllegalArgumentAssertion.assertFalse
public static Boolean assertFalse(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; }
[ "public", "static", "Boolean", "assertFalse", "(", "Boolean", "value", ",", "String", "message", ")", "{", "if", "(", "Boolean", ".", "valueOf", "(", "value", ")", ")", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "return", "value", ...
Throws an IllegalArgumentException when the given value is not false. @param value the value to assert if false @param message the message to display if the value is false @return the value
[ "Throws", "an", "IllegalArgumentException", "when", "the", "given", "value", "is", "not", "false", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/config/src/main/java/org/wildfly/extras/config/internal/IllegalArgumentAssertion.java#L66-L70
train
wildfly-extras/wildfly-camel
cxfhttp/src/main/java/org/apache/cxf/transport/undertow/UndertowHTTPDestination.java
UndertowHTTPDestination.retrieveEngine
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 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 + "\""); } }
[ "public", "void", "retrieveEngine", "(", ")", "throws", "GeneralSecurityException", ",", "IOException", "{", "if", "(", "serverEngineFactory", "==", "null", ")", "{", "return", ";", "}", "engine", "=", "serverEngineFactory", ".", "retrieveHTTPServerEngine", "(", "...
Post-configure retreival of server engine.
[ "Post", "-", "configure", "retreival", "of", "server", "engine", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/cxfhttp/src/main/java/org/apache/cxf/transport/undertow/UndertowHTTPDestination.java#L82-L105
train
wildfly-extras/wildfly-camel
cxfhttp/src/main/java/org/apache/cxf/transport/undertow/UndertowHTTPDestination.java
UndertowHTTPDestination.finalizeConfig
public void finalizeConfig() { assert !configFinalized; try { retrieveEngine(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } configFinalized = true; }
java
public void finalizeConfig() { assert !configFinalized; try { retrieveEngine(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } configFinalized = true; }
[ "public", "void", "finalizeConfig", "(", ")", "{", "assert", "!", "configFinalized", ";", "try", "{", "retrieveEngine", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ".", "getMessage", "(", ")...
This method is used to finalize the configuration after the configuration items have been set.
[ "This", "method", "is", "used", "to", "finalize", "the", "configuration", "after", "the", "configuration", "items", "have", "been", "set", "." ]
9ebd7e28574f277a6d5b583e8a4c357e1538c370
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/cxfhttp/src/main/java/org/apache/cxf/transport/undertow/UndertowHTTPDestination.java#L112-L121
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportMetadata.java
ReportMetadata.getStylesheetPath
public File getStylesheetPath() { String path = System.getProperty(STYLESHEET_KEY); return path == null ? null : new File(path); }
java
public File getStylesheetPath() { String path = System.getProperty(STYLESHEET_KEY); return path == null ? null : new File(path); }
[ "public", "File", "getStylesheetPath", "(", ")", "{", "String", "path", "=", "System", ".", "getProperty", "(", "STYLESHEET_KEY", ")", ";", "return", "path", "==", "null", "?", "null", ":", "new", "File", "(", "path", ")", ";", "}" ]
If a custom CSS file has been specified, returns the path. Otherwise returns null. @return A {@link File} pointing to the stylesheet, or null if no stylesheet is specified.
[ "If", "a", "custom", "CSS", "file", "has", "been", "specified", "returns", "the", "path", ".", "Otherwise", "returns", "null", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportMetadata.java#L95-L99
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java
JUnitXMLReporter.flattenResults
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 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(); }
[ "private", "Collection", "<", "TestClassResults", ">", "flattenResults", "(", "List", "<", "ISuite", ">", "suites", ")", "{", "Map", "<", "IClass", ",", "TestClassResults", ">", "flattenedResults", "=", "new", "HashMap", "<", "IClass", ",", "TestClassResults", ...
Flatten a list of test suite results into a collection of results grouped by test class. This method basically strips away the TestNG way of organising tests and arranges the results by test class.
[ "Flatten", "a", "list", "of", "test", "suite", "results", "into", "a", "collection", "of", "results", "grouped", "by", "test", "class", ".", "This", "method", "basically", "strips", "away", "the", "TestNG", "way", "of", "organising", "tests", "and", "arrange...
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java#L94-L112
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java
JUnitXMLReporter.getResultsForClass
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
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; }
[ "private", "TestClassResults", "getResultsForClass", "(", "Map", "<", "IClass", ",", "TestClassResults", ">", "flattenedResults", ",", "ITestResult", "testResult", ")", "{", "TestClassResults", "resultsForClass", "=", "flattenedResults", ".", "get", "(", "testResult", ...
Look-up the results data for a particular test class.
[ "Look", "-", "up", "the", "results", "data", "for", "a", "particular", "test", "class", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java#L128-L138
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.createContext
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 VelocityContext createContext() { VelocityContext context = new VelocityContext(); context.put(META_KEY, META); context.put(UTILS_KEY, UTILS); context.put(MESSAGES_KEY, MESSAGES); return context; }
[ "protected", "VelocityContext", "createContext", "(", ")", "{", "VelocityContext", "context", "=", "new", "VelocityContext", "(", ")", ";", "context", ".", "put", "(", "META_KEY", ",", "META", ")", ";", "context", ".", "put", "(", "UTILS_KEY", ",", "UTILS", ...
Helper method that creates a Velocity context and initialises it with a reference to the ReportNG utils, report metadata and localised messages. @return An initialised Velocity context.
[ "Helper", "method", "that", "creates", "a", "Velocity", "context", "and", "initialises", "it", "with", "a", "reference", "to", "the", "ReportNG", "utils", "report", "metadata", "and", "localised", "messages", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L87-L94
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.generateFile
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 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(); } }
[ "protected", "void", "generateFile", "(", "File", "file", ",", "String", "templateName", ",", "VelocityContext", "context", ")", "throws", "Exception", "{", "Writer", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ";",...
Generate the specified output file by merging the specified Velocity template with the supplied context.
[ "Generate", "the", "specified", "output", "file", "by", "merging", "the", "specified", "Velocity", "template", "with", "the", "supplied", "context", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L101-L118
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.copyClasspathResource
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 copyClasspathResource(File outputDirectory, String resourceName, String targetFileName) throws IOException { String resourcePath = classpathPrefix + resourceName; InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath); copyStream(outputDirectory, resourceStream, targetFileName); }
[ "protected", "void", "copyClasspathResource", "(", "File", "outputDirectory", ",", "String", "resourceName", ",", "String", "targetFileName", ")", "throws", "IOException", "{", "String", "resourcePath", "=", "classpathPrefix", "+", "resourceName", ";", "InputStream", ...
Copy a single named resource from the classpath to the output directory. @param outputDirectory The destination directory for the copied resource. @param resourceName The filename of the resource. @param targetFileName The name of the file created in {@literal outputDirectory}. @throws IOException If the resource cannot be copied.
[ "Copy", "a", "single", "named", "resource", "from", "the", "classpath", "to", "the", "output", "directory", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L128-L135
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.copyFile
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 copyFile(File outputDirectory, File sourceFile, String targetFileName) throws IOException { InputStream fileStream = new FileInputStream(sourceFile); try { copyStream(outputDirectory, fileStream, targetFileName); } finally { fileStream.close(); } }
[ "protected", "void", "copyFile", "(", "File", "outputDirectory", ",", "File", "sourceFile", ",", "String", "targetFileName", ")", "throws", "IOException", "{", "InputStream", "fileStream", "=", "new", "FileInputStream", "(", "sourceFile", ")", ";", "try", "{", "...
Copy a single named file to the output directory. @param outputDirectory The destination directory for the copied resource. @param sourceFile The path of the file to copy. @param targetFileName The name of the file created in {@literal outputDirectory}. @throws IOException If the file cannot be copied.
[ "Copy", "a", "single", "named", "file", "to", "the", "output", "directory", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L145-L158
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.copyStream
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 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(); } } }
[ "protected", "void", "copyStream", "(", "File", "outputDirectory", ",", "InputStream", "stream", ",", "String", "targetFileName", ")", "throws", "IOException", "{", "File", "resourceFile", "=", "new", "File", "(", "outputDirectory", ",", "targetFileName", ")", ";"...
Helper method to copy the contents of a stream to a file. @param outputDirectory The directory in which the new file is created. @param stream The stream to copy. @param targetFileName The file to write the stream contents to. @throws IOException If the stream cannot be copied.
[ "Helper", "method", "to", "copy", "the", "contents", "of", "a", "stream", "to", "a", "file", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L168-L200
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java
AbstractReporter.removeEmptyDirectories
protected void removeEmptyDirectories(File outputDirectory) { if (outputDirectory.exists()) { for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter())) { file.delete(); } } }
java
protected void removeEmptyDirectories(File outputDirectory) { if (outputDirectory.exists()) { for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter())) { file.delete(); } } }
[ "protected", "void", "removeEmptyDirectories", "(", "File", "outputDirectory", ")", "{", "if", "(", "outputDirectory", ".", "exists", "(", ")", ")", "{", "for", "(", "File", "file", ":", "outputDirectory", ".", "listFiles", "(", "new", "EmptyDirectoryFilter", ...
Deletes any empty directories under the output directory. These directories are created by TestNG for its own reports regardless of whether those reports are generated. If you are using the default TestNG reports as well as ReportNG, these directories will not be empty and will be retained. Otherwise they will be removed. @param outputDirectory The directory to search for empty directories.
[ "Deletes", "any", "empty", "directories", "under", "the", "output", "directory", ".", "These", "directories", "are", "created", "by", "TestNG", "for", "its", "own", "reports", "regardless", "of", "whether", "those", "reports", "are", "generated", ".", "If", "y...
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/AbstractReporter.java#L211-L220
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.generateReport
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
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); } }
[ "public", "void", "generateReport", "(", "List", "<", "XmlSuite", ">", "xmlSuites", ",", "List", "<", "ISuite", ">", "suites", ",", "String", "outputDirectoryName", ")", "{", "removeEmptyDirectories", "(", "new", "File", "(", "outputDirectoryName", ")", ")", "...
Generates a set of HTML files that contain data about the outcome of the specified test suites. @param suites Data about the test runs. @param outputDirectoryName The directory in which to create the report.
[ "Generates", "a", "set", "of", "HTML", "files", "that", "contain", "data", "about", "the", "outcome", "of", "the", "specified", "test", "suites", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L90-L119
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.createFrameset
private void createFrameset(File outputDirectory) throws Exception { VelocityContext context = createContext(); generateFile(new File(outputDirectory, INDEX_FILE), INDEX_FILE + TEMPLATE_EXTENSION, context); }
java
private void createFrameset(File outputDirectory) throws Exception { VelocityContext context = createContext(); generateFile(new File(outputDirectory, INDEX_FILE), INDEX_FILE + TEMPLATE_EXTENSION, context); }
[ "private", "void", "createFrameset", "(", "File", "outputDirectory", ")", "throws", "Exception", "{", "VelocityContext", "context", "=", "createContext", "(", ")", ";", "generateFile", "(", "new", "File", "(", "outputDirectory", ",", "INDEX_FILE", ")", ",", "IND...
Create the index file that sets up the frameset. @param outputDirectory The target directory for the generated file(s).
[ "Create", "the", "index", "file", "that", "sets", "up", "the", "frameset", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L126-L132
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.createSuiteList
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 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); }
[ "private", "void", "createSuiteList", "(", "List", "<", "ISuite", ">", "suites", ",", "File", "outputDirectory", ",", "boolean", "onlyFailures", ")", "throws", "Exception", "{", "VelocityContext", "context", "=", "createContext", "(", ")", ";", "context", ".", ...
Create the navigation frame. @param outputDirectory The target directory for the generated file(s).
[ "Create", "the", "navigation", "frame", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L153-L163
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.createResults
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 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; } }
[ "private", "void", "createResults", "(", "List", "<", "ISuite", ">", "suites", ",", "File", "outputDirectory", ",", "boolean", "onlyShowFailures", ")", "throws", "Exception", "{", "int", "index", "=", "1", ";", "for", "(", "ISuite", "suite", ":", "suites", ...
Generate a results file for each test in each suite. @param outputDirectory The target directory for the generated file(s).
[ "Generate", "a", "results", "file", "for", "each", "test", "in", "each", "suite", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L170-L200
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java
HTMLReporter.copyResources
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
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); } } } }
[ "private", "void", "copyResources", "(", "File", "outputDirectory", ")", "throws", "IOException", "{", "copyClasspathResource", "(", "outputDirectory", ",", "\"reportng.css\"", ",", "\"reportng.css\"", ")", ";", "copyClasspathResource", "(", "outputDirectory", ",", "\"r...
Reads the CSS and JavaScript files from the JAR file and writes them to the output directory. @param outputDirectory Where to put the resources. @throws IOException If the resources can't be read or written.
[ "Reads", "the", "CSS", "and", "JavaScript", "files", "from", "the", "JAR", "file", "and", "writes", "them", "to", "the", "output", "directory", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L295-L319
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java
ReportNGUtils.getCauses
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
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; }
[ "public", "List", "<", "Throwable", ">", "getCauses", "(", "Throwable", "t", ")", "{", "List", "<", "Throwable", ">", "causes", "=", "new", "LinkedList", "<", "Throwable", ">", "(", ")", ";", "Throwable", "next", "=", "t", ";", "while", "(", "next", ...
Convert a Throwable into a list containing all of its causes. @param t The throwable for which the causes are to be returned. @return A (possibly empty) list of {@link Throwable}s.
[ "Convert", "a", "Throwable", "into", "a", "list", "containing", "all", "of", "its", "causes", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java#L100-L110
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java
ReportNGUtils.commaSeparate
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
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(); }
[ "private", "String", "commaSeparate", "(", "Collection", "<", "String", ">", "strings", ")", "{", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "Iterator", "<", "String", ">", "iterator", "=", "strings", ".", "iterator", "(", ")", ...
Takes a list of Strings and combines them into a single comma-separated String. @param strings The Strings to combine. @return The combined, comma-separated, String.
[ "Takes", "a", "list", "of", "Strings", "and", "combines", "them", "into", "a", "single", "comma", "-", "separated", "String", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java#L248-L262
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java
ReportNGUtils.stripThreadName
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 String stripThreadName(String threadId) { if (threadId == null) { return null; } else { int index = threadId.lastIndexOf('@'); return index >= 0 ? threadId.substring(0, index) : threadId; } }
[ "public", "String", "stripThreadName", "(", "String", "threadId", ")", "{", "if", "(", "threadId", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "int", "index", "=", "threadId", ".", "lastIndexOf", "(", "'", "'", ")", ";", "return", ...
TestNG returns a compound thread ID that includes the thread name and its numeric ID, separated by an 'at' sign. We only want to use the thread name as the ID is mostly unimportant and it takes up too much space in the generated report. @param threadId The compound thread ID. @return The thread name.
[ "TestNG", "returns", "a", "compound", "thread", "ID", "that", "includes", "the", "thread", "name", "and", "its", "numeric", "ID", "separated", "by", "an", "at", "sign", ".", "We", "only", "want", "to", "use", "the", "thread", "name", "as", "the", "ID", ...
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java#L354-L365
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java
ReportNGUtils.getStartTime
public long getStartTime(List<IInvokedMethod> methods) { long startTime = System.currentTimeMillis(); for (IInvokedMethod method : methods) { startTime = Math.min(startTime, method.getDate()); } return startTime; }
java
public long getStartTime(List<IInvokedMethod> methods) { long startTime = System.currentTimeMillis(); for (IInvokedMethod method : methods) { startTime = Math.min(startTime, method.getDate()); } return startTime; }
[ "public", "long", "getStartTime", "(", "List", "<", "IInvokedMethod", ">", "methods", ")", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "for", "(", "IInvokedMethod", "method", ":", "methods", ")", "{", "startTime", "=", ...
Find the earliest start time of the specified methods. @param methods A list of test methods. @return The earliest start time.
[ "Find", "the", "earliest", "start", "time", "of", "the", "specified", "methods", "." ]
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java#L373-L381
train
dwdyer/reportng
reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java
ReportNGUtils.getEndTime
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
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."); }
[ "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", ".", "ge...
Returns the timestamp for the time at which the suite finished executing. This is determined by finding the latest end time for each of the individual tests in the suite. @param suite The suite to find the end time of. @return The end time (as a number of milliseconds since 00:00 1st January 1970 UTC).
[ "Returns", "the", "timestamp", "for", "the", "time", "at", "which", "the", "suite", "finished", "executing", ".", "This", "is", "determined", "by", "finding", "the", "latest", "end", "time", "for", "each", "of", "the", "individual", "tests", "in", "the", "...
df11f9cd9ab3fb5847fbba94ed3098ae0448f770
https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/ReportNGUtils.java#L410-L440
train
cverges/expect4j
src/main/java/expect4j/PollingConsumer.java
PollingConsumer.waitForBuffer
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 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"); } } }
[ "public", "void", "waitForBuffer", "(", "long", "timeoutMilli", ")", "{", "//assert(callerProcessing.booleanValue() == false);", "synchronized", "(", "buffer", ")", "{", "if", "(", "dirtyBuffer", ")", "return", ";", "if", "(", "!", "foundEOF", "(", ")", ")", "{"...
What is something came in between when we last checked and when this method is called
[ "What", "is", "something", "came", "in", "between", "when", "we", "last", "checked", "and", "when", "this", "method", "is", "called" ]
97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/PollingConsumer.java#L164-L184
train
cverges/expect4j
src/main/java/expect4j/PollingConsumer.java
PollingConsumer.main
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
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); }
[ "public", "static", "void", "main", "(", "String", "args", "[", "]", ")", "throws", "Exception", "{", "final", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", "\"The lazy fox\"", ")", ";", "Thread", "t1", "=", "new", "Thread", "(", ")", "{", "...
We have more input since wait started
[ "We", "have", "more", "input", "since", "wait", "started" ]
97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/PollingConsumer.java#L217-L244
train
cverges/expect4j
src/main/java/expect4j/ConsumerImpl.java
ConsumerImpl.notifyBufferChange
protected void notifyBufferChange(char[] newData, int numChars) { synchronized(bufferChangeLoggers) { Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator(); while (iterator.hasNext()) { iterator.next().bufferChanged(newData, numChars); } } }
java
protected void notifyBufferChange(char[] newData, int numChars) { synchronized(bufferChangeLoggers) { Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator(); while (iterator.hasNext()) { iterator.next().bufferChanged(newData, numChars); } } }
[ "protected", "void", "notifyBufferChange", "(", "char", "[", "]", "newData", ",", "int", "numChars", ")", "{", "synchronized", "(", "bufferChangeLoggers", ")", "{", "Iterator", "<", "BufferChangeLogger", ">", "iterator", "=", "bufferChangeLoggers", ".", "iterator"...
Notifies all registered BufferChangeLogger instances of a change. @param newData the buffer that contains the new data being added @param numChars the number of valid characters in the buffer
[ "Notifies", "all", "registered", "BufferChangeLogger", "instances", "of", "a", "change", "." ]
97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/ConsumerImpl.java#L175-L182
train