List of usage examples for java.io PrintStream flush
public void flush()
From source file:com.datatorrent.stram.cli.ApexCli.java
private void printJson(String json) throws IOException { PrintStream os = getOutputPrintStream(); if (jsonp != null) { os.println(jsonp + "(" + json + ");"); } else {/* w w w . j av a 2s. c o m*/ os.println(json); } os.flush(); closeOutputPrintStream(os); }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
@Override protected void handleDeployEdition(Integer editionId) throws Exception { try {//from w ww. j a va 2 s . c o m editionCronService.logEditionStatusInfo(LiveserverDeployStatus.CreateDeployFileForExport, editionId); if (log.isDebugEnabled()) log.debug("Start creating Edition"); EditionHbm edition = getEditionHbmDao().load(editionId); PrintStream out = createEditionOutputStream(edition); // if (log.isDebugEnabled()) log.debug("siteToXml"); getEditionHbmDao().siteToXml(edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("picturesToXmlRecursive"); getEditionHbmDao().picturesToXmlRecursive(null, edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("documentsToXmlRecursive"); getEditionHbmDao().documentsToXmlRecursive(null, edition.getSiteId(), out, true, edition); System.gc(); if (log.isDebugEnabled()) log.debug("unitsToXmlRecursive"); getEditionHbmDao().unitsToXmlRecursive(edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("hostsToXmlRecursive"); getEditionHbmDao().hostsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("viewdocumentsToXmlRecursive"); getEditionHbmDao().viewdocumentsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("realmsToXmlRecursive"); getEditionHbmDao().realmsToXmlRecursive(edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("Creating ViewComponent Data"); Iterator vdIt = getViewDocumentHbmDao().findAll(edition.getSiteId()).iterator(); while (vdIt.hasNext()) { ViewDocumentHbm vdl = (ViewDocumentHbm) vdIt.next(); getViewComponentHbmDao().toXml(vdl.getViewComponent(), null, true, true, false, false, -1, false, false, Constants.DEPLOY_TYPE_FULL, out); } if (log.isDebugEnabled()) log.debug("Finished creating ViewComponent Data"); out.println("</edition>"); out.flush(); out.close(); out = null; if (log.isDebugEnabled()) log.debug("Finished creating Edition"); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Error while creating Edition", e); editionCronService.logEditionStatusException(editionId, e.getMessage()); throw new UserException(e.getMessage(), e); } }
From source file:MailHandlerDemo.java
/** * Used debug problems with the logging.properties. The system property * java.security.debug=access,stack can be used to trace access to the * LogManager reset.//from w ww . ja v a2 s . c om * * @param prefix a string to prefix the output. * @param err any PrintStream or null for System.out. */ @SuppressWarnings("UseOfSystemOutOrSystemErr") private static void checkConfig(String prefix, PrintStream err) { if (prefix == null || prefix.trim().length() == 0) { prefix = "DEBUG"; } if (err == null) { err = System.out; } try { err.println(prefix + ": java.version=" + System.getProperty("java.version")); err.println(prefix + ": LOGGER=" + LOGGER.getLevel()); err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName()); err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug")); SecurityManager sm = System.getSecurityManager(); if (sm != null) { err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName()); err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader())); err.println(prefix + ": SecurityManager.toString=" + sm); } else { err.println(prefix + ": SecurityManager.class=null"); err.println(prefix + ": SecurityManager.toString=null"); err.println(prefix + ": SecurityManager classLoader=null"); } String policy = System.getProperty("java.security.policy"); if (policy != null) { File f = new File(policy); err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); err.println(prefix + ": length=" + f.length()); err.println(prefix + ": canRead=" + f.canRead()); err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified())); } LogManager manager = LogManager.getLogManager(); String key = "java.util.logging.config.file"; String cfg = System.getProperty(key); if (cfg != null) { err.println(prefix + ": " + cfg); File f = new File(cfg); err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); err.println(prefix + ": length=" + f.length()); err.println(prefix + ": canRead=" + f.canRead()); err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified())); } else { err.println(prefix + ": " + key + " is not set as a system property."); } err.println(prefix + ": LogManager.class=" + manager.getClass().getName()); err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader())); err.println(prefix + ": LogManager.toString=" + manager); err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader())); err.println( prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader())); err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader())); err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader())); final String p = MailHandler.class.getName(); key = p.concat(".mail.to"); String to = manager.getProperty(key); err.println(prefix + ": TO=" + to); if (to != null) { err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true))); } key = p.concat(".mail.from"); String from = manager.getProperty(key); if (from == null || from.length() == 0) { Session session = Session.getInstance(new Properties()); InternetAddress local = InternetAddress.getLocalAddress(session); err.println(prefix + ": FROM=" + local); } else { err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false))); err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true))); } synchronized (manager) { final Enumeration<String> e = manager.getLoggerNames(); while (e.hasMoreElements()) { final Logger l = manager.getLogger(e.nextElement()); if (l != null) { final Handler[] handlers = l.getHandlers(); if (handlers.length > 0) { err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName()); for (Handler h : handlers) { err.println(prefix + ":\t" + toString(prefix, err, h)); } } } } } } catch (Throwable error) { err.print(prefix + ": "); error.printStackTrace(err); } err.flush(); }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
@Override protected void handleDeployUnitEdition(Integer editionId, Integer unitId) throws Exception { try {/*www .j a v a2 s . c o m*/ if (log.isDebugEnabled()) log.debug("Start creating unitEdition"); editionCronService.logEditionStatusInfo(LiveserverDeployStatus.CreateDeployFileForExport, editionId); //if (log.isInfoEnabled())log.info("createDeployFile " + AuthenticationHelper.getUserName()); EditionHbm edition = getEditionHbmDao().load(editionId); PrintStream out = createEditionOutputStream(edition); if (log.isDebugEnabled()) log.debug("creating outputstream for unitEdition"); // site info is needed to connect to the live server if (log.isDebugEnabled()) log.debug("siteToXml"); getEditionHbmDao().siteToXml(edition.getSiteId(), out, edition); System.gc(); // Alle ..toXML + unitID to reuse them in unitDeploy if (log.isDebugEnabled()) log.debug("picturesToXmlRecursive"); getEditionHbmDao().picturesToXmlRecursive(unitId, edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("documentsToXmlRecursive"); getEditionHbmDao().documentsToXmlRecursive(unitId, edition.getSiteId(), out, true, edition); System.gc(); if (log.isDebugEnabled()) log.debug("unitToXml"); getEditionHbmDao().unitToXml(unitId, out, edition); System.gc(); // if (log.isDebugEnabled()) log.debug("viewdocumentsToXmlRecursive"); // getEditionHbmDao().viewdocumentsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("realmsToXmlUsed: unit - " + unitId); getEditionHbmDao().realmsToXmlUsed(unitId, out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("Creating ViewComponent Data"); Iterator vdIt = getViewDocumentHbmDao().findAll(edition.getSiteId()).iterator(); // while (vdIt.hasNext()) { ViewDocumentHbm vdl = (ViewDocumentHbm) vdIt.next(); ViewComponentHbm vch = getViewComponentHbmDao().find4Unit(unitId, vdl.getViewDocumentId()); if (vch != null) getViewComponentHbmDao().toXml(vch, unitId, true, true, true, false, -1, false, false, Constants.DEPLOY_TYPE_UNIT, out); } if (log.isDebugEnabled()) log.debug("Finished creating ViewComponent Data"); out.println("</edition>"); out.flush(); out.close(); out = null; if (log.isDebugEnabled()) log.debug("Finished creating unitEdition"); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("error while creating unitEdition", e); editionCronService.logEditionStatusException(editionId, e.getMessage()); throw new UserException(e.getMessage(), e); } }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
/** * Creates a new FULL-Edition for the active site and returns it as SOAP-Attachment. * //w w w .j a v a 2 s . co m * @see de.juwimm.cms.remote.ContentServiceSpring#exportEditionFull() */ @Override protected InputStream handleExportEditionFull() throws Exception { try { if (log.isInfoEnabled()) log.info("createEditionForExport " + AuthenticationHelper.getUserName()); File fle = File.createTempFile("edition_full_export", ".xml.gz"); FileOutputStream fout = new FileOutputStream(fle); GZIPOutputStream gzoudt = new GZIPOutputStream(fout); PrintStream out = new PrintStream(gzoudt, true, "UTF-8"); UserHbm invoker = getUserHbmDao().load(AuthenticationHelper.getUserName()); SiteHbm site = invoker.getActiveSite(); if (log.isDebugEnabled()) log.debug("Invoker is: " + invoker.getUserId() + " within Site " + site.getName()); EditionHbm edition = getEditionHbmDao().create("INTERIMEDITION", null, null, true); if (log.isDebugEnabled()) log.debug("Dummy-Editon create"); out.println("<edition>"); if (log.isDebugEnabled()) log.debug("picturesToXmlRecursive"); getEditionHbmDao().picturesToXmlRecursive(null, site.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("documentsToXmlRecursive"); getEditionHbmDao().documentsToXmlRecursive(null, site.getSiteId(), out, true, edition); System.gc(); if (log.isDebugEnabled()) log.debug("unitsToXmlRecursive"); getEditionHbmDao().unitsToXmlRecursive(site.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("hostsToXmlRecursive"); getEditionHbmDao().hostsToXmlRecursive(site.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("viewdocumentsToXmlRecursive"); getEditionHbmDao().viewdocumentsToXmlRecursive(site.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("realmsToXmlRecursive"); getEditionHbmDao().realmsToXmlRecursive(site.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("Creating ViewComponent Data"); Iterator vdIt = getViewDocumentHbmDao().findAll(site.getSiteId()).iterator(); while (vdIt.hasNext()) { ViewDocumentHbm vdl = (ViewDocumentHbm) vdIt.next(); // vdl.getViewComponent().toXml(null, 0, true, false, 1, false, false, out); getViewComponentHbmDao().toXml(vdl.getViewComponent(), null, true, false, -1, false, false, out); } if (log.isDebugEnabled()) log.debug("Finished creating ViewComponent Data"); out.println("</edition>"); getEditionHbmDao().remove(edition); out.flush(); out.close(); out = null; return new FileInputStream(fle); } catch (Exception e) { throw new UserException(e.getMessage(), e); } }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
@Override protected void handleDeployRootUnitEdition(Integer editionId) throws Exception { try {/*from w ww .j a va 2s . c om*/ editionCronService.logEditionStatusInfo(LiveserverDeployStatus.CreateDeployFileForExport, editionId); if (log.isDebugEnabled()) log.debug("Start creating RootEdition"); EditionHbm edition = getEditionHbmDao().load(editionId); PrintStream out = createEditionOutputStream(edition); // site info is needed to connect to the live server if (log.isDebugEnabled()) log.debug("siteToXml"); getEditionHbmDao().siteToXml(edition.getSiteId(), out, edition); System.gc(); // Alle ..toXML + unitID to reuse them in unitDeploy if (log.isDebugEnabled()) log.debug("picturesToXmlRecursive"); //TODO: change -1 to null and check edition.type later .... - for the moment -1 = rootdeploy getEditionHbmDao().picturesToXmlRecursive(-1, edition.getSiteId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("documentsToXmlRecursive"); //TODO: change -1 to null and check edition.type later .... - for the moment -1 = rootdeploy getEditionHbmDao().documentsToXmlRecursive(-1, edition.getSiteId(), out, true, edition); System.gc(); if (log.isDebugEnabled()) log.debug("unitsToXmlRecursive"); getEditionHbmDao().unitsToXmlRecursive(edition.getSiteId(), out, edition); System.gc(); // if (log.isDebugEnabled()) log.debug("viewdocumentsToXmlRecursive"); // getEditionHbmDao().viewdocumentsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("hostsToXmlRecursive"); getEditionHbmDao().hostsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("viewdocumentsToXmlRecursive"); getEditionHbmDao().viewdocumentsToXmlRecursive(edition.getSiteId(), out, edition); if (log.isDebugEnabled()) log.debug("realmsToXmlRecursive"); getEditionHbmDao().realmsToXmlUsed(edition.getUnitId(), out, edition); System.gc(); if (log.isDebugEnabled()) log.debug("Creating ViewComponent Data"); Iterator vdIt = getViewDocumentHbmDao().findAll(edition.getSiteId()).iterator(); while (vdIt.hasNext()) { ViewDocumentHbm vdl = (ViewDocumentHbm) vdIt.next(); getViewComponentHbmDao().toXml(vdl.getViewComponent(), edition.getUnitId(), true, true, true, false, -1, false, false, Constants.DEPLOY_TYPE_ROOT, out); } out.println("</edition>"); out.flush(); out.close(); log.info("output file closed."); out = null; if (log.isDebugEnabled()) log.debug("Finished creating Edition"); } catch (Exception e) { if (log.isWarnEnabled()) log.warn("Error while creating RootEdition"); editionCronService.logEditionStatusException(editionId, e.getMessage()); throw new UserException(e.getMessage(), e); } }
From source file:org.kuali.kfs.module.tem.batch.service.impl.CreditCardDataImportServiceImpl.java
/** * @see org.kuali.kfs.module.tem.batch.service.CreditCardDataImportService#validateCreditCardData(org.kuali.kfs.module.tem.businessobject.CreditCardImportData, java.lang.String) *///from w w w . jav a 2 s . co m @Override public List<CreditCardStagingData> validateCreditCardData(CreditCardImportData creditCardList, String dataFileName) { PrintStream reportDataStream = dataReportService.getReportPrintStream(getCreditCardDataReportDirectory(), getCreditCardDataReportFilePrefix()); List<CreditCardStagingData> validData = new ArrayList<CreditCardStagingData>(); try { dataReportService.writeReportHeader(reportDataStream, dataFileName, TemKeyConstants.MESSAGE_CREDIT_CARD_DATA_REPORT_HEADER, getCreditCardDataUploadReportHelper()); Integer count = 1; for (CreditCardStagingData creditCardData : creditCardList.getCreditCardData()) { LOG.info("Validating credit card import. Record# " + count + " of " + creditCardList.getCreditCardData().size()); creditCardData.setErrorCode(CreditCardStagingDataErrorCodes.CREDIT_CARD_NO_ERROR); creditCardData.setImportBy(creditCardList.getImportBy()); creditCardData.setStagingFileName(StringUtils.substringAfterLast(dataFileName, File.separator)); List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); if (validateAndSetCreditCardAgency(creditCardData)) { if (creditCardData.getExpenseImport() == ExpenseImport.traveler) { TemProfileAccount temProfileAccount = findTraveler(creditCardData); if (ObjectUtils.isNotNull(temProfileAccount)) { //Set Traveler Id if (ObjectUtils.isNull(creditCardData.getTravelerId()) || creditCardData.getTravelerId() == 0) { Integer travelerId = new Integer(temProfileAccount.getProfile().getEmployeeId()) .intValue(); creditCardData.setTravelerId(travelerId); } creditCardData.setTemProfileId(temProfileAccount.getProfileId()); //Set expense type code to O-Other if null if (creditCardData.getExpenseTypeCode() == null) { creditCardData.setExpenseTypeCode(ExpenseTypes.OTHER); } // write an error if the expense type code is not valid final ExpenseType expenseType = businessObjectService .findBySinglePrimaryKey(ExpenseType.class, creditCardData.getExpenseTypeCode()); if (ObjectUtils.isNotNull(expenseType)) { //Set Credit Card Key(traveler Id + Credit Card Agency + Credit Card number creditCardData.setCreditCardKey(creditCardData.getTravelerId() + temProfileAccount.getCreditCardAgency().getCreditCardOrAgencyCode() + creditCardData.getCreditCardNumber()); // need to do the duplicate check at this point, since the CC key is one of the fields being checked if (!isDuplicate(creditCardData, errorMessages)) { creditCardData.setMoveToHistoryIndicator(true); creditCardData.setProcessingTimestamp(dateTimeService.getCurrentTimestamp()); validData.add(creditCardData); } } else { LOG.error("Invalid expense type code " + creditCardData.getExpenseTypeCode() + " in Credit Card Data record"); errorMessages.add(new ErrorMessage( TemKeyConstants.MESSAGE_CREDIT_CARD_DATA_INVALID_EXPENSE_TYPE_CODE, creditCardData.getExpenseTypeCode())); } } else { LOG.error("No traveler found for credit card number: " + creditCardData.getCreditCardNumber()); errorMessages.add( new ErrorMessage(TemKeyConstants.MESSAGE_CREDIT_CARD_DATA_NO_TRAVELER_FOUND, creditCardData.getCreditCardNumber())); } } else if (creditCardData.getExpenseImport() == ExpenseImport.trip) { if (!isDuplicate(creditCardData, errorMessages)) { creditCardData.setProcessingTimestamp(dateTimeService.getCurrentTimestamp()); validData.add(creditCardData); } } } else { errorMessages.add(new ErrorMessage(TemKeyConstants.MESSAGE_AGENCY_CREDIT_CARD_DATA_INVALID_CCA, creditCardData.getCreditCardOrAgencyCode())); } //writer to error report if (!errorMessages.isEmpty()) { dataReportService.writeToReport(reportDataStream, creditCardData, errorMessages, getCreditCardDataUploadReportHelper()); } count++; } } finally { if (reportDataStream != null) { reportDataStream.flush(); reportDataStream.close(); } } return validData; }
From source file:org.archive.crawler.Heritrix.java
public void instanceMain(String[] args) throws Exception { System.out.println(System.getProperty("java.vendor") + ' ' + System.getProperty("java.runtime.name") + ' ' + System.getProperty("java.runtime.version")); // ensure using java 1.6+ before hitting a later cryptic error String version = System.getProperty("java.version"); float floatVersion = Float.valueOf(version.substring(0, version.indexOf('.', 2))); if (floatVersion < 1.6) { System.err.println("Heritrix (as of version 3) requires Java 1.6 or higher."); System.err.println("You attempted to launch with: " + version); System.err.println("Please try again with a later Java."); System.exit(1);// w ww . j ava 2s . c o m } // Set some system properties early. // Can't use class names here without loading them. String ignoredSchemes = "org.archive.net.UURIFactory.ignored-schemes"; if (System.getProperty(ignoredSchemes) == null) { System.setProperty(ignoredSchemes, "mailto, clsid, res, file, rtsp, about"); } String maxFormSize = "org.mortbay.jetty.Request.maxFormContentSize"; if (System.getProperty(maxFormSize) == null) { System.setProperty(maxFormSize, "52428800"); } BufferedOutputStream startupOutStream = new BufferedOutputStream( new FileOutputStream(new File(getHeritrixHome(), STARTLOG)), 16384); PrintStream startupOut = new PrintStream(new TeeOutputStream(System.out, startupOutStream)); CommandLine cl = getCommandLine(startupOut, args); if (cl == null) return; if (cl.hasOption('h')) { usage(startupOut, args); return; } // DEFAULTS until changed by cmd-line options int port = 8443; Set<String> bindHosts = new HashSet<String>(); String authLogin = "admin"; String authPassword = null; String keystorePath; String keystorePassword; String keyPassword; File properties = getDefaultPropertiesFile(); String aOption = cl.getOptionValue('a'); if (cl.hasOption('a')) { String usernameColonPassword = aOption; try { if (aOption.startsWith("@")) { usernameColonPassword = FileUtils.readFileToString(new File(aOption.substring(1))).trim(); } int colonIndex = usernameColonPassword.indexOf(':'); if (colonIndex > -1) { authLogin = usernameColonPassword.substring(0, colonIndex); authPassword = usernameColonPassword.substring(colonIndex + 1); } else { authPassword = usernameColonPassword; } } catch (IOException e) { // only if @filename read had problems System.err.println("Unable to read [username:]password from " + aOption); } } if (authPassword == null) { System.err.println("You must specify a valid [username:]password for the web interface using -a."); System.exit(1); authPassword = ""; // suppresses uninitialized warning } File jobsDir = null; if (cl.hasOption('j')) { jobsDir = new File(cl.getOptionValue('j')); } else { jobsDir = new File("./jobs"); } if (cl.hasOption('l')) { properties = new File(cl.getOptionValue('l')); } if (cl.hasOption('b')) { String hosts = cl.getOptionValue('b'); List<String> list; if ("/".equals(hosts)) { // '/' means all, signified by empty-list list = new ArrayList<String>(); } else { list = Arrays.asList(hosts.split(",")); } bindHosts.addAll(list); } else { // default: only localhost bindHosts.add("localhost"); } if (cl.hasOption('p')) { port = Integer.parseInt(cl.getOptionValue('p')); } // SSL options (possibly none, in which case adhoc keystore // is created or reused if (cl.hasOption('s')) { String[] sslParams = cl.getOptionValue('s').split(","); keystorePath = sslParams[0]; keystorePassword = sslParams[1]; keyPassword = sslParams[2]; } else { // use ad hoc keystore, creating if necessary keystorePath = ADHOC_KEYSTORE; keystorePassword = ADHOC_PASSWORD; keyPassword = ADHOC_PASSWORD; useAdhocKeystore(startupOut); } if (properties.exists()) { FileInputStream finp = new FileInputStream(properties); LogManager.getLogManager().readConfiguration(finp); finp.close(); } // Set timezone here. Would be problematic doing it if we're running // inside in a container. TimeZone.setDefault(TimeZone.getTimeZone("GMT")); setupGlobalProperties(port); // Start Heritrix. try { engine = new Engine(jobsDir); component = new Component(); if (bindHosts.isEmpty()) { // listen all addresses setupServer(port, null, keystorePath, keystorePassword, keyPassword); } else { // bind only to declared addresses, or just 'localhost' for (String address : bindHosts) { setupServer(port, address, keystorePath, keystorePassword, keyPassword); } } component.getClients().add(Protocol.FILE); component.getClients().add(Protocol.CLAP); Guard guard = new RateLimitGuard(null, ChallengeScheme.HTTP_DIGEST, "Authentication Required"); guard.getSecrets().put(authLogin, authPassword.toCharArray()); component.getDefaultHost().attach(guard); guard.setNext(new EngineApplication(engine)); component.start(); startupOut.println("engine listening at port " + port); startupOut.println( "operator login set per " + ((aOption.startsWith("@")) ? "file " + aOption : "command-line")); if (authPassword.length() < 8 || authPassword.matches("[a-zA-Z]{0,10}") || authPassword.matches("\\d{0,10}")) { startupOut.println("NOTE: We recommend a longer, stronger password, especially if your web \n" + "interface will be internet-accessible."); } if (cl.hasOption('r')) { engine.requestLaunch(cl.getOptionValue('r')); } } catch (Exception e) { // Show any exceptions in STARTLOG. e.printStackTrace(startupOut); if (component != null) { component.stop(); } throw e; } finally { startupOut.flush(); // stop writing to side startup file startupOutStream.close(); System.out.println("Heritrix version: " + ArchiveUtils.VERSION); } }
From source file:tds.websim.presentation.services.WebSimXHR.java
@RequestMapping(value = "GetTestBlueprintCSV") @ResponseBody/*from w w w. j av a 2s. c o m*/ public void getTestBlueprintCSV(@RequestParam(value = "sessionkey", required = false) String sessionKey, @RequestParam(value = "testkey", required = false) String testKey, HttpServletResponse response) throws TDSSecurityException, ReturnStatusException, IOException { getUser(); if (!_user.isAuth()) { throw new TDSSecurityException(); } SessionTestBlueprint bp = null; if (checkStringsNotNullNotEmpty(sessionKey, testKey)) { bp = this.getSetupSimTask().getTestBlueprint(sessionKey, testKey); setStatus(response, HttpServletResponse.SC_OK); response.setContentType("text/csv"); response.addHeader("Content-Disposition", "attachment;filename=TestBlueprint.csv"); PrintStream responseTW = new PrintStream(response.getOutputStream()); // write blueprint segment String strToWrite = ""; responseTW.println("Segments"); strToWrite = StringUtils.join(new String[] { "SegmentID", "SegmentPosition", "StartAbility", "StartInfo", "MinItems", "MaxItems", "FtStartPos", "FtEndPos", "FtMinItems", "FtMaxItems", "formSelection", "BlueprintWeight", "Cset1Size", "Cset2InitialRandom", "Cset2Random", "LoadConfig", "UpdateConfig", "ItemWeight", "AbilityOffset", "SelectionAlgorithm", "Cset1Order", "RCAbilityWeight", "AbilityWeight", "PrecisionTargetNotMetWeight", "PrecisionTargetMetWeight", "PrecisionTarget", "AdaptiveCut", "TooCloseSEs", "TerminationMinCount", "TerminationOverallInfo", "TerminationRCInfo", "TerminationTooClose", "TerminationFlagsAnd" }, ','); responseTW.println(strToWrite); for (BlueprintSegment segment : bp.getBlueprintSegments()) { strToWrite = StringUtils.join(new String[] { segment.getSegmentID(), "" + segment.getSegmentPosition(), "" + segment.getStartAbility(), "" + segment.getStartInfo(), "" + segment.getMinItems(), "" + segment.getMaxItems(), "" + segment.getFtStartPos(), "" + segment.getFtEndPos(), "" + segment.getFtMinItems(), "" + segment.getFtMaxItems(), segment.getFormSelection(), "" + segment.getBlueprintWeight(), "" + segment.getCset1Size(), "" + segment.getCset2InitialRandom(), "" + segment.getCset2Random(), "" + segment.getLoadConfig(), "" + segment.getUpdateConfig(), "" + segment.getItemWeight(), "" + segment.getAbilityOffset(), "" + segment.getSelectionAlgorithm(), "" + segment.getCset1Order(), "" + segment.getRcAbilityWeight(), "" + segment.getAbilityWeight(), "" + segment.getPrecisionTargetNotMetWeight(), "" + segment.getPrecisionTargetMetWeight(), "" + segment.getPrecisionTarget(), "" + segment.getAdaptiveCut(), "" + segment.getTooCloseSEs(), "" + segment.getTerminationMinCount(), "" + segment.getTerminationOverallInfo(), "" + segment.getTerminationRCInfo(), "" + segment.getTerminationTooClose(), "" + segment.getTerminationFlagsAnd() }, ','); responseTW.println(strToWrite); } responseTW.println('\n'); responseTW.println("Strands"); strToWrite = StringUtils.join(new String[] { "SegmentKey", "Strand", "StartAbility", "StartInfo", "MinItems", "MaxItems", "BlueprintWeight", "IsStrictMax", "AdaptiveCut", "Scalar", "AbilityWeight", "PrecisionTargetNotMetWeight", "PrecisionTargetMetWeight", "PrecisionTarget" }, ','); responseTW.println(strToWrite); for (BlueprintSegmentStrand strand : bp.getBlueprintSegmentStrands()) { strToWrite = StringUtils.join(new String[] { strand.getSegmentKey(), strand.getStrand(), "" + strand.getStartAbility(), "" + strand.getStartInfo(), "" + strand.getMinItems(), "" + strand.getMaxItems(), "" + strand.getBlueprintWeight(), "" + strand.getIsStrictMax(), "" + strand.getAdaptiveCut(), "" + strand.getScalar(), "" + strand.getAbilityWeight(), "" + strand.getPrecisionTargetNotMetWeight(), "" + strand.getPrecisionTargetMetWeight(), "" + strand.getPrecisionTarget() }, ','); responseTW.println(strToWrite); } responseTW.println('\n'); responseTW.println("Content Levels"); strToWrite = StringUtils.join(new String[] { "SegmentKey", "ContentLevelID", "MinItems", "MaxItems", "bpWeight", "isStrictMax" }, ','); responseTW.println(strToWrite); for (BlueprintSegmentContentLevel contLvl : bp.getBlueprintSegmentContentLevels()) { strToWrite = StringUtils.join(new String[] { "" + contLvl.getSegmentKey(), "" + contLvl.getContentLevel(), "" + contLvl.getMinItems(), "" + contLvl.getMaxItems(), "" + contLvl.getBlueprintWeight(), "" + contLvl.getIsStrictMax() }, ','); responseTW.println(strToWrite); } responseTW.flush(); } else { // throw new ReturnStatusException (new ReturnStatus ("failed", // "No session key or test key found.", HttpServletResponse.SC_OK)); throw new ReturnStatusException(new ReturnStatus("failed", "No session key or test key found.")); } }
From source file:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java
@Override public void buildProjectData(String uuid, BuildOutputData outputData, String projectId, ProjectDataType dataType) throws SandboxServiceException { PrintStream outPrint = null; ClientMessageOutputStream outStream = null; ByteArrayOutputStream byteOutStream = null; if (outputData != null) { byteOutStream = new ByteArrayOutputStream(); outPrint = new PrintStream(byteOutStream); }/* w w w. j a va2 s . c om*/ try { outStream = new ClientMessageOutputStream(uuid, outPrint); Project project = projectsMap.get(projectId); if (project != null) { String sdkProfileId = project.getSdkProfileId(); outStream.println("SDK profile id of project: " + sdkProfileId); outStream.println("Getting SDK for requested project..."); FileData sdkFileData = cacheService.getSdk(project.getId()); if (sdkFileData != null) { outStream.println("Successfuly got SDK."); File rootDir = createTempDirectory("demo-project"); try { outStream.println("Processing project archive..."); String sourceArchiveFile = Environment.getServerHomeDir() + "/" + DEMO_PROJECTS_FOLDER + "/" + project.getSourceArchive(); String rootProjectDir = rootDir.getAbsolutePath(); executeCommand(outStream, new String[] { "tar", "-C", rootProjectDir, "-xzvf", sourceArchiveFile }, null); File sdkFile = new File( rootProjectDir + "/" + project.getSdkLibDir() + "/" + sdkFileData.getFileName()); FileOutputStream fos = FileUtils.openOutputStream(sdkFile); fos.write(sdkFileData.getFileData()); fos.flush(); fos.close(); ProjectDataKey dataKey = new ProjectDataKey(projectId, dataType); if (dataType == ProjectDataType.SOURCE) { String sourceArchiveName = FilenameUtils.getName(sourceArchiveFile); outStream.println("Compressing source project archive..."); File sourceFile = new File(rootDir, sourceArchiveName); String[] files = rootDir.list(); String[] command = (String[]) ArrayUtils.addAll(new String[] { "tar", "-czvf", sourceFile.getAbsolutePath(), "-C", rootProjectDir }, files); executeCommand(outStream, command, null); outStream.println("Source project archive compressed."); byte[] sourceFileBytes = FileUtils.readFileToByteArray(sourceFile); FileData sourceFileData = new FileData(); sourceFileData.setFileName(sourceArchiveName); sourceFileData.setFileData(sourceFileBytes); sourceFileData.setContentType("application/x-compressed"); cacheService.putProjectFile(dataKey, sourceFileData); } else { outStream.println("Building binary file..."); File projectFolder = rootDir; if (project.getProjectFolder() != null && !project.getProjectFolder().trim().isEmpty()) { projectFolder = new File(rootDir, project.getProjectFolder()); } executeCommand(outStream, new String[] { "ant" }, projectFolder); outStream.println("Build finished."); File binaryFile = new File(rootDir, project.getDestBinaryFile()); byte[] binaryFileBytes = FileUtils.readFileToByteArray(binaryFile); FileData binaryFileData = new FileData(); String binaryFileName = FilenameUtils.getName(binaryFile.getAbsolutePath()); binaryFileData.setFileName(binaryFileName); binaryFileData.setFileData(binaryFileBytes); if (project.getSdkLanguage() == SdkLanguage.JAVA) { if (project.getPlatforms().contains(Platform.ANDROID)) { binaryFileData.setContentType("application/vnd.android.package-archive"); } else { binaryFileData.setContentType("application/java-archive"); } } cacheService.putProjectFile(dataKey, binaryFileData); } } finally { FileUtils.deleteDirectory(rootDir); } } else { outStream.println("Unable to get/create SDK for requested project!"); } } else { outStream.println("No project configuration found!"); } } catch (Exception e) { if (outStream != null) { outStream.println("Unexpected error occurred: " + e.getMessage()); } throw Utils.handleException(e); } finally { if (uuid != null) { broadcastMessage(uuid, uuid + " finished"); } if (outPrint != null) { outPrint.flush(); outPrint.close(); outputData.setOutputData(byteOutStream.toByteArray()); } } }