List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:xdroid.ui.core.cache.LruDiskCache.java
private static String readFully(Reader reader) throws IOException { StringWriter writer = null; try {//w ww .ja v a2 s .com writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (Exception e) { // TODO: handle exception } } }
From source file:com.osbitools.ws.shared.web.BasicWebUtils.java
public WebResponse readHttpData(String method, String url, byte[] params, String sheader, String stoken, String ctype) {/* www .j av a 2 s . c o m*/ WebResponse res; InputStreamReader in = null; HttpURLConnection conn = null; Boolean fparams = params.length != 0; try { conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setDoOutput(fparams); conn.setRequestMethod(method); if (ctype != null) { conn.setRequestProperty("Content-Type", ctype); conn.setRequestProperty("Content-Length", String.valueOf(params.length)); } if (stoken != null) conn.setRequestProperty(sheader == null ? "Cookie" : sheader, (sheader == null ? Constants.SECURE_TOKEN_NAME + "=" : "") + stoken); // Initiate connection conn.connect(); if (fparams) { OutputStream os = null; try { os = conn.getOutputStream(); os.write(params); } catch (IOException e) { return new WebResponse(conn); } finally { if (os != null) os.close(); } } // Response code int code; try { in = new InputStreamReader(conn.getInputStream()); } catch (IOException e) { return new WebResponse(conn); } // Read response try { code = conn.getResponseCode(); } catch (IOException e) { return null; } try { StringWriter out = new StringWriter(); GenericUtils.copy(in, out); String msg = out.toString(); out.close(); in.close(); res = new WebResponse(code, msg.replaceFirst("\"request_id\":\\d*", "\"request_id\":")); // Read and remember cookie for POST method if (method == "POST") { res.setCookie(conn.getHeaderField("Set-Cookie")); } } catch (IOException e) { return new WebResponse(code); } } catch (IOException e) { System.out.println("HTTP Request failed. " + e.getMessage()); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Do nothing } } if (conn != null) conn.disconnect(); } return res; }
From source file:com.webcohesion.enunciate.modules.objc_json_client.ObjCJSONClientModule.java
/** * Processes the specified template with the given model. * * @param templateURL// w w w .jav a2 s .co m * The template URL. * @param model * The root model. */ public String processTemplate(URL templateURL, Object model) throws IOException, TemplateException { debug("Processing template %s.", templateURL); Configuration configuration = new Configuration(Configuration.VERSION_2_3_22); configuration.setTemplateLoader(new URLTemplateLoader() { protected URL getURL(String name) { try { return new URL(name); } catch (MalformedURLException e) { return null; } } }); configuration.setTemplateExceptionHandler(new TemplateExceptionHandler() { public void handleTemplateException(TemplateException templateException, Environment environment, Writer writer) throws TemplateException { throw templateException; } }); configuration.setLocalizedLookup(false); configuration.setDefaultEncoding("UTF-8"); configuration.setObjectWrapper(new ObjCJSONClientObjectWrapper()); Template template = configuration.getTemplate(templateURL.toString()); StringWriter unhandledOutput = new StringWriter(); template.process(model, unhandledOutput); unhandledOutput.close(); return unhandledOutput.toString(); }
From source file:livecanvas.mesheditor.MeshEditor.java
private void open(File file) { if (file == null) { FileDialog fd = new FileDialog(JOptionPane.getFrameForComponent(MeshEditor.this), "Load"); fd.setVisible(true);//from w w w. jav a 2 s . co m String file_str = fd.getFile(); if (file_str == null) { return; } file = new File(fd.getDirectory() + "/" + file_str); } try { StringWriter out = new StringWriter(); InputStreamReader in = new InputStreamReader(new FileInputStream(file)); Utils.copy(in, out); in.close(); out.close(); clear(); JSONObject doc = new JSONObject(out.toString()); Layer rootLayer = Layer.fromJSON(doc.getJSONObject("rootLayer")); layersView.setRootLayer(rootLayer); rootLayer.setCanvas(canvas); for (Layer layer : rootLayer.getSubLayersRecursively()) { layer.setCanvas(canvas); } JSONObject canvasJSON = doc.optJSONObject("canvas"); if (canvasJSON != null) { canvas.fromJSON(canvasJSON); } canvas.setCurrLayer(rootLayer); } catch (Exception e1) { e1.printStackTrace(); String msg = "An error occurred while trying to load."; JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(MeshEditor.this), msg, "Error", JOptionPane.ERROR_MESSAGE); } repaint(); }
From source file:org.guanxi.idp.service.shibboleth.SSO.java
@SuppressWarnings("unchecked") public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mAndV = new ModelAndView(); // Load up the config file IdpDocument.Idp idpConfig = (IdpDocument.Idp) getServletContext() .getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG); /* The cookie interceptor should populate this if it finds a principal. The chain also * includes the cookie handlers so that will include embedded mode authentication. *///from w w w . j a v a 2s . c om GuanxiPrincipal principal = (GuanxiPrincipal) request.getAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL); // Need these for the Response String issuer = null; String nameQualifier = null; String nameQualifierFormat = null; // Need this for signing the Response Creds credsConfig = null; /* Now load the appropriate identity and creds from the config file. * We'll either use the default or the ones that the particular SP * needs to be sent. */ String spID = null; ServiceProvider[] spList = idpConfig.getServiceProviderArray(); for (int c = 0; c < spList.length; c++) { if (spList[c].getName().equals(request.getParameter(Shibboleth.PROVIDER_ID))) { spID = request.getParameter(Shibboleth.PROVIDER_ID); } } if (spID == null) { // No specific requirement for this SP so use the default identity and creds spID = defaultSPEntry; } // Now we've sorted the SP id to use, load the identity and creds for (int c = 0; c < spList.length; c++) { if (spList[c].getName().equals(spID)) { String identityToUse = spList[c].getIdentity(); String credsToUse = spList[c].getCreds(); // We've found the <service-provider> node so look for the corresponding <identity> node org.guanxi.xal.idp.Identity[] ids = idpConfig.getIdentityArray(); for (int cc = 0; cc < ids.length; cc++) { if (ids[cc].getName().equals(identityToUse)) { issuer = ids[cc].getIssuer(); nameQualifier = ids[cc].getNameQualifier(); nameQualifierFormat = ids[cc].getFormat(); } } // Look for the corresponding <creds> node org.guanxi.xal.idp.Creds[] creds = idpConfig.getCredsArray(); for (int ccc = 0; ccc < creds.length; ccc++) { if (creds[ccc].getName().equals(credsToUse)) { credsConfig = creds[ccc]; } } } } // Associate the principal with the issuer to use... principal.addIssuer(request.getParameter(Shibboleth.PROVIDER_ID), issuer); // ...and the SAML signing credentials principal.addSigningCreds(request.getParameter(Shibboleth.PROVIDER_ID), credsConfig); // Sort out the namespaces for saving the Response HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put(Shibboleth.NS_SAML_10_PROTOCOL, Shibboleth.NS_PREFIX_SAML_10_PROTOCOL); namespaces.put(Shibboleth.NS_SAML_10_ASSERTION, Shibboleth.NS_PREFIX_SAML_10_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveSuggestedPrefixes(namespaces); xmlOptions.setSaveNamespacesFirst(); /* No need to set the InResponseTo attribute as SAML1.1 core states that if the * corresponding RequestID attribute of the request can't be determined then we * shouldn't include InResponseTo. Shibboleth makes a request, though not through * SAML, so RequestID in the initial GET request doesn't exist. */ ResponseDocument samlResponseDoc = ResponseDocument.Factory.newInstance(xmlOptions); ResponseType samlResponse = samlResponseDoc.addNewResponse(); samlResponse.setResponseID(Utils.createNCNameID()); samlResponse.setMajorVersion(new BigInteger("1")); samlResponse.setMinorVersion(new BigInteger("1")); samlResponse.setIssueInstant(Calendar.getInstance()); samlResponse.setRecipient(request.getParameter(Shibboleth.SHIRE)); Utils.zuluXmlObject(samlResponse, 0); // Get a Status ready StatusDocument statusDoc = StatusDocument.Factory.newInstance(); StatusType status = statusDoc.addNewStatus(); StatusCodeType topLevelStatusCode = status.addNewStatusCode(); topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_SUCCESS)); // Add the Status to the Response samlResponse.setStatus(status); // Get an Assertion ready AssertionDocument assertionDoc = AssertionDocument.Factory.newInstance(); AssertionType assertion = assertionDoc.addNewAssertion(); assertion.setAssertionID(Utils.createNCNameID()); assertion.setMajorVersion(new BigInteger("1")); assertion.setMinorVersion(new BigInteger("1")); assertion.setIssuer(issuer); assertion.setIssueInstant(Calendar.getInstance()); Utils.zuluXmlObject(assertion, 0); // Conditions for the Assertion ConditionsDocument conditionsDoc = ConditionsDocument.Factory.newInstance(); ConditionsType conditions = conditionsDoc.addNewConditions(); conditions.setNotBefore(Calendar.getInstance()); conditions.setNotOnOrAfter(Calendar.getInstance()); Utils.zuluXmlObject(conditions, 5); // By attaching an Audience, we're saying that only the current SP can use this Assertion AudienceRestrictionConditionDocument audienceDoc = AudienceRestrictionConditionDocument.Factory .newInstance(); AudienceRestrictionConditionType audience = audienceDoc.addNewAudienceRestrictionCondition(); audience.setAudienceArray(new String[] { request.getParameter(Shibboleth.PROVIDER_ID) }); // Add an Audience to the Conditions conditions.setAudienceRestrictionConditionArray(new AudienceRestrictionConditionType[] { audience }); // Add Conditions to the Assertion assertion.setConditions(conditions); // Get an AuthenticationStatement ready AuthenticationStatementDocument authStatementDoc = AuthenticationStatementDocument.Factory.newInstance(); AuthenticationStatementType authStatement = authStatementDoc.addNewAuthenticationStatement(); authStatement.setAuthenticationInstant(Calendar.getInstance()); authStatement.setAuthenticationMethod(SAML.URN_AUTH_METHOD_PASSWORD); Utils.zuluXmlObject(authStatement, 0); // Get a Subject ready SubjectDocument subjectDoc = SubjectDocument.Factory.newInstance(); SubjectType subject = subjectDoc.addNewSubject(); // Build the NameIdentifier NameIdentifierDocument nameIDDoc = NameIdentifierDocument.Factory.newInstance(); NameIdentifierType nameID = nameIDDoc.addNewNameIdentifier(); nameID.setNameQualifier(nameQualifier); nameID.setFormat(nameQualifierFormat); nameID.setStringValue(principal.getUniqueId()); // Add the NameIdentifier to the Subject subject.setNameIdentifier(nameID); // Get a SubjectConfirmation ready SubjectConfirmationDocument subjectConfirmationDoc = SubjectConfirmationDocument.Factory.newInstance(); SubjectConfirmationType subjectConfirmation = subjectConfirmationDoc.addNewSubjectConfirmation(); subjectConfirmation.addConfirmationMethod(SAML.URN_CONFIRMATION_METHOD_BEARER); // Add the SubjectConfirmation to the Subject subject.setSubjectConfirmation(subjectConfirmation); // Add the Subject to the AuthenticationStatement authStatement.setSubject(subject); // Add the Conditions to the Assertion assertion.setConditions(conditions); // Add the AuthenticationStatement to the Assertion assertion.setAuthenticationStatementArray(new AuthenticationStatementType[] { authStatement }); // Add the Assertion to the Response samlResponse.setAssertionArray(new AssertionType[] { assertion }); // Get the config ready for signing SecUtilsConfig secUtilsConfig = new SecUtilsConfig(); secUtilsConfig.setKeystoreFile(credsConfig.getKeystoreFile()); secUtilsConfig.setKeystorePass(credsConfig.getKeystorePassword()); secUtilsConfig.setKeystoreType(credsConfig.getKeystoreType()); secUtilsConfig.setPrivateKeyAlias(credsConfig.getPrivateKeyAlias()); secUtilsConfig.setPrivateKeyPass(credsConfig.getPrivateKeyPassword()); secUtilsConfig.setCertificateAlias(credsConfig.getCertificateAlias()); secUtilsConfig.setKeyType(credsConfig.getKeyType()); // Break out to DOM land to get the SAML Response signed... Document signedDoc = null; try { // Need to use newDomNode to preserve namespace information signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document) samlResponseDoc.newDomNode(xmlOptions), ""); } catch (GuanxiException ge) { logger.error("Couldn't sign the Response", ge); mAndV.setViewName(errorView); return mAndV; } try { // ...and go back to XMLBeans land when it's ready samlResponseDoc = ResponseDocument.Factory.parse(signedDoc); } catch (XmlException xe) { logger.error("Couldn't get a signed Response", xe); mAndV.setViewName(errorView); return mAndV; } // Base 64 encode the SAML Response String samlResponseB64 = Utils.base64(signedDoc); // Bung the encoded Response in the HTML form request.setAttribute("saml_response", samlResponseB64); // Debug syphoning? if (idpConfig.getDebug() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions().equals("yes")) { logger.info("======================================================="); logger.info("IdP response to Shire with providerId " + request.getParameter(Shibboleth.PROVIDER_ID)); logger.info(""); StringWriter sw = new StringWriter(); samlResponseDoc.save(sw, xmlOptions); logger.info(sw.toString()); sw.close(); logger.info(""); logger.info("======================================================="); } } } for (IdPFilter filter : filters) { filter.filter(principal, request.getParameter(Shibboleth.PROVIDER_ID), samlResponseDoc); } // Send the Response to the SP mAndV.setViewName(shibView); mAndV.getModel().put(Shibboleth.SHIRE, request.getParameter(Shibboleth.SHIRE)); return mAndV; }
From source file:com.icesoft.applications.faces.auctionMonitor.beans.ReadmeBean.java
/** * Method to load a default readme file (at readme.html) The file will be * read in and converted to a displayable string * * @return boolean true on successful read *///from www.j av a 2 s .c o m private boolean loadDefaultReadmeFile() { try { Reader readmeReader = new InputStreamReader(this.getClass().getClassLoader() .getResourceAsStream("com/icesoft/applications/faces/auctionMonitor/readme.html")); StringWriter readmeWriter = new StringWriter(); char[] buf = new char[2000]; int len; try { while ((len = readmeReader.read(buf)) > -1) { readmeWriter.write(buf, 0, len); } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Something went wrong while parsing the readme file, likely because of " + e); } } // clean up the stream reader readmeReader.close(); this.readmeText = readmeWriter.toString(); // clean up the writer readmeWriter.close(); return true; } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("General error while attempting to load the readme file, cause may be " + e); } } return false; }
From source file:HtmlUtils.java
public String getTableContents(String align, Vector values, int elementCounter) throws IOException { StringWriter Cells = new StringWriter(); String contents = new String(); int vsize = values.size(); Cells.write("<TR>"); for (int i = 0; i < vsize; i++) { String value = values.elementAt(i).toString(); if (i != 0) { if (i >= elementCounter) { if (i % elementCounter == 0) { Cells.write("</TR>\n\n<TR>"); }/*from w w w. j a v a2 s . c om*/ } } Cells.write("<TD align=" + align + "> " + value + " </TD> \n"); } Cells.write("</TR>"); contents = Cells.toString(); Cells.flush(); Cells.close(); return contents; }
From source file:org.bibalex.gallery.model.BAGGalleryAbstract.java
public String getMetaAlbumStrForMetadataFile(String metaAlbumFileName) throws BAGException { try {/*from w w w. j a va2s . c o m*/ Element albumElt = this.getAlbumEltForMetadataFile(metaAlbumFileName); XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setEncoding("UTF-8")); StringWriter resultWriter = new StringWriter(); outputter.output(albumElt, resultWriter); resultWriter.flush(); resultWriter.close(); String result = resultWriter.toString(); return result; } catch (IOException e) { throw new BAGException(e); } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java
protected String loadHtml() throws IOException { StringWriter buffer = null; BufferedReader reader = null; try {//from w w w .j av a 2s .c o m buffer = new StringWriter(); reader = new BufferedReader(new InputStreamReader( TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html"), CharEncoding.UTF_8)); String line; while ((line = reader.readLine()) != null) { buffer.write(line); } return buffer.toString(); } finally { if (reader != null) { reader.close(); } if (buffer != null) { buffer.close(); } } }
From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java
private void updateDataGetterLabels(OntModel displayModel, Model addStatements, Model removeStatements, UpdateSettings settings) {// w w w .ja va2 s.c om log.debug("Checking: BEFORE adding any statements, what do we have for pageList page"); Resource testResource = ResourceFactory.createResource(DisplayVocabulary.DISPLAY_NS + "pageListPage"); StmtIterator testIt = addStatements.listStatements(testResource, null, (RDFNode) null); if (!testIt.hasNext()) { log.debug("Add statements does not have the page list page resource " + testResource.getURI()); } while (testIt.hasNext()) { log.debug("Statement for page list resource: " + testIt.nextStatement().toString()); } log.debug("Triple checking -- before this method, the add statements model contains"); StringWriter sw = new StringWriter(); try { addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in adding resource labels ", ex); } OntModel newDisplayModel = settings.getNewDisplayModelFromFile(); List<Resource> resourcesForLabels = new ArrayList<Resource>(); resourcesForLabels.add(ResourceFactory .createResource("java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.ClassGroupPageData")); resourcesForLabels.add(ResourceFactory .createResource("java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.BrowseDataGetter")); resourcesForLabels.add(ResourceFactory.createResource( "java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.IndividualsForClassesDataGetter")); resourcesForLabels.add(ResourceFactory.createResource( "java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter")); resourcesForLabels.add(ResourceFactory .createResource("java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter")); for (Resource r : resourcesForLabels) { log.debug("Adding the following for " + r.getURI()); log.debug(newDisplayModel.listStatements(r, RDFS.label, (RDFNode) null).toList().toString()); addStatements.add(newDisplayModel.listStatements(r, RDFS.label, (RDFNode) null)); log.debug("After adding statements, we now have the following in addStatements:::"); sw = new StringWriter(); try { addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in adding resource labels ", ex); } } //Add statements now includes log.debug("AFTER all resources added, Add statements now includes "); sw = new StringWriter(); try { addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in adding resource labels ", ex); } }