Java Code Examples for java.util.Scanner

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Archimedes, under directory /br.org.archimedes.core/src/br/org/archimedes/.

Source file: Utils.java

  20 
vote

/** 
 * Get the double value from a string.
 * @param parameter Text to extract the double.
 * @return The double value from the string.
 */
public static double getDouble(String parameter){
  String withDots=withDot(parameter);
  Scanner stringScanner=new Scanner(withDots);
  stringScanner.useLocale(Locale.US);
  return stringScanner.nextDouble();
}
 

Example 2

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.

Source file: AbstractReader.java

  19 
vote

protected final Scanner createLineScanner(BufferedReader source) throws IOException {
  String line=source.readLine();
  if (log.isDebugEnabled()) {
    log.debug("Raw request/response line is (" + passwordFilter(line) + ")");
  }
  if (line == null) {
    return new Scanner("");
  }
  line+="\r\n";
  Scanner scanner=new Scanner(line);
  scanner.useDelimiter(DEFAULT_DELIMITERS);
  return scanner;
}
 

Example 3

From project ajah, under directory /ajah-crypto/src/main/java/com/ajah/crypto/.

Source file: Crypto.java

  19 
vote

private static void keyGen(){
  final SecureRandom sr=new SecureRandom();
  final byte[] keyBytes=new byte[128];
  sr.nextBytes(keyBytes);
  final Scanner scanner=new Scanner(System.in);
  System.out.print("Algorithm: [HmacSHA1] ");
  final String algorithm=scanner.nextLine();
  if (StringUtils.isBlank(algorithm) || algorithm.equals("HmacSHA1")) {
    System.out.print("Secret: ");
    final String secret=scanner.nextLine();
    System.out.print(getHmacSha1Hex(secret));
  }
}
 

Example 4

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/data/script/.

Source file: ScriptExecutor.java

  18 
vote

List<String> splitScriptIntoStatements(String script){
  final Scanner scriptReader=new Scanner(new StringReader(script));
  scriptReader.useDelimiter(SQL_DELIMITER);
  final List<String> statements=new LinkedList<String>();
  while (scriptReader.hasNext()) {
    final String line=scriptReader.next().trim();
    if (line.length() > 0 && !isComment(line)) {
      statements.add(line);
    }
  }
  return statements;
}
 

Example 5

From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/internal/.

Source file: SocketConnectionFacadeImpl.java

  18 
vote

private void initialize(Socket socket,Pattern pattern) throws IOException {
  this.socket=socket;
  InputStream inputStream=socket.getInputStream();
  OutputStream outputStream=socket.getOutputStream();
  BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
  this.scanner=new Scanner(reader);
  this.scanner.useDelimiter(pattern);
  this.writer=new BufferedWriter(new OutputStreamWriter(outputStream));
}
 

Example 6

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/.

Source file: Util.java

  18 
vote

public String capitalize(String string){
  String result="";
  Scanner scn=new Scanner(string);
  while (scn.hasNext()) {
    String next=scn.next();
    result+=Character.toString(next.charAt(0)).toUpperCase();
    for (int i=1; i < next.length(); i++) {
      result+=Character.toString(next.charAt(i));
    }
  }
  return result;
}
 

Example 7

From project boilerpipe_1, under directory /boilerpipe-core/src/.

Source file: boilerpipe.java

  18 
vote

public static void main(String[] args) throws Exception {
  String inputText="";
  Scanner scanner=new Scanner(System.in);
  while (scanner.hasNextLine()) {
    inputText+=scanner.nextLine() + "\n";
  }
  String output=ArticleExtractor.INSTANCE.getText(inputText);
  System.out.println(output);
}
 

Example 8

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/ext/.

Source file: ExtensionRegistry.java

  18 
vote

static List<String> analyzeString(String activities){
  List<String> basicActivities=new ArrayList<String>();
  Scanner scanner=new Scanner(activities);
  scanner.useDelimiter(",");
  while (scanner.hasNext()) {
    basicActivities.add(scanner.next().trim());
  }
  return basicActivities;
}
 

Example 9

From project CircDesigNA, under directory /src/circdesigna/batch/.

Source file: ExtractScoresFromRun.java

  18 
vote

public static void main(String[] args) throws IOException {
  Scanner in=new Scanner(System.in);
  String file=in.nextLine();
  String Domains=readToEnd(in);
  String Molecules=readToEnd(in);
  DomainDefinitions dsd=new DomainDefinitions(new CircDesigNAConfig());
  dsd.readDomainDefs(Domains,dsd);
  DesignMultipleTimes.RunEvaluation(new File(file),Molecules,dsd,-1,false);
}
 

Example 10

From project clustermeister, under directory /cli/src/main/java/com/github/nethad/clustermeister/provisioning/cli/.

Source file: UserInputEvaluation.java

  18 
vote

@VisibleForTesting protected void handleCommand(CommandLineArguments arguments) throws Exception {
  Scanner scanner=arguments.asScanner();
  final String command=scanner.next();
  String fullLine="";
  if (scanner.hasNext()) {
    fullLine=scanner.nextLine();
  }
  if (commands.containsKey(command)) {
    commandMarshalling(command,fullLine);
  }
 else {
    unknownCommand();
  }
}
 

Example 11

From project Core_2, under directory /project-model-maven-tests/src/test/java/org/jboss/forge/maven/facets/.

Source file: JavaExectionFacetTest.java

  18 
vote

@Test public void testExecuteProjectClassWithArguments() throws Exception {
  executionFacet.executeProjectClass("test.TestClass","a","b","c");
  File f=new File(tempFolder + "/test.txt");
  Scanner scanner=new Scanner(f);
  String s=scanner.nextLine();
  assertThat(s,is("a b c"));
  scanner.close();
}
 

Example 12

From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/.

Source file: CramBatch.java

  18 
vote

public static void main(String[] args) throws Exception {
  List<String> sources=new ArrayList<String>();
  if (args.length == 0)   sources.add("cram.options");
 else   sources.add(args[0]);
  for (  String sourceFileName : sources) {
    File optionsFile=new File(sourceFileName);
    InputStream is;
    if (!optionsFile.exists())     is=System.in;
 else     is=new FileInputStream(optionsFile);
    Scanner scanner=new Scanner(is);
    String[] options=scanner.nextLine().split(" ");
    CramTools.main(options);
  }
}
 

Example 13

From project dolphin, under directory /dolphinmaple/test/com/tan/udp/.

Source file: UDPClient.java

  18 
vote

/** 
 * @param args
 * @throws SocketException 
 */
public static void main(String[] args) throws Exception {
  System.out.println("------ Client ------");
  Scanner scanner=new Scanner(System.in);
  String content=scanner.next();
  byte[] buff=content.getBytes();
  DatagramPacket dp=new DatagramPacket(buff,0,buff.length,new InetSocketAddress("127.0.0.1",9999));
  DatagramSocket ds=new DatagramSocket();
  ds.send(dp);
  ds.close();
}
 

Example 14

From project edna-rcp, under directory /org.edna.plugingenerator/src/org/edna/plugingenerator/generator/.

Source file: WizardHelpers.java

  18 
vote

public static void copyAndUpdateFile(IFile input,IFile copy,Map<String,String> substitutionMap,IProgressMonitor monitor) throws CoreException {
  Scanner scanner=new Scanner(input.getContents());
  scanner.useDelimiter("\\A");
  String fileContents=scanner.next();
  for (  String key : substitutionMap.keySet()) {
    fileContents=fileContents.replaceAll(key,substitutionMap.get(key));
  }
  InputStream is=new ByteArrayInputStream(fileContents.getBytes());
  copy.create(is,true,monitor);
}
 

Example 15

From project figgo, under directory /migration_tools/src/main/java/br/figgo/.

Source file: TransformFile.java

  18 
vote

private static void processFile(File file) throws FileNotFoundException {
  Scanner scan=new Scanner(file);
  while (scan.hasNextLine()) {
    lineNumber++;
    String line=scan.nextLine();
    try {
      processLine(line);
    }
 catch (    NoSuchElementException e) {
      System.err.printf("Erro processando arquivo %s:%d - %s\n",file.getName(),lineNumber,line);
    }
  }
}
 

Example 16

From project fire-samples, under directory /cache-demo/src/test/java/demo/vmware/commands/.

Source file: CommandProcessorTest.java

  18 
vote

/** 
 */
@Test public void testScanner(){
  CommandProcessor jig=new CommandProcessor(null);
  assertNotNull(jig);
  InputStream stream=new ByteArrayInputStream("0 cow \"my dog\" cat a-file_name.fake.xml".getBytes());
  Scanner scanJig=jig.createScanner(stream);
  assertEquals("0",jig.getNextToken(scanJig));
  assertEquals("cow",jig.getNextToken(scanJig));
  assertEquals("my dog",jig.getNextToken(scanJig));
  assertEquals("cat",jig.getNextToken(scanJig));
  assertEquals("a-file_name.fake.xml",jig.getNextToken(scanJig));
}
 

Example 17

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/client/utils/.

Source file: URLEncodedUtils.java

  18 
vote

/** 
 * Returns a list of  {@link NameValuePair NameValuePairs} as built from theURI's query portion. For example, a URI of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for b=2, and one for c=3. <p> This is typically useful while parsing an HTTP PUT.
 * @param uri uri to parse
 * @param encoding encoding to use while parsing the query
 */
public static List<NameValuePair> parse(final URI uri,final String encoding){
  final String query=uri.getRawQuery();
  if (query != null && query.length() > 0) {
    List<NameValuePair> result=new ArrayList<NameValuePair>();
    Scanner scanner=new Scanner(query);
    parse(result,scanner,encoding);
    return result;
  }
 else {
    return Collections.emptyList();
  }
}
 

Example 18

From project idea-sbt-plugin, under directory /sbt-plugin/src/test/java/net/orfjackal/sbt/runner/.

Source file: SbtRunnerTester.java

  18 
vote

private static void inputLoop(InputStream source){
  Scanner in=new Scanner(source);
  while (true) {
    String action=in.nextLine();
    if (action.equals("force-exit")) {
      System.exit(1);
    }
    executeAsynchronously(action);
  }
}
 

Example 19

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/index/storage/.

Source file: InMemoryStorage.java

  18 
vote

/** 
 * Allows testing changes to the compression method, it first validates the correctness of the implementation and then lists the compression value and ratio for several document sizes. First argument should be the text to use for texting, it will be clipped to different sizes for ratio testing.
 */
public static void main(String[] args) throws IOException {
  InMemoryStorage ims=new InMemoryStorage(new File(args[0]),true);
  Scanner in=new Scanner(System.in);
  while (in.hasNextLine()) {
    Document document=ims.getDocument(in.nextLine());
    System.out.println(document);
  }
}
 

Example 20

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/qrcode/html/.

Source file: HTMLCreator.java

  18 
vote

private String loadAndAssignFileContents(String fileLocation){
  Scanner fileScanner=new Scanner(getClass().getResourceAsStream(fileLocation));
  StringBuilder sb=new StringBuilder();
  while (fileScanner.hasNextLine()) {
    sb.append(fileScanner.nextLine());
  }
  return sb.toString();
}
 

Example 21

From project isohealth, under directory /isohealth/src/com/isobar/isohealth/.

Source file: OAuthInit.java

  18 
vote

public static void main(String[] args){
  OAuthInit oauthInit=new OAuthInit(GraphConstants.CLIENT_ID,GraphConstants.CLIENT_SECRET,GraphConstants.REDIRECT_URI);
  System.out.println(oauthInit.authorizationUrl());
  System.out.println("\n\nCopy url in browser, Allow the access to account and enter the received access token here:");
  Scanner read=new Scanner(System.in);
  String code=read.next();
  oauthInit.getAccessToken(code);
}
 

Example 22

From project jabox, under directory /jabox-persistence/src/main/java/org/jabox/utils/.

Source file: WebappManager.java

  18 
vote

/** 
 * Reads the data from the file and converts them to List.
 * @param file
 * @return a List of the data of the file.
 * @throws FileNotFoundException
 */
private static List<String> readData(final File file) throws FileNotFoundException {
  List<String> list=new ArrayList<String>();
  Scanner scanner=new Scanner(file);
  while (scanner.hasNextLine()) {
    list.add(scanner.nextLine());
  }
  return list;
}
 

Example 23

From project james, under directory /filesystem-api/src/main/java/org/apache/james/filesystem/api/.

Source file: SieveFileRepository.java

  18 
vote

/** 
 * Read a file with the specified encoding into a String
 * @param file
 * @param encoding
 * @return
 * @throws FileNotFoundException
 */
static protected String toString(File file,String encoding) throws FileNotFoundException {
  String script=null;
  Scanner scanner=null;
  try {
    scanner=new Scanner(file,encoding).useDelimiter("\\A");
    script=scanner.next();
  }
  finally {
    if (null != scanner) {
      scanner.close();
    }
  }
  return script;
}
 

Example 24

From project javagit, under directory /src/main/java/com/logisima/javagit/cli/checkout/.

Source file: GitCheckoutParser.java

  18 
vote

private String extractFileName(String line){
  String filename=null;
  Scanner scanner=new Scanner(line);
  while (scanner.hasNext()) {
    filename=scanner.next();
  }
  return filename;
}
 

Example 25

From project jolda, under directory /src/main/java/vagueobjects/ir/lda/tokens/.

Source file: PlainVocabulary.java

  18 
vote

public PlainVocabulary(String path) throws IOException {
  Scanner scanner=new Scanner(new File(path));
  while (scanner.hasNextLine()) {
    strings.add(scanner.nextLine().trim());
  }
}
 

Example 26

From project JoshEdit, under directory /org/lateralgm/joshedit/.

Source file: Runner.java

  18 
vote

public static String[] splitLines(String text){
  if (text == null)   return null;
  LinkedList<String> list=new LinkedList<String>();
  Scanner sc=new Scanner(text);
  while (sc.hasNext())   list.add(sc.nextLine());
  return list.toArray(new String[0]);
}
 

Example 27

From project joshua, under directory /src/joshua/ui/hypergraph_visualizer/.

Source file: Browser.java

  18 
vote

private static ArrayList<String> populateListFromFile(String filename) throws IOException {
  ArrayList<String> retValue=new ArrayList<String>();
  Scanner fileScanner=new Scanner(new File(filename));
  while (fileScanner.hasNextLine()) {
    retValue.add(fileScanner.nextLine());
  }
  return retValue;
}
 

Example 28

From project jsecurity, under directory /core/src/main/java/org/apache/ki/io/.

Source file: TextResource.java

  18 
vote

protected void doLoad(BufferedReader reader){
  Scanner s=new Scanner(reader);
  try {
    load(s);
  }
  finally {
    s.close();
  }
}
 

Example 29

From project Kairos, under directory /src/java/org/apache/nutch/kairos/crf/.

Source file: ConditionalRandomFieldSingleton.java

  18 
vote

public static void main(String[] args){
  ConditionalRandomFieldSingleton crf=ConditionalRandomFieldSingleton.getInstance();
  System.out.println("Train and create the conditional random field model");
  crf.training();
  System.out.println();
  System.out.println("Do you like to evaluate the trained conditional random field now? (y/n)");
  Scanner in=new Scanner(System.in);
  String answer=in.nextLine();
  answer=answer.trim().toLowerCase();
  if (answer.length() >= 0 && answer.charAt(0) == 'y') {
    crf.evaluate();
  }
}
 

Example 30

From project activejdbc, under directory /examples/activejdbc-cluster-test/src/main/java/activejdbc_test/.

Source file: ClusterTest.java

  17 
vote

public void work(){
  Scanner s=new Scanner(System.in);
  print("Hint: commands are: 'i' for insert, 's' for select");
  System.out.print("command$ ");
  while (s.hasNext()) {
    String command=s.next();
    if (!command.equalsIgnoreCase("i") && !command.equalsIgnoreCase("s")) {
      print("wrong command, use 's' or 'i'");
    }
 else     if (command.equalsIgnoreCase("i")) {
      insert();
    }
 else {
      select();
    }
    System.out.print("$ ");
  }
}
 

Example 31

From project activemq-apollo, under directory /apollo-distro/src/main/release/examples/openwire/jms-example-transaction/src/main/java/example/transaction/.

Source file: Client.java

  17 
vote

private static void acceptInputFromUser(Session senderSession,MessageProducer sender) throws JMSException {
  System.out.println("Type a message. Type COMMIT to send to receiver, type ROLLBACK to cancel");
  Scanner inputReader=new Scanner(System.in);
  while (true) {
    String line=inputReader.nextLine();
    if (line == null) {
      System.out.println("Done!");
      break;
    }
 else     if (line.length() > 0) {
      if (line.trim().equals("ROLLBACK")) {
        System.out.println("Rolling back...");
        senderSession.rollback();
        System.out.println("Messages have been rolledback");
      }
 else       if (line.trim().equals("COMMIT")) {
        System.out.println("Committing... ");
        senderSession.commit();
        System.out.println("Messages should have been sent");
      }
 else {
        TextMessage message=senderSession.createTextMessage();
        message.setText(line);
        System.out.println("Batching up:'" + message.getText() + "'");
        sender.send(message);
      }
    }
  }
}
 

Example 32

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/util/.

Source file: UriUtility.java

  17 
vote

/** 
 * Parses the parameters from the given url query string. When no encoding is passed, default UTF-8 is used. Based on the implementation in Commons httpclient UrlEncodedUtils.
 */
public static Map<String,String> parseQueryParameters(String queryString,String encoding){
  Map<String,String> parameters=new LinkedHashMap<String,String>();
  if (queryString != null) {
    if (queryString.startsWith(QUERY_STRING_SEPARATOR)) {
      queryString=queryString.substring(1);
    }
    Scanner scanner=new Scanner(queryString);
    scanner.useDelimiter(PARAMETER_SEPARATOR);
    while (scanner.hasNext()) {
      final String[] nameValue=scanner.next().split(NAME_VALUE_SEPARATOR);
      if (nameValue.length == 0 || nameValue.length > 2)       throw new IllegalArgumentException("bad parameter");
      final String name=decode(nameValue[0],encoding);
      String value=null;
      if (nameValue.length == 2) {
        value=decode(nameValue[1],encoding);
      }
      parameters.put(name,value);
    }
  }
  return parameters;
}
 

Example 33

From project alljoyn_java, under directory /samples/java/JavaSDKDoc/JavaSDKDocSecurityLogonClient/src/org/alljoyn/bus/samples/.

Source file: Client.java

  17 
vote

public boolean requested(String mechanism,String peerName,int count,String userName,AuthRequest[] requests){
  System.out.println(String.format("AuthListener.requested(%s, %s, %d, %s, %s);",mechanism,peerName,count,userName,AuthRequestsToString(requests)));
  PasswordRequest passwordRequest=null;
  UserNameRequest userNameRequest=null;
  for (  AuthRequest request : requests) {
    if (request instanceof PasswordRequest) {
      passwordRequest=(PasswordRequest)request;
    }
 else     if (request instanceof UserNameRequest) {
      userNameRequest=(UserNameRequest)request;
    }
  }
  if (count <= 3) {
    System.out.print("Please enter user name [user1]: ");
    Scanner in=new Scanner(System.in);
    String user=in.nextLine();
    if (user != null && user.length() == 0) {
      user="user1";
    }
    System.out.print("Please enter password [password1]: ");
    String password=in.nextLine();
    if (user != null && password.length() == 0) {
      password="password1";
    }
    userNameRequest.setUserName(user);
    passwordRequest.setPassword(password.toCharArray());
    return true;
  }
  return false;
}
 

Example 34

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/client/utils/.

Source file: URLEncodedUtils.java

  17 
vote

/** 
 * Returns a list of  {@link NameValuePair NameValuePairs} as built from theURI's query portion. For example, a URI of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for b=2, and one for c=3. <p> This is typically useful while parsing an HTTP PUT.
 * @param uri uri to parse
 * @param encoding encoding to use while parsing the query
 */
public static List<NameValuePair> parse(final URI uri,final String encoding){
  List<NameValuePair> result=Collections.emptyList();
  final String query=uri.getRawQuery();
  if (query != null && query.length() > 0) {
    result=new ArrayList<NameValuePair>();
    parse(result,new Scanner(query),encoding);
  }
  return result;
}
 

Example 35

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/.

Source file: Utils.java

  17 
vote

public boolean readToken(String inputToken){
  File file=new File("plugins/AuthMe/passpartu.token");
  if (!file.exists())   return false;
  if (inputToken.isEmpty())   return false;
  Scanner reader=null;
  try {
    reader=new Scanner(file);
    while (reader.hasNextLine()) {
      final String line=reader.nextLine();
      if (line.contains(":")) {
        String[] tokenInfo=line.split(":");
        if (tokenInfo[0].equals(inputToken) && System.currentTimeMillis() / 1000 - 30 <= Integer.parseInt(tokenInfo[1])) {
          file.delete();
          reader.close();
          return true;
        }
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  reader.close();
  return false;
}
 

Example 36

From project BazaarUtils, under directory /src/com/congenialmobile/utils/.

Source file: BazaarUtils.java

  17 
vote

/** 
 * @param packageName
 * @return versionCode of the latest version on Bazaar, or -1 if not found
 * @throws IOException
 */
public static long getLatestVersionCodeOnBazaar(String packageName) throws IOException {
  URL url=new URL(URLPREFIX_CAFEBAZAAR_VERSION + URLEncoder.encode(packageName));
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setConnectTimeout(20000);
  connection.setReadTimeout(20000);
  connection.addRequestProperty("Cache-Control","no-cache,max-age=0");
  connection.addRequestProperty("Pragma","no-cache");
  int responseCode=connection.getResponseCode();
  if (responseCode == HttpURLConnection.HTTP_OK) {
    InputStream is=connection.getInputStream();
    Scanner sc=new Scanner(is);
    return sc.nextLong();
  }
 else {
    if (DEBUG_BAZAARUTILS)     Log.w(TAG,"HTTPError for " + packageName + ": "+ responseCode);
  }
  return -1;
}
 

Example 37

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/ea2/client/.

Source file: EvaluationStarter.java

  17 
vote

public String run(String input){
  String result="";
  try {
    Process process=evaluatorBuilder.start();
    OutputStream outStream=process.getOutputStream();
    outStream.write(input.getBytes());
    outStream.close();
    InputStream inStream=process.getInputStream();
    Scanner inScanner=new Scanner(inStream);
    process.waitFor();
    while (inScanner.hasNextLine()) {
      result+=inScanner.nextLine().replaceAll("[\n\r]","") + "\n";
    }
    return result;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
  }
  return null;
}
 

Example 38

From project camel-beanstalk, under directory /src/main/java/com/osinka/camel/beanstalk/.

Source file: ConnectionSettings.java

  17 
vote

public ConnectionSettings(final String host,final int port,final String tube){
  this.host=host;
  this.port=port;
  final Scanner scanner=new Scanner(tube);
  scanner.useDelimiter("\\+");
  final ArrayList<String> buffer=new ArrayList<String>();
  while (scanner.hasNext()) {
    final String tubeRaw=scanner.next();
    try {
      buffer.add(URLDecoder.decode(tubeRaw,"UTF-8"));
    }
 catch (    UnsupportedEncodingException e) {
      buffer.add(tubeRaw);
    }
  }
  this.tubes=buffer.toArray(new String[0]);
  scanner.close();
}
 

Example 39

From project cascading, under directory /src/core/cascading/tuple/.

Source file: Tuple.java

  17 
vote

/** 
 * Method parse will parse the  {@link #print()} String representation of a Tuple instance and return a new Tuple instance.<p/> This method has been deprecated as it doesn't properly handle nulls, and any types other than primitive types.
 * @param string of type String
 * @return Tuple
 * @deprecated
 */
@Deprecated public static Tuple parse(String string){
  if (string == null || string.length() == 0)   return null;
  string=string.replaceAll("^ *\\[*","");
  string=string.replaceAll("\\]* *$","");
  Scanner scanner=new Scanner(new StringReader(string));
  scanner.useDelimiter("(' *, *')|(^ *')|(' *$)");
  Tuple result=new Tuple();
  while (scanner.hasNext()) {
    if (scanner.hasNextInt())     result.add(scanner.nextInt());
 else     if (scanner.hasNextDouble())     result.add(scanner.nextDouble());
 else     result.add(scanner.next());
  }
  scanner.close();
  return result;
}
 

Example 40

From project CIShell, under directory /testing/org.cishell.testing.convertertester.commandline/src/org/cishell/testing/convertertester/commandline/.

Source file: Activator.java

  17 
vote

public void startCommandLine(){
  Scanner in=new Scanner(System.in);
  while (true) {
    System.out.println("Welcome to NWB's Converter Tester");
    System.out.println("Please enter the name of a configuration " + "file or\n a directory of configuration files (" + QUIT + ") to quit): ");
    String s=in.nextLine();
    if (s.trim().equalsIgnoreCase(QUIT))     break;
    try {
      configFile=new File(s);
      processConfigurationFile(configFile);
    }
 catch (    NullPointerException ex) {
      System.out.println("Invalid file name");
      ;
    }
catch (    FileNotFoundException fnfe) {
      System.out.println("Could not find the specified " + "configuration file");
    }
  }
}
 

Example 41

From project clojure-maven-plugin, under directory /src/main/java/com/theoryinpractise/clojure/.

Source file: NamespaceDiscovery.java

  17 
vote

private List<NamespaceInFile> findNamespaceInFile(File path,File file) throws MojoExecutionException {
  List<NamespaceInFile> namespaces=new ArrayList<NamespaceInFile>();
  Scanner scanner=null;
  try {
    scanner=new Scanner(file);
    scanner.useDelimiter("\n");
    while (scanner.hasNext()) {
      String line=scanner.next();
      Matcher matcher=nsPattern.matcher(line);
      if (matcher.find()) {
        String ns=file.getPath();
        ns=ns.substring(path.getPath().length() + 1,ns.length() - ".clj".length());
        ns=ns.replace(File.separatorChar,'.');
        ns=ns.replace('_','-');
        log.debug("Found namespace " + ns + " in file "+ file.getPath());
        namespaces.add(new NamespaceInFile(ns,file));
      }
    }
  }
 catch (  FileNotFoundException e) {
    throw new MojoExecutionException(e.getMessage());
  }
  return namespaces;
}
 

Example 42

From project cogroo4, under directory /cogroo-ann/src/main/java/org/cogroo/.

Source file: CLI.java

  17 
vote

/** 
 * @param args the language to be used, "pt_BR" by default
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws FileNotFoundException {
  long start=System.nanoTime();
  if (args.length != 1) {
    System.err.println("Language is missing! usage: CLI pt_br");
    return;
  }
  ComponentFactory factory=ComponentFactory.create(new Locale("pt","BR"));
  AnalyzerI pipe=factory.createPipe();
  System.out.println("Loading time [" + ((System.nanoTime() - start) / 1000000) + "ms]");
  Scanner kb=new Scanner(System.in);
  System.out.print("Enter the sentence: ");
  String input=kb.nextLine();
  while (!input.equals("q")) {
    if (input.equals("0")) {
      input="Fomos levados ? crer que os menino s?o burro de doer. As menina chegaram.";
    }
    Document document=new DocumentImpl();
    document.setText(input);
    pipe.analyze(document);
    System.out.println(TextUtils.nicePrint(document));
    System.out.print("Enter the sentence: ");
    input=kb.nextLine();
  }
}
 

Example 43

From project cotopaxi-core, under directory /src/main/java/br/octahedron/cotopaxi/config/.

Source file: ConfigurationParser.java

  17 
vote

/** 
 * @return
 */
private String getFromLine(){
  if (this.lineScanner == null || !this.lineScanner.hasNext()) {
    String line;
    do {
      line=this.inScanner.nextLine().trim();
    }
 while (line.startsWith("#") || line.isEmpty());
    this.lineScanner=new Scanner(line);
  }
  return this.lineScanner.next();
}
 

Example 44

From project cpp-maven-plugins, under directory /cpp-compiler-maven-plugin/src/main/java/com/ericsson/tools/cpp/compiler/compilation/gcc/.

Source file: GccIncludesAnalyzer.java

  17 
vote

@Override public List<File> getIncludedFiles(final NativeCodeFile ncf) throws MojoExecutionException {
  final List<File> includedFiles=new ArrayList<File>();
  try {
    Scanner scan=new Scanner(ncf.getDependFile());
    scan.useDelimiter("\\Z");
    for (    String path : scan.next().split(" ")) {
      if (path.isEmpty())       continue;
      if (path.startsWith("\\"))       continue;
      if (path.equals(ncf.getSourceFile().getName()))       continue;
      if (path.equals(ncf.getObjectFile().getName() + ":"))       continue;
      includedFiles.add(findIncludedFile(ncf,path));
    }
  }
 catch (  FileNotFoundException e) {
    throw new MojoExecutionException("Could not open depend file.",e);
  }
  return includedFiles;
}
 

Example 45

From project crest, under directory /sample/src/main/java/org/codegist/crest/flickr/security/.

Source file: MultiPartEntityParamExtractor.java

  17 
vote

public List<EncodedPair> extract(String contentType,Charset charset,InputStream entity) throws IOException {
  String boundary=getBoundary(contentType);
  BufferedReader reader=new BufferedReader(new InputStreamReader(entity,charset));
  Scanner partsScanner=new Scanner(reader).useDelimiter(Pattern.quote(boundary));
  List<EncodedPair> pairs=new ArrayList<EncodedPair>();
  while (partsScanner.hasNext()) {
    String part=partsScanner.next();
    Matcher m=PARAM_PATTERN.matcher(part);
    if (m.find()) {
      if ("text/plain".equals(m.group(2))) {
        pairs.add(toPreEncodedPair(m.group(1),m.group(3)));
      }
    }
  }
  return pairs;
}
 

Example 46

From project fanfoudroid, under directory /src/eriji/com/oauth/.

Source file: OAuthHelper.java

  17 
vote

public static void main(String arg[]) throws Exception {
  Weibo api=new Weibo();
  OAuthClient oauth=api.getHttpClient().getOAuthClient();
  oauth.setStore(new OAuthFileStore("/sdcard/fanfoudroid/"));
  try {
    if (!oauth.hasAccessToken()) {
      String authUrl=oauth.retrieveRequestToken();
      Log.i("LDS","???????????????, ????????????, ?????inCode : " + authUrl);
      System.out.println("?????inCode:");
      Scanner in=new Scanner(System.in);
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 47

From project Flapi, under directory /src/test/java/unquietcode/tools/flapi/.

Source file: ActualDescriptorTest.java

  17 
vote

public void generateAndRetrieve() throws Exception {
  MainDescriptor.main(new String[]{getTemporaryFolder()});
  String print[]={"DescriptorGenerator"};
  for (  String name : print) {
    String path=getTemporaryFolder();
    path+="/unquietcode/tools/flapi/builder/" + name + ".java";
    File file=new File(path);
    Scanner scanner=new Scanner(file);
    String text=scanner.useDelimiter("\\A").next();
    System.out.println(name + ":");
    System.out.println("---------------------------------");
    System.out.println(text);
    System.out.println("\n\n");
  }
}
 

Example 48

From project frascati-studio-social, under directory /src/org/apache/commons/codec/language/bm/.

Source file: Languages.java

  17 
vote

public static Languages getInstance(String languagesResourceName){
  Set<String> ls=new HashSet<String>();
  InputStream langIS=Languages.class.getClassLoader().getResourceAsStream(languagesResourceName);
  if (langIS == null) {
    throw new IllegalArgumentException("Unable to resolve required resource: " + languagesResourceName);
  }
  Scanner lsScanner=new Scanner(langIS,ResourceConstants.ENCODING);
  boolean inExtendedComment=false;
  while (lsScanner.hasNextLine()) {
    String line=lsScanner.nextLine().trim();
    if (inExtendedComment) {
      if (line.endsWith(ResourceConstants.EXT_CMT_END)) {
        inExtendedComment=false;
      }
 else {
      }
    }
 else {
      if (line.startsWith(ResourceConstants.EXT_CMT_START)) {
        inExtendedComment=true;
      }
 else       if (line.length() > 0) {
        ls.add(line);
      }
 else {
      }
    }
  }
  return new Languages(Collections.unmodifiableSet(ls));
}
 

Example 49

From project g414-hash, under directory /src/main/java/com/g414/hash/cmd/.

Source file: ckblm.java

  17 
vote

public static void main(String[] args) throws Exception {
  LinkedList<String> theArgs=new LinkedList<String>();
  theArgs.addAll(Arrays.asList(args));
  log.info("loading...");
  ObjectInputStream in=new ObjectInputStream(new FileInputStream(theArgs.removeFirst()));
  FilterState state=(FilterState)in.readObject();
  in.close();
  BloomFilter bloom=new BloomFilter(state);
  boolean reverse=Boolean.valueOf(System.getProperty("reverse","false"));
  boolean lower=Boolean.valueOf(System.getProperty("lower","false"));
  long j=0;
  for (  String file : theArgs) {
    log.info("processing: " + file);
    Scanner x=new Scanner(new File(file));
    long i=0;
    while (x.hasNextLine()) {
      String m=x.nextLine();
      if (lower) {
        m=m.toLowerCase();
      }
      boolean hasEntry=bloom.contains(m);
      if (hasEntry == reverse) {
        System.out.println(m);
      }
      if (i % 100000 == 0) {
        log.info(file + " : " + i+ " "+ j+ " "+ m);
      }
      i+=1;
    }
  }
  log.info("done.");
}
 

Example 50

From project galaxy, under directory /src/co/paralleluniverse/galaxy/jgroups/.

Source file: ReplicatedTree.java

  17 
vote

private Node findNode(String fqn,boolean create,Address ephemeral){
  if (fqn == null || fqn.equals(SSEPARATOR) || "".equals(fqn))   return root;
  final Scanner scanner=new Scanner(fqn).useDelimiter(SSEPARATOR);
  Node curr=root;
  while (scanner.hasNext()) {
    final String name=scanner.next();
    Node node=curr.getChild(name);
    if (create) {
      if (node == null) {
        LOG.debug("Creating node {}",curr.fqn + (!curr.fqn.equals(SSEPARATOR) ? SEPARATOR : "") + name);
        node=curr.createChild(name,ephemeral,null,pendingListeners);
      }
 else {
        if (node.getEphemeralAddress() != null) {
          if (ephemeral == null) {
            LOG.debug("Making node {} non-ephemeral.",node.fqn);
            node.setNotEphemeral();
          }
 else           if (!ephemeral.equals(node.getEphemeralAddress())) {
            LOG.info("Node {} ephemeral conflict {} vs {} - making non-ephemeral.",new Object[]{node.fqn,node.getEphemeralAddress(),ephemeral});
            node.setNotEphemeral();
          }
        }
      }
    }
    if (node == null)     return null;
 else     curr=node;
  }
  return curr;
}
 

Example 51

From project gast-lib, under directory /app/src/root/gast/playground/sensor/altitude/.

Source file: DetermineAltitudeActivity.java

  17 
vote

@Override protected Float doInBackground(Number... params){
  Float mslp=null;
  HttpURLConnection urlConnection=null;
  try {
    Uri uri=Uri.parse(WS_URL).buildUpon().appendQueryParameter("lat",String.valueOf(params[0])).appendQueryParameter("lng",String.valueOf(params[1])).build();
    URL url=new URL(uri.toString());
    urlConnection=(HttpURLConnection)url.openConnection();
    InputStream inputStream=new BufferedInputStream(urlConnection.getInputStream());
    Scanner inputStreamScanner=new Scanner(inputStream).useDelimiter("\\A");
    String response=inputStreamScanner.next();
    inputStreamScanner.close();
    Log.d(TAG,"Web Service Response -> " + response);
    JSONObject json=new JSONObject(response);
    String observation=json.getJSONObject("weatherObservation").getString("observation");
    String[] values=observation.split("\\s");
    String slpString=null;
    for (int i=1; i < values.length; i++) {
      String value=values[i];
      if (value.startsWith(SLP_STRING.toLowerCase()) || value.startsWith(SLP_STRING.toUpperCase())) {
        slpString=value.substring(SLP_STRING.length());
        break;
      }
    }
    StringBuffer sb=new StringBuffer(slpString);
    sb.insert(sb.length() - 1,".");
    float val1=Float.parseFloat("10" + sb);
    float val2=Float.parseFloat("09" + sb);
    mslp=(Math.abs((1000 - val1)) < Math.abs((1000 - val2))) ? val1 : val2;
  }
 catch (  Exception e) {
    Log.e(TAG,"Could not communicate with web service",e);
  }
 finally {
    if (urlConnection != null) {
      urlConnection.disconnect();
    }
  }
  return mslp;
}
 

Example 52

From project genobyte, under directory /genobyte-hapmap/src/main/java/ca/mcgill/genome/hapmap/.

Source file: HapMapGenotypeFileParser.java

  17 
vote

private void parseHeader() throws IOException {
  String header[]={"rs#","SNPalleles","chrom","pos","strand","genome_build","center","protLSID","assayLSID","panelLSID","QC_code"};
  LineNumberReader lnr=new LineNumberReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file_))));
  Scanner lineScanner=new Scanner(lnr.readLine());
  int h=0;
  while (lineScanner.hasNext()) {
    String value=lineScanner.next();
    if (value.equals(header[h]) == false) {
      throw new IllegalStateException("Cannot parse HapMap file=[" + file_.getName() + "]: invalid header. Expected ["+ header[h]+ "] parsed ["+ value+ "]");
    }
    if (++h == header.length) {
      break;
    }
  }
  while (lineScanner.hasNext()) {
    sampleNames_.add(lineScanner.next());
  }
  while (lnr.readLine() != null) {
    assayCount_++;
  }
}
 

Example 53

From project geolatte-mapserver, under directory /src/main/java/org/geolatte/mapserver/wms/.

Source file: WMSRequest.java

  17 
vote

private static Envelope convertToEnvelope(String strVal) throws InvalidWMSRequestException {
  Scanner scanner=new Scanner(strVal);
  scanner.useDelimiter(",");
  double[] xyvals=new double[4];
  int i=0;
  try {
    while (scanner.hasNext()) {
      xyvals[i++]=Double.valueOf(scanner.next());
    }
  }
 catch (  NumberFormatException e) {
    throw new InvalidWMSRequestException(String.format("Invalid Boundingbox: %s",strVal));
  }
catch (  IndexOutOfBoundsException e) {
    throw new InvalidWMSRequestException(String.format("Invalid Boundingbox: %s",strVal));
  }
  Envelope result=new Envelope(xyvals[0],xyvals[1],xyvals[2],xyvals[3],null);
  if (result.isEmpty()) {
    throw new InvalidWMSRequestException("Empty or invalid bounding box.");
  }
  return result;
}
 

Example 54

From project GraphLab, under directory /src/graphlab/extensions/io/.

Source file: LoadNetGraph.java

  17 
vote

public GraphModel read(File file) throws GraphIOException {
  try {
    Scanner sc=new Scanner(file);
    String _, s="";
    String l=sc.next();
    if (!l.contains("ertices"))     throw new GraphIOException("Incorrect Format(in the first line)");
    int n=sc.nextInt();
    sc.nextLine();
    GraphModel g=new GraphModel(false);
    ArrayList<Vertex> V=new ArrayList<Vertex>(n);
    for (int i=0; i < n; i++) {
      Vertex curv=new Vertex();
      l=sc.nextLine();
      int start=l.indexOf('"');
      int end=l.indexOf('"',start + 1);
      curv.setLabel(l.substring(start + 1,end));
      l=l.substring(end + 1);
      Scanner ss=new Scanner(l);
      if (ss.hasNextDouble())       curv.setLocation(new GraphPoint(ss.nextDouble(),ss.nextDouble()));
      V.add(curv);
    }
    g.insertVertices(V);
    l=sc.next();
    if (!l.contains("dges"))     throw new GraphIOException("Incorrect Format(in the first line)");
    ArrayList<Edge> E=new ArrayList<Edge>();
    while (sc.hasNext()) {
      Vertex src=V.get(sc.nextInt() - 1);
      Vertex trg=V.get(sc.nextInt() - 1);
      Edge cure=new Edge(src,trg);
      cure.setWeight(sc.nextInt());
      E.add(cure);
    }
    g.insertEdges(E);
    return g;
  }
 catch (  IOException e) {
    throw new GraphIOException(e.getMessage());
  }
}
 

Example 55

From project guvnorng, under directory /guvnorng-showcase/src/main/java/org/drools/guvnor/server/util/.

Source file: DroolsHeader.java

  17 
vote

public static String getPackageHeaderImports(String packageHeader){
  final StringBuilder drl=new StringBuilder();
  Scanner scanner=new Scanner(packageHeader);
  try {
    while (scanner.hasNextLine()) {
      final String line=scanner.nextLine();
      if (isImport(line)) {
        drl.append(line).append(NL);
      }
    }
  }
  finally {
    scanner.close();
  }
  return drl.toString();
}
 

Example 56

From project Hackathon_Chutaum, under directory /src/br/com/chutaum/servlet/.

Source file: UploadPolitician.java

  17 
vote

public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
  Map<String,BlobKey> blobs=blobstoreService.getUploadedBlobs(req);
  BlobKey blobKey=blobs.get("myFile");
  Scanner data=new Scanner(new String(blobstoreService.fetchData(blobKey,0,1015807),"UTF8"));
  if (blobKey == null) {
    res.sendRedirect("/");
  }
 else {
    data.nextLine();
    while (data.hasNextLine()) {
      String line=data.nextLine();
      com.google.appengine.api.taskqueue.Queue queue=QueueFactory.getQueue("PoliticianQueue");
      TaskOptions taskOptions=TaskOptions.Builder.withUrl("/politician-queue").param("politician",line).method(Method.POST).header("Host",BackendServiceFactory.getBackendService().getBackendAddress("action-backend"));
      queue.add(taskOptions);
    }
  }
}
 

Example 57

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/main/java/org/isatools/isatab/export/sra/.

Source file: SRAXMLSchemaInjector.java

  17 
vote

public static File addNameSpaceToFile(File originalFile,String namespace,String openingXMLTag){
  if (originalFile != null) {
    PrintStream outputStream=null;
    if (originalFile.exists()) {
      try {
        File newFile=getNewFileName(originalFile);
        outputStream=new PrintStream(newFile);
        Scanner originalFileScanner=new Scanner(originalFile);
        String line;
        outputStream.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        while (originalFileScanner.hasNextLine()) {
          line=originalFileScanner.nextLine();
          if (line.contains(openingXMLTag) && openingXMLTag.contains(">")) {
            line=openingXMLTag.substring(0,openingXMLTag.indexOf(">")) + (line.contains("xmlns:xsi") ? " " : " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ") + STD_SRA_NAMESPACE+ namespace+ "\">";
          }
 else           if (line.contains(openingXMLTag) && openingXMLTag.contains("alias")) {
            String insertnamespace="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + STD_SRA_NAMESPACE + namespace+ "\""+ " alias";
            line=line.replaceFirst("alias",insertnamespace);
          }
 else           if (line.contains(openingXMLTag) && openingXMLTag.contains("center_name")) {
            String insertnamespace="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + STD_SRA_NAMESPACE + namespace+ "\""+ " center_name";
            line=line.replaceFirst("center_name",insertnamespace);
          }
          outputStream.println(line);
        }
        return newFile;
      }
 catch (      FileNotFoundException e) {
        e.printStackTrace();
      }
 finally {
        if (outputStream != null) {
          outputStream.flush();
          outputStream.close();
        }
      }
    }
  }
  return null;
}
 

Example 58

From project Java3DTest, under directory /Java3D/src/.

Source file: Logger.java

  17 
vote

public void readFile(){
  try {
    File file=new File(getFilename());
    Scanner scanner=new Scanner(file);
    String log="";
    while (scanner.hasNextLine()) {
      log+=scanner.nextLine() + "\n";
    }
    scanner.close();
    this.log=log + getLog();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
}
 

Example 59

From project JavaChat, under directory /ChatServer/src/Core/.

Source file: Config.java

  17 
vote

public static void loadConfig() throws Exception {
  config=new Properties();
  System.out.printf("Begin to load config.\n");
  Scanner scanner=new Scanner(new File("config.conf"));
  while (scanner.hasNextLine()) {
    String line=scanner.nextLine().trim();
    if (line.startsWith("#") || line.equals(""))     continue;
    if (!line.contains("=")) {
      System.out.printf("An error occur while reading config file!\n");
      System.exit(0);
    }
    String key=line.substring(0,line.indexOf("=")).trim();
    String value=line.substring(line.indexOf("=") + 1).trim().replace("\"","");
    config.setProperty(key,value);
  }
  System.out.printf("Config loaded successfully.\n");
}
 

Example 60

From project JGAAP, under directory /src/com/jgaap/classifiers/.

Source file: VectorOutputAnalysis.java

  17 
vote

public void train(List<EventSet> knowns) throws AnalyzeException {
  key=new ArrayList<Event>();
  String keyFile=JGAAPConstants.JGAAP_LIBDIR + "l1.key";
  Scanner input;
  try {
    input=new Scanner(new File(keyFile));
  }
 catch (  FileNotFoundException e) {
    throw new AnalyzeException("Problem Opening Key file");
  }
  while (input.hasNextLine()) {
    key.add(new Event(input.nextLine()));
  }
  input.close();
}
 

Example 61

From project jOryx_1, under directory /src/com/oryxhatesjava/xml/.

Source file: Char.java

  17 
vote

public void parseElement(Element e){
  if (!e.getName().equals("Char")) {
    return;
  }
  id=Integer.parseInt(e.getAttributeValue("id"));
  objectType=Integer.parseInt(e.getChildText("ObjectType"));
  level=Integer.parseInt(e.getChildText("Level"));
  exp=Integer.parseInt(e.getChildText("Exp"));
  currentFame=Integer.parseInt(e.getChildText("CurrentFame"));
  equipment=new int[12];
  Scanner scan=new Scanner(e.getChildText("Equipment"));
  scan.useDelimiter(",");
  for (int i=0; i < 12; i++) {
    equipment[i]=scan.nextInt();
  }
  maxHP=Integer.parseInt(e.getChildText("MaxHitPoints"));
  HP=Integer.parseInt(e.getChildText("HitPoints"));
  maxMP=Integer.parseInt(e.getChildText("MaxMagicPoints"));
  MP=Integer.parseInt(e.getChildText("MagicPoints"));
  att=Integer.parseInt(e.getChildText("Attack"));
  def=Integer.parseInt(e.getChildText("Defense"));
  spd=Integer.parseInt(e.getChildText("Speed"));
  dex=Integer.parseInt(e.getChildText("Dexterity"));
  vit=Integer.parseInt(e.getChildText("HpRegen"));
  wis=Integer.parseInt(e.getChildText("MpRegen"));
  pcStats=e.getChildText("PCStats");
  dead=Boolean.parseBoolean(e.getChildText("Dead"));
  pet=Integer.parseInt(e.getChildText("Pet"));
  if (e.getChild("Account") != null) {
    accountName=e.getChild("Account").getChildText("Name");
  }
}
 

Example 62

From project jPOS-EE, under directory /modules/sshd/src/main/java/org/jpos/ee/cli/.

Source file: AuthorizedKeysFileBasedPKA.java

  17 
vote

protected List<PublicKey> parseAuthorizedKeys() throws Exception {
  List<PublicKey> authorizedKeys=new ArrayList<PublicKey>();
  AuthorizedKeysDecoder decoder=new AuthorizedKeysDecoder();
  File file=new File(filename);
  Scanner scanner=null;
  try {
    scanner=new Scanner(file).useDelimiter("\n");
    while (scanner.hasNext()) {
      final PublicKey publicKey=decoder.decodePublicKey(scanner.next());
      authorizedKeys.add(publicKey);
    }
  }
  finally {
    if (scanner != null) {
      scanner.close();
    }
  }
  return authorizedKeys;
}
 

Example 63

From project karaf, under directory /instance/core/src/main/java/org/apache/karaf/instance/core/internal/.

Source file: InstanceServiceImpl.java

  17 
vote

private void copyResourceToDir(File target,String resource,boolean printOutput) throws Exception {
  File outFile=new File(target,resource);
  if (outFile.exists()) {
    return;
  }
  logInfo("Creating file: %s",printOutput,outFile.getPath());
  String sourcePath="org/apache/karaf/instance/resources/" + resource;
  InputStream is=getClass().getClassLoader().getResourceAsStream(sourcePath);
  if (is == null) {
    throw new IOException("Unable to find resource " + sourcePath + " on classpath");
  }
  try {
    PrintStream out=new PrintStream(new FileOutputStream(outFile));
    try {
      Scanner scanner=new Scanner(is);
      while (scanner.hasNextLine()) {
        String line=scanner.nextLine();
        out.println(line);
      }
    }
  finally {
      safeClose(out);
    }
  }
  finally {
    safeClose(is);
  }
}
 

Example 64

From project kernel_1, under directory /exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/.

Source file: MimeTypeResolver.java

  17 
vote

public MimeTypeResolver(){
  try {
    SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Void>(){
      public Void run() throws Exception {
        Scanner scanner=null;
        String mimeTypeProperties=System.getProperty("org.exoplatform.mimetypes");
        if (mimeTypeProperties != null) {
          InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream(mimeTypeProperties);
          if (stream != null) {
            scanner=new Scanner(stream,"ISO-8859-1");
          }
        }
        if (scanner == null) {
          scanner=new Scanner(getClass().getResourceAsStream("mimetypes.properties"),"ISO-8859-1");
        }
        try {
          while (scanner.hasNextLine()) {
            processLine(scanner.nextLine());
          }
        }
  finally {
          scanner.close();
        }
        return null;
      }
    }
);
  }
 catch (  IOException e) {
    throw new InternalError("Unable to load mimetypes: " + e.toString());
  }
}
 

Example 65

From project arquillian-testrunner-spock, under directory /container/src/test/java/org/jboss/arquillian/spock/container/.

Source file: SpockDeploymentAppenderTestCase.java

  16 
vote

private String getResourceContent(Archive<?> archive,ArchivePath path){
  final InputStream openStream=archive.get(path).getAsset().openStream();
  String content="";
  try {
    content=new Scanner(openStream).useDelimiter("\\A").next();
    return content.trim();
  }
  finally {
    try {
      openStream.close();
    }
 catch (    IOException ignore) {
    }
  }
}
 

Example 66

From project Clotho-Core, under directory /ClothoApps/SequenceChecker/src/org/clothocad/tool/sequencechecker/.

Source file: SeqCheckController.java

  16 
vote

protected String fetchConstructSequence(String constructID){
  InputStream inputStream=null;
  URL url=null;
  HttpURLConnection connection=null;
  String seq="";
  if (constructID != null && constructID.length() > 0) {
    try {
      url=new URL(_webServiceBaseUrl + "?id=" + constructID+ "&format=seq");
      inputStream=url.openStream();
      seq=new Scanner(inputStream).useDelimiter("\\A").next();
    }
 catch (    MalformedURLException ex) {
      Exceptions.printStackTrace(ex);
    }
catch (    IOException ex) {
      Exceptions.printStackTrace(ex);
    }
 finally {
      try {
        if (inputStream != null) {
          inputStream.close();
        }
      }
 catch (      IOException ex) {
        Exceptions.printStackTrace(ex);
      }
    }
  }
  return seq;
}
 

Example 67

From project JsonPath, under directory /json-path/src/test/java/com/jayway/jsonpath/util/.

Source file: ScriptEngineJsonPath.java

  16 
vote

private static String readScript(String script){
  InputStream is=null;
  try {
    is=ScriptEngineJsonPath.class.getClassLoader().getSystemResourceAsStream("js/" + script);
    return new Scanner(is).useDelimiter("\\A").next();
  }
  finally {
    if (is != null) {
      try {
        is.close();
      }
 catch (      IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
 

Example 68

From project dimdwarf, under directory /test-utils/src/main/java/net/orfjackal/dimdwarf/testutils/.

Source file: StreamWatcher.java

  15 
vote

private void copyInBackground(final Reader source){
  Thread t=new Thread(new Runnable(){
    public void run(){
      Scanner in=new Scanner(source);
      while (in.hasNextLine()) {
        lines.add(in.nextLine());
      }
      lines.add(END_OF_STREAM);
    }
  }
);
  t.setDaemon(true);
  t.start();
}
 

Example 69

From project idigi-java-monitor-api, under directory /netty/src/main/java/com/idigi/api/monitor/netty/example/.

Source file: NettyMonitorExample.java

  15 
vote

/** 
 * Creates an iDigi monitor client and prints message received to stdout.
 */
public static void main(String[] args) throws IOException {
  if (args.length != 4) {
    System.out.println("usage: " + NettyMonitorExample.class.getName() + " <host> <username> <password> <monitorId>");
    return;
  }
  String host=args[0];
  String username=args[1];
  String password=args[2];
  int monitorId=Integer.parseInt(args[3]);
  MonitorClientFactory service=new SecureNettyMonitorClientFactory(host,username,password);
  MessageListener listener=new MessageListener(){
    @Override public void messageReceived(    Message message){
      Scanner isScanner=new Scanner(message.getPayload());
      while (isScanner.hasNextLine()) {
        System.out.println(isScanner.nextLine());
      }
    }
  }
;
  MonitorClientContext context=service.buildClient(monitorId,listener);
  context.start();
  System.out.println("Press [enter] to quit.");
  System.in.read();
  context.stop();
}
 

Example 70

From project jPOS, under directory /jpos/src/test/java/org/jpos/transaction/.

Source file: PausedTransactionTest.java

  15 
vote

@Test public void testForceAbort() throws Throwable {
  byte[] bytes=new byte[2];
  PausedTransaction pausedTransaction=new PausedTransaction(new TransactionManager(),100L,new Stack(),new Scanner(new ByteArrayInputStream(bytes)),false,new TSpace());
  pausedTransaction.forceAbort();
  assertTrue("pausedTransaction.isAborting()",pausedTransaction.isAborting());
}