List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException(String s)
InterruptedException
with the specified detail message. From source file:org.alfresco.extension.bulkfilesystemimport.impl.AbstractBulkFilesystemImporter.java
/** * Method to be called by subclasses on a per-directory basis. This method will import the given source directory only * (i.e. non-recursively), returning the list of its sub-directories. * /*from w ww. j a v a2 s . com*/ * @param target The target space to ingest the content into <i>(must not be null and must be a valid, writable space in the repository)</i>. * @param sourceRoot The original directory from which this import was initiated <i>(must not be null)</i>. * @param source The source directory on the local filesystem to read content from <i>(must not be null and must be a valid, readable directory on the local filesystem)</i>. * @param replaceExisting A flag indicating whether to replace (true) or skip (false) files that are already in the repository. * @param inPlaceImport A flag indicating whether this is an "in place" import (i.e. the source directory is already located inside the configured content store). * @return A list of sub-directories that have yet to be loaded, along with their associated NodeRefs in the repository <i>(will not be null, but may be empty)</i>. */ protected final List<Pair<NodeRef, File>> importDirectory(final NodeRef target, final String sourceRoot, final File source, final boolean replaceExisting, final boolean inPlaceImport) throws InterruptedException { List<Pair<NodeRef, File>> result = new ArrayList<Pair<NodeRef, File>>(); importStatus.setCurrentFileBeingProcessed(getFileName(source)); // PHASE 1: analyse the source directory final AnalysedDirectory analysedDirectory = directoryAnalyser.analyseDirectory(source); if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException( Thread.currentThread().getName() + " was interrupted. Terminating early."); // PHASE 2: filter ImportableItems from the source directory final List<ImportableItem> filteredImportableItems = filterImportableItems( analysedDirectory.importableItems); if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException( Thread.currentThread().getName() + " was interrupted. Terminating early."); // PHASE 3: batch ImportableItems final List<List<ImportableItem>> batchedImportableItems = batchImportableItems(filteredImportableItems); if (log.isDebugEnabled()) log.debug("---- Bulk Filesystem Importer - Directory Analysis for: " + getFileName(source) + "\n\t" + analysedDirectory.originalListing.size() + " file" + (analysedDirectory.originalListing.size() == 1 ? "" : "s") + "\n\t" + analysedDirectory.importableItems.size() + " importable item" + (analysedDirectory.importableItems.size() == 1 ? "" : "s") + "\n\t" + filteredImportableItems.size() + " filtered importable item" + (filteredImportableItems.size() == 1 ? "" : "s") + "\n\t" + batchedImportableItems.size() + " batch" + (batchedImportableItems.size() == 1 ? "" : "es")); if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException( Thread.currentThread().getName() + " was interrupted. Terminating early."); // PHASE 4: load the batches result.addAll(importImportableItemBatches(target, sourceRoot, batchedImportableItems, replaceExisting, inPlaceImport)); if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException( Thread.currentThread().getName() + " was interrupted. Terminating early."); return (result); }
From source file:com.amalto.workbench.editors.TransformerMainPage.java
public void execute() { try {//ww w .j a v a 2 s. co m service = getService(); if (service == null) { return; } java.util.List<WSTransformerContextPipelinePipelineItem> items = new ArrayList<WSTransformerContextPipelinePipelineItem>(); for (Line line : cacheList) { String variableName = line.keyValues.get(0).value; String contentType = line.keyValues.get(1).value; String value = line.keyValues.get(2).value; items.add(new WSTransformerContextPipelinePipelineItem(variableName, new WSTypedContent(contentType, null, new WSByteArray(value.getBytes("utf-8"))))); //$NON-NLS-1$ } final WSBackgroundJobPK jobPK = service.executeTransformerV2AsJob(new WSExecuteTransformerV2AsJob( new WSTransformerContext(new WSTransformerContextPipeline(items), null, new WSTransformerV2PK(transformer.getName())))); IRunnableWithProgress progress = new IRunnableWithProgress() { WSBackgroundJob job = null; public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { /****************************************** * Watch the Background Job ******************************************/ try { boolean firstTime = true; do { if (firstTime) { Thread.sleep(1500L); firstTime = false; } else { Thread.sleep(5000L); } if (monitor.isCanceled()) { throw new InterruptedException(Messages.TransformerMainPage_UserCancel); } job = service.getBackgroundJob(new WSGetBackgroundJob(jobPK.getPk())); monitor.subTask(job.getMessage()); } while (job.getStatus().equals(BackgroundJobStatusType.RUNNING) || job.getStatus().equals(BackgroundJobStatusType.SCHEDULED)); if (job.getStatus().equals(BackgroundJobStatusType.STOPPED)) { getSite().getShell().getDisplay().syncExec(new Runnable() { public void run() { MessageDialog.openError( TransformerMainPage.this.getEditor().getSite().getShell(), Messages.bind(Messages.TransformerMainPage_ErrorMsg, transformer.getName()), job.getMessage()); } }); throw new XtentisException( Messages.bind(Messages.TransformerMainPage_JobWasStoped, job.getMessage())); } monitor.worked(1); monitor.done(); /****************************************** * Build the result console ******************************************/ // Auto sorts the entries final TreeMap pipeline = new TreeMap<String, WSExtractedContent>(); WSPipeline wsPipeline = job.getPipeline(); java.util.List<WSPipelineTypedContentEntry> entries = wsPipeline.getTypedContentEntry(); for (WSPipelineTypedContentEntry entry : entries) { pipeline.put(entry.getOutput(), entry.getWsExtractedContent()); } getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { try { /* * ProcessResultsPage page = new ProcessResultsPage(editor,pipeline); * parent.editor.addPage(page); parent.editor.setActivePage(page.getId()); * * parent.editor.getEditorSite().getShell() */ // Shell shell = new Shell(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); ProcessResultsDialog dialog = new ProcessResultsDialog(getSite().getShell(), Messages.bind(Messages.TransformerMainPage_DailogTitle, sdf.format(new Date(System.currentTimeMillis()))), pipeline); dialog.setBlockOnOpen(false); dialog.open(); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } } }); } catch (Exception e1) { log.error(e1.getMessage(), e1); } } }; new ProgressMonitorDialog(TransformerMainPage.this.getSite().getWorkbenchWindow().getShell()).run(true, // fork true, progress); } catch (Exception e1) { log.error(e1.getMessage(), e1); } }
From source file:org.openconcerto.sql.replication.MemoryRep.java
protected final void replicateData() throws SQLException, IOException, InterruptedException { final SQLSyntax slaveSyntax = SQLSyntax.get(this.slave); final File tempDir = FileUtils.createTempDir(getClass().getCanonicalName() + "_StoreData"); try {//from w w w .ja va 2s. co m final List<String> queries = new ArrayList<String>(); final List<ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(); final Map<File, SQLTable> files = new HashMap<File, SQLTable>(); for (final Entry<String, Set<String>> e : this.tables.entrySet()) { if (Thread.interrupted()) throw new InterruptedException("While creating handlers"); final String rootName = e.getKey(); final File rootDir = new File(tempDir, rootName); FileUtils.mkdir_p(rootDir); final DBRoot root = this.master.getRoot(rootName); final DBRoot slaveRoot = this.slave.getRoot(rootName); for (final String tableName : e.getValue()) { final SQLTable masterT = root.getTable(tableName); final SQLSelect select = new SQLSelect(true).addSelectStar(masterT); queries.add(select.asString()); // don't use cache to be sure to have up to date data handlers.add(new IResultSetHandler(new ResultSetHandler() { private final CSVHandler csvH = new CSVHandler(masterT.getOrderedFields()); @Override public Object handle(ResultSet rs) throws SQLException { final File tempFile = new File(rootDir, FileUtils.FILENAME_ESCAPER.escape(tableName) + ".csv"); assert !tempFile.exists(); try { FileUtils.write(this.csvH.handle(rs), tempFile); files.put(tempFile, slaveRoot.getTable(tableName)); } catch (IOException e) { throw new SQLException(e); } return null; } }, false)); } } try { SQLUtils.executeAtomic(this.master.getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() { @Override public Object handle(SQLDataSource ds) throws SQLException { SQLUtils.executeMultiple(MemoryRep.this.master, queries, handlers); return null; } }); } catch (RTInterruptedException e) { final InterruptedException exn = new InterruptedException("Interrupted while querying the master"); exn.initCause(e); throw exn; } SQLUtils.executeAtomic(this.slave.getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() { @Override public Object handle(SQLDataSource ds) throws SQLException, IOException { for (final Entry<File, SQLTable> e : files.entrySet()) { final SQLTable slaveT = e.getValue(); // loadData() fires table modified slaveSyntax.loadData(e.getKey(), slaveT, true); } return null; } }); this.count.incrementAndGet(); } finally { FileUtils.rm_R(tempDir); } }
From source file:com.nttec.everychan.chans.infinity.InfinityModule.java
private void checkCaptcha(String answer, CancellableTask task) throws Exception { try {/*from www . j a va 2 s. c o m*/ if (torCaptchaCookie == null) throw new Exception("Invalid captcha"); String url = getUsingUrl() + "dnsbls_bypass.php"; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("captcha_text", answer)); pairs.add(new BasicNameValuePair("captcha_cookie", torCaptchaCookie)); HttpRequestModel rqModel = HttpRequestModel.builder().setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")) .setTimeout(30000).build(); String response = HttpStreamer.getInstance().getStringFromUrl(url, rqModel, httpClient, null, task, true); if (response.contains("Error") && !response.contains("Success")) throw new HttpWrongStatusCodeException(400, "400"); needTorCaptcha = false; } catch (HttpWrongStatusCodeException e) { if (task != null && task.isCancelled()) throw new InterruptedException("interrupted"); if (e.getStatusCode() == 400) throw new Exception("You failed the CAPTCHA"); throw e; } }
From source file:nya.miku.wishmaster.chans.infinity.InfinityModule.java
@Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { if (needTorCaptcha) checkCaptcha(model.captchaAnswer, task); if (task != null && task.isCancelled()) throw new InterruptedException("interrupted"); String url = getUsingUrl() + "post.php"; ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task) .addString("name", model.name).addString("email", model.sage ? "sage" : model.email) .addString("subject", model.subject).addString("body", model.comment) .addString("post", model.threadNumber == null ? "New Topic" : "New Reply") .addString("board", model.boardName); if (model.threadNumber != null) postEntityBuilder.addString("thread", model.threadNumber); if (model.custommark) postEntityBuilder.addString("spoiler", "on"); postEntityBuilder.addString("password", TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password); if (model.attachments != null) { String[] images = new String[] { "file", "file2", "file3", "file4", "file5" }; for (int i = 0; i < model.attachments.length; ++i) { postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash); }/*w w w . ja v a 2s . c o m*/ } if (needNewthreadCaptcha) { postEntityBuilder.addString("captcha_text", model.captchaAnswer).addString("captcha_cookie", newThreadCaptchaId); needNewthreadCaptcha = false; } UrlPageModel refererPage = new UrlPageModel(); refererPage.chanName = getChanName(); refererPage.boardName = model.boardName; if (model.threadNumber == null) { refererPage.type = UrlPageModel.TYPE_BOARDPAGE; refererPage.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE; } else { refererPage.type = UrlPageModel.TYPE_THREADPAGE; refererPage.threadNumber = model.threadNumber; } Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, buildUrl(refererPage)) }; HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()) .setCustomHeaders(customHeaders).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, listener, task); if (response.statusCode == 200) { Logger.d(TAG, "200 OK"); ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); if (htmlResponse.contains("<div class=\"ban\">")) { String error = "You are banned! ;_;"; Matcher banReasonMatcher = BAN_REASON_PATTERN.matcher(htmlResponse); if (banReasonMatcher.find()) { error += "\nReason: " + banReasonMatcher.group(1); } throw new Exception(error); } return null; } else if (response.statusCode == 303) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { return fixRelativeUrl(header.getValue()); } } } else if (response.statusCode == 400) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); if (htmlResponse.contains("dnsbls_bypass.php")) { needTorCaptcha = true; throw new Exception("Please complete your CAPTCHA. (Bypass DNSBL)"); } else if (htmlResponse.contains("captcha_text") || htmlResponse.contains("entrypoint.php")) { needNewthreadCaptcha = true; throw new Exception(htmlResponse.contains("entrypoint.php") ? "You seem to have mistyped the verification, or your CAPTCHA expired. Please fill it out again." : "Please complete your CAPTCHA."); } else if (htmlResponse.contains("<h1>Error</h1>")) { Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse); if (errorMatcher.find()) { String error = errorMatcher.group(1); if (error.contains( "To post on 8chan over Tor, you must use the hidden service for security reasons.")) throw new Exception("To post on 8chan over Tor, you must use the onion domain."); throw new Exception(error); } } } throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } }
From source file:com.nttec.everychan.chans.infinity.InfinityModule.java
@Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { if (needTorCaptcha) checkCaptcha(model.captchaAnswer, task); if (task != null && task.isCancelled()) throw new InterruptedException("interrupted"); String url = "https://sys.8ch.net/post.php"; ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task) .addString("name", model.name).addString("email", model.sage ? "sage" : model.email) .addString("subject", model.subject).addString("body", model.comment) .addString("post", model.threadNumber == null ? "New Topic" : "New Reply") .addString("board", model.boardName); if (model.threadNumber != null) postEntityBuilder.addString("thread", model.threadNumber); if (model.custommark) postEntityBuilder.addString("spoiler", "on"); postEntityBuilder.addString("password", TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password); if (model.attachments != null) { String[] images = new String[] { "file", "file1", "file2", "file3", "file4" }; for (int i = 0; i < model.attachments.length; ++i) { postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash); }//from w w w . j ava 2 s . c o m } if (needNewthreadCaptcha) { postEntityBuilder.addString("captcha_text", model.captchaAnswer).addString("captcha_cookie", newThreadCaptchaId); needNewthreadCaptcha = false; } UrlPageModel refererPage = new UrlPageModel(); refererPage.chanName = getChanName(); refererPage.boardName = model.boardName; if (model.threadNumber == null) { refererPage.type = UrlPageModel.TYPE_BOARDPAGE; refererPage.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE; } else { refererPage.type = UrlPageModel.TYPE_THREADPAGE; refererPage.threadNumber = model.threadNumber; } Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, buildUrl(refererPage)) }; HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()) .setCustomHeaders(customHeaders).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, listener, task); if (response.statusCode == 200) { Logger.d(TAG, "200 OK"); ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); if (htmlResponse.contains("<div class=\"ban\">")) { String error = "You are banned! ;_;"; Matcher banReasonMatcher = BAN_REASON_PATTERN.matcher(htmlResponse); if (banReasonMatcher.find()) { error += "\nReason: " + banReasonMatcher.group(1); } throw new Exception(error); } return null; } else if (response.statusCode == 303) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { return fixRelativeUrl(header.getValue()); } } } else if (response.statusCode == 400) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); if (htmlResponse.contains("dnsbls_bypass.php")) { needTorCaptcha = true; throw new Exception("Please complete your CAPTCHA. (Bypass DNSBL)"); } else if (htmlResponse.contains("captcha_text") || htmlResponse.contains("entrypoint.php")) { needNewthreadCaptcha = true; throw new Exception(htmlResponse.contains("entrypoint.php") ? "You seem to have mistyped the verification, or your CAPTCHA expired. Please fill it out again." : "Please complete your CAPTCHA."); } else if (htmlResponse.contains("<h1>Error</h1>")) { Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse); if (errorMatcher.find()) { String error = errorMatcher.group(1); if (error.contains( "To post on 8chan over Tor, you must use the hidden service for security reasons.")) throw new Exception("To post on 8chan over Tor, you must use the onion domain."); throw new Exception(error); } } } throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } }
From source file:org.apache.axis2.tool.codegen.eclipse.CodeGenWizard.java
/** * The worker method, generates the code itself. *//*from w w w .ja va2s. co m*/ private void doFinishWSDL2Java() { WorkspaceModifyOperation op = new WorkspaceModifyOperation() { protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); } /* * "3" is the total amount of steps, see below monitor.worked(amount) */ monitor.beginTask(CodegenWizardPlugin.getResourceString("generator.generating"), 3); try { /* * TODO: Introduce a progress monitor interface for CodeGenerationEngine. * Since this monitor here doesn't make much sense, we * should either remove the progress monitor from the CodeGenWizard, * or give a (custom) progress monitor to the generate() method, so * we will be informed by Axis2 about the progress of code generation. */ WSDL2JavaGenerator generator = new WSDL2JavaGenerator(); monitor.subTask(CodegenWizardPlugin.getResourceString("generator.readingWOM")); AxisService service = generator.getAxisService(wsdlSelectionPage.getFileName()); monitor.worked(1); //The generate all fix (Axis2-1862) boolean isServerside, isServiceXML, isGenerateServerSideInterface = false; if (optionsPage.getGenerateAll()) { isServerside = true; isServiceXML = true; isGenerateServerSideInterface = true; } else { isServerside = optionsPage.isServerside(); isServiceXML = optionsPage.isServerXML(); isGenerateServerSideInterface = optionsPage.getGenerateServerSideInterface(); } Map optionsMap = generator.fillOptionMap(optionsPage.isAsyncOnlyOn(), optionsPage.isSyncOnlyOn(), isServerside, isServiceXML, optionsPage.isGenerateTestCase(), optionsPage.getGenerateAll(), optionsPage.getServiceName(), optionsPage.getPortName(), optionsPage.getDatabinderName(), wsdlSelectionPage.getFileName(), optionsPage.getPackageName(), optionsPage.getSelectedLanguage(), outputPage.getOutputLocation(), optionsPage.getNs2PkgMapping(), isGenerateServerSideInterface, optionsPage.getAdvanceOptions()); //Fix for the CodeGenConfiguration Contructor Change //CodeGenConfiguration codegenConfig = new CodeGenConfiguration(service, optionsMap); CodeGenConfiguration codegenConfig = new CodeGenConfiguration(optionsMap); codegenConfig.addAxisService(service); //set the wsdl definision for codegen config for skeleton generarion. WSDLPropertyReader reader = new WSDLPropertyReader(); reader.readWSDL(wsdlSelectionPage.getFileName()); Definition wsdlDefinition = reader.getWsdlDefinition(); codegenConfig.setWsdlDefinition(wsdlDefinition); //set the baseURI codegenConfig.setBaseURI(generator.getBaseUri(wsdlSelectionPage.getFileName())); monitor.worked(1); monitor.subTask(CodegenWizardPlugin.getResourceString("generator.generating")); new CodeGenerationEngine(codegenConfig).generate(); //TODO refresh the eclipse project space to show the generated files //Add the codegen libs that are coming with the plugin to the project lib that has been created if (outputPage.getAxis2PluginLibCopyCheckBoxSelection()) { String eclipseHome = System.getProperty("user.dir"); String pluginLibLocation = eclipseHome + File.separator + UIConstants.PLUGINS + File.separator + UIConstants.AXIS_CODEGEN_PLUGIN_FOLDER + File.separator + UIConstants.LIB; addLibsToProjectLib(pluginLibLocation, outputPage.getOutputLocation()); } //Also another requirement arises //If the codegen project was newly buided project or else the eclipse //project intended to save this generated code does not have the required libs //to compile the generated code. We need to add the relevent libs to a lib directory //of the <code>outputPage.getOutputLocation()</code> //Add the libraries on the plugin lib directory to the created project lib if (outputPage.getAxisLibCopyCheckBoxSelection() && outputPage.oktoLoadLibs()) { // String libDirectory = outputPage.getAxisHomeLocation()+File.separator+ // UIConstants.TARGET+File.separator+UIConstants.LIB; String libDirectory = outputPage.getAxisJarsLocation(); addLibsToProjectLib(libDirectory, outputPage.getOutputLocation()); } //This will Create a jar file from the codegen results and add to the output //locations lib directory if (outputPage.getCreateJarCheckBoxSelection()) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); String tempCodegenLocation = workspace.getRoot().getLocation().toString() + File.separator + "codegen"; String tempProjectSrcLocation = tempCodegenLocation + File.separator + "codegen_temp_src_" + System.currentTimeMillis(); String tempProjectClassLocation = tempCodegenLocation + File.separator + "codegen_temp_class_" + System.currentTimeMillis(); File tempCodegenFile = new File(tempCodegenLocation); File tempSrcFile = new File(tempProjectSrcLocation); File tempClassFile = new File(tempProjectClassLocation); tempCodegenFile.mkdir(); tempSrcFile.mkdir(); tempClassFile.mkdir(); copyDirectory(new File(outputPage.getOutputLocation()), tempSrcFile); //Compile the source to another directory SrcCompiler srcCompileTool = new SrcCompiler(); srcCompileTool.compileSource(tempClassFile, tempProjectSrcLocation); //create the jar file and add that to the lib directory String projectLib = outputPage.getOutputLocation() + File.separator + "lib"; JarFileWriter jarFileWriter = new JarFileWriter(); String jarFileName = "CodegenResults.jar"; if (!outputPage.getJarFilename().equals("")) { jarFileName = outputPage.getJarFilename(); } outputPage.setJarFileName(jarFileName); jarFileWriter.writeJarFile(new File(projectLib), jarFileName, tempClassFile); //Delete the temp folders deleteDir(tempCodegenFile); } monitor.worked(1); } catch (Exception e) { /////////////////////////////// e.printStackTrace(); ///////////////////////////// throw new InterruptedException(e.getMessage()); } monitor.done(); } }; /* * Start the generation as new Workbench Operation, so the user * can see the progress and, if needed, can stop the operation. */ try { getContainer().run(false, true, op); } catch (InvocationTargetException e1) { ///////////////////////// e1.printStackTrace(); //////////////////////// throw new RuntimeException(e1); } catch (InterruptedException e1) { throw new RuntimeException(e1); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java
protected InputStream getCDX(String qurl) throws InterruptedException, IOException { final String url = buildURL(qurl); HttpGet m = new HttpGet(url); m.setConfig(RequestConfig.custom().setConnectTimeout(connectionTimeout).setSocketTimeout(socketTimeout) .build());//from w w w . j ava2s. c o m HttpEntity entity = null; int attempts = 0; do { if (Thread.interrupted()) throw new InterruptedException("interrupted while GET " + url); if (attempts > 0) { Thread.sleep(5000); } try { long t0 = System.currentTimeMillis(); HttpResponse resp = getHttpClient().execute(m); cumulativeFetchTime.addAndGet(System.currentTimeMillis() - t0); StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() != 200) { log.error("GET " + url + " failed with status=" + sl.getStatusCode() + " " + sl.getReasonPhrase()); entity = resp.getEntity(); entity.getContent().close(); entity = null; continue; } entity = resp.getEntity(); } catch (IOException ex) { log.error("GEt " + url + " failed with error " + ex.getMessage()); } catch (Exception ex) { log.error("GET " + url + " failed with error ", ex); } } while (entity == null && ++attempts < 3); if (entity == null) { throw new IOException("giving up on GET " + url + " after " + attempts + " attempts"); } return entity.getContent(); }
From source file:fr.gael.dhus.sync.impl.ODataUserSynchronizer.java
@Override public boolean synchronize() throws InterruptedException { int created = 0, updated = 0; try {// w w w . ja va 2 s . c o m // Makes query parameters Map<String, String> query_param = new HashMap<>(); if (skip != 0) { query_param.put("$skip", String.valueOf(skip)); } query_param.put("$top", String.valueOf(pageSize)); log(Level.DEBUG, "Querying users from " + skip + " to " + skip + pageSize); ODataFeed userfeed = readFeedLogPerf("/Users", query_param); // For each entry, creates a DataBase Object for (ODataEntry pdt : userfeed.getEntries()) { String username = null; try { Map<String, Object> props = pdt.getProperties(); username = (String) props.get(UserEntitySet.USERNAME); String email = (String) props.get(UserEntitySet.EMAIL); String firstname = (String) props.get(UserEntitySet.FIRSTNAME); String lastname = (String) props.get(UserEntitySet.LASTNAME); String country = (String) props.get(UserEntitySet.COUNTRY); String domain = (String) props.get(UserEntitySet.DOMAIN); String subdomain = (String) props.get(UserEntitySet.SUBDOMAIN); String usage = (String) props.get(UserEntitySet.USAGE); String subusage = (String) props.get(UserEntitySet.SUBUSAGE); String phone = (String) props.get(UserEntitySet.PHONE); String address = (String) props.get(UserEntitySet.ADDRESS); String hash = (String) props.get(UserEntitySet.HASH); String password = (String) props.get(UserEntitySet.PASSWORD); Date creation = ((GregorianCalendar) props.get(UserEntitySet.CREATED)).getTime(); // Uses the Scheme encoder as it is the most restrictives, it only allows // '+' (forbidden char in usernames, so it's ok) // '-' (forbidden char in usernames, so it's ok) // '.' (allowed char in usernames, not problematic) // the alphanumeric character class (a-z A-Z 0-9) String encoded_username = UriUtils.encodeScheme(username, "UTF-8"); // Retrieves Roles String roleq = String.format("/Users('%s')/SystemRoles", encoded_username); ODataFeed userrole = readFeedLogPerf(roleq, null); List<ODataEntry> roles = userrole.getEntries(); List<Role> new_roles = new ArrayList<>(); for (ODataEntry role : roles) { String rolename = (String) role.getProperties().get(SystemRoleEntitySet.NAME); new_roles.add(Role.valueOf(rolename)); } // Has restriction? String restricq = String.format("/Users('%s')/Restrictions", encoded_username); ODataFeed userrestric = readFeedLogPerf(restricq, null); boolean has_restriction = !userrestric.getEntries().isEmpty(); // Reads user in database, may be null User user = USER_SERVICE.getUserNoCheck(username); // Updates existing user if (user != null && (force || creation.equals(user.getCreated()))) { boolean changed = false; // I wish users had their `Updated` field exposed on OData if (!username.equals(user.getUsername())) { user.setUsername(username); changed = true; } if (email == null && user.getEmail() != null || email != null && !email.equals(user.getEmail())) { user.setEmail(email); changed = true; } if (firstname == null && user.getFirstname() != null || firstname != null && !firstname.equals(user.getFirstname())) { user.setFirstname(firstname); changed = true; } if (lastname == null && user.getLastname() != null || lastname != null && !lastname.equals(user.getLastname())) { user.setLastname(lastname); changed = true; } if (country == null && user.getCountry() != null || country != null && !country.equals(user.getCountry())) { user.setCountry(country); changed = true; } if (domain == null && user.getDomain() != null || domain != null && !domain.equals(user.getDomain())) { user.setDomain(domain); changed = true; } if (subdomain == null && user.getSubDomain() != null || subdomain != null && !subdomain.equals(user.getSubDomain())) { user.setSubDomain(subdomain); changed = true; } if (usage == null && user.getUsage() != null || usage != null && !usage.equals(user.getUsage())) { user.setUsage(usage); changed = true; } if (subusage == null && user.getSubUsage() != null || subusage != null && !subusage.equals(user.getSubUsage())) { user.setSubUsage(subusage); changed = true; } if (phone == null && user.getPhone() != null || phone != null && !phone.equals(user.getPhone())) { user.setPhone(phone); changed = true; } if (address == null && user.getAddress() != null || address != null && !address.equals(user.getAddress())) { user.setAddress(address); changed = true; } if (password == null && user.getPassword() != null || password != null && !password.equals(user.getPassword())) { if (hash == null) hash = PasswordEncryption.NONE.getAlgorithmKey(); user.setEncryptedPassword(password, User.PasswordEncryption.valueOf(hash)); changed = true; } //user.setPasswordEncryption(User.PasswordEncryption.valueOf(hash)); if (!SetUtils.isEqualSet(user.getRoles(), new_roles)) { user.setRoles(new_roles); changed = true; } if (has_restriction != !user.getRestrictions().isEmpty()) { if (has_restriction) { user.addRestriction(new LockedAccessRestriction()); } else { user.setRestrictions(Collections.EMPTY_SET); } changed = true; } if (changed) { log(Level.DEBUG, "Updating user " + user.getUsername()); USER_SERVICE.systemUpdateUser(user); updated++; } } // Creates new user else if (user == null) { user = new User(); user.setUsername(username); user.setEmail(email); user.setFirstname(firstname); user.setLastname(lastname); user.setCountry(country); user.setDomain(domain); user.setSubDomain(subdomain); user.setUsage(usage); user.setSubUsage(subusage); user.setPhone(phone); user.setAddress(address); user.setPassword(password); //user.setPasswordEncryption(User.PasswordEncryption.valueOf(hash)); user.setCreated(creation); user.setRoles(new_roles); if (has_restriction) { user.addRestriction(new LockedAccessRestriction()); } log(Level.DEBUG, "Creating new user " + user.getUsername()); USER_SERVICE.systemCreateUser(user); created++; } else { log(Level.ERROR, "Namesake '" + username + "' detected!"); } } catch (RootNotModifiableException e) { } // Ignored exception catch (RequiredFieldMissingException ex) { log(Level.ERROR, "Cannot create user '" + username + "'", ex); } catch (IOException | ODataException ex) { log(Level.ERROR, "OData failure on user '" + username + "'", ex); } this.skip++; } // This is the end, resets `skip` to 0 if (userfeed.getEntries().size() < pageSize) { this.skip = 0; } } catch (IOException | ODataException ex) { log(Level.ERROR, "OData failure", ex); } catch (LockAcquisitionException | CannotAcquireLockException e) { throw new InterruptedException(e.getMessage()); } finally { StringBuilder sb = new StringBuilder("done: "); sb.append(created).append(" new Users, "); sb.append(updated).append(" updated Users, "); sb.append(" from ").append(this.client.getServiceRoot()); log(Level.INFO, sb.toString()); this.syncConf.setConfig("skip", String.valueOf(skip)); SYNC_SERVICE.saveSynchronizer(this); } return false; }
From source file:edu.umd.cloud9.collection.wikipedia.BuildWikipediaWeightedLinkGraph.java
private String phase1(String inputPath, int reduceNo, String lang) throws IOException, InterruptedException, ClassNotFoundException { String output = "tmp/wiki-link/phase1"; Job job = Job.getInstance(getConf()); job.setJobName("Build Wikipedia Weighted Link Graph. Phase 1"); job.setJarByClass(BuildWikipediaWeightedLinkGraph.class); job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", false); job.getConfiguration().setBoolean("mapred.reduce.tasks.speculative.execution", false); job.getConfiguration().set("mapred.child.java.opts", "-Xmx2048m"); job.setNumReduceTasks(reduceNo);//from w w w. ja v a 2s .com FileInputFormat.setInputPaths(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(output)); if ("en".equals(lang)) { job.setInputFormatClass(WikipediaPageInputFormat.class); } else throw new InterruptedException("Wikipedia dump with language " + lang + " is not supported "); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(PairOfStringInt.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(PairOfStringInt.class); job.setMapperClass(LinkEmitMapClass.class); job.setReducerClass(RedirectResolveReduceClass.class); job.waitForCompletion(true); return output; }