code
stringlengths
73
34.1k
label
stringclasses
1 value
public static String decodeUrlIso(String stringToDecode) { try { return URLDecoder.decode(stringToDecode, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new RuntimeException(e1); } }
java
public static String ellipsize(String text, int maxLength, String end) { if (text != null && text.length() > maxLength) { return text.substring(0, maxLength - end.length()) + end; } return text; }
java
public static String join(Iterable<?> iterable, String separator) { if (iterable != null) { StringBuilder buf = new StringBuilder(); Iterator<?> it = iterable.iterator(); char singleChar = separator.length() == 1 ? separator.charAt(0) : 0; while (it.hasNext()) { ...
java
public static String join(int[] array, String separator) { if (array != null) { StringBuilder buf = new StringBuilder(Math.max(16, (separator.length() + 1) * array.length)); char singleChar = separator.length() == 1 ? separator.charAt(0) : 0; for (int i = 0; i < array.length;...
java
protected void prepareForwardedResponseHeaders(ResponseData response) { HttpHeaders headers = response.getHeaders(); headers.remove(TRANSFER_ENCODING); headers.remove(CONNECTION); headers.remove("Public-Key-Pins"); headers.remove(SERVER); headers.remove("Strict-Transport-...
java
protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) { HttpHeaders headers = request.getHeaders(); headers.set(HOST, destination.getUri().getAuthority()); headers.remove(TE); }
java
private String normalizePath(String scriptPath) { StringBuilder builder = new StringBuilder(scriptPath.length() + 1); if (scriptPath.startsWith("/")) { builder.append(scriptPath.substring(1)); } else { builder.append(scriptPath); } if (!scriptPath.endsWith...
java
public List<DbMigration> getMigrationsSinceVersion(int version) { List<DbMigration> dbMigrations = new ArrayList<>(); migrationScripts.stream().filter(script -> script.getVersion() > version).forEach(script -> { String content = loadScriptContent(script); dbMigrations.add(new DbM...
java
public int getVersion() { ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName())); Row result = resultSet.one(); if (result == null) { return 0; } return result.getInt(0); }
java
private void logMigration(DbMigration migration, boolean wasSuccessful) { BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(), migration.getScriptName(), migration.getMigrationScript(), new Date()); session.execute(boundStatement); }
java
public void migrate() { if (databaseIsUpToDate()) { LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(), database.getVersion())); return; } List<DbMigration> migrations = repository.getMigrationsSinceVersio...
java
public Set<String> findResourceNames(String location, URI locationUri) throws IOException { String filePath = toFilePath(locationUri); File folder = new File(filePath); if (!folder.isDirectory()) { LOGGER.debug("Skipping path as it is not a directory: " + filePath); retur...
java
private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) { LOGGER.debug("Scanning for resources in path: {} ({})", folder.getPath(), scanRootLocation); File[] files = folder.listFiles(); if (files == null) { return emptySe...
java
private String toResourceNameOnClasspath(String classPathRootOnDisk, File file) { String fileName = file.getAbsolutePath().replace("\\", "/"); return fileName.substring(classPathRootOnDisk.length()); }
java
public static <T> T notNull(T argument, String argumentName) { if (argument == null) { throw new IllegalArgumentException("Argument " + argumentName + " must not be null."); } return argument; }
java
public static String notNullOrEmpty(String argument, String argumentName) { if (argument == null || argument.trim().isEmpty()) { throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty."); } return argument; }
java
public static TestSuiteResult unmarshal(File testSuite) throws IOException { try (InputStream stream = new FileInputStream(testSuite)) { return unmarshal(stream); } }
java
public static List<TestSuiteResult> unmarshalSuites(File... directories) throws IOException { List<TestSuiteResult> results = new ArrayList<>(); List<File> files = listTestSuiteFiles(directories); for (File file : files) { results.add(unmarshal(file)); } return resu...
java
public static List<File> listFilesByRegex(String regex, File... directories) { return listFiles(directories, new RegexFileFilter(regex), CanReadFileFilter.CAN_READ); }
java
public static List<File> listFiles(File[] directories, IOFileFilter fileFilter, IOFileFilter dirFilter) { List<File> files = new ArrayList<>(); for (File directory : directories) { if (!directory.isDirectory()) { continue; } Collection<File> filesInDir...
java
private void populateAnnotations(Collection<Annotation> annotations) { for (Annotation each : annotations) { this.annotations.put(each.annotationType(), each); } }
java
public void setDefaults(Annotation[] defaultAnnotations) { if (defaultAnnotations == null) { return; } for (Annotation each : defaultAnnotations) { Class<? extends Annotation> key = each.annotationType(); if (Title.class.equals(key) || Description.class.equals...
java
private static String getHostname() { if (Hostname == null) { try { Hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { Hostname = "default"; LOGGER.warn("Can not get current hostname", e); } } ...
java
public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) { event.getLabels().add(createHostLabel(getHostname())); event.getLabels().add(createThreadLabel(format("%s.%s(%s)", ManagementFactory.getRuntimeMXBean().getName(), Thread.curr...
java
private void openBrowser(URI url) throws IOException { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(url); } else { LOGGER.error("Can not open browser because this capability is not supported on " + "your platform. You can use the link below ...
java
private Server setUpServer() { Server server = new Server(port); ResourceHandler handler = new ResourceHandler(); handler.setDirectoriesListed(true); handler.setWelcomeFiles(new String[]{"index.html"}); handler.setResourceBase(getReportDirectoryPath().toAbsolutePath().toString())...
java
private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) { int modifiers = pluginClass.getModifiers(); return !Modifier.isAbstract(modifiers) && !Modifier.isInterface(modifiers) && !Modifier.isPrivate(modifiers); }
java
@Override public void fire(StepStartedEvent event) { for (LifecycleListener listener : listeners) { try { listener.fire(event); } catch (Exception e) { logError(listener, e); } } }
java
private void logError(LifecycleListener listener, Exception e) { LOGGER.error("Error for listener " + listener.getClass(), e); }
java
public static String cutEnd(String data, int maxLength) { if (data.length() > maxLength) { return data.substring(0, maxLength) + "..."; } else { return data; } }
java
public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) { List<T> foundServices = new ArrayList<>(); Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator(); while (checkHasNextSafely(iterator)) { try { T item = iterator.n...
java
private static void unpackFace(File outputDirectory) throws IOException { ClassLoader loader = AllureMain.class.getClassLoader(); for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) { Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName()); ...
java
protected Path createTempDirectory(String prefix) { try { return Files.createTempDirectory(tempDirectory, prefix); } catch (IOException e) { throw new AllureCommandException(e); } }
java
private Level getLogLevel() { return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO; }
java
public static boolean isBadXmlCharacter(char c) { boolean cDataCharacter = c < '\u0020' && c != '\t' && c != '\r' && c != '\n'; cDataCharacter |= (c >= '\uD800' && c < '\uE000'); cDataCharacter |= (c == '\uFFFE' || c == '\uFFFF'); return cDataCharacter; }
java
public static void replaceBadXmlCharactersBySpace(char[] cbuf, int off, int len) { for (int i = off; i < off + len; i++) { if (isBadXmlCharacter(cbuf[i])) { cbuf[i] = '\u0020'; } } }
java
@Override public int read(char[] cbuf, int off, int len) throws IOException { int numChars = super.read(cbuf, off, len); replaceBadXmlCharactersBySpace(cbuf, off, len); return numChars; }
java
@Override protected void runUnsafe() throws Exception { Path reportDirectory = getReportDirectoryPath(); Files.walkFileTree(reportDirectory, new DeleteVisitor()); LOGGER.info("Report directory <{}> was successfully cleaned.", reportDirectory); }
java
public static void main(String[] args) { if (args.length < 2) { // NOSONAR LOGGER.error("There must be at least two arguments"); return; } int lastIndex = args.length - 1; AllureReportGenerator reportGenerator = new AllureReportGenerator( getFiles(...
java
public static void setPropertySafely(Marshaller marshaller, String name, Object value) { try { marshaller.setProperty(name, value); } catch (PropertyException e) { LOGGER.warn(String.format("Can't set \"%s\" property to given marshaller", name), e); } }
java
public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) { String message = throwable.getMessage(); try { return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title); } catch (Exception e) { e.addSuppressed(throwable...
java
public static String getExtensionByMimeType(String type) { MimeTypes types = getDefaultMimeTypes(); try { return types.forName(type).getExtension(); } catch (Exception e) { LOGGER.warn("Can't detect extension for MIME-type " + type, e); return ""; } ...
java
@Override public void process(TestCaseResult context) { context.getParameters().add(new Parameter() .withName(getName()) .withValue(getValue()) .withKind(ParameterKind.valueOf(getKind())) ); }
java
protected void validateResultsDirectories() { for (String result : results) { if (Files.notExists(Paths.get(result))) { throw new AllureCommandException(String.format("Report directory <%s> not found.", result)); } } }
java
protected String getClasspath() throws IOException { List<String> classpath = new ArrayList<>(); classpath.add(getBundleJarPath()); classpath.addAll(getPluginsPath()); return StringUtils.toString(classpath.toArray(new String[classpath.size()]), " "); }
java
protected String getExecutableJar() throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, MAIN); manifest.getMainAttributes().put(Attributes.Name.CLA...
java
protected String getBundleJarPath() throws MalformedURLException { Path path = PROPERTIES.getAllureHome().resolve("app/allure-bundle.jar").toAbsolutePath(); if (Files.notExists(path)) { throw new AllureCommandException(String.format("Bundle not found by path <%s>", path)); } ...
java
protected List<String> getPluginsPath() throws IOException { List<String> result = new ArrayList<>(); Path pluginsDirectory = PROPERTIES.getAllureHome().resolve("plugins").toAbsolutePath(); if (Files.notExists(pluginsDirectory)) { return Collections.emptyList(); } tr...
java
protected String getJavaExecutablePath() { String executableName = isWindows() ? "bin/java.exe" : "bin/java"; return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString(); }
java
@Override public void run() { for (Map.Entry<String, TestSuiteResult> entry : testSuites) { for (TestCaseResult testCase : entry.getValue().getTestCases()) { markTestcaseAsInterruptedIfNotFinishedYet(testCase); } entry.getValue().getTestCases().add(createF...
java
public static void checkDirectory(File directory) { if (!(directory.exists() || directory.mkdirs())) { throw new ReportGenerationException( String.format("Can't create data directory <%s>", directory.getAbsolutePath()) ); } }
java
public static int serialize(final File directory, String name, Object obj) { try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) { return serialize(stream, obj); } catch (IOException e) { throw new ReportGenerationException(e); } }
java
public static int serialize(OutputStream stream, Object obj) { ObjectMapper mapper = createMapperWithJaxbAnnotationInspector(); try (DataOutputStream data = new DataOutputStream(stream); OutputStreamWriter writer = new OutputStreamWriter(data, StandardCharsets.UTF_8)) { mapper....
java
@Override public void process(Step step) { step.setName(getName()); step.setStatus(Status.PASSED); step.setStart(System.currentTimeMillis()); step.setTitle(getTitle()); }
java
@Override protected Deque<Step> childValue(Deque<Step> parentValue) { Deque<Step> queue = new LinkedList<>(); queue.add(parentValue.getFirst()); return queue; }
java
public Step createRootStep() { return new Step() .withName("Root step") .withTitle("Allure step processing error: if you see this step something went wrong.") .withStart(System.currentTimeMillis()) .withStatus(Status.BROKEN); }
java
@Override public void process(Step context) { Iterator<Attachment> iterator = context.getAttachments().listIterator(); while (iterator.hasNext()) { Attachment attachment = iterator.next(); if (pattern.matcher(attachment.getSource()).matches()) { deleteAttachme...
java
public void fire(StepStartedEvent event) { Step step = new Step(); event.process(step); stepStorage.put(step); notifier.fire(event); }
java
public void fire(StepEvent event) { Step step = stepStorage.getLast(); event.process(step); notifier.fire(event); }
java
public void fire(StepFinishedEvent event) { Step step = stepStorage.adopt(); event.process(step); notifier.fire(event); }
java
public void fire(TestCaseStartedEvent event) { //init root step in parent thread if needed stepStorage.get(); TestCaseResult testCase = testCaseStorage.get(); event.process(testCase); synchronized (TEST_SUITE_ADD_CHILD_LOCK) { testSuiteStorage.get(event.getSuiteUid(...
java
public void fire(TestCaseEvent event) { TestCaseResult testCase = testCaseStorage.get(); event.process(testCase); notifier.fire(event); }
java
public void fire(TestCaseFinishedEvent event) { TestCaseResult testCase = testCaseStorage.get(); event.process(testCase); Step root = stepStorage.pollLast(); if (Status.PASSED.equals(testCase.getStatus())) { new RemoveAttachmentsEvent(AllureConfig.newInstance().getRemoveAtt...
java
public static String strMapToStr(Map<String, String> map) { StringBuilder sb = new StringBuilder(); if (map == null || map.isEmpty()) return sb.toString(); for (Entry<String, String> entry : map.entrySet()) { sb.append("< " + entry.getKey() + ", " + entry.getValue() +...
java
public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){ StringBuilder res = new StringBuilder(); for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap .entrySet()) { LinkedHashSet<String> valueSet = entry.getValue...
java
public static String renderJson(Object o) { Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting() .create(); return gson.toJson(o); }
java
public void sendMessageUntilStopCount(int stopCount) { // always send with valid data. for (int i = processedWorkerCount; i < workers.size(); ++i) { ActorRef worker = workers.get(i); try { /** * !!! This is a must; without this sleep; stuck occu...
java
public void waitAndRetry() { ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager( processedWorkerCount); logger.debug("NOW WAIT Another " + asstManagerRetryIntervalMillis + " MS. at " + PcDateUtils.ge...
java
public String getUuidFromResponse(ResponseOnSingeRequest myResponse) { String uuid = PcConstants.NA; String responseBody = myResponse.getResponseBody(); Pattern regex = Pattern.compile(getJobIdRegex()); Matcher matcher = regex.matcher(responseBody); if (matcher.matches()) { ...
java
public double getProgressFromResponse(ResponseOnSingeRequest myResponse) { double progress = 0.0; try { if (myResponse == null || myResponse.isFailObtainResponse()) { return progress; } String responseBody = myResponse.getResponseBody(); ...
java
public boolean ifTaskCompletedSuccessOrFailureFromResponse( ResponseOnSingeRequest myResponse) { boolean isCompleted = false; try { if (myResponse == null || myResponse.isFailObtainResponse()) { return isCompleted; } String responseBody ...
java
public BoundRequestBuilder createRequest() throws HttpRequestCreateException { BoundRequestBuilder builder = null; getLogger().debug("AHC completeUrl " + requestUrl); try { switch (httpMethod) { case GET: builder = client.prepareGet(requestU...
java
public ResponseOnSingeRequest onComplete(Response response) { cancelCancellable(); try { Map<String, List<String>> responseHeaders = null; if (responseHeaderMeta != null) { responseHeaders = new LinkedHashMap<String, List<String>>(); ...
java
public void onThrowable(Throwable cause) { this.cause = cause; getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf()); }
java
public static List<String> getNodeListFromStringLineSeperateOrSpaceSeperate( String listStr, boolean removeDuplicate) { List<String> nodes = new ArrayList<String>(); for (String token : listStr.split("[\\r?\\n| +]+")) { // 20131025: fix if fqdn has space in the end. ...
java
public static int removeDuplicateNodeList(List<String> list) { int originCount = list.size(); // add elements to all, including duplicates HashSet<String> hs = new LinkedHashSet<String>(); hs.addAll(list); list.clear(); list.addAll(hs); return originCount - list...
java
public ParallelTaskBuilder setResponseContext( Map<String, Object> responseContext) { if (responseContext != null) this.responseContext = responseContext; else logger.error("context cannot be null. skip set."); return this; }
java
public ParallelTask execute(ParallecResponseHandler handler) { ParallelTask task = new ParallelTask(); try { targetHostMeta = new TargetHostMeta(targetHosts); final ParallelTask taskReal = new ParallelTask(requestProtocol, concurrency, httpMeta, targetHostM...
java
public boolean validation() throws ParallelTaskInvalidException { ParallelTask task = new ParallelTask(); targetHostMeta = new TargetHostMeta(targetHosts); task = new ParallelTask(requestProtocol, concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null,...
java
public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath, String sourcePath, HostsSourceType sourceType) throws TargetHostsLoadException { this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath, sourceType); return this;...
java
public ParallelTaskBuilder setTargetHostsFromLineByLineText( String sourcePath, HostsSourceType sourceType) throws TargetHostsLoadException { this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath, sourceType); return this; }
java
public ParallelTaskBuilder setReplacementVarMapNodeSpecific( Map<String, StrStrMap> replacementVarMapNodeSpecific) { this.replacementVarMapNodeSpecific.clear(); this.replacementVarMapNodeSpecific .putAll(replacementVarMapNodeSpecific); this.requestReplacementType = R...
java
public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap( Map<String, StrStrMap> replacementVarMapNodeSpecific, String uniformTargetHost) { setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific); if (Strings.isNullOrEmpty(uniformTargetHost)) { logger...
java
public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar( String variable, List<String> replaceList, String uniformTargetHost) { if (Strings.isNullOrEmpty(uniformTargetHost)) { logger.error("uniform target host is empty or null. skil setting."); return this; ...
java
public ParallelTaskBuilder setReplaceVarMapToSingleTarget( List<StrStrMap> replacementVarMapList, String uniformTargetHost) { if (Strings.isNullOrEmpty(uniformTargetHost)) { logger.error("uniform target host is empty or null. skil setting."); return this; } t...
java
public ParallelTaskBuilder setReplacementVarMap( Map<String, String> replacementVarMap) { this.replacementVarMap = replacementVarMap; // TODO Check and warning of overwriting // set as uniform this.requestReplacementType = RequestReplacementType.UNIFORM_VAR_REPLACEMENT; ...
java
public ParallelTaskBuilder setHttpPollerProcessor( HttpPollerProcessor httpPollerProcessor) { this.httpMeta.setHttpPollerProcessor(httpPollerProcessor); this.httpMeta.setPollable(true); return this; }
java
public ParallelTaskBuilder setSshPassword(String password) { this.sshMeta.setPassword(password); this.sshMeta.setSshLoginType(SshLoginType.PASSWORD); return this; }
java
public ParallelTaskBuilder setSshPrivKeyRelativePath( String privKeyRelativePath) { this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath); this.sshMeta.setSshLoginType(SshLoginType.KEY); return this; }
java
public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase( String privKeyRelativePath, String passphrase) { this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath); this.sshMeta.setPrivKeyUsePassphrase(true); this.sshMeta.setPassphrase(passphrase); this.sshMeta.setS...
java
public static String getDateTimeStr(Date d) { if (d == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); // 20140315 test will problem +0000 return sdf.format(d); }
java
public static String getDateTimeStrStandard(Date d) { if (d == null) return ""; if (d.getTime() == 0L) return "Never"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSSZ"); return sdf.format(d); }
java
public static String getDateTimeStrConcise(Date d) { if (d == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); return sdf.format(d); }
java
public static Date getDateFromConciseStr(String str) { Date d = null; if (str == null || str.isEmpty()) return null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); d = sdf.parse(str); } catch (Exception ex) { lo...
java
private final void handleHttpWorkerResponse( ResponseOnSingeRequest respOnSingleReq) throws Exception { // Successful response from GenericAsyncHttpWorker // Jeff 20310411: use generic response String responseContent = respOnSingleReq.getResponseBody(); response.setResponse...
java
private final void processMainRequest() { sender = getSender(); startTimeMillis = System.currentTimeMillis(); timeoutDuration = Duration.create( request.getActorMaxOperationTimeoutSec(), TimeUnit.SECONDS); actorMaxOperationTimeoutSec = request.getActorMaxOperationTimeou...
java
@SuppressWarnings("deprecation") private final void operationTimeout() { /** * first kill async http worker; before suicide LESSON: MUST KILL AND * WAIT FOR CHILDREN to reply back before kill itself. */ cancelCancellable(); if (asyncWorker != null && !asyncWorker....
java
private final void replyErrors(final String errorMessage, final String stackTrace, final String statusCode, final int statusCodeInt) { reply(true, errorMessage, stackTrace, statusCode, statusCodeInt, PcConstants.NA, null); }
java
public static void addHeaders(BoundRequestBuilder builder, Map<String, String> headerMap) { for (Entry<String, String> entry : headerMap.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); builder.addHeader(name, value); } }
java
@SuppressWarnings("deprecation") public boolean cancelOnTargetHosts(List<String> targetHosts) { boolean success = false; try { switch (state) { case IN_PROGRESS: if (executionManager != null && !executionManager.isTerminated()) { ...
java