public class Underlay extends AbstractConsoleCommand { private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Underlay.class); private final UnderlayLocator underlayLocator; public Underlay( List<String> args, String host, String currentDir, ResourceFactory resourceFactory, DeploymentService deploymentService, UnderlayLocator underlayLocator) { super(args, host, currentDir, resourceFactory); this.underlayLocator = underlayLocator; } @Override public Result execute() { Folder cur; try { cur = currentResource(); } catch (NotAuthorizedException | BadRequestException ex) { return result("can't lookup current resource", ex); } if (cur == null) { return result("current dir not found: " + currentDir); } String cmd = args.get(0); args.remove(0); switch (cmd) { case "add": return doAdd(cur.getHost()); case "remove": return doRemove(cur.getHost()); default: return result("Unknown command: " + cmd); } } private Result doAdd(Host currentHost) { UnderlayVector v = new UnderlayVector(); v.setGroupId(args.get(0)); v.setArtifcatId(args.get(1)); v.setVersion(args.get(2)); List<UnderlayVector> vectors = currentHost.getUnderlayVectors(); if (vectors == null) { vectors = new ArrayList<>(); } Iterator<UnderlayVector> it = vectors.iterator(); while (it.hasNext()) { UnderlayVector oldV = it.next(); // if( oldV.getGroupId().equals(v.getGroupId())) } return null; } private Result doRemove(Host currentHost) { throw new UnsupportedOperationException("Not yet implemented"); } }
public Graph(WeightedBVGraph graph, String[] names) { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph"); logger.setLevel(org.apache.log4j.Level.FATAL); if (names.length != graph.numNodes()) throw new Error("Problem with the list of names for the nodes in the graph."); try { File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath()); nodes = recMan.hashMap("nodes"); nodesReverse = recMan.hashMap("nodesReverse"); } catch (IOException ex) { throw new Error(ex); } nodes.clear(); nodesReverse.clear(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); this.graph = graph; WeightedArcSet list = new WeightedArcSet(); ArcLabelledNodeIterator it = graph.nodeIterator(); while (it.hasNext()) { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } Integer aux1 = it.nextInt(); Integer aux2 = null; ArcLabelledNodeIterator.LabelledArcIterator suc = it.successors(); while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { WeightedArc arc = (WeightedArc) cons[0].newInstance(aux2, aux1, suc.label().getFloat()); list.add(arc); this.nodes.put(aux1, names[aux1]); this.nodes.put(aux2, names[aux2]); this.nodesReverse.put(names[aux1], aux1); this.nodesReverse.put(names[aux2], aux2); } catch (Exception ex) { throw new Error(ex); } } reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0])); numArcs = list.size(); iterator = nodeIterator(); try { File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); String basename = auxFile.getAbsolutePath(); store(basename); } catch (IOException ex) { throw new Error(ex); } commit(); }
public Graph(String file) throws IOException { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph"); logger.setLevel(org.apache.log4j.Level.FATAL); try { File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath()); nodes = recMan.hashMap("nodes"); nodesReverse = recMan.hashMap("nodesReverse"); } catch (IOException ex) { throw new Error(ex); } nodes.clear(); nodesReverse.clear(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); String aux = null; Float weight = (float) 1.0; WeightedArcSet list = new WeightedArcSet(); BufferedReader br; try { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)))); } catch (Exception ex) { br = new BufferedReader(new FileReader(file)); } while ((aux = br.readLine()) != null) try { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } String parts[] = aux.split("\t"); String l1 = new String(parts[0]); String l2 = new String(parts[1]); if (!nodesReverse.containsKey(l1)) { nodesReverse.put(l1, nodesReverse.size()); nodes.put(nodes.size(), l1); } if (!nodesReverse.containsKey(l2)) { nodesReverse.put(l2, nodesReverse.size()); nodes.put(nodes.size(), l2); } if (parts.length == 3) weight = new Float(parts[2]); list.add( (WeightedArc) cons[0].newInstance(nodesReverse.get(l1), nodesReverse.get(l2), weight)); } catch (Exception ex) { throw new Error(ex); } this.graph = new WeightedBVGraph(list.toArray(new WeightedArc[0])); br.close(); list = new WeightedArcSet(); br = new BufferedReader(new FileReader(file)); while ((aux = br.readLine()) != null) try { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } String parts[] = aux.split("\t"); String l1 = new String(parts[0]); String l2 = new String(parts[1]); if (parts.length == 3) weight = new Float(parts[2]); list.add( (WeightedArc) cons[0].newInstance(nodesReverse.get(l2), nodesReverse.get(l1), weight)); } catch (Exception ex) { throw new Error(ex); } br.close(); this.reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0])); numArcs = list.size(); iterator = nodeIterator(); try { File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); String basename = auxFile.getAbsolutePath(); store(basename); } catch (IOException ex) { throw new Error(ex); } commit(); }
public Graph(BVGraph graph) { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph"); logger.setLevel(org.apache.log4j.Level.FATAL); try { File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath()); nodes = recMan.hashMap("nodes"); nodesReverse = recMan.hashMap("nodesReverse"); } catch (IOException ex) { throw new Error(ex); } nodes.clear(); nodesReverse.clear(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); Integer aux1 = null; WeightedArcSet list = new WeightedArcSet(); it.unimi.dsi.webgraph.NodeIterator it = graph.nodeIterator(); while ((aux1 = it.nextInt()) != null) { LazyIntIterator suc = it.successors(); Integer aux2 = null; while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { if (commit++ % COMMIT_SIZE == 0) { list.commit(); } list.add((WeightedArc) cons[0].newInstance(aux1, aux2, (float) 1.0)); } catch (Exception ex) { throw new Error(ex); } } this.graph = new WeightedBVGraph(list.toArray(new WeightedArc[0])); list = new WeightedArcSet(); it = graph.nodeIterator(); while ((aux1 = it.nextInt()) != null) { LazyIntIterator suc = it.successors(); Integer aux2 = null; while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } list.add((WeightedArc) cons[0].newInstance(aux2, aux1, (float) 1.0)); this.nodes.put(aux1, "" + aux1); this.nodes.put(aux2, "" + aux2); this.nodesReverse.put("" + aux1, aux1); this.nodesReverse.put("" + aux2, aux2); } catch (Exception ex) { throw new Error(ex); } } this.reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0])); numArcs = list.size(); iterator = nodeIterator(); try { File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); String basename = auxFile.getAbsolutePath(); store(basename); } catch (IOException ex) { throw new Error(ex); } commit(); }
public abstract class Connection { private static final boolean TRAKTOR_USED = false; private static final org.apache.log4j.Logger CAT = org.apache.log4j.Logger.getLogger(Connection.class.getName()); private Frame traktor; private static boolean traktorConnectionDown = false; /** * Creates a new connection to the specified host of specified type. <br> * <br> * type: Type of connection to create <br> * destination: Host to connect to (in "host:port" or "host" syntax) */ public Connection(java.net.InetAddress host, int port, PluginContext ctx) throws MessagingNetworkException, java.io.IOException { if (TRAKTOR_USED) { if (traktorConnectionDown) throw new IOException("network is down"); traktor = new Frame("" + host + ":" + port + " - Traktor"); final Checkbox c = new Checkbox("break this & ALL future connections"); c.setState(traktorConnectionDown); c.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { traktorConnectionDown = c.getState(); try { if (traktorConnectionDown) closeSocket(); } catch (Exception ex) { } } }); traktor.add(c); traktor.setSize(100, 50); traktor.setLocation(230, 450); traktor.setVisible(true); } else { traktor = null; } } public final int available() throws IOException { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); if (isClosed()) throw new IOException("connection closed"); return getInputStream().available(); } public abstract void closeSocket(); public final void flush() throws IOException, MessagingNetworkException { OutputStream os = getOutputStream(); synchronized (os) { os.flush(); } } protected final java.io.InputStream getInputStream() throws IOException { if (isClosed()) throw new IOException("connection closed"); InputStream is = getInputStream0(); if (is == null) throw new IOException("connection closed"); return is; } protected abstract java.io.InputStream getInputStream0() throws IOException; protected final java.io.OutputStream getOutputStream() throws IOException { if (isClosed()) { if (TRAKTOR_USED && traktor != null && !traktorConnectionDown) { traktor.dispose(); traktor = null; } throw new IOException("connection closed"); } OutputStream os = getOutputStream0(); if (os == null) throw new IOException("connection closed"); return os; } protected abstract java.io.OutputStream getOutputStream0() throws IOException; public abstract boolean isClosed(); /* private byte[] buf = new byte[8192]; private int ofs = 0; private int len = 0; private void fill(InputStream is, long abortTime) throws IOException { for (;;) { if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); int av = is.available(); if (av == 0) { try { Thread.currentThread().sleep(100); } catch (InterruptedException ex) { throw new InterruptedIOException(); } continue; } int capacity = buf.length - len; if (av > capacity) av = capacity; int rc = capacity - ofs; int pos = ofs + len; if (rc >= av) { int read = is.read(buf, pos, av); if (read < 0) read = 0; len += read; return; } //rc < av while (rc > 0) { int read = is.read(buf, ofs, rc); if (read < 0) read = 0; len += read; rc -= read; if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); } //rc <= 0 //case 1, when buf.length-1 >= ofs+len-1 (=> rc > 0) //cells ofs, ..., ofs+len-1 are filled //case 2, when buf.length-1 < ofs+len-1 (<=> buf.length-1 <= ofs+len-2) //cells ofs, ..., buf.length-1 are filled //cells 0, ..., ofs+len-2 - (buf.length-1) are filled, too int lm = ofs+len-1 - buf.length; if (lm > av) lm = av; rc = 0; while (lm > 0) { int read = is.read(buf, ofs, rc); if (read < 0) read = 0; len += read; rc -= read; if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); } } } */ public final String readCommand(byte[] b) throws IOException, InterruptedException, MessagingNetworkException { InputStream is = getInputStream(); synchronized (is) { long abortTime = System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS; int ofs = 0; boolean d = false; for (; ; ) { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); int by = is.read(); if (by == -1) throw new IOException("unexpected EOF"); if (by == 10 && d) break; d = (by == 13); if (ofs < b.length) { b[ofs++] = (byte) by; } if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); /* if (len >= buffer.length) { ... return ...; } int pos = findCRLF(); if (pos != -1) break; fill(is, abortTime); */ } if (b[ofs - 1] == 13) --ofs; String line = new String(b, 0, ofs, "ASCII"); if (StringUtil.startsWith(line, "MSG")) { StringTokenizer st = new StringTokenizer(line); String len_s = null; while (st.hasMoreTokens()) { len_s = st.nextToken(); } if (len_s == null) throw new AssertException("len_s is null"); int len; try { len = Integer.parseInt(len_s); } catch (NumberFormatException ex) { ServerConnection.throwProtocolViolated("MSG length must be int"); len = 0; } String msg = readMSG(len); line = line + "\r\n" + msg; } if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line); return line; } } private final String readMSG(final int len) throws IOException, InterruptedException, MessagingNetworkException { if (len > 65000) ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes"); byte[] b = new byte[len]; InputStream is = getInputStream(); synchronized (is) { long abortTime = System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS; int ofs = 0; while (ofs < len) { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); int read = is.read(b, ofs, len - ofs); if (read < 0) read = 0; ofs += read; if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out"); /* if (len >= buffer.length) { ... return ...; } int pos = findCRLF(); if (pos != -1) break; fill(is, abortTime); */ } String msg = new String(b, 0, len, "UTF-8"); return msg; } } public final void writeASCII(String s) throws IOException { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); OutputStream os = getOutputStream(); synchronized (os) { if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + s); os.write(s.getBytes("ASCII")); os.write((byte) 13); os.write((byte) 10); os.flush(); } } /** * UTF byte count is appended to the asciiPrefix, then UTF bytes are appended to the result; the * final result is sent. */ public final void writeMSG(String asciiPrefix, String msgBody) throws IOException { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); OutputStream os = getOutputStream(); synchronized (os) { byte[] utfBytes = msgBody.getBytes("UTF-8"); asciiPrefix = asciiPrefix + ' ' + utfBytes.length; if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + asciiPrefix + "\r\n" + msgBody); os.write(asciiPrefix.getBytes("ASCII")); os.write((byte) 13); os.write((byte) 10); os.write(utfBytes); os.flush(); } } }
@Controller public class ProposalDevelopmentS2SController extends ProposalDevelopmentControllerBase { private static final String CONTENT_TYPE_XML = "text/xml"; private static final String CONTENT_TYPE_PDF = "application/pdf"; private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ProposalDevelopmentS2SController.class); @Autowired @Qualifier("s2sSubmissionService") private S2sSubmissionService s2sSubmissionService; @Autowired @Qualifier("s2sUserAttachedFormService") private S2sUserAttachedFormService s2sUserAttachedFormService; @Autowired @Qualifier("userAttachedFormService") private UserAttachedFormService userAttachedFormService; @Autowired @Qualifier("globalVariableService") private GlobalVariableService globalVariableService; @Autowired @Qualifier("formPrintService") private FormPrintService formPrintService; @Autowired @Qualifier("parameterService") private ParameterService parameterService; @Autowired @Qualifier("proposalTypeService") private ProposalTypeService proposalTypeService; @Autowired @Qualifier("proposalDevelopmentDocumentViewAuthorizer") private ProposalDevelopmentDocumentViewAuthorizer proposalDevelopmentDocumentViewAuthorizer; private static final String ERROR_NO_GRANTS_GOV_FORM_SELECTED = "error.proposalDevelopment.no.grants.gov.form.selected"; @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=refresh", "refreshCaller=S2sOpportunity-LookupView"}) public ModelAndView refresh( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ProposalDevelopmentDocument document = form.getProposalDevelopmentDocument(); DevelopmentProposal proposal = document.getDevelopmentProposal(); if (form.getNewS2sOpportunity() != null && StringUtils.isNotEmpty(form.getNewS2sOpportunity().getOpportunityId())) { proposal.setS2sOpportunity(form.getNewS2sOpportunity()); proposal.getS2sOpportunity().setDevelopmentProposal(proposal); // Set default S2S Submission Type if (StringUtils.isBlank(form.getNewS2sOpportunity().getS2sSubmissionTypeCode())) { String defaultS2sSubmissionTypeCode = getProposalTypeService().getDefaultSubmissionTypeCode(proposal.getProposalTypeCode()); proposal.getS2sOpportunity().setS2sSubmissionTypeCode(defaultS2sSubmissionTypeCode); getDataObjectService() .wrap(proposal.getS2sOpportunity()) .fetchRelationship("s2sSubmissionType"); } final String opportunityTitle = form.getNewS2sOpportunity().getOpportunityTitle(); String trimmedTitle = StringUtils.substring( opportunityTitle, 0, ProposalDevelopmentConstants.S2sConstants.OPP_TITLE_MAX_LENGTH); // Set Opportunity Title and Opportunity ID in the Sponsor & Program Information section proposal.setProgramAnnouncementTitle(trimmedTitle); proposal.setCfdaNumber(form.getNewS2sOpportunity().getCfdaNumber()); proposal.setProgramAnnouncementNumber(form.getNewS2sOpportunity().getOpportunityId()); form.setNewS2sOpportunity(new S2sOpportunity()); } S2sOpportunity s2sOpportunity = proposal.getS2sOpportunity(); try { if (s2sOpportunity != null && s2sOpportunity.getSchemaUrl() != null) { List<String> missingMandatoryForms = s2sSubmissionService.setMandatoryForms(proposal, s2sOpportunity); if (!CollectionUtils.isEmpty(missingMandatoryForms)) { globalVariableService .getMessageMap() .putError( Constants.NO_FIELD, KeyConstants.ERROR_IF_OPPORTUNITY_ID_IS_INVALID, s2sOpportunity.getOpportunityId(), StringUtils.join(missingMandatoryForms, ",")); proposal.setS2sOpportunity(null); } } } catch (S2sCommunicationException ex) { if (ex.getErrorKey().equals(KeyConstants.ERROR_GRANTSGOV_NO_FORM_ELEMENT)) { ex.setMessage(s2sOpportunity.getOpportunityId()); } globalVariableService .getMessageMap() .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams()); proposal.setS2sOpportunity(new S2sOpportunity()); } super.save(form, result, request, response); return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=clearOpportunity"}) public ModelAndView clearOpportunity( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception { ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService()) .clearOpportunity(form.getDevelopmentProposal()); return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=printFormsXml"}) public ModelAndView printFormsXml( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, HttpServletResponse response) throws Exception { form.getDevelopmentProposal().setGrantsGovSelectFlag(true); return printForms(form, response); } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=printForms"}) public ModelAndView printForms( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form, HttpServletResponse response) throws Exception { ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument(); proposalDevelopmentDocumentViewAuthorizer.initializeDocumentAuthorizerIfNecessary( form.getProposalDevelopmentDocument()); if (!((ProposalDevelopmentDocumentAuthorizer) proposalDevelopmentDocumentViewAuthorizer.getDocumentAuthorizer()) .isAuthorizedToPrint( proposalDevelopmentDocument, globalVariableService.getUserSession().getPerson())) { throw new AuthorizationException( globalVariableService.getUserSession().getPrincipalName(), "printForms", "Proposal"); } if (proposalDevelopmentDocument.getDevelopmentProposal().getSelectedS2sOppForms().isEmpty()) { getGlobalVariableService() .getMessageMap() .putError("noKey", ERROR_NO_GRANTS_GOV_FORM_SELECTED); return getModelAndViewService().getModelAndView(form); } FormPrintResult formPrintResult = getFormPrintService().printForm(proposalDevelopmentDocument); setValidationErrorMessage(formPrintResult.getErrors()); KcFile attachmentDataSource = formPrintResult.getFile(); if (((attachmentDataSource == null || attachmentDataSource.getData() == null || attachmentDataSource.getData().length == 0) && !proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag()) || CollectionUtils.isNotEmpty(formPrintResult.getErrors())) { boolean grantsGovErrorExists = copyAuditErrorsToPage(Constants.GRANTSGOV_ERRORS, "grantsGovFormValidationErrors"); if (grantsGovErrorExists) { getGlobalVariableService() .getMessageMap() .putError( "grantsGovFormValidationErrors", KeyConstants.VALIDATTION_ERRORS_BEFORE_GRANTS_GOV_SUBMISSION); } proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false); return getModelAndViewService().getModelAndView(form); } if (proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag()) { File grantsGovXmlDirectoryFile = getS2sSubmissionService().getGrantsGovSavedFile(proposalDevelopmentDocument); byte[] bytes = new byte[(int) grantsGovXmlDirectoryFile.length()]; FileInputStream fileInputStream = new FileInputStream(grantsGovXmlDirectoryFile); fileInputStream.read(bytes); int size = bytes.length; try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(size)) { outputStream.write(bytes); ControllerFileUtils.streamOutputToResponse( response, outputStream, "binary/octet-stream", grantsGovXmlDirectoryFile.getName(), size); response.flushBuffer(); } proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false); return getModelAndViewService().getModelAndView(form); } ControllerFileUtils.streamToResponse(attachmentDataSource, response); return getModelAndViewService().getModelAndView(form); } protected void setValidationErrorMessage( List<org.kuali.coeus.s2sgen.api.core.AuditError> errors) { if (errors != null) { LOG.info("Error list size:" + errors.size() + errors.toString()); List<org.kuali.rice.krad.util.AuditError> auditErrors = new ArrayList<>(); for (org.kuali.coeus.s2sgen.api.core.AuditError error : errors) { auditErrors.add( new org.kuali.rice.krad.util.AuditError( error.getErrorKey(), Constants.GRANTS_GOV_GENERIC_ERROR_KEY, error.getLink(), new String[] {error.getMessageKey()})); } if (!auditErrors.isEmpty()) { getGlobalVariableService() .getAuditErrorMap() .put( "grantsGovAuditErrors", new AuditCluster( Constants.GRANTS_GOV_OPPORTUNITY_PANEL, auditErrors, Constants.GRANTSGOV_ERRORS)); } } } protected boolean copyAuditErrorsToPage(String auditClusterCategory, String errorkey) { boolean auditClusterFound = false; Iterator<String> iter = getGlobalVariableService().getAuditErrorMap().keySet().iterator(); while (iter.hasNext()) { String errorKey = (String) iter.next(); AuditCluster auditCluster = getGlobalVariableService().getAuditErrorMap().get(errorKey); if (auditClusterCategory == null || StringUtils.equalsIgnoreCase(auditCluster.getCategory(), auditClusterCategory)) { auditClusterFound = true; for (Object error : auditCluster.getAuditErrorList()) { AuditError auditError = (AuditError) error; getGlobalVariableService() .getMessageMap() .putError( errorKey == null ? auditError.getErrorKey() : errorKey, auditError.getMessageKey(), auditError.getParams()); } } } return auditClusterFound; } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=addUserAttachedForm"}) public ModelAndView addUserAttachedForm( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception { S2sUserAttachedForm s2sUserAttachedForm = form.getS2sUserAttachedForm(); ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument(); MultipartFile userAttachedFormFile = s2sUserAttachedForm.getNewFormFile(); s2sUserAttachedForm.setNewFormFileBytes(userAttachedFormFile.getBytes()); s2sUserAttachedForm.setFormFileName(userAttachedFormFile.getOriginalFilename()); s2sUserAttachedForm.setProposalNumber( proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber()); try { List<S2sUserAttachedForm> userAttachedForms = getS2sUserAttachedFormService() .extractNSaveUserAttachedForms(proposalDevelopmentDocument, s2sUserAttachedForm); proposalDevelopmentDocument .getDevelopmentProposal() .getS2sUserAttachedForms() .addAll(userAttachedForms); form.setS2sUserAttachedForm(new S2sUserAttachedForm()); } catch (S2SException ex) { LOG.error(ex.getMessage(), ex); if (ex.getTabErrorKey() != null) { if (getGlobalVariableService() .getMessageMap() .getErrorMessagesForProperty(ex.getTabErrorKey()) == null) { getGlobalVariableService() .getMessageMap() .putError(ex.getTabErrorKey(), ex.getErrorKey(), ex.getParams()); } } else { getGlobalVariableService() .getMessageMap() .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams()); } } return super.save(form); } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=viewUserAttachedFormXML"}) public ModelAndView viewUserAttachedFormXML( ProposalDevelopmentDocumentForm form, HttpServletResponse response, @RequestParam("selectedLine") String selectedLine) throws Exception { DevelopmentProposal developmentProposal = form.getDevelopmentProposal(); List<S2sUserAttachedForm> s2sAttachedForms = developmentProposal.getS2sUserAttachedForms(); S2sUserAttachedForm selectedForm = s2sAttachedForms.get(Integer.parseInt(selectedLine)); S2sUserAttachedFormFileContract userAttachedFormFile = getUserAttachedFormService().findUserAttachedFormFile(selectedForm); if (userAttachedFormFile != null) { ControllerFileUtils.streamToResponse( userAttachedFormFile.getXmlFile().getBytes(), selectedForm.getFormName() + ".xml", CONTENT_TYPE_XML, response); } else { return getModelAndViewService().getModelAndView(form); } return null; } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=viewUserAttachedFormPDF"}) public ModelAndView viewUserAttachedFormPDF( ProposalDevelopmentDocumentForm form, HttpServletResponse response, @RequestParam("selectedLine") String selectedLine) throws Exception { DevelopmentProposal developmentProposal = form.getDevelopmentProposal(); List<S2sUserAttachedForm> s2sAttachedForms = developmentProposal.getS2sUserAttachedForms(); S2sUserAttachedForm selectedForm = s2sAttachedForms.get(Integer.parseInt(selectedLine)); S2sUserAttachedFormFileContract userAttachedFormFile = getUserAttachedFormService().findUserAttachedFormFile(selectedForm); if (userAttachedFormFile != null) { ControllerFileUtils.streamToResponse( userAttachedFormFile.getFormFile(), selectedForm.getFormFileName(), CONTENT_TYPE_PDF, response); } else { return getModelAndViewService().getModelAndView(form); } return null; } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=deleteUserAttachedForm"}) public ModelAndView deleteUserAttachedForm( ProposalDevelopmentDocumentForm form, HttpServletResponse response, @RequestParam("selectedLine") String selectedLine) throws Exception { S2sUserAttachedForm deleteForm = form.getDevelopmentProposal() .getS2sUserAttachedForms() .remove(Integer.parseInt(selectedLine)); getDataObjectService().delete(deleteForm); getS2sUserAttachedFormService() .resetFormAvailability(form.getProposalDevelopmentDocument(), deleteForm.getNamespace()); return getModelAndViewService().getModelAndView(form); } @Transactional @RequestMapping( value = "/proposalDevelopment", params = {"methodToCall=refreshSubmissionDetails"}) public ModelAndView refreshSubmissionDetails(ProposalDevelopmentDocumentForm form) throws Exception { ProposalDevelopmentDocument document = form.getProposalDevelopmentDocument(); try { getS2sSubmissionService().refreshGrantsGov(document); } catch (S2sCommunicationException ex) { LOG.error(ex.getMessage(), ex); getGlobalVariableService() .getMessageMap() .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessage()); } return getRefreshControllerService().refresh(form); } @Transactional @RequestMapping(value = "/proposalDevelopment", params = "methodToCall=saveUserAttachedForm") public ModelAndView saveUserAttachedForm( @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception { final String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_PATH); String selectedLine = form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX); if (form.getEditableCollectionLines().containsKey(selectedCollectionPath)) { form.getEditableCollectionLines().get(selectedCollectionPath).remove(selectedLine); } return super.save(form); } public S2sSubmissionService getS2sSubmissionService() { return s2sSubmissionService; } public void setS2sSubmissionService(S2sSubmissionService s2sSubmissionService) { this.s2sSubmissionService = s2sSubmissionService; } public GlobalVariableService getGlobalVariableService() { return globalVariableService; } public void setGlobalVariableService(GlobalVariableService globalVariableService) { this.globalVariableService = globalVariableService; } public FormPrintService getFormPrintService() { return formPrintService; } public void setFormPrintService(FormPrintService formPrintService) { this.formPrintService = formPrintService; } public ParameterService getParameterService() { return parameterService; } public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } public S2sUserAttachedFormService getS2sUserAttachedFormService() { return s2sUserAttachedFormService; } public void setS2sUserAttachedFormService(S2sUserAttachedFormService s2sUserAttachedFormService) { this.s2sUserAttachedFormService = s2sUserAttachedFormService; } public UserAttachedFormService getUserAttachedFormService() { return userAttachedFormService; } public void setUserAttachedFormService(UserAttachedFormService userAttachedFormService) { this.userAttachedFormService = userAttachedFormService; } public ProposalTypeService getProposalTypeService() { return proposalTypeService; } public void setProposalTypeService(ProposalTypeService proposalTypeService) { this.proposalTypeService = proposalTypeService; } public ProposalDevelopmentDocumentViewAuthorizer getProposalDevelopmentDocumentViewAuthorizer() { return proposalDevelopmentDocumentViewAuthorizer; } public void setProposalDevelopmentDocumentViewAuthorizer( ProposalDevelopmentDocumentViewAuthorizer proposalDevelopmentDocumentViewAuthorizer) { this.proposalDevelopmentDocumentViewAuthorizer = proposalDevelopmentDocumentViewAuthorizer; } }
public class Deploy extends AbstractConsoleCommand { private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Deploy.class); private final DeploymentService deploymentService; private final UnderlayLocator underlayLocator; private String mavenRoot; public Deploy( List<String> args, String host, String currentDir, ResourceFactory resourceFactory, DeploymentService deploymentService, UnderlayLocator underlayLocator) { super(args, host, currentDir, resourceFactory); this.deploymentService = deploymentService; this.underlayLocator = underlayLocator; } @Override public Result execute() { Folder cur; try { cur = currentResource(); } catch (NotAuthorizedException | BadRequestException ex) { return result("can't lookup current resource", ex); } if (cur == null) { return result("current dir not found: " + currentDir); } String deployUrl = ""; if (cur instanceof Folder) { Folder col = cur; try { if (args.size() == 1) { deployUrl = args.get(0); return deploySimple(deployUrl, col); } else if (args.size() >= 3) { String s = args.get(0); boolean isUnderlay = false; if (s.equals("-underlay")) { isUnderlay = true; args.remove(0); } if (mavenRoot == null || mavenRoot.length() == 0) { return result("Cant deploy maven spec, no maven root has been configred"); } String group = args.get(0); String artifact = args.get(1); String version = args.get(2); deployUrl = mavenRoot + "/" + group.replace(".", "/") + "/" + artifact + "/" + version + "/" + artifact + "-" + version + ".war"; log.info("Built maven URL: " + deployUrl); if (isUnderlay) { UnderlayVector v = new UnderlayVector(); v.setArtifcatId(artifact); v.setGroupId(group); v.setVersion(version); return deployUnderlay(deployUrl, v); } else { return deploySimple(deployUrl, col); } } else { return result( "Invalid number of arguments. Either give single URL or 3 arguments for a maven vector group artifact id"); } } catch (MalformedURLException ex) { return result("Bad url: " + deployUrl); } catch (Exception ex) { return result("Exception deploying: " + deployUrl, ex); } } else { return result("not a collection: " + cur.getHref()); } } private Result deployUnderlay(String deployUrl, UnderlayVector v) throws MalformedURLException, IOException, Exception { try { VfsTransactionManager.setRollbackOnly(true); Host underlayHost = underlayLocator.createUnderlay(v); return deploySimple(deployUrl, underlayHost); } finally { VfsTransactionManager.setRollbackOnly(false); } } private Result deploySimple(String deployUrl, Folder currentFolder) throws MalformedURLException, IOException, Exception { URL url = new URL(deployUrl); try (InputStream in = url.openStream(); BufferedInputStream bufIn = new BufferedInputStream(in)) { VfsTransactionManager.setRollbackOnly(true); Path path = Path.path(url.getPath()); File deployWar = File.createTempFile("ettrema-deploy", path.getName()); try (FileOutputStream fout = new FileOutputStream(deployWar); BufferedOutputStream bufOut = new BufferedOutputStream(fout)) { StreamUtils.readTo(bufIn, bufOut); bufOut.flush(); fout.flush(); } String deployName = findDeployName(path); deploymentService.deploy(deployWar, deployName, currentFolder.getWeb()); VfsTransactionManager.setRollbackOnly(false); commit(); return result("Deployed ok: " + deployName); } finally { VfsTransactionManager.setRollbackOnly(false); } } private String findDeployName(Path p) { String s = p.getName(); // eg issues-web-1.0.war int pos = s.lastIndexOf("-"); s = s.substring(0, pos); return s; } public String getMavenRoot() { return mavenRoot; } public void setMavenRoot(String mavenRoot) { this.mavenRoot = mavenRoot; } }
/** * This is a utility class used to create pipe advertisement named and BinaryID for the pipeID to * create a private address space that can be hosted in the public discovery system or sent over * unencrypted channeds without revealing their intent or purpose. * * <p>We use a one-way hashing algorythum to create an ID from private information like a user's * social security number or a user's email address. We search for the pipe by with this private * information securly by creating the matching hash using the same methods. * * <p>The purpose of this system is to create a way to search for a pipe (or other BinaryID based * system) without exposing the pipe owner's clearTextID while allowing for people that know what * they are looking for to find the right pipe. The system also has the ability to create pipes that * have a specific purpose. For example, the email address is appended with a function name. Say you * have a pipe for messages and one for administrative purposes. You would supply the email and a * string for the function. The same combination can be created by another peer to search for either * of these pipes. * * <p>This implementation uses the "SHA-1" algorythum. This was selected for relitive speed. It is * used as a one-way conversion that cannot be reversed engineered to create the original string. * This allows you to publish the hash without the possibility of the contents being decoded. This * allows for public indexing of data that is only known by the parties involved. * * <p>Note that this can also be used to generate safe password verification hash codes. Sample * useage: <code> * String clearTextID = "*****@*****.**"; * String function = "eventPipe"; * System.out.println("clear text ID: "+clearTextID); * System.out.println("function text: "+function); * String digest1 = DigestID.generateHashString(clearTextID, function); * String digest2 = DigestID.generateHashString(clearTextID); * System.out.println("Digest1: '"+digest1+"'"); * System.out.println("Digest2: '"+digest2+"'"); * System.out.println("test1: "+DigestID.test(clearTextID, function,digest1)); * System.out.println("test2: "+DigestID.test(clearTextID, digest2)); * System.out.println("Digest1 != Digest2: "+DigestID.test(clearTextID, function,digest2)); * </code> * * <p>To use an algorythum other than SHA-1, you will need stronger encyption. The BouncyCastle that * comes with JXTA is just a minimum implimentation so a good choice is the normal bouncy castle (it * is much larger, nearing a meg, which is why it is not a part of the normal JXTA distribution. The * full version of bouncy includes SHA-128, SHA-256, SHA-384, and SHA-512. * * <p>Here is how you create a provider from the full version of Bouncy. Once you do this, you can * access the extended Digest ecryption levels. <code> * provider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); * System.out.println("provider:"+provider.getName()); * Security.addProvider(provider); * </code> * * <p>Security Note * * <p> * * <p>This class should have all of its fields and properties marked as 'final' to prevent * overriding the default behavior. Failure to do so could allow a less scrupulous person to cause * the BinaryID or hash codes to contain the original information. Note that the class itself is not * final to allow for additional convienience methods to be added. There a no methods for creating * ModuleClassBinaryID, ModuleSpecBinaryID, or CodatID because this is meant for general' use, not * for extending platform (you can write your own using similar code). * * <p> * * @version $Revision: 1.1 $ * @author Daniel Brookshier <a HREF="mailto:[email protected]">[email protected]</a> */ public class DigestTool { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DigestTool.class.getName()); /** varaible used for conditional compile of debug printing. */ public static final boolean debug = true; /** * Defualt SHA-1 digest algorithm type. This is a 20 byte hash function (note: that MD5 is only 16 * so we don't use it). */ public static final String SHAOne = "SHA-1"; /** * SHA-128 digest algorithm type. This is a 128 bit hash function (note: must have another * provider registered to use). */ public static final String SHA128 = "SHA-128"; /** * SHA-256 digest algorithm type. This is a 256 bit hash function (note: must have another * provider registered to use). */ public static final String SHA256 = "SHA-256"; /** * SHA-384 digest algorithm type. This is a 384 bit hash function (note: must have another * provider registered to use). */ public static final String SHA384 = "SHA-384"; /** * SHA-512 digest algorithm type. This is a 512 bit hash function (note: must have another * provider registered to use). */ public static final String SHA512 = "SHA-512"; /** Tilde character used to seperate candidate strings from a function. */ public final String functionSeperator = "~"; String algorithmType; public DigestTool() { algorithmType = SHAOne; } public DigestTool(String algorithmType) { this.algorithmType = algorithmType; } /** * Create a PipeID based on the BinaryID type with a digest of the clearTextID and function. * * @param peerGroupID Parent peer group ID. * @param clearTextID String used as the significant part of the address * @param function String used to diferentiate different clearTextID addresses (can be null). * @return PipeBinaryID with the digest hash of the string: clearTextID+"~"+function. */ public final PipeBinaryID createPipeID( net.jxta.peergroup.PeerGroupID peerGroupID, String clearTextID, String function) { byte[] digest = generateHash(clearTextID, function); PipeBinaryID pipe = new PipeBinaryID(peerGroupID, digest, false); return pipe; } /** * Create a PeerGroupID based on the BinaryID type with a digest of the clearTextID and function. * * @param peerGroupID Parent peer group ID. * @param clearTextID String used as the significant part of the address * @param function String used to diferentiate different clearTextID addresses (can be null). * @return PeerGroupBinaryID with the digest hash of the string: clearTextID+"~"+function. */ public final PeerGroupBinaryID createPeerGroupID( net.jxta.peergroup.PeerGroupID parentPeerGroupID, String clearTextID, String function) { byte[] digest = generateHash(clearTextID, function); PeerGroupBinaryID peerGroupID = new PeerGroupBinaryID(parentPeerGroupID, digest, false); return peerGroupID; } /** * Create a PeerID based on the BinaryID type with a digest of the clearTextID and function. * * @param peerGroupID Parent peer group ID. * @param clearTextID String used as the significant part of the address * @param function String used to diferentiate different clearTextID addresses (can be null). * @return PeerBinaryID with the digest hash of the string: clearTextID+"~"+function. */ public final PeerBinaryID createPeerID( net.jxta.peergroup.PeerGroupID peerGroupID, String clearTextID, String function) { byte[] digest = generateHash(clearTextID, function); PeerBinaryID peerID = new PeerBinaryID(peerGroupID, digest, false); return peerID; } /** * Creates a new instance of DigestPipe. Because this is a utility, this is private to prevent * construction. */ /** * Generates a Base64 encoded string of an SHA-1 digest hash of the string: clearTextID. * * <p> * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @return Base64 encoded string containing the hash of the string: clearTextID. */ public final String generateHashString(String clearTextID) { try { java.io.StringWriter base64 = new java.io.StringWriter(); net.jxta.impl.util.BASE64OutputStream encode = new net.jxta.impl.util.BASE64OutputStream(base64); encode.write(generateHash(clearTextID)); encode.close(); return base64.toString(); } catch (Exception failed) { LOG.error("Unable to encode hash value.", failed); throw new RuntimeException("Unable to encode hash value."); } } /** * Generates a Base64 encoded string of an SHA-1 digest hash of the string: * clearTextID+"-"+function or: clearTextID if function was blank. * * <p> * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @param function A function related to the clearTextID string. This is used to create a hash * associated with clearTextID so that it is a uique code. * @return Base64 encoded string containing the hash of the string: clearTextID+"-"+function or * clearTextID if function was blank. */ public final String generateHashString(String clearTextID, String function) { try { java.io.StringWriter base64 = new java.io.StringWriter(); net.jxta.impl.util.BASE64OutputStream encode = new net.jxta.impl.util.BASE64OutputStream(base64); encode.write(generateHash(clearTextID, function)); encode.close(); return base64.toString(); } catch (Exception failed) { LOG.error("Unable to encode hash value.", failed); throw new RuntimeException("Unable to encode hash value."); } } /** * Generates a SHA-1 digest hash of the string: clearTextID. * * <p> * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @return String containing the hash of the string: clearTextID. */ public final byte[] generateHash(String clearTextID) { return generateHash(clearTextID, null); } /** * Generates an SHA-1 digest hash of the string: clearTextID+"-"+function or: clearTextID if * function was blank. * * <p>Note that the SHA-1 used only creates a 20 byte hash. * * <p> * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @param function A function related to the clearTextID string. This is used to create a hash * associated with clearTextID so that it is a uique code. * @return array of bytes containing the hash of the string: clearTextID+"-"+function or * clearTextID if function was blank. Can return null if SHA-1 does not exist on platform. */ public final byte[] generateHash(String clearTextID, String function) { String id; if (function == null) { id = clearTextID; } else { id = clearTextID + functionSeperator + function; } byte[] buffer = id.getBytes(); MessageDigest algorithm = null; try { algorithm = MessageDigest.getInstance(algorithmType); } catch (Exception e) { LOG.error("Cannot load selected Digest Hash implementation", e); return null; } // Generate the digest. algorithm.reset(); algorithm.update(buffer); try { byte[] digest1 = algorithm.digest(); return digest1; } catch (Exception de) { LOG.error("Failed to creat a digest.", de); return null; } } /** * Generates an SHA-1 digest hash of the string: clearTextID. * * <p> * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @return String containing the hash of the string: clearTextID. */ public final boolean test(String clearTextID, String function, String testHash) { String id = clearTextID + functionSeperator + function; return test(id, testHash); } /** * Compares a clear text code or ID with a candidate hash code. This is used to confirm that the * clearTextID can be successfully converted to the hash. * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @param testHash A string of hashed string. * @return true if the hash created from clearTextID is equal to the testHash string.Can return * false if SHA-1 does not exist on platform. */ public final boolean test(String clearTextID, String testHash) { byte[] digest1 = generateHash(clearTextID); byte[] digest2; try { java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); net.jxta.impl.util.BASE64InputStream decoder = new net.jxta.impl.util.BASE64InputStream(new java.io.StringReader(testHash)); while (true) { int c = decoder.read(); if (-1 == c) { break; } bos.write(c); } digest2 = bos.toByteArray(); } catch (Exception e) { LOG.error("Failed to create a digest.", e); return false; } if (digest1.length != digest2.length) { // Not a match! because of length. return false; } for (int i = 0; i < digest1.length; i++) { if (digest1[i] != digest2[i]) { // Not a match because of byte:"+i+" did not match return false; } } // Match was ok return true; } /** * Compares a clear text code or ID with a candidate hash code. This is used to confirm that the * clearTextID can be successfully converted to the hash. * * @param clearTextID A string that is to be hashed. This can be any string used for hashing or * hiding data. * @param testHash A string of hashed string. * @return true if the hash created from clearTextID is equal to the testHash string.Can return * false if SHA-1 does not exist on platform. */ public final boolean test(String clearTextID, byte[] testHash) { byte[] digest1 = generateHash(clearTextID); if (digest1.length != testHash.length) { // Not a match! because of length. return false; } for (int i = 0; i < testHash.length; i++) { if (digest1[i] != testHash[i]) { // Not a match because of byte:"+i+" did not match return false; } } // Match was ok return true; } }
public class SshClient { public static long DEFAULT_WAITING_TIME_PER_CYCLE = 1000; public static long MAXIMUM_WAITING_TIME_INACTIVITY = 10000; private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("SshClient"); protected String host = null; protected Integer port = null; protected String user = null; protected final JSch jsch; protected String knownHostsFile = null; protected Session session = null;; public SshClient() throws JSchException { this.jsch = new JSch(); } public SshClient(String knownHostsFile) throws JSchException { this.knownHostsFile = knownHostsFile; this.jsch = new JSch(); jsch.setKnownHosts(this.knownHostsFile); } public void addIdentityFile(String identityFileName) throws JSchException { this.jsch.addIdentity(identityFileName); } public void setHost(String host) { this.host = host; } public void setPort(Integer port) { this.port = port; } public void setUser(String user) { this.user = user; } public void createSession(String host, String user, Boolean hostKeyChecking) throws JSchException { log.info("creating session"); this.session = this.getSession(host, user, hostKeyChecking); } public void createSession(String host, Integer port, String user, Boolean hostKeyChecking) throws JSchException { log.info("creating session"); this.session = this.getSession(host, port, user, hostKeyChecking); } public Session getSession(String host, String user, Boolean hostKeyChecking) throws JSchException { return this.getSession(host, 22, user, hostKeyChecking); } public Session getSession(String host, Integer port, String user, Boolean hostKeyChecking) throws JSchException { if (this.session != null) return this.session; this.setHost(host); this.setUser(user); this.session = jsch.getSession(user, host, port); java.util.Properties config = new java.util.Properties(); if (hostKeyChecking) { log.info("strict host key checking enabled"); config.put("StrictHostKeyChecking", "yes"); } else { log.info("strict host key checking disabled"); config.put("StrictHostKeyChecking", "no"); } session.setConfig(config); return session; } public void setSessionPassword(String pw) { log.info("password set"); this.session.setPassword(pw); } public void connectSession() throws JSchException { log.info("connecting session"); this.session.connect(); } public void disconnectSession() throws JSchException { log.info("disconnecting session"); this.session.disconnect(); } public ChannelExec getExecutionChannel() throws JSchException { Channel channel = session.openChannel("exec"); log.info("opening execution channel"); return (ChannelExec) channel; } public ChannelShell getShellChannel() throws JSchException { Channel channel = session.openChannel("shell"); log.info("opening shell channel"); return (ChannelShell) channel; } public ChannelSftp getSftpChannel() throws JSchException { Channel channel = session.openChannel("sftp"); log.info("opening sftp channel"); return (ChannelSftp) channel; } public void listKnownHosts() { HostKeyRepository hkr = this.jsch.getHostKeyRepository(); HostKey[] hks = hkr.getHostKey(); if (hks != null) { System.out.println("Host keys in " + hkr.getKnownHostsRepositoryID()); for (int i = 0; i < hks.length; i++) { HostKey hk = hks[i]; System.out.println(hk.getHost() + " " + hk.getType() + " " + hk.getFingerPrint(jsch)); } System.out.println(""); } } public void addHostKey(byte[] key) throws JSchException { HostKeyRepository hkr = this.jsch.getHostKeyRepository(); HostKey hk = new HostKey(this.host, key); UserInfo userInfo = new MyUserInfo(); hkr.add(hk, userInfo); log.info("hostkey added"); } /** * Executes the specified command on the specified host, using loginCredentials. * * <p>The function can't respond to requests on the default input! If a command waits for an * input, the execution will be terminated after a certain waiting time without changes to stderr * or stdin. * * @param nodeAddress * @param nodeCredentials * @param command * @return */ public CommandExecution getCommandExecutor( String nodeAddress, LoginCredentials nodeCredentials, String command) { return new CommandExecution(nodeAddress, nodeCredentials, command); } public static ChannelExec getExecutionChannel(Session session, String cmd) throws JSchException { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(cmd); return ((ChannelExec) channel); } public static class CommandExecution implements Callable<Integer> { protected static ExecutorService executor = Executors.newFixedThreadPool(4); protected StringBuffer output = new StringBuffer(); protected StringBuffer error = new StringBuffer(); private Long timeStamp = System.currentTimeMillis(); private String nodeAddress; private LoginCredentials nodeCredentials; private String command; public CommandExecution(String nodeAddress, LoginCredentials nodeCredentials, String command) { this.nodeAddress = nodeAddress; this.nodeCredentials = nodeCredentials; this.command = command; } public Future<Integer> execute() { if (executor == null) executor = Executors.newFixedThreadPool(4); if (executor.isShutdown()) executor = Executors.newFixedThreadPool(4); ExecutorCompletionService<Integer> commandExecutor = new ExecutorCompletionService<Integer>(executor); return commandExecutor.submit(this); } public void shutdown() { if (!executor.isShutdown()) executor.shutdown(); } @Override public Integer call() { int exitstatus = Integer.MAX_VALUE; Boolean useIdentityFile = null; String credentials = null; String userName = nodeCredentials.getUsername(); if (nodeCredentials instanceof LoginCredentialsPassword) { useIdentityFile = false; credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword(); } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) { useIdentityFile = true; credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath(); } ChannelExec c = null; SshClient ssh = null; try { ssh = new SshClient(); ssh.createSession(nodeAddress, userName, false); log.info("connecting with username: "******"connecting using identity file: " + credentials); } else { log.info("connecting using password: "******"executing command: " + command); c.connect(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedInputReader = new BufferedReader(new InputStreamReader(is)); try { while ((line = bufferedInputReader.readLine()) != null) { output.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedErrorReader = new BufferedReader(new InputStreamReader(err)); try { while ((line = bufferedErrorReader.readLine()) != null) { error.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); while (!c.isClosed()) { synchronized (this.timeStamp) { if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) { log.warn("command execution seems inactive, canceling!"); break; } } log.info("waiting for command to finish."); try { Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE); } catch (InterruptedException e) { e.printStackTrace(); } } exitstatus = c.getExitStatus(); } catch (JSchException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (c != null) { c.disconnect(); } if (ssh != null) { try { ssh.disconnectSession(); } catch (JSchException e) { e.printStackTrace(); } } } return exitstatus; } } public static void main(String[] args) throws JSchException { SshClient ssh = new SshClient(); CommandExecution exec = ssh.getCommandExecutor( ChefNodeManager.DEFAULT_CHEF_HOST, new LoginCredentialsPassword("chef login creds", "root", "redundant"), // "ps aux"); "knife bootstrap 23.20.100.107 -i /tmp/creds3268697130713915657.tmp -x ubuntu --sudo --no-host-key-verify -d ubuntu10.04-apt -N mytestNode1"); Future<Integer> result = exec.execute(); System.out.println("result: " + result); exec.shutdown(); } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { public String getPassword() { return passwd; } public boolean promptYesNo(String str) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog( null, str, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); return foo == 0; } String passwd; JTextField passwordField = (JTextField) new JPasswordField(20); public String getPassphrase() { return null; } public boolean promptPassphrase(String message) { return true; } public boolean promptPassword(String message) { Object[] ob = {passwordField}; int result = JOptionPane.showConfirmDialog(null, ob, message, JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { passwd = passwordField.getText(); return true; } else { return false; } } public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } final GridBagConstraints gbc = new GridBagConstraints( 0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private Container panel; public String[] promptKeyboardInteractive( String destination, String name, String instruction, String[] prompt, boolean[] echo) { panel = new JPanel(); panel.setLayout(new GridBagLayout()); gbc.weightx = 1.0; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridx = 0; panel.add(new JLabel(instruction), gbc); gbc.gridy++; gbc.gridwidth = GridBagConstraints.RELATIVE; JTextField[] texts = new JTextField[prompt.length]; for (int i = 0; i < prompt.length; i++) { gbc.fill = GridBagConstraints.NONE; gbc.gridx = 0; gbc.weightx = 1; panel.add(new JLabel(prompt[i]), gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 1; if (echo[i]) { texts[i] = new JTextField(20); } else { texts[i] = new JPasswordField(20); } panel.add(texts[i], gbc); gbc.gridy++; } if (JOptionPane.showConfirmDialog( null, panel, destination + ": " + name, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) { String[] response = new String[prompt.length]; for (int i = 0; i < prompt.length; i++) { response[i] = texts[i].getText(); } return response; } else { return null; // cancel } } } }