code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public Response remove(String id, String rev) {
assertNotEmpty(id, "id");
assertNotEmpty(id, "rev");
return db.remove(ensureDesignPrefix(id), rev);
} | java |
public Response remove(DesignDocument designDocument) {
assertNotEmpty(designDocument, "DesignDocument");
ensureDesignPrefixObject(designDocument);
return db.remove(designDocument);
} | java |
public List<DesignDocument> list() throws IOException {
return db.getAllDocsRequestBuilder()
.startKey("_design/")
.endKey("_design0")
.inclusiveEnd(false)
.includeDocs(true)
.build()
.getResponse().getDocsAs(... | 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 (Fil... | 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 FileInputStre... | 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 wi... | java |
public static HttpConnection connect(String requestMethod,
URL url,
String contentType) {
return new HttpConnection(requestMethod, url, contentType);
} | java |
public B partialFilterSelector(Selector selector) {
instance.def.selector = Helpers.getJsonObjectFromSelector(selector);
return returnThis();
} | java |
protected B fields(List<F> fields) {
if (instance.def.fields == null) {
instance.def.fields = new ArrayList<F>(fields.size());
}
instance.def.fields.addAll(fields);
return returnThis();
} | java |
public SchedulerDocsResponse.Doc schedulerDoc(String docId) {
assertNotEmpty(docId, "docId");
return this.get(new DatabaseURIHelper(getBaseUri()).
path("_scheduler").path("docs").path("_replicator").path(docId).build(),
SchedulerDocsResponse.Doc.class);
} | java |
public List<String> uuids(long count) {
final URI uri = new URIBase(clientUri).path("_uuids").query("count", count).build();
final JsonObject json = get(uri, JsonObject.class);
return getGson().fromJson(json.get("uuids").toString(), DeserializationTypes.STRINGS);
} | java |
public Response executeToResponse(HttpConnection connection) {
InputStream is = null;
try {
is = this.executeToInputStream(connection);
Response response = getResponse(is, Response.class, getGson());
response.setStatusCode(connection.getConnection().getResponseCode())... | java |
Response delete(URI uri) {
HttpConnection connection = Http.DELETE(uri);
return executeToResponse(connection);
} | java |
public <T> T get(URI uri, Class<T> classType) {
HttpConnection connection = Http.GET(uri);
InputStream response = executeToInputStream(connection);
try {
return getResponse(response, classType, getGson());
} finally {
close(response);
}
} | java |
Response put(URI uri, InputStream instream, String contentType) {
HttpConnection connection = Http.PUT(uri, contentType);
connection.setRequestBody(instream);
return executeToResponse(connection);
} | java |
public HttpConnection execute(HttpConnection connection) {
//set our HttpUrlFactory on the connection
connection.connectionFactory = factory;
// all CouchClient requests want to receive application/json responses
connection.requestProperties.put("Accept", "application/json");
c... | 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 != nul... | 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/jso... | java |
public QueryBuilder useIndex(String designDocument, String indexName) {
useIndex = new String[]{designDocument, indexName};
return this;
} | java |
private static String quoteSort(Sort[] sort) {
LinkedList<String> sorts = new LinkedList<String>();
for (Sort pair : sort) {
sorts.add(String.format("{%s: %s}", Helpers.quote(pair.getName()), Helpers.quote(pair.getOrder().toString())));
}
return sorts.toString();
} | java |
public <K, V> MultipleRequestBuilder<K, V> newMultipleRequest(Key.Type<K> keyType,
Class<V> valueType) {
return new MultipleRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(),
valueType));
} | java |
public <T> T find(Class<T> classType, String id, String rev) {
assertNotEmpty(classType, "Class");
assertNotEmpty(id, "id");
assertNotEmpty(id, "rev");
final URI uri = new DatabaseURIHelper(dbUri).documentUri(id, "rev", rev);
return couchDbClient.get(uri, classType);
} | java |
public boolean contains(String id) {
assertNotEmpty(id, "id");
InputStream response = null;
try {
response = couchDbClient.head(new DatabaseURIHelper(dbUri).documentUri(id));
} catch (NoDocumentException e) {
return false;
} finally {
close(res... | 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) {
jsonObjec... | 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).getA... | 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();
... | 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 thi... | 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);
}
... | java |
public List<Index<Field>> allIndexes() {
List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();
indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));
return indexesOfAnyType;
} | java |
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {
List<T> indexesOfType = new ArrayList<T>();
Gson g = new Gson();
for (JsonElement index : indexes) {
if (index.isJsonObject()) {
JsonObject indexDefinition = index.getAsJsonObject();
... | 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(_lo... | 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()) {
... | java |
public static ClientBuilder account(String account) {
logger.config("Account: " + account);
return ClientBuilder.url(
convertStringToURL(String.format("https://%s.cloudant.com", account)));
} | java |
public HttpConnection setRequestBody(final String input) {
try {
final byte[] inputBytes = input.getBytes("UTF-8");
return setRequestBody(inputBytes);
} catch (UnsupportedEncodingException e) {
// This should never happen as every implementation of the java platform i... | 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 stre... | java |
private String getLogRequestIdentifier() {
if (logIdentifier == null) {
logIdentifier = String.format("%s-%s %s %s", Integer.toHexString(hashCode()),
numberOfRetries, connection.getRequestMethod(), connection.getURL());
}
return logIdentifier;
} | java |
private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {
PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());
Iterator rIt = keyrings.getKeyRings();
while (rIt.hasN... | java |
private String trim(String line) {
char[] chars = line.toCharArray();
int len = chars.length;
while (len > 0) {
if (!Character.isWhitespace(chars[len - 1])) {
break;
}
len--;
}
return line.substring(0, len);
} | java |
public void validate() throws PackagingException {
if (control == null || !control.isDirectory()) {
throw new PackagingException("The 'control' attribute doesn't point to a directory. " + control);
}
if (changesIn != null) {
if (changesIn.exists() && (!changesIn.isFile(... | 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);
}
}
... | 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... | 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 = ... | java |
public static String movePath( final String file,
final String target ) {
final String name = new File(file).getName();
return target.endsWith("/") ? target + name : target + '/' + name;
} | java |
public static String lookupIfEmpty( final String value,
final Map<String, String> props,
final String key ) {
return value != null ? value : props.get(key);
} | java |
public static Collection<String> getKnownPGPSecureRingLocations() {
final LinkedHashSet<String> locations = new LinkedHashSet<String>();
final String os = System.getProperty("os.name");
final boolean runOnWindows = os == null || os.toLowerCase().contains("win");
if (runOnWindows) {
... | 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()) {
... | java |
public static String defaultString(final String str, final String fallback) {
return isNullOrEmpty(str) ? fallback : str;
} | java |
static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {
TarArchiveEntry entry = new TarArchiveEntry(fileName, true);
entry.setUserId(ROOT_UID);
entry.setUserName(ROOT_NAME);
entry.setGroupId(ROOT_UID);
entry.setGroupName(ROOT_NAME);
entry.setMode(TarArc... | 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(TarArchiv... | java |
static void produceInputStreamWithEntry( final DataConsumer consumer,
final InputStream inputStream,
final TarArchiveEntry entry ) throws IOException {
try {
consumer.onEachFile(inputStream, entry);
} f... | 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");
... | 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"))... | java |
private void initializeSignProperties() {
if (!signPackage && !signChanges) {
return;
}
if (key != null && keyring != null && passphrase != null) {
return;
}
Map<String, String> properties =
readPropertiesFromActiveProfiles(signCfgPrefix,... | java |
public Map<String, String> readPropertiesFromActiveProfiles( final String prefix,
final String... properties ) {
if (settings == null) {
console.debug("No maven setting injected");
return Collections.emptyMap();
}
... | 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 ne... | 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 && para... | 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);
... | 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 =... | java |
public T transitFloat(int propertyId, float... vals) {
String property = getPropertyName(propertyId);
mHolders.put(propertyId, PropertyValuesHolder.ofFloat(property, vals));
mShadowHolders.put(propertyId, ShadowValuesHolder.ofFloat(property, vals));
return self();
} | java |
public T transitInt(int propertyId, int... vals) {
String property = getPropertyName(propertyId);
mHolders.put(propertyId, PropertyValuesHolder.ofInt(property, vals));
mShadowHolders.put(propertyId, ShadowValuesHolder.ofInt(property, vals));
return self();
} | java |
@CheckResult
public boolean isCompatible(AbstractTransition another) {
if (getClass().equals(another.getClass()) && mTarget == another.mTarget && mReverse == another.mReverse && ((mInterpolator == null && another.mInterpolator == null) ||
mInterpolator.getClass().equals(another.mInterpolator... | 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() + anoth... | java |
public void removeAllAnimations() {
for (int i = 0, size = mAnimationList.size(); i < size; i++) {
mAnimationList.get(i).removeAnimationListener(mAnimationListener);
}
mAnimationList.clear();
} | java |
@Override
public void stopTransition() {
//call listeners so they can perform their actions first, like modifying this adapter's transitions
for (int i = 0, size = mListenerList.size(); i < size; i++) {
mListenerList.get(i).onTransitionEnd(this);
}
for (int i = 0, size =... | 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++) {
transitionContro... | java |
public void end() {
if (TransitionConfig.isPrintDebug()) {
getTransitionStateHolder().end();
getTransitionStateHolder().print();
}
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).end();
}
} | java |
public void reverse() {
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).reverse();
}
} | java |
private LoginContext getClientLoginContext() throws LoginException {
Configuration config = new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<String, String>();
... | 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;
... | java |
public static <T> T assertNull(T value, String message) {
if (value != null)
throw new IllegalStateException(message);
return value;
} | java |
public static <T> T assertNotNull(T value, String message) {
if (value == null)
throw new IllegalStateException(message);
return value;
} | java |
public static Boolean assertTrue(Boolean value, String message) {
if (!Boolean.valueOf(value))
throw new IllegalStateException(message);
return value;
} | java |
public static Boolean assertFalse(Boolean value, String message) {
if (Boolean.valueOf(value))
throw new IllegalStateException(message);
return value;
} | java |
public static <T> T assertNotNull(T value, String name) {
if (value == null)
throw new IllegalArgumentException("Null " + name);
return value;
} | java |
public static Boolean assertTrue(Boolean value, String message) {
if (!Boolean.valueOf(value))
throw new IllegalArgumentException(message);
return value;
} | java |
public static Boolean assertFalse(Boolean value, String message) {
if (Boolean.valueOf(value))
throw new IllegalArgumentException(message);
return value;
} | java |
public void retrieveEngine() throws GeneralSecurityException, IOException {
if (serverEngineFactory == null) {
return;
}
engine = serverEngineFactory.retrieveHTTPServerEngine(nurl.getPort());
if (engine == null) {
engine = serverEngineFactory.getHTTPServerEngine(n... | java |
public void finalizeConfig() {
assert !configFinalized;
try {
retrieveEngine();
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
configFinalized = true;
} | java |
public File getStylesheetPath()
{
String path = System.getProperty(STYLESHEET_KEY);
return path == null ? null : new File(path);
} | java |
private Collection<TestClassResults> flattenResults(List<ISuite> suites)
{
Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();
for (ISuite suite : suites)
{
for (ISuiteResult suiteResult : suite.getResults().values())
{
... | java |
private TestClassResults getResultsForClass(Map<IClass, TestClassResults> flattenedResults,
ITestResult testResult)
{
TestClassResults resultsForClass = flattenedResults.get(testResult.getTestClass());
if (resultsForClass == null)
{
... | java |
protected VelocityContext createContext()
{
VelocityContext context = new VelocityContext();
context.put(META_KEY, META);
context.put(UTILS_KEY, UTILS);
context.put(MESSAGES_KEY, MESSAGES);
return context;
} | java |
protected void generateFile(File file,
String templateName,
VelocityContext context) throws Exception
{
Writer writer = new BufferedWriter(new FileWriter(file));
try
{
Velocity.mergeTemplate(classpathPrefix + templat... | java |
protected void copyClasspathResource(File outputDirectory,
String resourceName,
String targetFileName) throws IOException
{
String resourcePath = classpathPrefix + resourceName;
InputStream resourceStream = getClass().... | java |
protected void copyFile(File outputDirectory,
File sourceFile,
String targetFileName) throws IOException
{
InputStream fileStream = new FileInputStream(sourceFile);
try
{
copyStream(outputDirectory, fileStream, targetFileNam... | java |
protected void copyStream(File outputDirectory,
InputStream stream,
String targetFileName) throws IOException
{
File resourceFile = new File(outputDirectory, targetFileName);
BufferedReader reader = null;
Writer writer = null;
... | java |
protected void removeEmptyDirectories(File outputDirectory)
{
if (outputDirectory.exists())
{
for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter()))
{
file.delete();
}
}
} | java |
public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
boolean useFrames = System.getProperty(FRAMES_PROPERTY, "true").equals... | java |
private void createFrameset(File outputDirectory) throws Exception
{
VelocityContext context = createContext();
generateFile(new File(outputDirectory, INDEX_FILE),
INDEX_FILE + TEMPLATE_EXTENSION,
context);
} | java |
private void createSuiteList(List<ISuite> suites,
File outputDirectory,
boolean onlyFailures) throws Exception
{
VelocityContext context = createContext();
context.put(SUITES_KEY, suites);
context.put(ONLY_FAILURES_KEY, onlyFa... | 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 : sui... | 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 = M... | java |
public List<Throwable> getCauses(Throwable t)
{
List<Throwable> causes = new LinkedList<Throwable>();
Throwable next = t;
while (next.getCause() != null)
{
next = next.getCause();
causes.add(next);
}
return causes;
} | java |
private String commaSeparate(Collection<String> strings)
{
StringBuilder buffer = new StringBuilder();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext())
{
String string = iterator.next();
buffer.append(string);
if (iterator... | java |
public String stripThreadName(String threadId)
{
if (threadId == null)
{
return null;
}
else
{
int index = threadId.lastIndexOf('@');
return index >= 0 ? threadId.substring(0, index) : threadId;
}
} | java |
public long getStartTime(List<IInvokedMethod> methods)
{
long startTime = System.currentTimeMillis();
for (IInvokedMethod method : methods)
{
startTime = Math.min(startTime, method.getDate());
}
return startTime;
} | java |
private long getEndTime(ISuite suite, IInvokedMethod method)
{
// Find the latest end time for all tests in the suite.
for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet())
{
ITestContext testContext = entry.getValue().getTestContext();
for (ITes... | 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");
... | 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 mid... | java |
protected void notifyBufferChange(char[] newData, int numChars) {
synchronized(bufferChangeLoggers) {
Iterator<BufferChangeLogger> iterator = bufferChangeLoggers.iterator();
while (iterator.hasNext()) {
iterator.next().bufferChanged(newData, numChars);
}
... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.