Java Code Examples for java.io.StringReader

The following are top voted examples for showing how to use java.io.StringReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: richfaces   File: Test.java View source code Vote up 7 votes
static void testStandardReaders() throws IOException {
    String s = "This is a senseless text to test readers.\n";

    for (int i = 0; i < 10; i++) {
        s = s + s; // repeated 16 times
    }

    char[] bytes = s.toCharArray();
    StringWriter output = new StringWriter(16);

    // write it several times.
    for (int i = 0; i < 4; i++) {
        output.write(bytes);
    }

    // write it one more time by one byte
    for (int i = 0; i < bytes.length; i++) {
        output.write(bytes[i]);
    }

    StringReader input = new StringReader(output.toString());
    StringBuffer sb = new StringBuffer();

    // use for reading unconvenient array length.
    char[] bs = new char[ARRAY_LENGTH];
    int l = 0;

    while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
        if (BUILD_STRING) {
            sb.append(new String(bs, READ_OFF, l));
        }
    }

    if (BUILD_STRING && OUT_STRING) {
        System.out.println(sb);
    }
}
 
Example 2
Project: javalang   File: ASTManager.java View source code Vote up 6 votes
/**
 * Parses Java code and store the AST into a
 * [email protected] org.walkmod.javalang.ast.CompilationUnit} object with or without
 * the nodes start & end locations (line numbers and columns).
 * 
 * @param code
 *            source code to parse.
 * @param withoutLocation
 *            true does not fulfill the location information inside the AST.
 *            Otherwise, it is defined.
 * @return the abstract syntax tree (AST).
 * @throws ParseException
 *             when the code contains an invalid syntax.
 */
public static CompilationUnit parse(String code, boolean withoutLocation)
		throws ParseException {

	ASTParser astParser = null;
	StringReader sr = new StringReader(code);

	if (!withoutLocation) {
		astParser = new ASTParser(sr);
		astParser.jj_input_stream.setTabSize(1);
	} else {
		JavaCharStream stream = new JavaCharStream(sr, 1, 1);
		CleanerTokenManager ctm = new CleanerTokenManager(stream);
		astParser = new ASTParser(ctm);
	}

	CompilationUnit cu = null;
	try {
		cu = astParser.CompilationUnit();
	} finally {
		sr.close();
	}
	return cu;
}
 
Example 3
Project: SOLR   File: SynonymFilterFactory.java View source code Vote up 6 votes
private static List<String> splitByTokenizer(String source, TokenizerFactory tokFactory){
  StringReader reader = new StringReader( source );
  TokenStream ts = loadTokenizer(tokFactory, reader);
  List<String> tokList = new ArrayList<String>();
  try {
    for( Token token = ts.next(); token != null; token = ts.next() ){
      String text = new String(token.termBuffer(), 0, token.termLength());
      if( text.length() > 0 )
        tokList.add( text );
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  finally{
    reader.close();
  }
  return tokList;
}
 
Example 4
Project: avaje-ebeanorm   File: DnodeReader.java View source code Vote up 6 votes
public Dnode parseXml(String str) {
    
    try {
        ByteArrayOutputStream bao = new ByteArrayOutputStream(str.length());
        OutputStreamWriter osw = new OutputStreamWriter(bao);
        
        StringReader sr = new StringReader(str);
        
        int charBufferSize = 1024;
        char[] buf = new char[charBufferSize];
        int len;
        while ((len = sr.read(buf, 0, buf.length)) != -1) {
            osw.write(buf, 0, len);
        }
        sr.close();
        osw.flush();
        osw.close();
        
        bao.flush();
        bao.close();

        InputStream is = new ByteArrayInputStream(bao.toByteArray());
        return parseXml(is);
        
    } catch (IOException ex){
        throw new RuntimeException(ex);
    }
}
 
Example 5
Project: jsr223-nativeshell   File: BashScriptEngineTest.java View source code Vote up 6 votes
@Test
public void reading_input() throws Exception {
    StringReader stringInput = new StringReader("hello\n");
    scriptEngine.getContext().setReader(stringInput);
    stringInput.close();
    assertEquals(NativeShellRunner.RETURN_CODE_OK, scriptEngine.eval("cat"));
}
 
Example 6
Project: bioknime   File: SequenceAlignerNodeModel.java View source code Vote up 6 votes
private DataRow do_alignment(int align_id, String a1, String str1, String a2, String str2, String align_type, 
   				DataTableSpec spec, double gap_open_penalty, double gap_extend_penalty) 
   					throws FileNotFoundException, IOException, InvalidSequenceException, IncompatibleScoringSchemeException, InvalidScoringMatrixException {
   
	AlignmentReporter ar;
	if (align_type.indexOf("Local - JAligner") >= 0) {
		Sequence seq1 = new Sequence(str1);
		Sequence seq2 = new Sequence(str2);
		Alignment a = SmithWatermanGotoh.align(seq1, seq2, m_jalign_matrix, (float) gap_open_penalty, (float) gap_extend_penalty);
		ar = new AlignmentReporter(a, a1, str1, a2, str2);
	} else {
		StringReader sr1 = new StringReader(str1);
		StringReader sr2 = new StringReader(str2);
		PairwiseAlignmentAlgorithm algorithm;
		if (align_type.startsWith("Local")) {
			algorithm = align_type.endsWith("Waterman") ? new SmithWaterman() : new CrochemoreLandauZivUkelsonLocalAlignment();
		} else {
			algorithm = align_type.endsWith("Wunsch") ? new NeedlemanWunsch() : new CrochemoreLandauZivUkelsonGlobalAlignment();
		}
	
		// TODO: neobio does not support gap open/extend cost model... fix this?
		algorithm.setScoringScheme (m_neobio_matrix);
		algorithm.loadSequences (sr1, sr2);

		// now compute the alignment
		PairwiseAlignment alignment = algorithm.getPairwiseAlignment();
		sr1.close();
		sr2.close();
		
    	ar = new AlignmentReporter(alignment, a1, str1, a2, str2);
	}
   	return ar.getRow(align_id, spec);
}
 
Example 7
Project: freemind-mmx   File: ClientCommunication.java View source code Vote up 6 votes
void createNewMap(String map) throws IOException {
	{
		// // deregister from old controller:
		// deregisterFilter();
		logger.info("Restoring the map...");
		MindMapController newModeController = (MindMapController) getMindMapController()
				.getMode().createModeController();
		MapAdapter newModel = new MindMapMapModel(getMindMapController()
				.getFrame(), newModeController);
		HashMap IDToTarget = new HashMap();
		StringReader reader = new StringReader(map);
		MindMapNodeModel rootNode = (MindMapNodeModel) newModeController
				.createNodeTreeFromXml(reader, IDToTarget);
		reader.close();
		newModel.setRoot(rootNode);
		rootNode.setMap(newModel);
		getMindMapController().newMap(newModel);
		newModeController.invokeHooksRecursively((NodeAdapter) rootNode,
				newModel);
		setController(newModeController);
		// add new hook
		toggleHook();
		// tell him about this thread.
		Collection activatedHooks = getMindMapController().getRootNode()
				.getActivatedHooks();
		for (Iterator it = activatedHooks.iterator(); it.hasNext();) {
			PermanentNodeHook hook = (PermanentNodeHook) it.next();
			if (hook instanceof SocketConnectionHook) {
				SocketConnectionHook connHook = null;
				connHook = (SocketConnectionHook) hook;
				// Tell the hook about me
				connHook.setClientCommunication(this);
				/* register as listener, as I am a slave. */
				connHook.registerFilter();
				this.mSocketConnectionHook = connHook;
				break;
			}
		}
	}
}
 
Example 8
Project: Desktop   File: ScaledEditorKit.java View source code Vote up 6 votes
/**
 * Overriden to return our own slimmed down style sheet.
 */
public StyleSheet getStyleSheet() {
	if (defaultStyles == null) {
		defaultStyles = new StyleSheet();
		StringReader r = new StringReader(ScaledHTML.styleChanges);
		try {
			defaultStyles.loadRules(r, null);
		}
		catch (Throwable e) {
			// don't want to die in static initialization... 
			// just display things wrong.
		}
		r.close();
		defaultStyles.addStyleSheet(super.getStyleSheet());
	}
	return defaultStyles;
}
 
Example 9
Project: eGov   File: PropertyTaxUtil.java View source code Vote up 6 votes
public Properties loadTaxRates() {
    final Properties taxRates = new Properties();
    final String s = appConfigValuesService.getAppConfigValueByDate(PTMODULENAME, "PT_TAXRATES", new Date()).getValue();
    final StringReader sr = new StringReader(s);
    try {
        taxRates.load(sr);
    } catch (final IOException e) {
        throw new ApplicationRuntimeException("Could not decipher Tax rates from string" + s, e);
    }
    sr.close();
    return taxRates;
}
 
Example 10
Project: cloudpier-adapters   File: Openshift_Aux.java View source code Vote up 6 votes
public static void writeTo(String data, File file) throws IOException {
	StringReader reader = null;
	FileWriter writer = null;
	try {
		writer = new FileWriter(file);
		reader = new StringReader(data);
		for (int character = -1; (character = reader.read()) != -1;) {
			writer.write(character);
		}
	} finally {
		if (writer != null) {
			writer.flush();
			writer.close();
		}
		if (reader != null) {
			reader.close();
		}
	}
}
 
Example 11
Project: GeoBI   File: CustomXPathTest.java View source code Vote up 6 votes
public void testXslt() throws TransformerException, IOException {
    final StringReader xsltStream = new StringReader(
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n" +
                    "                xmlns:xalan=\"http://xml.apache.org/xalan\"\n" +
                    "                xmlns:custom=\"Custom\"\n" +
                    "                version=\"1.0\">\n" +
                    "  <xalan:component prefix=\"custom\" functions=\"factorArray\">\n" +
                    "    <xalan:script lang=\"javaclass\" src=\"org.mapfish.print.CustomXPath\"/>\n" +
                    "  </xalan:component>\n" +
                    "  <xsl:template match=\"/*\">\n" +
                    "    <tutu b=\"{custom:factorArray(@a,3)}\"/>\n" +
                    "  </xsl:template>\n" +
                    "</xsl:stylesheet>");
    final StringReader xmlStream = new StringReader(
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<toto a=\"1,2,3\"/>");


    DOMResult transformedSvg = new DOMResult();
    final TransformerFactory factory = TransformerFactory.newInstance();
    javax.xml.transform.Transformer xslt = factory.newTransformer(new StreamSource(xsltStream));
    xslt.transform(new StreamSource(xmlStream), transformedSvg);
    Document doc = (Document) transformedSvg.getNode();

    Node main = doc.getFirstChild();
    assertEquals("tutu", main.getNodeName());
    final Node attrB = main.getAttributes().getNamedItem("b");
    assertNotNull(attrB);
    assertEquals("3,6,9", attrB.getNodeValue());

    xmlStream.close();
    xsltStream.close();
}
 
Example 12
Project: deprecated-snow-1.x   File: FileUtil.java View source code Vote up 6 votes
/**
 * Write a full string to a file. Use PrintWriter and BufferedReader
 * 
 * @param content
 * @param dest
 * @throws IOException
 */
public static void saveStringToFile(String content, File dest) throws IOException {
	Writer out = null;
	StringReader sr = null;
	PrintWriter pw = null;

	try {
		sr = new StringReader(content);
		BufferedReader br = new BufferedReader(sr);
		// FileWriter fw = new FileWriter(f);

		FileOutputStream fos = new FileOutputStream(dest);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		BufferedWriter bw = new BufferedWriter(osw);
		out = new PrintWriter(bw);
		pw = (PrintWriter) out;
		String s;
		while ((s = br.readLine()) != null) {
			pw.println(s);
		}
		pw.flush();
	} finally {
		sr.close();
		try {
			pw.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
}
 
Example 13
Project: Solr-Advert   File: SchemaTool.java View source code Vote up 6 votes
public String analyze(String field, String text) {
  IndexSchema schema = rb.req.getSchema();
  Analyzer analyzer = schema.getAnalyzer();
  StringReader reader = new StringReader(text);
  TokenStream ts = analyzer.tokenStream(field, reader);
  ts.addAttribute(CharTermAttribute.class);
  String result = null;
  
  try {
    if(ts.incrementToken()) {
      CharTermAttribute term = ts.getAttribute(CharTermAttribute.class);
      result = term.toString();
    }
    ts.close();
    reader.close();
  } catch(IOException ex) {
    ex.printStackTrace();
  }
  
  return result;
}
 
Example 14
Project: emf.compare   File: ThreeWayTextDiff.java View source code Vote up 6 votes
/**
 * Determine the line separator used in the given [email protected] string}.
 * 
 * @param string
 *            The string to get the line separator from.
 * @return The line separator used in string or &quot;\n&quot; as default.
 */
private String determineLineSeparator(String string) {
	final StringReader stringReader = new StringReader(nullToEmpty(string));
	try {
		int read = 0;
		while (read != -1) {
			read = stringReader.read();
			final char currentChar = (char)read;
			if (currentChar == '\n' || currentChar == '\r') {
				String separator = String.valueOf(currentChar);
				read = stringReader.read();
				final char nextChar = (char)read;
				if ((read != -1) && (nextChar != currentChar)
						&& ((nextChar == '\r') || (nextChar == '\n'))) {
					separator += nextChar;
				}
				return separator;
			}
		}
	} catch (IOException e) {
		// must never happen as we read strings
	} finally {
		stringReader.close();
	}
	return "\n"; //$NON-NLS-1$
}
 
Example 15
Project: ps3mediaserver   File: PmsProperties.java View source code Vote up 6 votes
public void loadFromByteArray(byte[] data) throws IOException {
	try {
		String utf = new String(data, ENCODING);
		StringReader reader = new StringReader(utf);
		properties.clear();
		properties.load(reader);
		reader.close();
	} catch (UnsupportedEncodingException e) {
		throw new IOException("Could not decode " + ENCODING);
	}
}
 
Example 16
Project: XmlBlackBox   File: CheckDatabase.java View source code Vote up 6 votes
public List<DataSetXBB> readDbUnit(Element dbcheckElement) throws DataSetException, IOException{

		XMLOutputter outputter = new XMLOutputter();
        List<DataSetXBB> dataSetList = new ArrayList();

        Element dataset = null;
		Iterator<Element> iter = dbcheckElement.getChildren("dataset", uriXsd).iterator();

        while(iter.hasNext()){

            DataSetXBB dataSetXbb = new DataSetXBB();
            dataset = iter.next();
            if (dataset!=null){
                dataSetXbb.setSqlWhere(dataset.getChild("table", uriXsd).getAttributeValue("where-condition"));
                logger.debug("getSqlWhere() "+dataSetXbb.getSqlWhere());
                dataSetXbb.setSqlIsPresent(dataset.getChild("table", uriXsd).getAttributeValue("is-present"));
                logger.debug("getSqlIsPresent() "+dataSetXbb.getSqlIsPresent());
            }

            logger.debug("new XMLOutputter().outputString(dataset) "+ new XMLOutputter().outputString(dataset));
            StringReader srDataset=new StringReader(new XMLOutputter().outputString(dataset));
            IDataSet expectedDataSet = null;
            logger.debug("geVersion "+getVersion());
            if (getVersion().equals(VERSION11)){
                expectedDataSet = new XmlDataSet(srDataset);
            }else if(getVersion().equals(VERSION10)){
                expectedDataSet = new FlatXmlDataSet(srDataset);
            }
            dataSetXbb.setDataSet(expectedDataSet);
            dataSetList.add(dataSetXbb);
            srDataset.close();

        }

		return dataSetList;


	}
 
Example 17
Project: compomics-utilities   File: TestModificationFactory.java View source code Vote up 6 votes
/**
 * This method test the correct parsing of the 'modifications.txt' file .
 */
public void testModificationsParsing() {
    try {
        String result = ModificationFactory.modificationsToString();

        StringReader sr = new StringReader(result);
        BufferedReader test = new BufferedReader(sr);
        BufferedReader control = new BufferedReader(new FileReader(TestCaseLM.getFullFilePath("testModificationParser_control.txt").replace("%20", " ")));
        String line = null;
        while((line = test.readLine()) != null) {
            Assert.assertEquals(control.readLine(), line);
        }
        Assert.assertTrue(control.readLine() == null);
        control.close();
        test.close();
        sr.close();
    } catch(IOException ioe) {
        fail("IOException occurred while testing the parsing of the 'modifications.txt' file by the ModificationFactory class: " + ioe.getMessage());
    }
}
 
Example 18
Project: netty-book   File: AbstractHttpXmlDecoder.java View source code Vote up 6 votes
protected Object decode0(ChannelHandlerContext arg0, ByteBuf body)
        throws Exception {
    factory = BindingDirectory.getFactory(clazz);
    String content = body.toString(UTF_8);
    if (isPrint)
        System.out.println("The body is : " + content);
    reader = new StringReader(content);
    IUnmarshallingContext uctx = factory.createUnmarshallingContext();
    Object result = uctx.unmarshalDocument(reader);
    reader.close();
    reader = null;
    return result;
}
 
Example 19
Project: aipo   File: EcsStylesheetElement.java View source code Vote up 6 votes
/**
 * Processes the referenced XML content using the referenced XSLT stylesheet and 
 * parameters.
 *
 * @param out The print writer to be used for writing the result.
 */
public void output(PrintWriter out)
{
    try {

        StringReader rdr = new StringReader (SimpleTransform.transform( content_, stylesheet_, params_ ) );
        int count = 0;
        char buff[] = new char[1024];
        while( (count = rdr.read( buff, 0, buff.length ) ) > 0 ) {
            out.write( buff, 0, count );
            }

    /*    // Get a new XSLT Processor 
        XSLTProcessor processor = XSLTProcessorFactory.getProcessor();

        // set the parameters for the stylesheet
        if (params_ != null) 
        {
            Enumeration keys = params_.keys();
            while (keys.hasMoreElements()) 
            {
                String name = (String) keys.nextElement();
                processor.setStylesheetParam(name, (String) params_.get(name));
            }
        }

        //  process the stylesheet
        processor.process( content_, stylesheet_, new XSLTResultTarget(out) ); */

        } catch (Exception e) 
        {
            String message = "ECSStylesheetElement.output(PrintWriter): error processing stylesheet" + e.getMessage(); 
            logger.error(message, e);
            out.print(message);
            e.printStackTrace(out);
        }
}
 
Example 20
Project: eclipse-integration-commons   File: ArrayEncoder.java View source code Vote up 6 votes
/**
 * Decode an array of Strings encoded as a single String by StringUtils encodeArray.
 */
public static String[] decode(String encoded) {
	if (encoded==null) {
		return null;
	}
	// Encoding: String are terminated by a special terminator char. If the original String contains a separator
	// character or an escape character it is escaped by preceding it with an escape character.

	// Note: we use terminator char rather than a separator between Strings.
	// This is because with a true separator, it will be impossible to distinguish between the encoding of an empty array
	// and the encoding of an array with a single empty String.

	// Examples: (terminator = ';' escape = '\\')

	// new String[0]       ==encode==> ""
	// new String[] { "" } ==encode==> ";"
	// new String[] { "Hello", "World" } ==encode==> "Hello;World;"

	StringReader in = new StringReader(encoded);
	List<String> strings = new ArrayList<String>();
	StringBuffer currentString = new StringBuffer();
	try {
		for (int _c = in.read(); _c>=0; _c = in.read()) {
			char c = (char)_c;
			if (c==TERMINATOR_CHAR) {
				strings.add(currentString.toString());
				currentString = new StringBuffer();
			} else if (c==ESCAPE_CHAR) {
				c = (char)in.read();
				currentString.append(c);
			} else {
				currentString.append(c);
			}
		}
	} catch (Exception e) {
		throw new IllegalStateException(e);
	}
	return strings.toArray(new String[strings.size()]);
}
 
Example 21
Project: grails-ide   File: ArrayEncoder.java View source code Vote up 6 votes
/**
 * Decode an array of Strings encoded as a single String by this same class's encoder.
 */
public static String[] decode(String encoded) {
	// Encoding: String are terminated by a special terminator char. If the original String contains a separator
	// character or an escape character it is escaped by preceding it with an escape character.
	
	// Note: we use terminator char rather than a separator between Strings.
	// This is because with a true separator, it will be impossible to distinguish between the encoding of an empty array
	// and the encoding of an array with a single empty String.
	
	// Examples: (terminator = ';' escape = '\\')
	
	// new String[0]       ==encode==> ""
	// new String[] { "" } ==encode==> ";"
	// new String[] { "Hello", "World" } ==encode==> "Hello;World;"
	
	StringReader in = new StringReader(encoded);
	List<String> strings = new ArrayList<String>();
	StringBuffer currentString = new StringBuffer();
	try {
		for (int _c = in.read(); _c>=0; _c = in.read()) { 
			char c = (char)_c;
			if (c==TERMINATOR_CHAR) {
				strings.add(currentString.toString());
				currentString = new StringBuffer();
			} else if (c==ESCAPE_CHAR) {
				c = (char)in.read();
				currentString.append(c);
			} else {
				currentString.append(c);
			}
		}
	} catch (Exception e) {
		throw new IllegalStateException(e);
	}
	return strings.toArray(new String[strings.size()]);
}
 
Example 22
Project: dbmaintain   File: OracleStoredProcedureMatcherTest.java View source code Vote up 6 votes
@Test
public void testPerformance() throws IOException {
    List<String> randomTestCases = createRandomTestStrings(10000);
    //System.out.println("randomTestCases = " + randomTestCases);
    List<String> startOfStoredProcedureTestCases = createStartOfStoredProcedureTestStrings(10000);
    //System.out.println("startOfStoredProcedureTestCases = " + startOfStoredProcedureTestCases);
    List<String> testCases = mix(randomTestCases, startOfStoredProcedureTestCases);
    //System.out.println("testCases = " + testCases);
    int storedProcCount = 0;
    long time = System.nanoTime();
    for (String testCase : testCases) {
        StringReader stringReader = new StringReader(testCase);
        StringBuilder stringBuilder = new StringBuilder();
        int next = stringReader.read();
        while (next != -1) {
            stringBuilder.append((char) next);
            if (isStartOfStoredProcedureOrig(stringBuilder)) {
                storedProcCount++;
                continue;
            }
            next = stringReader.read();
        }
    }
    System.out.println("Time = " + ((System.nanoTime() - time) / 1000000) + " milliseconds");
    assertEquals(startOfStoredProcedureTestCases.size(), storedProcCount);
}
 
Example 23
Project: gatein-portal   File: ScriptLoader.java View source code Vote up 6 votes
public ScriptResult retrieve(ControllerContext context, ScriptKey key) throws Exception {
    JavascriptConfigService service = (JavascriptConfigService) PortalContainer.getComponent(JavascriptConfigService.class);

    //
    Reader script = service.getScript(key.id, key.locale);
    String sourceName = key.id.getScope() + "/" + key.id.getName() + ".js";

    //
    if (script != null) {
        if (key.minified) {
            CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
            CompilerOptions options = new CompilerOptions();
            level.setOptionsForCompilationLevel(options);
            com.google.javascript.jscomp.Compiler compiler = new Compiler();
            compiler.setErrorManager(new LoggerErrorManager(java.util.logging.Logger.getLogger(ResourceRequestHandler.class
                    .getName())));
            StringWriter code = new StringWriter();
            IOTools.copy(script, code);
            JSSourceFile[] inputs = new JSSourceFile[] { JSSourceFile.fromCode(sourceName, code.toString()) };
            Result res = compiler.compile(new JSSourceFile[0], inputs, options);
            if (res.success) {
                script = new StringReader(compiler.toSource());
            } else {
                StringBuilder msg = new StringBuilder("Handle me gracefully JS errors\n");
                for (JSError error : res.errors) {
                    msg.append(error.sourceName).append(":").append(error.lineNumber).append(" ").append(error.description)
                            .append("\n");
                }
                return new ScriptResult.Error(msg.toString());
            }
        }

        // Encode data
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            TextEncoder encoder = CharsetTextEncoder.getUTF8();
            char[] buffer = new char[256];
            for (int l = script.read(buffer); l != -1; l = script.read(buffer)) {
                encoder.encode(buffer, 0, l, out);
            }
            return new ScriptResult.Resolved(out.toByteArray());
        } finally {
            Safe.close(script);
        }
    }

    //
    return ScriptResult.NOT_FOUND;
}
 
Example 24
Project: hudson_plugins   File: UcmChangeLogActionTest.java View source code Vote up 6 votes
@Test(expected=IOException.class)
public void assertLshistoryReaderIsClosed() throws Exception {
    final StringReader lshistoryReader = new StringReader(
                                                          "\"20080509.140451\" " +
                                                          "\"vobs/projects/Server//config-admin-client\" " +
                                                          "\"/main/Product/Release_3_3_int/Release_3_3_jdk5/2\" " +
                                                          "\"Release_3_3_jdk5.20080509.155359\" " +
                                                          "\"create directory version\" " +
                                                          "\"checkin\" \"username\" ");
    context.checking(new Expectations() {
            {
                one(cleartool).lshistory(with(any(String.class)), with(aNull(Date.class)), 
                                         with(equal("VIEW_NAME")), with(equal("Release_2_1_int")), with(equal(new String[]{"VIEW_NAME" + File.separator + "vobs/projects/Server"})));
                will(returnValue(lshistoryReader));
                ignoring(cleartool).lsactivity(
                                               with(equal("Release_3_3_jdk5.20080509.155359")), 
                                               with(aNonNull(String.class)),with(aNonNull(String.class)));
                will(returnValue(new StringReader("\"Convert to Java 6\" " +
                                                  "\"Release_3_3_jdk5\" " +
                                                  "\"bob\" ")));
            }
        });
    
    UcmChangeLogAction action = new UcmChangeLogAction(cleartool,null);
    action.getChanges( null, "VIEW_NAME", new String[]{"Release_2_1_int"}, new String[]{"vobs/projects/Server"});        
    context.assertIsSatisfied();
    lshistoryReader.ready();
}
 
Example 25
Project: hudson_plugins   File: UcmChangeLogActionTest.java View source code Vote up 6 votes
@Test(expected=IOException.class)
public void assertLsactivityReaderIsClosed() throws Exception {
    final StringReader lsactivityReader = new StringReader("\"Convert to Java 6\" " +
                                                           "\"Release_3_3_jdk5\" " +
                                                           "\"bob\" ");
    context.checking(new Expectations() {
            {
                one(cleartool).lshistory(with(any(String.class)), with(aNull(Date.class)), 
                                         with(equal("VIEW_NAME")), with(equal("Release_2_1_int")), with(equal(new String[]{"VIEW_NAME" + File.separator + "vobs/projects/Server"})));
                will(returnValue(new StringReader(
                                                  "\"20080509.140451\" " +
                                                  "\"vobs/projects/Server//config-admin-client\" " +
                                                  "\"/main/Product/Release_3_3_int/Release_3_3_jdk5/2\" " +
                                                  "\"Release_3_3_jdk5.20080509.155359\" " +
                                                  "\"create directory version\" " +
                                                  "\"checkin\" \"username\" ")));
                ignoring(cleartool).lsactivity(
                                               with(equal("Release_3_3_jdk5.20080509.155359")), 
                                               with(aNonNull(String.class)),with(aNonNull(String.class)));
                will(returnValue(lsactivityReader));
            }
        });
    
    UcmChangeLogAction action = new UcmChangeLogAction(cleartool,null);
    action.getChanges(null, "VIEW_NAME", new String[]{"Release_2_1_int"}, new String[]{"vobs/projects/Server"});        
    context.assertIsSatisfied();
    lsactivityReader.ready();
}
 
Example 26
Project: juzu   File: StreamsTestCase.java View source code Vote up 6 votes
@Test
public void testFoo() throws IOException {

  StringReader readable = new StringReader("HELLO");
  StringBuilder buffer = new StringBuilder();
  OutputStream appendable = OutputStream.create(Tools.UTF_8, buffer);
  appendable.provide(Chunk.create(readable));
  assertEquals("HELLO", buffer.toString());
  try {
    readable.ready();
    fail();
  }
  catch (IOException expected) {
  }
}
 
Example 27
Project: android-sdk-sources-for-api-level-23   File: StringReaderTest.java View source code Vote up 6 votes
/**
 * java.io.StringReader#ready()
 */
public void test_ready() throws Exception {
    // Test for method boolean java.io.StringReader.ready()
    sr = new StringReader(testString);
    assertTrue("Steam not ready", sr.ready());
    sr.close();
    int r = 0;
    try {
        sr.ready();
    } catch (IOException e) {
        r = 1;
    }
    assertEquals("Expected IOException not thrown in read()", 1, r);
}
 
Example 28
Project: ARTPart   File: StringReaderTest.java View source code Vote up 6 votes
/**
 * java.io.StringReader#ready()
 */
public void test_ready() throws Exception {
    // Test for method boolean java.io.StringReader.ready()
    sr = new StringReader(testString);
    assertTrue("Steam not ready", sr.ready());
    sr.close();
    int r = 0;
    try {
        sr.ready();
    } catch (IOException e) {
        r = 1;
    }
    assertEquals("Expected IOException not thrown in read()", 1, r);
}
 
Example 29
Project: tcf   File: StringUtil.java View source code Vote up 5 votes
/**
 * Enquote the given string if necessary by putting double quotes around it.
 * <p>
 * <b>Note:</b> <i>This method has been designed for the specific needs of enquoting
 * command line arguments to launch external application from Java!</i>
 * <p>
 * Characters that require quoting are:
 * <dl>
 *   <dt>/\:;</dt><dd>Because they are file or path separators respectively</dd>
 *   <dt>\s</dt><dd>All whitespace characters, naturally</dd>
 *   <dt>|<>{}()$^~</dt><dd>Because they have shell or TCL special meaning</dd>
 *   <dt>*%?&</dt><dd>Because they are commonly used as wildcard's</dd>
 *   <dt>#</dt><dd>Because it is commonly used to start comments</dd>
 *   <dt>'"`</dt><dd>Because they are quoting characters</dd>
 * </dl>
 * To make a long story short, we only allow ASCII characters, numbers,
 * the underscore and <code>@.-</code> to go unquoted.
 *
 * @param unqouted The string to quote or <code>null</code>.
 *
 * @return The quoted string or "\"\"".
 */
public static String enQuote(String unqouted) {
	if (unqouted == null) {
		return "\"\""; //$NON-NLS-1$
	}
	else if (unqouted.length() == 0) {
		return "\"\""; //$NON-NLS-1$
	}
	else if (ALLOWED_STRING_PATTERN.matcher(unqouted).matches()) {
		return unqouted;
	}
	else {
		StringReader r = new StringReader(unqouted);
		StringBuffer buf = new StringBuffer(unqouted.length() + 16);
		boolean containsWhitespaces =
			Pattern.compile("\\s").matcher(unqouted).find(); //$NON-NLS-1$
		if (containsWhitespaces) {
			buf.append('\"');
		}
		try {
			int c = r.read();
			while (c >= 0) {
				switch (c) {
					// case '\\':
					case '\'':
					case '\"':
						buf.append('\\');
						buf.append((char)c);
						break;
					case '\b':
						buf.append("\\b");break; //$NON-NLS-1$
					case '\f':
						buf.append("\\f");break; //$NON-NLS-1$
					case '\n':
						buf.append("\\n");break; //$NON-NLS-1$
					case '\r':
						buf.append("\\r");break; //$NON-NLS-1$
					case '\t':
						buf.append("\\t");break; //$NON-NLS-1$
					default:
						if (c > 0xff) { // Unicode
							buf.append('\\');
							buf.append('u');
							String hexString = Integer.toHexString(c);
							if (hexString.length() < 4) {
								buf.append('0');
							}
							buf.append(hexString);
						}
						else if (c < 0x20 || c > '~') {
							// octal escape sequence
							buf.append('\\');
							buf.append(Integer.toOctalString(c));
						}
						else {
							buf.append((char)c);
						}
				}
				c = r.read();
			}
		}
		catch (IOException e) { /* ignore */
		}
		r.close();
		if (containsWhitespaces) {
			buf.append('\"');
		}
		return buf.toString();
	}
}
 
Example 30
Project: NemoVelo   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}
 
Example 31
Project: Banc   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}
 
Example 32
Project: zdal   File: StringUtil.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens, String stringCloses,
                                   boolean slashStarComments, boolean slashSlashComments,
                                   boolean hashComments, boolean dashDashComments) {
    if (src == null) {
        return null;
    }

    StringBuffer buf = new StringBuffer(src.length());

    // It's just more natural to deal with this as a stream
    // when parsing..This code is currently only called when
    // parsing the kind of metadata that developers are strongly
    // recommended to cache anyways, so we're not worried
    // about the _1_ extra object allocation if it cleans
    // up the code

    StringReader sourceReader = new StringReader(src);

    int contextMarker = Character.MIN_VALUE;
    boolean escaped = false;
    int markerTypeFound = -1;

    int ind = 0;

    int currentChar = 0;

    try {
        while ((currentChar = sourceReader.read()) != -1) {
            if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
                && !escaped) {
                contextMarker = Character.MIN_VALUE;
                markerTypeFound = -1;
            } else if ((ind = stringOpens.indexOf(currentChar)) != -1 && !escaped
                       && contextMarker == Character.MIN_VALUE) {
                markerTypeFound = ind;
                contextMarker = currentChar;
            }

            if (contextMarker == Character.MIN_VALUE && currentChar == '/'
                && (slashSlashComments || slashStarComments)) {
                currentChar = sourceReader.read();
                if (currentChar == '*' && slashStarComments) {
                    int prevChar = 0;
                    while ((currentChar = sourceReader.read()) != '/' || prevChar != '*') {
                        if (currentChar == '\r') {

                            currentChar = sourceReader.read();
                            if (currentChar == '\n') {
                                currentChar = sourceReader.read();
                            }
                        } else {
                            if (currentChar == '\n') {

                                currentChar = sourceReader.read();
                            }
                        }
                        if (currentChar < 0)
                            break;
                        prevChar = currentChar;
                    }
                    continue;
                } else if (currentChar == '/' && slashSlashComments) {
                    while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
                           && currentChar >= 0)
                        ;
                }
            } else if (contextMarker == Character.MIN_VALUE && currentChar == '#'
                       && hashComments) {
                // Slurp up everything until the newline
                while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
                       && currentChar >= 0)
                    ;
            } else if (contextMarker == Character.MIN_VALUE && currentChar == '-'
                       && dashDashComments) {
                currentChar = sourceReader.read();

                if (currentChar == -1 || currentChar != '-') {
                    buf.append('-');

                    if (currentChar != -1) {
                        buf.append(currentChar);
                    }

                    continue;
                }

                // Slurp up everything until the newline

                while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
                       && currentChar >= 0)
                    ;
            }

            if (currentChar != -1) {
                buf.append((char) currentChar);
            }
        }
    } catch (IOException ioEx) {
        // we'll never see this from a StringReader
    }

    return buf.toString();
}
 
Example 33
Project: SRS_CS_Project   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}
 
Example 34
Project: pom   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}
 
Example 35
Project: EclipseTrader   File: JavaScriptLineStyler.java View source code Vote up 5 votes
public void parseBlockComments(String text) {
    blockComments = new Vector<int[]>();
    StringReader buffer = new StringReader(text);
    int ch;
    boolean blkComment = false;
    int cnt = 0;
    int[] offsets = new int[2];
    boolean done = false;

    try {
        while (!done) {
            switch (ch = buffer.read()) {
                case -1: {
                    if (blkComment) {
                        offsets[1] = cnt;
                        blockComments.addElement(offsets);
                    }
                    done = true;
                    break;
                }
                case '/': {
                    ch = buffer.read();
                    if ((ch == '*') && (!blkComment)) {
                        offsets = new int[2];
                        offsets[0] = cnt;
                        blkComment = true;
                        cnt++;
                    }
                    else {
                        cnt++;
                    }
                    cnt++;
                    break;
                }
                case '*': {
                    if (blkComment) {
                        ch = buffer.read();
                        cnt++;
                        if (ch == '/') {
                            blkComment = false;
                            offsets[1] = cnt;
                            blockComments.addElement(offsets);
                        }
                    }
                    cnt++;
                    break;
                }
                default: {
                    cnt++;
                    break;
                }
            }
        }
    } catch (IOException e) {
        // ignore errors
    }
}
 
Example 36
Project: jxta   File: Util.java View source code Vote up 5 votes
public static String base64Encode(String s) {
    StringBuilder sb = new StringBuilder();
    StringReader r = new StringReader(s);
    int c = 0;
    int d = 0;
    int e = 0;
    int k = 0;
    int end = 0;
    byte u;
    byte v;
    byte w;
    byte x;

    while (end == 0) {
        try {
            if ((c = r.read()) == -1) {
                c = 0;
                end = 1;
            }
            if ((d = r.read()) == -1) {
                d = 0;
                end += 1;
            }
            if ((e = r.read()) == -1) {
                e = 0;
                end += 1;
            }
        } catch (IOException ioe) {
            if (VERBOSE) {
                ioe.printStackTrace();
            }
            sb = null;
            break;
        }
        u = code[c >> 2];
        v = code[(3 & c) << 4 | d >> 4];
        w = code[(15 & d) << 2 | e >> 6];
        x = code[e & 63];
        if (k == 76) {
            k = 0;
            System.out.println("");
        }
        if (end >= 1) {
            x = (byte) '=';
        }
        if (end == 2) {
            w = (byte) '=';
        }
        if (end < 3) {
            sb.append("" + (char) u + (char) v + (char) w + (char) x);
        }
        k += 4;
    }
    return sb != null ? sb.toString() : null;
}
 
Example 37
Project: i-Prog   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}
 
Example 38
Project: Netuno   File: StringUtils.java View source code Vote up 5 votes
/**
 * Returns the given string, with comments removed
 * 
 * @param src
 *            the source string
 * @param stringOpens
 *            characters which delimit the "open" of a string
 * @param stringCloses
 *            characters which delimit the "close" of a string, in
 *            counterpart order to <code>stringOpens</code>
 * @param slashStarComments
 *            strip slash-star type "C" style comments
 * @param slashSlashComments
 *            strip slash-slash C++ style comments to end-of-line
 * @param hashComments
 *            strip #-style comments to end-of-line
 * @param dashDashComments
 *            strip "--" style comments to end-of-line
 * @return the input string with all comment-delimited data removed
 */
public static String stripComments(String src, String stringOpens,
		String stringCloses, boolean slashStarComments,
		boolean slashSlashComments, boolean hashComments,
		boolean dashDashComments) {
	if (src == null) {
		return null;
	}

	StringBuffer buf = new StringBuffer(src.length());

	// It's just more natural to deal with this as a stream
	// when parsing..This code is currently only called when
	// parsing the kind of metadata that developers are strongly
	// recommended to cache anyways, so we're not worried
	// about the _1_ extra object allocation if it cleans
	// up the code

	StringReader sourceReader = new StringReader(src);

	int contextMarker = Character.MIN_VALUE;
	boolean escaped = false;
	int markerTypeFound = -1;

	int ind = 0;

	int currentChar = 0;

	try {
		while ((currentChar = sourceReader.read()) != -1) {

			if (false && currentChar == '\\') {
				escaped = !escaped;
			} else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
					&& !escaped) {
				contextMarker = Character.MIN_VALUE;
				markerTypeFound = -1;
			} else if ((ind = stringOpens.indexOf(currentChar)) != -1
					&& !escaped && contextMarker == Character.MIN_VALUE) {
				markerTypeFound = ind;
				contextMarker = currentChar;
			}

			if (contextMarker == Character.MIN_VALUE && currentChar == '/'
					&& (slashSlashComments || slashStarComments)) {
				currentChar = sourceReader.read();
				if (currentChar == '*' && slashStarComments) {
					int prevChar = 0;
					while ((currentChar = sourceReader.read()) != '/'
							|| prevChar != '*') {
						if (currentChar == '\r') {

							currentChar = sourceReader.read();
							if (currentChar == '\n') {
								currentChar = sourceReader.read();
							}
						} else {
							if (currentChar == '\n') {

								currentChar = sourceReader.read();
							}
						}
						if (currentChar < 0)
							break;
						prevChar = currentChar;
					}
					continue;
				} else if (currentChar == '/' && slashSlashComments) {
					while ((currentChar = sourceReader.read()) != '\n'
							&& currentChar != '\r' && currentChar >= 0)
						;
				}
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '#' && hashComments) {
				// Slurp up everything until the newline
				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			} else if (contextMarker == Character.MIN_VALUE
					&& currentChar == '-' && dashDashComments) {
				currentChar = sourceReader.read();

				if (currentChar == -1 || currentChar != '-') {
					buf.append('-');

					if (currentChar != -1) {
						buf.append(currentChar);
					}

					continue;
				}

				// Slurp up everything until the newline

				while ((currentChar = sourceReader.read()) != '\n'
						&& currentChar != '\r' && currentChar >= 0)
					;
			}

			if (currentChar != -1) {
				buf.append((char) currentChar);
			}
		}
	} catch (IOException ioEx) {
		// we'll never see this from a StringReader
	}

	return buf.toString();
}