_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3100
|
Ensure.notNullOrEmpty
|
train
|
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
|
{
"resource": ""
}
|
q3101
|
AllureFileUtils.unmarshal
|
train
|
public static TestSuiteResult unmarshal(File testSuite) throws IOException {
try (InputStream stream = new FileInputStream(testSuite)) {
return unmarshal(stream);
}
}
|
java
|
{
"resource": ""
}
|
q3102
|
AllureFileUtils.unmarshalSuites
|
train
|
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 results;
}
|
java
|
{
"resource": ""
}
|
q3103
|
AllureFileUtils.listFilesByRegex
|
train
|
public static List<File> listFilesByRegex(String regex, File... directories) {
return listFiles(directories,
new RegexFileFilter(regex),
CanReadFileFilter.CAN_READ);
}
|
java
|
{
"resource": ""
}
|
q3104
|
AllureFileUtils.listFiles
|
train
|
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> filesInDirectory = FileUtils.listFiles(directory,
fileFilter,
dirFilter);
files.addAll(filesInDirectory);
}
return files;
}
|
java
|
{
"resource": ""
}
|
q3105
|
AnnotationManager.populateAnnotations
|
train
|
private void populateAnnotations(Collection<Annotation> annotations) {
for (Annotation each : annotations) {
this.annotations.put(each.annotationType(), each);
}
}
|
java
|
{
"resource": ""
}
|
q3106
|
AnnotationManager.setDefaults
|
train
|
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(key)) {
continue;
}
if (!annotations.containsKey(key)) {
annotations.put(key, each);
}
}
}
|
java
|
{
"resource": ""
}
|
q3107
|
AnnotationManager.getHostname
|
train
|
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);
}
}
return Hostname;
}
|
java
|
{
"resource": ""
}
|
q3108
|
AnnotationManager.withExecutorInfo
|
train
|
public static TestCaseStartedEvent withExecutorInfo(TestCaseStartedEvent event) {
event.getLabels().add(createHostLabel(getHostname()));
event.getLabels().add(createThreadLabel(format("%s.%s(%s)",
ManagementFactory.getRuntimeMXBean().getName(),
Thread.currentThread().getName(),
Thread.currentThread().getId())
));
return event;
}
|
java
|
{
"resource": ""
}
|
q3109
|
ReportOpen.openBrowser
|
train
|
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 to open the report manually.");
}
}
|
java
|
{
"resource": ""
}
|
q3110
|
ReportOpen.setUpServer
|
train
|
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());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});
server.setStopAtShutdown(true);
server.setHandler(handlers);
return server;
}
|
java
|
{
"resource": ""
}
|
q3111
|
AbstractPlugin.checkModifiers
|
train
|
private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {
int modifiers = pluginClass.getModifiers();
return !Modifier.isAbstract(modifiers) &&
!Modifier.isInterface(modifiers) &&
!Modifier.isPrivate(modifiers);
}
|
java
|
{
"resource": ""
}
|
q3112
|
ListenersNotifier.fire
|
train
|
@Override
public void fire(StepStartedEvent event) {
for (LifecycleListener listener : listeners) {
try {
listener.fire(event);
} catch (Exception e) {
logError(listener, e);
}
}
}
|
java
|
{
"resource": ""
}
|
q3113
|
ListenersNotifier.logError
|
train
|
private void logError(LifecycleListener listener, Exception e) {
LOGGER.error("Error for listener " + listener.getClass(), e);
}
|
java
|
{
"resource": ""
}
|
q3114
|
AllureAspectUtils.cutEnd
|
train
|
public static String cutEnd(String data, int maxLength) {
if (data.length() > maxLength) {
return data.substring(0, maxLength) + "...";
} else {
return data;
}
}
|
java
|
{
"resource": ""
}
|
q3115
|
ServiceLoaderUtils.load
|
train
|
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.next();
foundServices.add(item);
LOGGER.debug(String.format("Found %s [%s]", serviceType.getSimpleName(), item.toString()));
} catch (ServiceConfigurationError e) {
LOGGER.trace("Can't find services using Java SPI", e);
LOGGER.error(e.getMessage());
}
}
return foundServices;
}
|
java
|
{
"resource": ""
}
|
q3116
|
AllureMain.unpackFace
|
train
|
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());
if (matcher.find()) {
String resourcePath = matcher.group(1);
File dest = new File(outputDirectory, resourcePath);
Files.createParentDirs(dest);
try (FileOutputStream output = new FileOutputStream(dest);
InputStream input = info.url().openStream()) {
IOUtils.copy(input, output);
LOGGER.debug("{} successfully copied.", resourcePath);
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3117
|
AbstractCommand.createTempDirectory
|
train
|
protected Path createTempDirectory(String prefix) {
try {
return Files.createTempDirectory(tempDirectory, prefix);
} catch (IOException e) {
throw new AllureCommandException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3118
|
AbstractCommand.getLogLevel
|
train
|
private Level getLogLevel() {
return isQuiet() ? Level.OFF : isVerbose() ? Level.DEBUG : Level.INFO;
}
|
java
|
{
"resource": ""
}
|
q3119
|
AllureNamingUtils.isBadXmlCharacter
|
train
|
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
|
{
"resource": ""
}
|
q3120
|
AllureNamingUtils.replaceBadXmlCharactersBySpace
|
train
|
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
|
{
"resource": ""
}
|
q3121
|
BadXmlCharacterFilterReader.read
|
train
|
@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
|
{
"resource": ""
}
|
q3122
|
ReportClean.runUnsafe
|
train
|
@Override
protected void runUnsafe() throws Exception {
Path reportDirectory = getReportDirectoryPath();
Files.walkFileTree(reportDirectory, new DeleteVisitor());
LOGGER.info("Report directory <{}> was successfully cleaned.", reportDirectory);
}
|
java
|
{
"resource": ""
}
|
q3123
|
DummyReportGenerator.main
|
train
|
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(Arrays.copyOf(args, lastIndex))
);
reportGenerator.generate(new File(args[lastIndex]));
}
|
java
|
{
"resource": ""
}
|
q3124
|
AllureResultsUtils.setPropertySafely
|
train
|
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
|
{
"resource": ""
}
|
q3125
|
AllureResultsUtils.writeAttachmentWithErrorMessage
|
train
|
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);
LOGGER.error(String.format("Can't write attachment \"%s\"", title), e);
}
return new Attachment();
}
|
java
|
{
"resource": ""
}
|
q3126
|
AllureResultsUtils.getExtensionByMimeType
|
train
|
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
|
{
"resource": ""
}
|
q3127
|
AddParameterEvent.process
|
train
|
@Override
public void process(TestCaseResult context) {
context.getParameters().add(new Parameter()
.withName(getName())
.withValue(getValue())
.withKind(ParameterKind.valueOf(getKind()))
);
}
|
java
|
{
"resource": ""
}
|
q3128
|
ReportGenerate.validateResultsDirectories
|
train
|
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
|
{
"resource": ""
}
|
q3129
|
ReportGenerate.getClasspath
|
train
|
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
|
{
"resource": ""
}
|
q3130
|
ReportGenerate.getExecutableJar
|
train
|
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.CLASS_PATH, getClasspath());
Path jar = createTempDirectory("exec").resolve("generate.jar");
try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) {
output.putNextEntry(new JarEntry("allure.properties"));
Path allureConfig = PROPERTIES.getAllureConfig();
if (Files.exists(allureConfig)) {
byte[] bytes = Files.readAllBytes(allureConfig);
output.write(bytes);
}
output.closeEntry();
}
return jar.toAbsolutePath().toString();
}
|
java
|
{
"resource": ""
}
|
q3131
|
ReportGenerate.getBundleJarPath
|
train
|
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));
}
return path.toUri().toURL().toString();
}
|
java
|
{
"resource": ""
}
|
q3132
|
ReportGenerate.getPluginsPath
|
train
|
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();
}
try (DirectoryStream<Path> plugins = Files.newDirectoryStream(pluginsDirectory, JAR_FILES)) {
for (Path plugin : plugins) {
result.add(plugin.toUri().toURL().toString());
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q3133
|
ReportGenerate.getJavaExecutablePath
|
train
|
protected String getJavaExecutablePath() {
String executableName = isWindows() ? "bin/java.exe" : "bin/java";
return PROPERTIES.getJavaHome().resolve(executableName).toAbsolutePath().toString();
}
|
java
|
{
"resource": ""
}
|
q3134
|
AllureShutdownHook.run
|
train
|
@Override
public void run() {
for (Map.Entry<String, TestSuiteResult> entry : testSuites) {
for (TestCaseResult testCase : entry.getValue().getTestCases()) {
markTestcaseAsInterruptedIfNotFinishedYet(testCase);
}
entry.getValue().getTestCases().add(createFakeTestcaseWithWarning(entry.getValue()));
Allure.LIFECYCLE.fire(new TestSuiteFinishedEvent(entry.getKey()));
}
}
|
java
|
{
"resource": ""
}
|
q3135
|
AllureReportUtils.checkDirectory
|
train
|
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
|
{
"resource": ""
}
|
q3136
|
AllureReportUtils.serialize
|
train
|
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
|
{
"resource": ""
}
|
q3137
|
AllureReportUtils.serialize
|
train
|
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.writerWithDefaultPrettyPrinter().writeValue(writer, obj);
return data.size();
} catch (IOException e) {
throw new ReportGenerationException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3138
|
StepStartedEvent.process
|
train
|
@Override
public void process(Step step) {
step.setName(getName());
step.setStatus(Status.PASSED);
step.setStart(System.currentTimeMillis());
step.setTitle(getTitle());
}
|
java
|
{
"resource": ""
}
|
q3139
|
StepStorage.childValue
|
train
|
@Override
protected Deque<Step> childValue(Deque<Step> parentValue) {
Deque<Step> queue = new LinkedList<>();
queue.add(parentValue.getFirst());
return queue;
}
|
java
|
{
"resource": ""
}
|
q3140
|
StepStorage.createRootStep
|
train
|
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
|
{
"resource": ""
}
|
q3141
|
RemoveAttachmentsEvent.process
|
train
|
@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()) {
deleteAttachment(attachment);
iterator.remove();
}
}
for (Step step : context.getSteps()) {
process(step);
}
}
|
java
|
{
"resource": ""
}
|
q3142
|
Allure.fire
|
train
|
public void fire(StepStartedEvent event) {
Step step = new Step();
event.process(step);
stepStorage.put(step);
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3143
|
Allure.fire
|
train
|
public void fire(StepEvent event) {
Step step = stepStorage.getLast();
event.process(step);
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3144
|
Allure.fire
|
train
|
public void fire(StepFinishedEvent event) {
Step step = stepStorage.adopt();
event.process(step);
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3145
|
Allure.fire
|
train
|
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()).getTestCases().add(testCase);
}
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3146
|
Allure.fire
|
train
|
public void fire(TestCaseEvent event) {
TestCaseResult testCase = testCaseStorage.get();
event.process(testCase);
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3147
|
Allure.fire
|
train
|
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().getRemoveAttachments()).process(root);
}
testCase.getSteps().addAll(root.getSteps());
testCase.getAttachments().addAll(root.getAttachments());
stepStorage.remove();
testCaseStorage.remove();
notifier.fire(event);
}
|
java
|
{
"resource": ""
}
|
q3148
|
PcStringUtils.strMapToStr
|
train
|
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() + "> ");
}
return sb.toString();
}
|
java
|
{
"resource": ""
}
|
q3149
|
PcStringUtils.getAggregatedResultHuman
|
train
|
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();
res.append("[" + entry.getKey() + " COUNT: " +valueSet.size() + " ]:\n");
for(String str: valueSet){
res.append("\t" + str + "\n");
}
res.append("###################################\n\n");
}
return res.toString();
}
|
java
|
{
"resource": ""
}
|
q3150
|
PcStringUtils.renderJson
|
train
|
public static String renderJson(Object o) {
Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()
.create();
return gson.toJson(o);
}
|
java
|
{
"resource": ""
}
|
q3151
|
AssistantExecutionManager.sendMessageUntilStopCount
|
train
|
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 occured at 5K.
* AKKA seems cannot handle too much too fast message send out.
*/
Thread.sleep(1L);
} catch (InterruptedException e) {
logger.error("sleep exception " + e + " details: ", e);
}
// send as if the sender is the origin manager; so reply back to
// origin manager
worker.tell(OperationWorkerMsgType.PROCESS_REQUEST, originalManager);
processedWorkerCount++;
if (processedWorkerCount > stopCount) {
return;
}
logger.debug("REQ_SENT: {} / {} taskId {}",
processedWorkerCount, requestTotalCount, taskIdTrim);
}// end for loop
}
|
java
|
{
"resource": ""
}
|
q3152
|
AssistantExecutionManager.waitAndRetry
|
train
|
public void waitAndRetry() {
ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(
processedWorkerCount);
logger.debug("NOW WAIT Another " + asstManagerRetryIntervalMillis
+ " MS. at " + PcDateUtils.getNowDateTimeStrStandard());
getContext()
.system()
.scheduler()
.scheduleOnce(
Duration.create(asstManagerRetryIntervalMillis,
TimeUnit.MILLISECONDS), getSelf(),
continueToSendToBatchSenderAsstManager,
getContext().system().dispatcher(), getSelf());
return;
}
|
java
|
{
"resource": ""
}
|
q3153
|
HttpPollerProcessor.getUuidFromResponse
|
train
|
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()) {
uuid = matcher.group(1);
}
return uuid;
}
|
java
|
{
"resource": ""
}
|
q3154
|
HttpPollerProcessor.getProgressFromResponse
|
train
|
public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {
double progress = 0.0;
try {
if (myResponse == null || myResponse.isFailObtainResponse()) {
return progress;
}
String responseBody = myResponse.getResponseBody();
Pattern regex = Pattern.compile(progressRegex);
Matcher matcher = regex.matcher(responseBody);
if (matcher.matches()) {
String progressStr = matcher.group(1);
progress = Double.parseDouble(progressStr);
}
} catch (Exception t) {
logger.error("fail " + t);
}
return progress;
}
|
java
|
{
"resource": ""
}
|
q3155
|
HttpPollerProcessor.ifTaskCompletedSuccessOrFailureFromResponse
|
train
|
public boolean ifTaskCompletedSuccessOrFailureFromResponse(
ResponseOnSingeRequest myResponse) {
boolean isCompleted = false;
try {
if (myResponse == null || myResponse.isFailObtainResponse()) {
return isCompleted;
}
String responseBody = myResponse.getResponseBody();
if (responseBody.matches(successRegex)
|| responseBody.matches(failureRegex)) {
isCompleted = true;
}
} catch (Exception t) {
logger.error("fail " + t);
}
return isCompleted;
}
|
java
|
{
"resource": ""
}
|
q3156
|
HttpWorker.createRequest
|
train
|
public BoundRequestBuilder createRequest()
throws HttpRequestCreateException {
BoundRequestBuilder builder = null;
getLogger().debug("AHC completeUrl " + requestUrl);
try {
switch (httpMethod) {
case GET:
builder = client.prepareGet(requestUrl);
break;
case POST:
builder = client.preparePost(requestUrl);
break;
case PUT:
builder = client.preparePut(requestUrl);
break;
case HEAD:
builder = client.prepareHead(requestUrl);
break;
case OPTIONS:
builder = client.prepareOptions(requestUrl);
break;
case DELETE:
builder = client.prepareDelete(requestUrl);
break;
default:
break;
}
PcHttpUtils.addHeaders(builder, this.httpHeaderMap);
if (!Strings.isNullOrEmpty(postData)) {
builder.setBody(postData);
String charset = "";
if (null!=this.httpHeaderMap) {
charset = this.httpHeaderMap.get("charset");
}
if(!Strings.isNullOrEmpty(charset)) {
builder.setBodyEncoding(charset);
}
}
} catch (Exception t) {
throw new HttpRequestCreateException(
"Error in creating request in Httpworker. "
+ " If BoundRequestBuilder is null. Then fail to create.",
t);
}
return builder;
}
|
java
|
{
"resource": ""
}
|
q3157
|
HttpWorker.onComplete
|
train
|
public ResponseOnSingeRequest onComplete(Response response) {
cancelCancellable();
try {
Map<String, List<String>> responseHeaders = null;
if (responseHeaderMeta != null) {
responseHeaders = new LinkedHashMap<String, List<String>>();
if (responseHeaderMeta.isGetAll()) {
for (Map.Entry<String, List<String>> header : response
.getHeaders()) {
responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());
}
} else {
for (String key : responseHeaderMeta.getKeys()) {
if (response.getHeaders().containsKey(key)) {
responseHeaders.put(key.toLowerCase(Locale.ROOT),
response.getHeaders().get(key));
}
}
}
}
int statusCodeInt = response.getStatusCode();
String statusCode = statusCodeInt + " " + response.getStatusText();
String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&
response.getContentType()!=null ?
AsyncHttpProviderUtils.parseCharset(response.getContentType())
: ParallecGlobalConfig.httpResponseBodyDefaultCharset;
if(charset == null){
getLogger().error("charset is not provided from response content type. Use default");
charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset;
}
reply(response.getResponseBody(charset), false, null, null, statusCode,
statusCodeInt, responseHeaders);
} catch (IOException e) {
getLogger().error("fail response.getResponseBody " + e);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q3158
|
HttpWorker.onThrowable
|
train
|
public void onThrowable(Throwable cause) {
this.cause = cause;
getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());
}
|
java
|
{
"resource": ""
}
|
q3159
|
PcTargetHostsUtils.getNodeListFromStringLineSeperateOrSpaceSeperate
|
train
|
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.
if (token != null && !token.trim().isEmpty()) {
nodes.add(token.trim());
}
}
if (removeDuplicate) {
removeDuplicateNodeList(nodes);
}
logger.info("Target hosts size : " + nodes.size());
return nodes;
}
|
java
|
{
"resource": ""
}
|
q3160
|
PcTargetHostsUtils.removeDuplicateNodeList
|
train
|
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.size();
}
|
java
|
{
"resource": ""
}
|
q3161
|
ParallelTaskBuilder.setResponseContext
|
train
|
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
|
{
"resource": ""
}
|
q3162
|
ParallelTaskBuilder.execute
|
train
|
public ParallelTask execute(ParallecResponseHandler handler) {
ParallelTask task = new ParallelTask();
try {
targetHostMeta = new TargetHostMeta(targetHosts);
final ParallelTask taskReal = new ParallelTask(requestProtocol,
concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,
handler, responseContext,
replacementVarMapNodeSpecific, replacementVarMap,
requestReplacementType,
config);
task = taskReal;
logger.info("***********START_PARALLEL_HTTP_TASK_"
+ task.getTaskId() + "***********");
// throws ParallelTaskInvalidException
task.validateWithFillDefault();
task.setSubmitTime(System.currentTimeMillis());
if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {
//late initialize the task scheduler
ParallelTaskManager.getInstance().initTaskSchedulerIfNot();
// add task to the wait queue
ParallelTaskManager.getInstance().getWaitQ().add(task);
logger.info("Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. "
+ task.getTaskId());
} else {
logger.info(
"Disabled CapacityAwareTaskScheduler. Immediately execute task {} ",
task.getTaskId());
Runnable director = new Runnable() {
public void run() {
ParallelTaskManager.getInstance()
.generateUpdateExecuteTask(taskReal);
}
};
new Thread(director).start();
}
if (this.getMode() == TaskRunMode.SYNC) {
logger.info("Executing task {} in SYNC mode... ",
task.getTaskId());
while (task != null && !task.isCompleted()) {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
logger.error("InterruptedException " + e);
}
}
}
} catch (ParallelTaskInvalidException ex) {
logger.info("Request is invalid with missing parts. Details: "
+ ex.getMessage() + " Cannot execute at this time. "
+ " Please review your request and try again.\nCommand:"
+ httpMeta.toString());
task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);
task.getTaskErrorMetas().add(
new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,
"validation eror"));
} catch (Exception t) {
logger.error("fail task builder. Unknown error: " + t, t);
task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);
task.getTaskErrorMetas().add(
new TaskErrorMeta(TaskErrorType.UNKNOWN, "unknown eror",
t));
}
logger.info("***********FINISH_PARALLEL_HTTP_TASK_" + task.getTaskId()
+ "***********");
return task;
}
|
java
|
{
"resource": ""
}
|
q3163
|
ParallelTaskBuilder.validation
|
train
|
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, responseContext,
replacementVarMapNodeSpecific,
replacementVarMap, requestReplacementType, config);
boolean valid = false;
try {
valid = task.validateWithFillDefault();
} catch (ParallelTaskInvalidException e) {
logger.info("task is invalid " + e);
}
return valid;
}
|
java
|
{
"resource": ""
}
|
q3164
|
ParallelTaskBuilder.setTargetHostsFromJsonPath
|
train
|
public ParallelTaskBuilder setTargetHostsFromJsonPath(String jsonPath,
String sourcePath, HostsSourceType sourceType)
throws TargetHostsLoadException {
this.targetHosts = targetHostBuilder.setTargetHostsFromJsonPath(jsonPath, sourcePath,
sourceType);
return this;
}
|
java
|
{
"resource": ""
}
|
q3165
|
ParallelTaskBuilder.setTargetHostsFromLineByLineText
|
train
|
public ParallelTaskBuilder setTargetHostsFromLineByLineText(
String sourcePath, HostsSourceType sourceType)
throws TargetHostsLoadException {
this.targetHosts = targetHostBuilder.setTargetHostsFromLineByLineText(sourcePath,
sourceType);
return this;
}
|
java
|
{
"resource": ""
}
|
q3166
|
ParallelTaskBuilder.setReplacementVarMapNodeSpecific
|
train
|
public ParallelTaskBuilder setReplacementVarMapNodeSpecific(
Map<String, StrStrMap> replacementVarMapNodeSpecific) {
this.replacementVarMapNodeSpecific.clear();
this.replacementVarMapNodeSpecific
.putAll(replacementVarMapNodeSpecific);
this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;
logger.info("Set requestReplacementType as {}"
+ requestReplacementType.toString());
return this;
}
|
java
|
{
"resource": ""
}
|
q3167
|
ParallelTaskBuilder.setReplaceVarMapToSingleTargetFromMap
|
train
|
public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(
Map<String, StrStrMap> replacementVarMapNodeSpecific,
String uniformTargetHost) {
setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);
if (Strings.isNullOrEmpty(uniformTargetHost)) {
logger.error("uniform target host is empty or null. skip setting.");
return this;
}
for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific
.entrySet()) {
if (entry.getValue() != null) {
entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,
uniformTargetHost);
}
}
return this;
}
|
java
|
{
"resource": ""
}
|
q3168
|
ParallelTaskBuilder.setReplaceVarMapToSingleTargetSingleVar
|
train
|
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;
}
this.replacementVarMapNodeSpecific.clear();
this.targetHosts.clear();
int i = 0;
for (String replace : replaceList) {
if (replace == null){
logger.error("null replacement.. skip");
continue;
}
String hostName = PcConstants.API_PREFIX + i;
replacementVarMapNodeSpecific.put(
hostName,
new StrStrMap().addPair(variable, replace).addPair(
PcConstants.UNIFORM_TARGET_HOST_VAR,
uniformTargetHost));
targetHosts.add(hostName);
++i;
}
this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;
logger.info(
"Set requestReplacementType as {} for single target. Will disable the set target hosts."
+ "Also Simulated "
+ "Now Already set targetHost list with size {}. \nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.",
requestReplacementType.toString(), targetHosts.size());
return this;
}
|
java
|
{
"resource": ""
}
|
q3169
|
ParallelTaskBuilder.setReplaceVarMapToSingleTarget
|
train
|
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;
}
this.replacementVarMapNodeSpecific.clear();
this.targetHosts.clear();
int i = 0;
for (StrStrMap ssm : replacementVarMapList) {
if (ssm == null)
continue;
String hostName = PcConstants.API_PREFIX + i;
ssm.addPair(PcConstants.UNIFORM_TARGET_HOST_VAR, uniformTargetHost);
replacementVarMapNodeSpecific.put(hostName, ssm);
targetHosts.add(hostName);
++i;
}
this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;
logger.info(
"Set requestReplacementType as {} for single target. Will disable the set target hosts."
+ "Also Simulated "
+ "Now Already set targetHost list with size {}. \nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.",
requestReplacementType.toString(), targetHosts.size());
return this;
}
|
java
|
{
"resource": ""
}
|
q3170
|
ParallelTaskBuilder.setReplacementVarMap
|
train
|
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;
return this;
}
|
java
|
{
"resource": ""
}
|
q3171
|
ParallelTaskBuilder.setHttpPollerProcessor
|
train
|
public ParallelTaskBuilder setHttpPollerProcessor(
HttpPollerProcessor httpPollerProcessor) {
this.httpMeta.setHttpPollerProcessor(httpPollerProcessor);
this.httpMeta.setPollable(true);
return this;
}
|
java
|
{
"resource": ""
}
|
q3172
|
ParallelTaskBuilder.setSshPassword
|
train
|
public ParallelTaskBuilder setSshPassword(String password) {
this.sshMeta.setPassword(password);
this.sshMeta.setSshLoginType(SshLoginType.PASSWORD);
return this;
}
|
java
|
{
"resource": ""
}
|
q3173
|
ParallelTaskBuilder.setSshPrivKeyRelativePath
|
train
|
public ParallelTaskBuilder setSshPrivKeyRelativePath(
String privKeyRelativePath) {
this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);
this.sshMeta.setSshLoginType(SshLoginType.KEY);
return this;
}
|
java
|
{
"resource": ""
}
|
q3174
|
ParallelTaskBuilder.setSshPrivKeyRelativePathWtihPassphrase
|
train
|
public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(
String privKeyRelativePath, String passphrase) {
this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);
this.sshMeta.setPrivKeyUsePassphrase(true);
this.sshMeta.setPassphrase(passphrase);
this.sshMeta.setSshLoginType(SshLoginType.KEY);
return this;
}
|
java
|
{
"resource": ""
}
|
q3175
|
PcDateUtils.getDateTimeStr
|
train
|
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
|
{
"resource": ""
}
|
q3176
|
PcDateUtils.getDateTimeStrStandard
|
train
|
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
|
{
"resource": ""
}
|
q3177
|
PcDateUtils.getDateTimeStrConcise
|
train
|
public static String getDateTimeStrConcise(Date d) {
if (d == null)
return "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ");
return sdf.format(d);
}
|
java
|
{
"resource": ""
}
|
q3178
|
PcDateUtils.getDateFromConciseStr
|
train
|
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) {
logger.error(ex + "Exception while converting string to date : "
+ str);
}
return d;
}
|
java
|
{
"resource": ""
}
|
q3179
|
OperationWorker.handleHttpWorkerResponse
|
train
|
private final void handleHttpWorkerResponse(
ResponseOnSingeRequest respOnSingleReq) throws Exception {
// Successful response from GenericAsyncHttpWorker
// Jeff 20310411: use generic response
String responseContent = respOnSingleReq.getResponseBody();
response.setResponseContent(respOnSingleReq.getResponseBody());
/**
* Poller logic if pollable: check if need to poll/ or already complete
* 1. init poller data and HttpPollerProcessor 2. check if task
* complete, if not, send the request again.
*/
if (request.isPollable()) {
boolean scheduleNextPoll = false;
boolean errorFindingUuid = false;
// set JobId of the poller
if (!pollerData.isUuidHasBeenSet()) {
String jobId = httpPollerProcessor
.getUuidFromResponse(respOnSingleReq);
if (jobId.equalsIgnoreCase(PcConstants.NA)) {
errorFindingUuid = true;
pollingErrorCount++;
logger.error("!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. "
+ "DEBUG: REGEX_JOBID: "
+ httpPollerProcessor.getJobIdRegex()
+ "RESPONSE: "
+ respOnSingleReq.getResponseBody()
+ " polling Error count"
+ pollingErrorCount
+ " at " + PcDateUtils.getNowDateTimeStrStandard());
// fail fast
pollerData.setError(true);
pollerData.setComplete(true);
} else {
pollerData.setJobIdAndMarkHasBeenSet(jobId);
// if myResponse has other errors, mark poll data as error.
pollerData.setError(httpPollerProcessor
.ifThereIsErrorInResponse(respOnSingleReq));
}
}
if (!pollerData.isError()) {
pollerData
.setComplete(httpPollerProcessor
.ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));
pollerData.setCurrentProgress(httpPollerProcessor
.getProgressFromResponse(respOnSingleReq));
}
// poll again only if not complete AND no error; 2015: change to
// over limit
scheduleNextPoll = !pollerData.isComplete()
&& (pollingErrorCount <= httpPollerProcessor
.getMaxPollError());
// Schedule next poll and return. (not to answer back to manager yet
// )
if (scheduleNextPoll
&& (pollingErrorCount <= httpPollerProcessor
.getMaxPollError())) {
pollMessageCancellable = getContext()
.system()
.scheduler()
.scheduleOnce(
Duration.create(httpPollerProcessor
.getPollIntervalMillis(),
TimeUnit.MILLISECONDS), getSelf(),
OperationWorkerMsgType.POLL_PROGRESS,
getContext().system().dispatcher(), getSelf());
logger.info("\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND"
+ String.format("PROGRESS:%.3f, BODY:%s ",
pollerData.getCurrentProgress(),
responseContent,
PcDateUtils.getNowDateTimeStrStandard()));
String responseContentNew = errorFindingUuid ? responseContent
+ "_PollingErrorCount:" + pollingErrorCount
: responseContent;
logger.info(responseContentNew);
// log
pollerData.getPollingHistoryMap().put(
"RECV_" + PcDateUtils.getNowDateTimeStrConciseNoZone(),
String.format("PROGRESS:%.3f, BODY:%s",
pollerData.getCurrentProgress(),
responseContent));
return;
} else {
pollerData
.getPollingHistoryMap()
.put("RECV_"
+ PcDateUtils.getNowDateTimeStrConciseNoZone(),
String.format(
"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s ",
pollerData.getCurrentProgress(),
responseContent));
}
}// end if (request.isPollable())
reply(respOnSingleReq.isFailObtainResponse(),
respOnSingleReq.getErrorMessage(),
respOnSingleReq.getStackTrace(),
respOnSingleReq.getStatusCode(),
respOnSingleReq.getStatusCodeInt(),
respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());
}
|
java
|
{
"resource": ""
}
|
q3180
|
OperationWorker.processMainRequest
|
train
|
private final void processMainRequest() {
sender = getSender();
startTimeMillis = System.currentTimeMillis();
timeoutDuration = Duration.create(
request.getActorMaxOperationTimeoutSec(), TimeUnit.SECONDS);
actorMaxOperationTimeoutSec = request.getActorMaxOperationTimeoutSec();
if (request.getProtocol() == RequestProtocol.HTTP
|| request.getProtocol() == RequestProtocol.HTTPS) {
String urlComplete = String.format("%s://%s:%d%s", request
.getProtocol().toString(), trueTargetNode, request
.getPort(), request.getResourcePath());
// http://stackoverflow.com/questions/1600291/validating-url-in-java
if (!PcHttpUtils.isUrlValid(urlComplete.trim())) {
String errMsg = "INVALID_URL";
logger.error("INVALID_URL: " + urlComplete + " return..");
replyErrors(errMsg, errMsg, PcConstants.NA, PcConstants.NA_INT);
return;
} else {
logger.debug("url pass validation: " + urlComplete);
}
asyncWorker = getContext().actorOf(
Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
client, urlComplete, request.getHttpMethod(),
request.getPostData(), request.getHttpHeaderMap(), request.getResponseHeaderMeta()));
} else if (request.getProtocol() == RequestProtocol.SSH ){
asyncWorker = getContext().actorOf(
Props.create(SshWorker.class, actorMaxOperationTimeoutSec,
request.getSshMeta(), trueTargetNode));
} else if (request.getProtocol() == RequestProtocol.TCP ){
asyncWorker = getContext().actorOf(
Props.create(TcpWorker.class, actorMaxOperationTimeoutSec,
request.getTcpMeta(), trueTargetNode));
} else if (request.getProtocol() == RequestProtocol.UDP ){
asyncWorker = getContext().actorOf(
Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
request.getUdpMeta(), trueTargetNode));
} else if (request.getProtocol() == RequestProtocol.PING ){
asyncWorker = getContext().actorOf(
Props.create(PingWorker.class, actorMaxOperationTimeoutSec, request.getPingMeta(),
trueTargetNode));
}
asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, getSelf());
cancelExistingIfAnyAndScheduleTimeoutCall();
}
|
java
|
{
"resource": ""
}
|
q3181
|
OperationWorker.operationTimeout
|
train
|
@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.isTerminated()) {
asyncWorker
.tell(RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getSelf());
} else {
logger.info("asyncWorker has been killed or uninitialized (null). "
+ "Not send PROCESS ON TIMEOUT.\nREQ: "
+ request.toString());
replyErrors(PcConstants.OPERATION_TIMEOUT,
PcConstants.OPERATION_TIMEOUT, PcConstants.NA,
PcConstants.NA_INT);
}
}
|
java
|
{
"resource": ""
}
|
q3182
|
OperationWorker.replyErrors
|
train
|
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
|
{
"resource": ""
}
|
q3183
|
PcHttpUtils.addHeaders
|
train
|
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
|
{
"resource": ""
}
|
q3184
|
ParallelTask.cancelOnTargetHosts
|
train
|
@SuppressWarnings("deprecation")
public boolean cancelOnTargetHosts(List<String> targetHosts) {
boolean success = false;
try {
switch (state) {
case IN_PROGRESS:
if (executionManager != null
&& !executionManager.isTerminated()) {
executionManager.tell(new CancelTaskOnHostRequest(
targetHosts), executionManager);
logger.info(
"asked task to stop from running on target hosts with count {}...",
targetHosts.size());
} else {
logger.info("manager already killed or not exist.. NO OP");
}
success = true;
break;
case COMPLETED_WITHOUT_ERROR:
case COMPLETED_WITH_ERROR:
case WAITING:
logger.info("will NO OP for cancelOnTargetHost as it is not in IN_PROGRESS state");
success = true;
break;
default:
break;
}
} catch (Exception e) {
logger.error(
"cancel task {} on hosts with count {} error with exception details ",
this.getTaskId(), targetHosts.size(), e);
}
return success;
}
|
java
|
{
"resource": ""
}
|
q3185
|
ParallelTask.generateTaskId
|
train
|
public String generateTaskId() {
final String uuid = UUID.randomUUID().toString().substring(0, 12);
int size = this.targetHostMeta == null ? 0 : this.targetHostMeta
.getHosts().size();
return "PT_" + size + "_"
+ PcDateUtils.getNowDateTimeStrConciseNoZone() + "_" + uuid;
}
|
java
|
{
"resource": ""
}
|
q3186
|
ParallelTask.getProgress
|
train
|
public Double getProgress() {
if (state.equals(ParallelTaskState.IN_PROGRESS)) {
if (requestNum != 0) {
return 100.0 * ((double) responsedNum / (double) requestNumActual);
} else {
return 0.0;
}
}
if (state.equals(ParallelTaskState.WAITING)) {
return 0.0;
}
// fix task if fail validation, still try to poll progress 0901
if (state.equals(ParallelTaskState.COMPLETED_WITH_ERROR)
|| state.equals(ParallelTaskState.COMPLETED_WITHOUT_ERROR)) {
return 100.0;
}
return 0.0;
}
|
java
|
{
"resource": ""
}
|
q3187
|
ParallelTask.getAggregateResultFullSummary
|
train
|
public Map<String, SetAndCount> getAggregateResultFullSummary() {
Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();
for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap
.entrySet()) {
summaryMap.put(entry.getKey(), new SetAndCount(entry.getValue()));
}
return summaryMap;
}
|
java
|
{
"resource": ""
}
|
q3188
|
ParallelTask.getAggregateResultCountSummary
|
train
|
public Map<String, Integer> getAggregateResultCountSummary() {
Map<String, Integer> summaryMap = new LinkedHashMap<String, Integer>();
for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap
.entrySet()) {
summaryMap.put(entry.getKey(), entry.getValue().size());
}
return summaryMap;
}
|
java
|
{
"resource": ""
}
|
q3189
|
MonitorProvider.getJVMMemoryUsage
|
train
|
public PerformUsage getJVMMemoryUsage() {
int mb = 1024 * 1024;
Runtime rt = Runtime.getRuntime();
PerformUsage usage = new PerformUsage();
usage.totalMemory = (double) rt.totalMemory() / mb;
usage.freeMemory = (double) rt.freeMemory() / mb;
usage.usedMemory = (double) rt.totalMemory() / mb - rt.freeMemory()
/ mb;
usage.maxMemory = (double) rt.maxMemory() / mb;
usage.memoryUsagePercent = usage.usedMemory / usage.maxMemory * 100.0;
// update current
currentJvmPerformUsage = usage;
return usage;
}
|
java
|
{
"resource": ""
}
|
q3190
|
MonitorProvider.getThreadDump
|
train
|
public ThreadInfo[] getThreadDump() {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
return threadMxBean.dumpAllThreads(true, true);
}
|
java
|
{
"resource": ""
}
|
q3191
|
MonitorProvider.getThreadUsage
|
train
|
public ThreadUsage getThreadUsage() {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
ThreadUsage threadUsage = new ThreadUsage();
long[] threadIds = threadMxBean.getAllThreadIds();
threadUsage.liveThreadCount = threadIds.length;
for (long tId : threadIds) {
ThreadInfo threadInfo = threadMxBean.getThreadInfo(tId);
threadUsage.threadData.put(Long.toString(tId), new ThreadData(
threadInfo.getThreadName(), threadInfo.getThreadState()
.name(), threadMxBean.getThreadCpuTime(tId)));
}
return threadUsage;
}
|
java
|
{
"resource": ""
}
|
q3192
|
MonitorProvider.getHealthMemory
|
train
|
public String getHealthMemory() {
StringBuilder sb = new StringBuilder();
sb.append("Logging JVM Stats\n");
MonitorProvider mp = MonitorProvider.getInstance();
PerformUsage perf = mp.getJVMMemoryUsage();
sb.append(perf.toString());
if (perf.memoryUsagePercent >= THRESHOLD_PERCENT) {
sb.append("========= WARNING: MEM USAGE > " + THRESHOLD_PERCENT
+ "!!");
sb.append(" !! Live Threads List=============\n");
sb.append(mp.getThreadUsage().toString());
sb.append("========================================\n");
sb.append("========================JVM Thread Dump====================\n");
ThreadInfo[] threadDump = mp.getThreadDump();
for (ThreadInfo threadInfo : threadDump) {
sb.append(threadInfo.toString() + "\n");
}
sb.append("===========================================================\n");
}
sb.append("Logged JVM Stats\n");
return sb.toString();
}
|
java
|
{
"resource": ""
}
|
q3193
|
HttpClientStore.shutdown
|
train
|
public void shutdown() {
for (Entry<HttpClientType, AsyncHttpClient> entry : map.entrySet()) {
AsyncHttpClient client = entry.getValue();
if (client != null)
client.close();
}
}
|
java
|
{
"resource": ""
}
|
q3194
|
TargetHostsBuilder.getContentFromPath
|
train
|
private String getContentFromPath(String sourcePath,
HostsSourceType sourceType) throws IOException {
String res = "";
if (sourceType == HostsSourceType.LOCAL_FILE) {
res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);
} else if (sourceType == HostsSourceType.URL) {
res = PcFileNetworkIoUtils.readStringFromUrlGeneric(sourcePath);
}
return res;
}
|
java
|
{
"resource": ""
}
|
q3195
|
TargetHostsBuilder.setTargetHostsFromLineByLineText
|
train
|
@Override
public List<String> setTargetHostsFromLineByLineText(String sourcePath,
HostsSourceType sourceType) throws TargetHostsLoadException {
List<String> targetHosts = new ArrayList<String>();
try {
String content = getContentFromPath(sourcePath, sourceType);
targetHosts = setTargetHostsFromString(content);
} catch (IOException e) {
throw new TargetHostsLoadException("IEException when reading "
+ sourcePath, e);
}
return targetHosts;
}
|
java
|
{
"resource": ""
}
|
q3196
|
UdpWorker.bootStrapUdpClient
|
train
|
public ConnectionlessBootstrap bootStrapUdpClient()
throws HttpRequestCreateException {
ConnectionlessBootstrap udpClient = null;
try {
// Configure the client.
udpClient = new ConnectionlessBootstrap(udpMeta.getChannelFactory());
udpClient.setPipeline(new UdpPipelineFactory(
TcpUdpSshPingResourceStore.getInstance().getTimer(), this)
.getPipeline());
} catch (Exception t) {
throw new TcpUdpRequestCreateException(
"Error in creating request in udp worker. "
+ " If udpClient is null. Then fail to create.", t);
}
return udpClient;
}
|
java
|
{
"resource": ""
}
|
q3197
|
ParallelClient.initialize
|
train
|
public void initialize() {
if (isClosed.get()) {
logger.info("Initialing Parallel Client Resources: actor system, HttpClientStore, Task Manager ....");
ActorConfig.createAndGetActorSystem();
httpClientStore.init();
tcpSshPingResourceStore.init();
isClosed.set(false);
logger.info("Parallel Client Resources has been initialized.");
} else {
logger.debug("NO OP. Parallel Client Resources has already been initialized.");
}
}
|
java
|
{
"resource": ""
}
|
q3198
|
ParallelClient.reinitIfClosed
|
train
|
public void reinitIfClosed() {
if (isClosed.get()) {
logger.info("External Resource was released. Now Re-initializing resources ...");
ActorConfig.createAndGetActorSystem();
httpClientStore.reinit();
tcpSshPingResourceStore.reinit();
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
logger.error("error reinit httpClientStore", e);
}
isClosed.set(false);
logger.info("Parallel Client Resources has been reinitialized.");
} else {
logger.debug("NO OP. Resource was not released.");
}
}
|
java
|
{
"resource": ""
}
|
q3199
|
ParallelClient.prepareSsh
|
train
|
public ParallelTaskBuilder prepareSsh() {
reinitIfClosed();
ParallelTaskBuilder cb = new ParallelTaskBuilder();
cb.setProtocol(RequestProtocol.SSH);
return cb;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.