List of usage examples for org.apache.commons.io.input ReaderInputStream ReaderInputStream
public ReaderInputStream(Reader reader, String charsetName)
From source file:com.github.rwitzel.streamflyer.experimental.bytestream.ByteStreamTest.java
private void assertInputConversion_viaCharsetName(String charsetName, boolean conversionErrorsExpected) throws Exception { byte[] originalBytes = createBytes(); {//from w ww . ja va 2 s . c o m // byte array as byte stream InputStream originalByteStream = new ByteArrayInputStream(originalBytes); // byte stream as character stream Reader originalReader = new InputStreamReader(originalByteStream, charsetName); // modifying reader (we don't modify here) Reader modifyingReader = new ModifyingReader(originalReader, new RegexModifier("a", 0, "a")); // character stream as byte stream InputStream modifyingByteStream = new ReaderInputStream(modifyingReader, charsetName); // byte stream as byte array byte[] modifiedBytes = IOUtils.toByteArray(modifyingByteStream); assertBytes(originalBytes, modifiedBytes, conversionErrorsExpected); } }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParserTest.java
@Test public void testNamespaceAwareXpathResolveWithPreparser() throws Exception { NamespaceTestSuite testSuite = new NamespaceTestSuite().invoke(); DocumentBuilderFactory domFactory = testSuite.getDomFactory(); String xmlString = testSuite.getXmlString(); XPath xPath = testSuite.getxPath(); Map<String, String> namespaces = testSuite.getNamespaces(); DocumentBuilder builder = domFactory.newDocumentBuilder(); // Document document = builder.parse(IOUtils.toInputStream(xmlString, Utils.UTF8)); XMLFromBinDataPreParser xmlFromBinDataPreParser = new XMLFromBinDataPreParser(); Document document = xmlFromBinDataPreParser.preParse(xmlString); NamespaceMap nsContext = new NamespaceMap(); xPath.setNamespaceContext(nsContext); nsContext.addPrefixUriMappings(namespaces); Document tDoc = document.getOwnerDocument(); Element docElem = tDoc == null ? null : tDoc.getDocumentElement(); if (tDoc == null || StringUtils.isEmpty(tDoc.getNamespaceURI())) { document = builder// w w w . j a v a 2s.c o m .parse(new ReaderInputStream(new StringReader(Utils.documentToString(document)), Utils.UTF8)); } NamespaceMap documentNamespaces = new NamespaceMap(); StreamsXMLUtils.resolveDocumentNamespaces(document, documentNamespaces, false); String evaluate = xPath.compile("/soapenv:Envelope/soapenv:Header/ch:TSYSprofileInq/ch:clientData") .evaluate(document); assertEquals("xxxxxx-343e-46af-86aa-634a3688cf30", evaluate); evaluate = xPath.compile("/Envelope/Header/TSYSprofileInq/clientData").evaluate(document); assertEquals("", evaluate); }
From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { chain.doFilter(req, res);/*from w ww .ja v a 2 s. c o m*/ return; } HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; if (httpRequest.getMethod().equals("OPTIONS")) { chain.doFilter(req, res); return; } String uri = httpRequest.getRequestURI(); for (Pattern pattern : endpointBlacklistRegex) { if (pattern.matcher(uri).matches()) { chain.doFilter(req, res); return; } } String informat = getInformat(httpRequest); String outformat = getOutformat(httpRequest); if (outformat != null && (informat == null || !outformat.equals(informat))) { Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat + "\" when informat is also \"" + outformat + "\""); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (outformat != null && !outputFormats.contains(outformat)) { Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format"); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (informat == null) { chain.doFilter(req, res); return; } boolean roundtripping = false; if (outformat != null) { roundtripping = true; logger.debug("convert from " + informat + " to " + outformat); } else { logger.debug("convert input from " + informat + " to nif"); } // do conversion of informat to nif // create BodySwappingServletRequest String inputQueryString = req.getParameter("input"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream requestInputStream = inputQueryString == null ? /* * read * data * from * request * body */req.getInputStream() : /* * read data from query string input * parameter */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) { // copy request content to buffer IOUtils.copy(requestInputStream, baos); } // create request wrapper that converts the body of the request from the // original format to turtle Reader nif; byte[] baosData = baos.toByteArray(); if (baosData.length == 0) { Exception exception = new BadRequestException("No input data found in request."); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } ByteArrayInputStream bais = new ByteArrayInputStream(baosData); try { nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase()); } catch (ConversionException e) { logger.error("Error", e); throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed"); } BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif, roundtripping); if (!roundtripping) { chain.doFilter(bssr, res); return; } ConversionHttpServletResponseWrapper dummyResponse; try { dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi, new ByteArrayInputStream(baosData), informat, outformat); chain.doFilter(bssr, dummyResponse); ServletOutputStream sos = httpResponse.getOutputStream(); byte[] data = dummyResponse.writeBackToClient(); httpResponse.setContentLength(data.length); sos.write(data); sos.flush(); sos.close(); } catch (ConversionException e) { e.printStackTrace(); // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new // InternalServerErrorException()); } }
From source file:com.github.rwitzel.streamflyer.experimental.bytestream.ByteStreamTest.java
private void assertInputConversion_viaCharsetDecoder(String charsetName, boolean conversionErrorsExpected) throws Exception { // find charset Charset charset = Charset.forName(charsetName); // configure decoder CharsetDecoder decoder = charset.newDecoder(); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // // configure encoder // CharsetEncoder encoder = charset.newEncoder(); // encoder.onUnmappableCharacter(CodingErrorAction.REPORT); byte[] originalBytes = createBytes(); boolean conversionErrorsFound; try {//from ww w. j a v a2 s.c o m // byte array as byte stream InputStream originalByteStream = new ByteArrayInputStream(originalBytes); // byte stream as character stream Reader originalReader = new InputStreamReader(originalByteStream, decoder); // modifying reader (we don't modify anything here) Reader modifyingReader = new ModifyingReader(originalReader, new RegexModifier("a", 0, "a")); // character stream as byte stream InputStream modifyingByteStream = new ReaderInputStream(modifyingReader, charset); // encoder // not // supported // byte stream as byte array byte[] modifiedBytes = IOUtils.toByteArray(modifyingByteStream); assertBytes(originalBytes, modifiedBytes, conversionErrorsExpected); conversionErrorsFound = false; } catch (MalformedInputException e) { conversionErrorsFound = true; } assertEquals(conversionErrorsExpected, conversionErrorsFound); }
From source file:com.evolveum.midpoint.web.page.admin.reports.PageNewReport.java
private void importReportFromFilePerformed(AjaxRequestTarget target) { OperationResult result = new OperationResult(OPERATION_IMPORT_REPORT); FileUploadField file = (FileUploadField) get( createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT)); final FileUpload uploadedFile = file.getFileUpload(); if (uploadedFile == null) { error(getString("PageNewReport.message.nullFile")); target.add(getFeedbackPanel());//from ww w . j ava 2 s . com return; } InputStream stream = null; File newFile = null; try { // Create new file MidPointApplication application = getMidpointApplication(); WebApplicationConfiguration config = application.getWebApplicationConfiguration(); File folder = new File(config.getImportFolder()); if (!folder.exists() || !folder.isDirectory()) { folder.mkdir(); } newFile = new File(folder, uploadedFile.getClientFileName()); // Check new file, delete if it already exists if (newFile.exists()) { newFile.delete(); } // Save file // Task task = createSimpleTask(OPERATION_IMPORT_FILE); newFile.createNewFile(); uploadedFile.writeTo(newFile); InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8"); // reader. stream = new ReaderInputStream(reader, reader.getEncoding()); byte[] reportIn = IOUtils.toByteArray(stream); setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(reportIn)))); } catch (Exception ex) { result.recordFatalError("Couldn't import file.", ex); LoggingUtils.logException(LOGGER, "Couldn't import file", ex); } finally { if (stream != null) { IOUtils.closeQuietly(stream); } if (newFile != null) { FileUtils.deleteQuietly(newFile); } } showResult(result); target.add(getFeedbackPanel()); }
From source file:com.evolveum.midpoint.web.page.admin.configuration.PageImportObject.java
private void saveFilePerformed(AjaxRequestTarget target) { OperationResult result = new OperationResult(OPERATION_IMPORT_FILE); FileUploadField file = (FileUploadField) get( createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT)); final FileUpload uploadedFile = file.getFileUpload(); if (uploadedFile == null) { error(getString("pageImportObject.message.nullFile")); target.add(getFeedbackPanel());//from w ww . ja v a 2s .c o m return; } InputStream stream = null; File newFile = null; try { // Create new file MidPointApplication application = getMidpointApplication(); WebApplicationConfiguration config = application.getWebApplicationConfiguration(); File folder = new File(config.getImportFolder()); if (!folder.exists() || !folder.isDirectory()) { folder.mkdir(); } newFile = new File(folder, uploadedFile.getClientFileName()); // Check new file, delete if it already exists if (newFile.exists()) { newFile.delete(); } // Save file Task task = createSimpleTask(OPERATION_IMPORT_FILE); newFile.createNewFile(); uploadedFile.writeTo(newFile); InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8"); stream = new ReaderInputStream(reader, reader.getEncoding()); getModelService().importObjectsFromStream(stream, model.getObject(), task, result); result.recomputeStatus(); } catch (Exception ex) { result.recordFatalError("Couldn't import file.", ex); LoggingUtils.logException(LOGGER, "Couldn't import file", ex); } finally { if (stream != null) { IOUtils.closeQuietly(stream); } if (newFile != null) { FileUtils.deleteQuietly(newFile); } } showResult(result); target.add(getFeedbackPanel()); }
From source file:com.github.rwitzel.streamflyer.experimental.bytestream.ByteStreamTest.java
public void testHomepageExample_InputStream() throws Exception { String charsetName = "ISO-8859-1"; byte[] originalBytes = new byte[] { 1, 2, "\r".getBytes("ISO-8859-1")[0], 4, 5 }; // get byte stream InputStream originalByteStream = new ByteArrayInputStream(originalBytes); // byte stream as character stream Reader originalReader = new InputStreamReader(originalByteStream, charsetName); // create the modifying reader Reader modifyingReader = new ModifyingReader(originalReader, new RegexModifier("\r", 0, "")); // character stream as byte stream InputStream modifyingByteStream = new ReaderInputStream(modifyingReader, charsetName); byte[] expectedBytes = new byte[] { 1, 2, 4, 5 }; assertBytes(expectedBytes, IOUtils.toByteArray(modifyingByteStream), false); }
From source file:com.ibm.jaggr.core.impl.cache.CacheManagerImpl.java
@Override public void createCacheFileAsync(final String fileNamePrefix, final Reader reader, final CreateCompletionCallback callback) { createCacheFileAsync(fileNamePrefix, new ReaderInputStream(reader, "UTF-8"), callback); //$NON-NLS-1$ }
From source file:eu.apenet.dpt.standalone.gui.APETabbedPane.java
/** * Creates the XML tree of the file or of the converted file (if file already converted) * @param file The file represented in the list * @return A JComponent containing the tree if it exists, or an error message if not */// w w w .j a v a 2 s.c om public JComponent createEditionTree(File file) { labels = dataPreparationToolGUI.getLabels(); if (file == null) { editionPane.setViewportView(createMsgEditionTree(labels.getString("noTreeBuild") + "...")); return null; } FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName()); if (tree != null && ((XMLTreeTableModel) tree.getTreeTableModel()).getName().equals(file.getName()) && fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) return null; // fileInstance.setLastOperation(FileInstance.Operation.CREATE_TREE); try { ReaderInputStream readerInputStream; if (fileInstance.getCurrentLocation() == null || fileInstance.getCurrentLocation().equals("")) { Reader reader = new FileReader(file.getAbsolutePath()); readerInputStream = new ReaderInputStream(reader, "UTF-8"); } else { Reader reader = new FileReader(fileInstance.getCurrentLocation()); readerInputStream = new ReaderInputStream(reader, "UTF-8"); } Document doc = DOMUtil.createDocument(readerInputStream); tree = new JXTreeTable(); tree.setTreeTableModel(new XMLTreeTableModel(doc, dataPreparationToolGUI.getDateNormalization(), dataPreparationToolGUI.getLevelList(), labels, fileInstance, dataPreparationToolGUI)); tree.setTreeCellRenderer(new XMLTreeTableRenderer()); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeExpanded(TreeExpansionEvent treeExpansionEvent) { int row = tree.getRowForPath(treeExpansionEvent.getPath()); tree.scrollRowToVisible(row); tree.scrollRowToVisible(row + 1); tree.scrollRowToVisible(row + 2); tree.scrollRowToVisible(row + 3); tree.scrollRowToVisible(row + 4); } public void treeCollapsed(TreeExpansionEvent treeExpansionEvent) { } }); expandFirstLevel(); // tree.expandAll(); // tree.setHighlighters(HighlighterFactory.createSimpleStriping (HighlighterFactory.QUICKSILVER)); JScrollPane paneTest = new JScrollPane(tree); editionPane.setViewportView(paneTest); tree.setEditable(true); dataPreparationToolGUI.enableSaveBtn(); dataPreparationToolGUI.setTree(tree); ((XMLTreeTableModel) tree.getTreeTableModel()).setName(file.getName()); } catch (Exception e) { LOG.info("Error creating tree", e); tree = null; editionPane .setViewportView(createMsgEditionTree(labels.getString("edition.error.fileNoXmlOrCorrupted"))); } return tree; }
From source file:com.ibm.jaggr.core.impl.cache.CacheManagerImpl.java
@Override public void createNamedCacheFileAsync(String fileNamePrefix, Reader reader, CreateCompletionCallback callback) { createNamedCacheFileAsync(fileNamePrefix, new ReaderInputStream(reader, "UTF-8"), callback); //$NON-NLS-1$ }