code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public static RequestBody<Collection<? extends Map.Entry<String, ?>>>
form(Collection<? extends Map.Entry<String, ?>> value) {
return new FormRequestBody(requireNonNull(value));
} | java |
public static RequestBody<Collection<? extends Part>> multiPart(Collection<? extends Part> parts) {
return new MultiPartRequestBody(requireNonNull(parts));
} | java |
public List<String> getHeaders(String name) {
requireNonNull(name);
List<String> values = lazyMap.get().get(name.toLowerCase());
if (values == null) {
return Lists.of();
}
return Collections.unmodifiableList(values);
} | java |
public long getLongHeader(String name, long defaultValue) {
String firstHeader = getHeader(name);
if (firstHeader == null) {
return defaultValue;
}
try {
return Long.parseLong(firstHeader.trim());
} catch (NumberFormatException e) {
return defa... | java |
public Charset getCharset(Charset defaultCharset) {
String contentType = getHeader(HttpHeaders.NAME_CONTENT_TYPE);
if (contentType == null) {
return defaultCharset;
}
String[] items = contentType.split(";");
for (String item : items) {
item = item.trim();
... | java |
static boolean isText(String contentType) {
return contentType.contains("text") || contentType.contains("json")
|| contentType.contains("xml") || contentType.contains("html");
} | java |
public RawResponse charset(Charset charset) {
return new RawResponse(method, url, statusCode, statusLine, cookies, headers, body, charset, decompress);
} | java |
public RawResponse decompress(boolean decompress) {
return new RawResponse(method, url, statusCode, statusLine, cookies, headers, body, charset, decompress);
} | java |
public String readToText() {
Charset charset = getCharset();
try (InputStream in = body();
Reader reader = new InputStreamReader(in, charset)) {
return Readers.readAll(reader);
} catch (IOException e) {
throw new RequestsException(e);
} finally {
... | java |
public byte[] readToBytes() {
try {
try (InputStream in = body()) {
return InputStreams.readAll(in);
}
} catch (IOException e) {
throw new RequestsException(e);
} finally {
close();
}
} | java |
public <T> Response<T> toResponse(ResponseHandler<T> handler) {
ResponseInfo responseInfo = new ResponseInfo(this.url, this.statusCode, this.headers, body());
try {
T result = handler.handle(responseInfo);
return new Response<>(this.url, this.statusCode, this.cookies, this.header... | java |
public <T> T readToJson(Type type) {
try {
return JsonLookup.getInstance().lookup().unmarshal(body(), getCharset(), type);
} catch (IOException e) {
throw new RequestsException(e);
} finally {
close();
}
} | java |
public Response<File> toFileResponse(Path path) {
File file = path.toFile();
this.writeToFile(file);
return new Response<>(this.url, this.statusCode, this.cookies, this.headers, file);
} | java |
public void writeTo(OutputStream out) {
try {
InputStreams.transferTo(body(), out);
} catch (IOException e) {
throw new RequestsException(e);
} finally {
close();
}
} | java |
public void discardBody() {
try (InputStream in = body) {
InputStreams.discardAll(in);
} catch (IOException e) {
throw new RequestsException(e);
} finally {
close();
}
} | java |
private InputStream decompressBody() {
if (!decompress) {
return body;
}
// if has no body, some server still set content-encoding header,
// GZIPInputStream wrap empty input stream will cause exception. we should check this
if (method.equals(Methods.HEAD)
... | java |
public static Result list(int page, String sortBy, String order, String filter) {
return ok(
list.render(
Computer.page(page, 10, sortBy, order, filter),
sortBy, order, filter
)
);
} | java |
public static Result edit(Long id) {
Form<Computer> computerForm = form(Computer.class).fill(
Computer.find.byId(id)
);
return ok(
editForm.render(id, computerForm)
);
} | java |
public static Result update(Long id) {
Form<Computer> computerForm = form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {
return badRequest(editForm.render(id, computerForm));
}
computerForm.get().update(id);
flash("success", "Computer " + computerFo... | java |
public static Result create() {
Form<Computer> computerForm = form(Computer.class);
return ok(
createForm.render(computerForm)
);
} | java |
public static Result save() {
Form<Computer> computerForm = form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {
return badRequest(createForm.render(computerForm));
}
computerForm.get().save();
flash("success", "Computer " + computerForm.get().name +... | java |
public static Result delete(Long id) {
Computer.find.ref(id).delete();
flash("success", "Computer has been deleted");
return GO_HOME;
} | java |
public static Page<Computer> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.findPagingList(pageSize)
... | java |
public void parse() throws ParserException {
try {
jsonParser.nextToken();
contentHandler.startDocument();
if (shouldAddArtificialRoot()) {
startElement(artificialRootName);
parseElement(artificialRootName, false);
endElement(ar... | java |
private int parseObject() throws Exception {
int elementsWritten = 0;
while (jsonParser.nextToken() != null && jsonParser.getCurrentToken() != END_OBJECT) {
if (FIELD_NAME.equals(jsonParser.getCurrentToken())) {
String elementName = convertName(jsonParser.getCurrentName());
... | java |
private void parseElement(final String elementName, final boolean inArray) throws Exception {
JsonToken currentToken = jsonParser.getCurrentToken();
if (inArray) {
startElement(elementName);
}
if (START_OBJECT.equals(currentToken)) {
parseObject();
} else ... | java |
public static Node convertToDom(final String json, final String namespace, final boolean addTypeAttributes, final String artificialRootName) throws TransformerConfigurationException, TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
InputSource source = ... | java |
private static void convertElement(JsonGenerator generator, Element element, boolean isArrayItem, ElementNameConverter converter) throws IOException {
TYPE type = toTYPE(element.getAttribute("type"));
String name = element.getTagName();
if (!isArrayItem) {
generator.writeFieldName(c... | java |
private static void convertChildren(JsonGenerator generator, Element element, boolean isArray, ElementNameConverter converter) throws IOException {
NodeList list = element.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node node = list.item(i);
... | java |
@Override
protected void postExecute(List<String> filesProcessed, int nonComplyingFiles)
throws MojoFailureException {
if (nonComplyingFiles > 0) {
String message = "Found " + nonComplyingFiles + " non-complying files, failing build";
getLog().error(message);
getLog().error("To fix formatt... | java |
public int lengthOf(String value) {
int length = 0;
if (value != null) {
length = value.length();
}
return length;
} | java |
public boolean textContains(String value, String expectedSubstring) {
boolean result = false;
if (value != null) {
result = value.contains(expectedSubstring);
}
return result;
} | java |
public String convertToUpperCase(String value) {
String result = null;
if (value != null) {
result = value.toUpperCase();
}
return result;
} | java |
public String convertToLowerCase(String value) {
String result = null;
if (value != null) {
result = value.toLowerCase();
}
return result;
} | java |
public String replaceAllInWith(String regEx, String value, String replace) {
String result = null;
if (value != null) {
if (replace == null) {
// empty cell in table is sent as null
replace = "";
}
result = getMatcher(regEx, value).repl... | java |
public Integer extractIntFromUsingGroup(String value, String regEx, int groupIndex) {
Integer result = null;
if (value != null) {
Matcher matcher = getMatcher(regEx, value);
if (matcher.matches()) {
String intStr = matcher.group(groupIndex);
result... | java |
public String getRawXPath(String xPathExpr, Object... params) {
return getRawXPath(getResponse(), xPathExpr, params);
} | java |
public XPathCheckResult checkXPaths(Map<String, Object> values, Map<String, String> expressionsToCheck) {
XPathCheckResult result;
String content = getResponse();
if (content == null) {
result = new XPathCheckResult();
result.setMismatchDetail("NOK: no response available.... | java |
private String fillPattern(String pattern, String[] parameters) {
boolean containsSingleQuote = false;
boolean containsDoubleQuote = false;
Object[] escapedParams = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
String param = parameters[i];
... | java |
public void registerPrefixForNamespace(String prefix, String namespace) {
getEnvironment().registerNamespace(prefix, getUrl(namespace));
} | java |
public boolean validateAgainstXsdFile(String xsdFileName) {
String xsdContent = new FileFixture().textIn(xsdFileName);
return new XMLValidator().validateAgainst(content, xsdContent);
} | java |
public boolean validateAgainstXsd(String xsdSchema) {
String xsdContent = cleanupValue(xsdSchema);
return new XMLValidator().validateAgainst(content, xsdContent);
} | java |
public XMLGregorianCalendar addDays(final XMLGregorianCalendar cal, final int amount) {
XMLGregorianCalendar to = buildXMLGregorianCalendarDate(cal);
// Add amount of months
to.add(addDays(amount));
return to;
} | java |
public XMLGregorianCalendar addMonths(final XMLGregorianCalendar cal, final int amount) {
XMLGregorianCalendar to = buildXMLGregorianCalendarDate(cal);
// Add amount of months
to.add(addMonths(amount));
return to;
} | java |
public XMLGregorianCalendar addYears(final XMLGregorianCalendar cal, final int amount) {
XMLGregorianCalendar to = buildXMLGregorianCalendarDate(cal);
// Add amount of months
to.add(addYears(amount));
return to;
} | java |
public int getDurationInYears(XMLGregorianCalendar startDate, XMLGregorianCalendar endDate) {
int startYear = startDate.getYear();
final int dec = 12;
if (startDate.getMonth() == dec) {
// started in December, increase year with one
startYear++;
}
int endY... | java |
Duration addDays(final int amount) {
Duration duration;
if (amount < 0) {
duration = getDatatypeFactory().newDuration(false, 0, 0, Math.abs(amount), 0, 0, 0);
} else {
duration = getDatatypeFactory().newDuration(true, 0, 0, amount, 0, 0, 0);
}
return durat... | java |
public String format(String json) {
String result = null;
if (json != null){
if (json.startsWith("{")) {
result = new JSONObject(json).toString(4);
} else if (json.startsWith("[")) {
JSONObject jsonObject = new JSONObject("{'a': " + json + "}");
... | java |
public Map<String, Object> jsonStringToMap(String jsonString) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString);
return jsonObjectToMap(jsonObject);
} catch (JSONExcepti... | java |
public String sort(String json, String arrayExpr, String nestedPathExpr) {
JsonPathHelper pathHelper = getPathHelper();
Object topLevel = pathHelper.getJsonPath(json, arrayExpr);
if (topLevel instanceof JSONArray) {
JSONArray a = (JSONArray) topLevel;
JSONArray aSorted = ... | java |
public void setWebDriver(WebDriver aWebDriver, int defaultTimeout) {
if (webDriver != null && !webDriver.equals(aWebDriver)) {
webDriver.quit();
}
webDriver = aWebDriver;
if (webDriver == null) {
webDriverWait = null;
} else {
webDriverWait = ... | java |
public T getElementToCheckVisibility(String place) {
return findByTechnicalSelectorOr(place, () -> {
T result = findElement(TextBy.partial(place));
if (!IsDisplayedFilter.mayPass(result)) {
result = findElement(ToClickBy.heuristic(place));
}
return... | java |
public Integer getNumberFor(WebElement element) {
Integer number = null;
if ("li".equalsIgnoreCase(element.getTagName())
&& element.isDisplayed()) {
int num;
String ownVal = element.getAttribute("value");
if (ownVal != null && !"0".equals(ownVal)) {
... | java |
public ArrayList<String> getAvailableOptions(WebElement element) {
ArrayList<String> result = null;
if (isInteractable(element)
&& "select".equalsIgnoreCase(element.getTagName())) {
result = new ArrayList<String>();
List<WebElement> options = element.findElements(... | java |
public String getText(WebElement element) {
String text = element.getText();
if (text != null) {
// Safari driver does not return as normal spacce, while others do
text = text.replace(NON_BREAKING_SPACE, ' ');
// Safari driver does not return trim, while others... | java |
public boolean setHiddenInputValue(String idOrName, String value) {
T element = findElement(By.id(idOrName));
if (element == null) {
element = findElement(By.name(idOrName));
if (element != null) {
executeJavascript("document.getElementsByName('%s')[0].value='%s'"... | java |
public Object executeJavascript(String statementPattern, Object... parameters) {
Object result;
String script = String.format(statementPattern, parameters);
if (statementPattern.contains("arguments")) {
result = executeScript(script, parameters);
} else {
result =... | java |
public void setImplicitlyWait(int implicitWait) {
try {
driver().manage().timeouts().implicitlyWait(implicitWait, TimeUnit.MILLISECONDS);
} catch (Exception e) {
// https://code.google.com/p/selenium/issues/detail?id=6015
System.err.println("Unable to set implicit tim... | java |
public void setScriptWait(int scriptTimeout) {
try {
driver().manage().timeouts().setScriptTimeout(scriptTimeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
// https://code.google.com/p/selenium/issues/detail?id=6015
System.err.println("Unable to set script timeo... | java |
public void setPageLoadWait(int pageLoadWait) {
try {
driver().manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.MILLISECONDS);
} catch (Exception e) {
// https://code.google.com/p/selenium/issues/detail?id=6015
System.err.println("Unable to set page load tim... | java |
public void clickWithKeyDown(WebElement element, CharSequence key) {
getActions().keyDown(key).click(element).keyUp(key).perform();
} | java |
public void dragAndDrop(WebElement source, WebElement target) {
getActions().dragAndDrop(source, target).perform();
} | java |
public T findByXPath(String pattern, String... parameters) {
By by = byXpath(pattern, parameters);
return findElement(by);
} | java |
public T findElement(By by, int index) {
T element = null;
List<T> elements = findElements(by);
if (elements.size() > index) {
element = elements.get(index);
}
return element;
} | java |
public <T> T waitUntil(int maxSecondsToWait, ExpectedCondition<T> condition) {
ExpectedCondition<T> cHandlingStale = getConditionIgnoringStaleElement(condition);
FluentWait<WebDriver> wait = waitDriver().withTimeout(Duration.ofSeconds(maxSecondsToWait));
return wait.until(cHandlingStale);
} | java |
public boolean isStaleElementException(WebDriverException e) {
boolean result = false;
if (e instanceof StaleElementReferenceException) {
result = true;
} else {
String msg = e.getMessage();
if (msg != null) {
result = msg.contains("Element doe... | java |
public byte[] findScreenshot(Throwable t) {
byte[] result = null;
if (t != null) {
if (t instanceof ScreenshotException) {
String encodedScreenshot = ((ScreenshotException)t).getBase64EncodedScreenshot();
result = Base64.getDecoder().decode(encodedScreenshot);... | java |
public void switchToFrame(T iframe) {
getTargetLocator().frame(iframe);
setCurrentContext(null);
currentIFramePath.add(iframe);
} | java |
public void copySeleniumCookies(Set<Cookie> browserCookies, CookieStore cookieStore) {
for (Cookie browserCookie : browserCookies) {
ClientCookie cookie = convertCookie(browserCookie);
cookieStore.addCookie(cookie);
}
} | java |
protected ClientCookie convertCookie(Cookie browserCookie) {
BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue());
String domain = browserCookie.getDomain();
if (domain != null && domain.startsWith(".")) {
// http client does not like do... | java |
public T waitForRequest(long maxWait) {
long start = System.currentTimeMillis();
try {
while (requestsReceived.get() < 1
&& (System.currentTimeMillis() - start) < maxWait) {
try {
Thread.sleep(50);
} catch (InterruptedEx... | java |
public static com.sun.net.httpserver.HttpServer bind(InetAddress address, int startPort, int maxPort) {
com.sun.net.httpserver.HttpServer aServer = createServer();
int port = -1;
for (int possiblePort = startPort; port == -1 && possiblePort <= maxPort; possiblePort++) {
try {
... | java |
public static JavascriptExecutor getJavascriptExecutor(SearchContext searchContext) {
JavascriptExecutor executor = null;
if (searchContext instanceof JavascriptExecutor) {
executor = (JavascriptExecutor) searchContext;
} else {
if (searchContext instanceof WrapsDriver) {... | java |
public static Object executeScript(JavascriptExecutor jse, String script, Object... parameters) {
Object result;
try {
result = jse.executeScript(script, parameters);
} catch (WebDriverException e) {
String msg = e.getMessage();
if (msg != null && msg.contains... | java |
public CheckResponse getRawCheckResponse() {
if (!checkCalled) {
setupMaxTries();
setupWaitTime();
addResultsToValuesForCheck(getCurrentRowValues());
long startTime = currentTimeMillis();
try {
executeCheckWithRetry();
} fi... | java |
public void setJsonPathTo(String path, Object value) {
Object cleanValue = cleanupValue(value);
String jsonPath = getPathExpr(path);
String newContent = getPathHelper().updateJsonPathWithValue(content, jsonPath, cleanValue);
content = newContent;
} | java |
public String savePageSource(String fileName) {
List<WebElement> framesWithFakeSources = new ArrayList<>(2);
Map<String, String> sourceReplacements = new HashMap<>();
List<WebElement> frames = getFrames();
for (WebElement frame : frames) {
String newLocation = saveFrameSource... | java |
public String randomLowerMaxLength(int minLength, int maxLength) {
int range = maxLength - minLength;
int randomLength = 0;
if (range > 0) {
randomLength = random(range);
}
return randomLower(minLength + randomLength);
} | java |
public String randomString(String permitted, int length) {
StringBuilder result = new StringBuilder(length);
int maxIndex = permitted.length();
for (int i = 0; i < length; i++) {
int index = random(maxIndex);
char value = permitted.charAt(index);
result.append... | java |
private Object getSymbolArrayValue(Object arraySymbol, int index) {
Object result = null;
if (index > -1 && index < ((Object[]) arraySymbol).length) {
result = ((Object[]) arraySymbol)[index];
}
return result;
} | java |
protected boolean configureSeleniumIfNeeded() {
setSeleniumDefaultTimeOut();
try {
DriverFactory factory = null;
SeleniumDriverFactoryFactory factoryFactory = getSeleniumDriverFactoryFactory();
if (factoryFactory != null) {
factory = factoryFactory.get... | java |
public void execute(ProgramResponse response, int timeout) {
ProcessBuilder builder = createProcessBuilder(response);
invokeProgram(builder, response, timeout);
} | java |
public String format(String xml) {
try {
boolean keepDeclaration = DECL_PATTERN.matcher(xml).find();
if (trimElements) {
xml = trimElements(xml);
}
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new ... | java |
public static String trim(String xml) {
String content = removeDeclaration(xml);
return trimElements(content);
} | java |
public <T> Supplier<T> getConstructor(Class<? extends T> clazz) {
return getConstructorAs(Supplier.class, "get", clazz);
} | java |
public <T, A> Function<A, T> getConstructor(Class<? extends T> clazz, Class<A> arg) {
return getConstructorAs(Function.class, "apply", clazz, arg);
} | java |
public <A1, A2, T> BiFunction<A1, A2, T> getConstructor(Class<? extends T> clazz, Class<A1> arg1, Class<A2> arg2) {
return getConstructorAs(BiFunction.class, "apply", clazz, new Class<?>[] {arg1, arg2});
} | java |
public static String loadFile(String filename) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream(filename);
if (is == null) {
throw new IllegalArgumentException("Unable to locate: " + filename);
}
... | java |
public static File copyFile(String source, String target) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(target).getChannel();
... | java |
public static File writeFile(String filename, String content) {
PrintWriter pw = null;
try {
pw = new PrintWriter(filename, FILE_ENCODING);
pw.write(content);
pw.flush();
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Unabl... | java |
public static File appendToFile(String filename, String extraContent, boolean onNewLine){
PrintWriter pw = null;
try {
pw = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fi... | java |
public String createContainingBase64Value(String basename, String key) {
String file;
Object value = value(key);
if (value == null) {
throw new SlimFixtureException(false, "No value for key: " + key);
} else if (value instanceof String) {
file = createFileFromBase... | java |
public void addTo(Object value, List aList) {
Object cleanValue = cleanupValue(value);
aList.add(cleanValue);
} | java |
public void copyValuesFromTo(Collection<Object> source, List<Object> target) {
target.addAll(source);
} | java |
private XmlHttpResponse getReportXml(String reportXmlFilename) {
String url = LalCallColumnFixture.getLalUrl() + "/xmlrr/archive/Report/" + reportXmlFilename;
return env.doHttpGetXml(url);
} | java |
public void setValueFor(Object value, String name) {
getMapHelper().setValueForIn(value, name, getCurrentValues());
} | java |
public boolean clearValue(String name) {
String cleanName = cleanupValue(name);
boolean result = getCurrentValues().containsKey(cleanName);
getCurrentValues().remove(cleanName);
return result;
} | java |
public String getRequiredSymbol(String key) {
String result = null;
Object symbol = getSymbol(key);
if (symbol == null) {
throw new FitFailureException("No Symbol defined with key: " + key);
} else {
result = symbol.toString();
}
return result;
... | java |
public void doHttpPost(String url, String templateName, Object model, HttpResponse result, Map<String, Object> headers, String contentType) {
String request = processTemplate(templateName, model);
result.setRequest(request);
doHttpPost(url, result, headers, contentType);
} | java |
public void doHttpPost(String url, HttpResponse result, Map<String, Object> headers, String contentType) {
httpClient.post(url, result, headers, contentType);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.