Exemplo n.º 1
4
  protected String getRallyXML(String apiUrl) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.addHeader("Authorization", "Basic " + encodeString);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      StringBuilder sb = new StringBuilder();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }

      responseXML = sb.toString();
    }

    log.debug("responseXML=" + responseXML);

    return responseXML;
  }
Exemplo n.º 2
0
 @Override
 public void actionPerformed(ActionEvent e) {
   JFileChooser f = new JFileChooser();
   f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器
   int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取
   if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔
     BufferedReader br = null;
     try {
       File file = f.getSelectedFile();
       br = new BufferedReader(new FileReader(file));
       TextDocument ta = new TextDocument(file.getName(), file);
       ta.addKeyListener(new SystemTrackSave());
       ta.read(br, null);
       td.add(ta);
       td.setTitleAt(docCount++, file.getName());
     } catch (Exception exc) {
       exc.printStackTrace();
     } finally {
       try {
         br.close();
       } catch (Exception ecx) {
         ecx.printStackTrace();
       }
     }
   }
 }
Exemplo n.º 3
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int a[] = new int[n];
    int c[] = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = Integer.parseInt(br.readLine());
    }

    for (int i = 0; i < n; i++) {
      c[i] = 1;
    }

    for (int j = 1; j < n; j++) {
      if (a[j] > a[j - 1]) c[j] = c[j - 1] + 1;
    }

    for (int k = n - 2; k >= 0; k--) {
      if (a[k] > a[k + 1]) c[k] = Math.max(c[k + 1] + 1, c[k]);
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
      count += c[i];
    }

    System.out.println(count);
  }
Exemplo n.º 4
0
  public static BufferedReader getBufferedReader(String fileName, String context) throws Throwable {
    includeNames.add(fileName);
    if (fileName.startsWith("http://") || fileName.startsWith("https://")) {
      String hashedFileName = MD5(fileName);
      File remoteCacheFile = new File(cacheDirectoryName + File.separator + hashedFileName);
      if (remoteCacheFile.exists()) {
        return new BufferedReader(new FileReader(remoteCacheFile));
      } else {
        URL input = new URL(fileName);
        BufferedReader remoteReader = new BufferedReader(new InputStreamReader(input.openStream()));
        BufferedWriter cacheWriter =
            new BufferedWriter(
                new FileWriter(cacheDirectoryName + File.separator + hashedFileName));

        String tmpLine = remoteReader.readLine();
        while (tmpLine != null) {
          cacheWriter.write(tmpLine);
          cacheWriter.newLine();
          tmpLine = remoteReader.readLine();
        }
        cacheWriter.close();
        return new BufferedReader(
            new FileReader(cacheDirectoryName + File.separator + hashedFileName));
      }
    } else {
      if (fileName.startsWith(context)) {
        return new BufferedReader(new FileReader(fileName));
      } else {
        return new BufferedReader(new FileReader(context + fileName));
      }
    }
  }
Exemplo n.º 5
0
  public static void main(String[] args) throws IOException {

    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
      int a = Integer.parseInt(br.readLine());
      if (a == 0) break;
      HashMap<String, Integer> map = new HashMap<String, Integer>();
      int sum = 0;

      while (a-- > 0) {
        StringTokenizer st = new StringTokenizer(br.readLine());
        int one = Integer.parseInt(st.nextToken()), two = Integer.parseInt(st.nextToken());
        country c = new country(one, two);
        country c_rev = new country(two, one);
        int s = 0;

        if (map.get(c.tostring()) != null) {
          s = map.get(c.tostring()) + 1;
          map.put(c.tostring(), s);
          sum++;
        } else if (map.get(c_rev.tostring()) != null) {
          s = map.get(c_rev.tostring()) - 1;
          map.put(c_rev.tostring(), s);
          sum--;
        } else {
          map.put(c.tostring(), 1);
          sum++;
        }
      }
      if (sum != 0) System.out.println("NO");
      else System.out.println("YES");
    }
  }
Exemplo n.º 6
0
  public static void main(String[] args) {
    String inputStr = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
      while ((inputStr = reader.readLine()) != null) {
        inputStr = inputStr.trim();

        if (DEST_MATCHER.reset(inputStr).matches()) {
          System.out.println("Destination field!\n");
        } else if (SOURCE_MATCHER.reset(inputStr).matches()) {
          System.out.println("Source field!\n");
        } else if (STRING_MATCHER.reset(inputStr).matches()) {
          System.out.println("String literal!\n");
        } else if (VAR_MATCHER.reset(inputStr).matches()) {
          System.out.println("Variable!\n");
        } else if (NUM_MATCHER.reset(inputStr).matches()) {
          System.out.println("Number!\n");
        } else {
          System.out.println("Huh???\n");
        }
      }
    } catch (Exception ioe) {
      System.out.println("Exception: " + ioe.toString());
      ioe.printStackTrace();
    }
  }
  public static void main(String[] args) throws IOException {
    // Get input html
    StringBuffer sb = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    for (String str = in.readLine(); str != null; str = in.readLine()) {
      sb.append("\n" + str);
    }
    String html = sb.toString();

    // Match all the questions
    Matcher matcher =
        Pattern.compile(
                "<\\s*div\\s+class\\s*=\\s*\"question-summary\"\\s*id\\s*=\\s*\"question-summary-(?<id>\\d+)\"\\s*>"
                    + ".*?<\\s*div\\s+class\\s*=\\s*\"summary\"\\s*>"
                    + ".*?<\\s*a\\s+.*?class\\s*=\\s*\"question-hyperlink\"\\s*>"
                    + "(?<title>.*?)"
                    + "</\\s*a\\s*>.*?<\\s*div\\s+class\\s*=\\s*\"user-action-time\"\\s*>"
                    + ".*?<\\s*span\\s+.*?>(?<time>.*?)</\\s*span\\s*>",
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
            .matcher(html);

    // Output the information
    while (matcher.find()) {
      String id = matcher.group("id");
      String title = matcher.group("title");
      String time = matcher.group("time");
      System.out.println(id + ";" + title + ";" + time);
    }
  }
Exemplo n.º 8
0
 /**
  * Get the noun and verb <roots> (i.e. 'the highest' synsets in WordNet) from the particular
  * 'icfile' (Information Content) that you are applying. Store a noun <root>: a synset offset
  * number of type Integer in nounroots: an ArrayList<Integer> defined in the constructor of this
  * class. Store a verb <root>: a synset offset number of type Integer in verbroots: an
  * ArrayList<Integer> defined in the constructor of this class.
  *
  * <p>An example line in an 'icfile', showing a noun <root>: 1740n 128767 ROOT
  */
 private void getRoots() {
   Pattern pn = Pattern.compile("[0-9]+n [0-9]+ ROOT"); // find noun <root>
   Pattern pv = Pattern.compile("[0-9]+v [0-9]+ ROOT"); // find verb <root>
   Matcher m = null;
   String root = "";
   try {
     BufferedReader in = new BufferedReader(new FileReader(icfile));
     String line;
     while ((line = in.readLine()) != null) {
       // nouns
       m = pn.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("n")[0]; // !!! double split !!!
         nounroots.add(Integer.parseInt(root));
       }
       // verbs
       m = pv.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("v")[0]; // !!! double split !!!
         verbroots.add(Integer.parseInt(root));
       }
     }
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * read the file with filename substrings -- existing files with those substrings will not get
   * preserved to preserve-dir.
   *
   * @author [email protected]
   * @date Thu Apr 5 17:43:37 2012
   */
  void initializeNoPreserve(String sFilename) {
    m_lNoPreserveSubstrings = new ArrayList<String>(10);

    BufferedReader in = null;

    try {
      in = new BufferedReader(new FileReader(sFilename));

      String s;
      while ((s = in.readLine()) != null) {
        s = s.trim();

        System.out.println("will not preserve files with substring: " + s);

        m_lNoPreserveSubstrings.add(s.trim());
      }
    } catch (Exception e) {
      System.out.println("ERROR: Failed to get no-preserve substrings: " + e);
      return;
    } finally {
      try {
        in.close();
      } catch (Exception e2) {
      }
    }
  }
Exemplo n.º 10
0
  public static void main(String[] args) throws Exception {
    Reader trainingFile = null;

    // Process arguments
    int restArgs = commandOptions.processOptions(args);

    // Check arguments
    if (restArgs != args.length) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Unexpected arg " + args[restArgs]);
    }
    if (trainFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --train-file FILE");
    }
    if (modelFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --model-file FILE");
    }

    // Get the CRF structure specification.
    ZipFile zipFile = new ZipFile(modelFileOption.value);
    ZipEntry zipEntry = zipFile.getEntry("crf-info.xml");
    CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry));

    StringBuffer crfInfoBuffer = new StringBuffer();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
    String line;
    while ((line = reader.readLine()) != null) {
      crfInfoBuffer.append(line).append('\n');
    }
    reader.close();

    // Create the CRF, and train it.
    CRF4 crf = createCRF(trainFileOption.value, crfInfo);

    // Create a new zip file for our output.  This will overwrite
    // the file we used for input.
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value));

    // Copy the CRF info xml to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-info.xml"));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos));
    writer.write(crfInfoBuffer.toString());
    writer.flush();
    zos.closeEntry();

    // Save the CRF classifier model to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-model.ser"));
    ObjectOutputStream oos = new ObjectOutputStream(zos);
    oos.writeObject(crf);
    oos.flush();
    zos.closeEntry();
    zos.close();
  }
 public BasicSpellChecker(String file) throws IOException {
   BufferedReader in = new BufferedReader(new FileReader(file));
   Pattern p = Pattern.compile("\\w+");
   for (String temp = ""; temp != null; temp = in.readLine()) {
     Matcher m = p.matcher(temp.toLowerCase());
     while (m.find())
       nWords.put((temp = m.group()), nWords.containsKey(temp) ? nWords.get(temp) + 1 : 1);
   }
   in.close();
 }
  public static void main(String args[]) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int T = Integer.parseInt(br.readLine());
    BasicSpellChecker spell =
        new BasicSpellChecker("C:\\Users\\Shivankur Kapoor\\Desktop\\corpus.txt");
    while (T-- > 0) {
      System.out.println((spell.correct(br.readLine())));
    }
  }
Exemplo n.º 13
0
 private static void readCaptchaFile(String fileName) {
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) captchaList.add(line);
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
 }
Exemplo n.º 14
0
 static {
   List<String> spamlist = new ArrayList<String>();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File("spamlist.txt")));
     String line;
     while ((line = reader.readLine()) != null) {
       if (line.trim().isEmpty()) continue;
       spamlist.add(line);
     }
     reader.close();
   } catch (Exception exception) {
   }
   spamList = spamlist.toArray(new String[0]);
 }
Exemplo n.º 15
0
  public void run() {
    // each file is processed into a local hash table and then merged with the global results
    // this will cause much less contention on the global table, but still avoids a sequential
    // update
    Hashtable<String, Integer> local_results =
        new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF);
    // grab a file to work on
    String cf;
    while ((cf = files.poll()) != null) {
      try {
        BufferedReader input = new BufferedReader(new FileReader(cf));
        String text;
        // well go line-by-line... maybe this is not the fastest
        while ((text = input.readLine()) != null) {
          // parse words
          Matcher matcher = pattern.matcher(text);
          while (matcher.find()) {
            String word = matcher.group(1);
            if (local_results.containsKey(word)) {
              local_results.put(word, 1 + local_results.get(word));
            } else {
              local_results.put(word, 1);
            }
          }
        }
        input.close();
      } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
        return;
      }
      // merge local hashmap with shared one,could have a
      // seperate thread do this but that might be cheating

      Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator();
      while (updates.hasNext()) {
        Map.Entry<String, Integer> kv = updates.next();
        String k = kv.getKey();
        Integer v = kv.getValue();
        synchronized (results) {
          if (results.containsKey(k)) {
            results.put(k, v + results.get(k));
          } else {
            results.put(k, v);
          }
        }
      }
      local_results.clear();
    }
  }
Exemplo n.º 16
0
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
      int tIndex = 0;
      int pIndex = 0;

      // This will probably change soon (name and implementation)
      NgramParser tnp = new NgramParser(args[1]);

      ArrayList<String> triplet = tnp.getTriplet();
      ArrayList<String> polarity = tnp.getPolarity();

      FileWriter sw = new FileWriter(args[2]);
      String line = null;

      while (((line = br.readLine()) != null)
          && (tIndex < triplet.size())
          && (pIndex < polarity.size())) {
        if (line.matches("^[\\d]*:")) {
          // System.out.println(line);
          sw.write(line + "\n");
        } else {
          Scanner sc = new Scanner(line);
          String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*"));
          // if (trip != null && trip.equals(triplet.get(tIndex))) {
          System.out.println(trip);
          if (trip != null && !trip.toLowerCase().contains("no#cl")) {
            // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex));
            String pol = polarity.get(pIndex);
            sw.write(line + " " + pol + "\n");
            sc.close();
            tIndex++;
            pIndex++;
          } else {
            String pol = "neg";
            sw.write("no#a#1" + " " + pol + "\n");
            sc.close();
          }
        }

        // sw.flush();
      }

      sw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 17
0
  public String getEntityString(HttpEntity entity) throws Exception {
    StringBuilder sb = new StringBuilder();

    if (entity != null) {
      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
    }

    return sb.toString();
  }
Exemplo n.º 18
0
  public static void lookingCode() {

    int procura = 0;
    boolean entrou = false;

    do {
      procura = Entrada.leiaInt("Digite o código da carta: ");
    } while (procura < 0 || procura > 32);

    try {
      FileReader arq = new FileReader(FileManenger.fileName);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();

      while (linha != null) {

        // procura na string '.'
        if (linha.toLowerCase().contains(".".toLowerCase())) {

          // separ em um array a linha que tem o nome do personagem ex: 1.CARLOS
          String columnArray[] = linha.split(Pattern.quote("."));

          // testa se o codigo é o que ele procura
          if (procura == Integer.parseInt(columnArray[0])) {

            // achou o codigo que ele procura
            entrou = true;
          }
        }

        // testa se a linha é igual a * se for ele já não é mais o personagem que procuramos
        if (linha.equals("*")) {
          entrou = false;
        }

        // mostra as inforamações do personagem
        if (entrou) {
          System.out.println(linha);
        }

        linha = lerArq.readLine();
      }

      arq.close();
    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }
  private int parse() throws IOException {
    String line;
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    int count = 0;

    line = reader.readLine(); // Quality Scores;
    String[] array = line.split("\t");
    qualityScores = new Integer[array.length - offset];
    for (int i = offset; i < array.length; i++) {
      qualityScores[i - offset] = Integer.parseInt(array[i]);
    }

    line = reader.readLine(); // Experiment Names
    array = line.split("\t");
    experiments = new String[array.length - offset];
    for (int i = offset; i < array.length; i++) {
      experiments[i - offset] = array[i];
      exptIndices.put(array[i], i - offset);
    }

    // Reads the rest of the table.
    while ((line = reader.readLine()) != null) {
      array = line.split("\t");
      String id = array[0]; // first column is the ID
      if (array.length != experiments.length + offset) {
        System.err.println(
            String.format(
                "Line %s has length %d != %d", id, array.length, experiments.length + offset));
      } else {
        // we're going to skip the second column (an index value), and
        // put the rest of the values in the array.  Any parsing exceptions
        // indicate missing (NULL) values.
        Float[] values = new Float[experiments.length];
        for (int i = 0; i < experiments.length; i++) {
          try {
            values[i] = Float.parseFloat(array[i + offset]);
            count += 1;
          } catch (NumberFormatException nfe) {
            values[i] = null;
          }
        }
        table.put(id, values);
      }
    }

    reader.close();
    return count;
  }
Exemplo n.º 20
0
  public static void t1986main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringBuilder reg = new StringBuilder();
    reg.append(in.readLine());

    String sent;
    Pattern pattern = Pattern.compile(reg.toString());
    Matcher matcher;
    while (in.ready()) {
      sent = in.readLine();
      matcher = pattern.matcher(sent);
      if (matcher.find()) System.out.println("YES");
      else System.out.println("NO");
    }
    System.exit(0);
  }
Exemplo n.º 21
0
 public static void main(String[] args) throws IOException {
   BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
   if (args.length != 1) {
     System.err.println("Usage: MatchLines pattern");
     System.exit(1);
   }
   Pattern patt = Pattern.compile(args[0]);
   Matcher matcher = patt.matcher("");
   String line = null;
   while ((line = is.readLine()) != null) {
     matcher.reset(line);
     if (matcher.find()) {
       System.out.println("MATCH: " + line);
     }
   }
 }
Exemplo n.º 22
0
 private void processResponse(InputStream response) throws IOException {
   Pattern p = Pattern.compile("<cdbId>\\s*(\\d+)");
   BufferedReader in = new BufferedReader(new InputStreamReader(response));
   String line = in.readLine();
   while (line != null) {
     System.out.println(line);
     Matcher m = p.matcher(line);
     if (m.find()) {
       String idText = m.group(1);
       if (idText != null) {
         cdbId = Integer.parseInt(idText);
       }
     }
     line = in.readLine();
   }
 }
Exemplo n.º 23
0
 private static List<String> loadLoginProxies(String fileName) {
   List<String> proxies = new ArrayList<String>();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) {
       if (line.trim().isEmpty()) continue;
       String[] parts = line.split(" ")[0].trim().split(":");
       proxies.add(parts[0].trim() + ":" + Integer.parseInt(parts[1].trim()));
     }
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
   System.out.println("Loaded " + proxies.size() + " login proxies.");
   return proxies;
 }
Exemplo n.º 24
0
  public String loadStream(InputStream is) {
    StringBuilder sb = new StringBuilder();

    try {
      InputStreamReader reader = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(reader);

      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
    } catch (Exception e) {
      log.error("", e);
    }

    return sb.toString();
  }
Exemplo n.º 25
0
 private void dumpStream(InputStream stream) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(stream));
   int i;
   try {
     while ((i = in.read()) != -1) {
       MessageOutput.printDirect((char) i); // Special case: use
       //   printDirect()
     }
   } catch (IOException ex) {
     String s = ex.getMessage();
     if (!s.startsWith("Bad file number")) {
       throw ex;
     }
     // else we got a Bad file number IOException which just means
     // that the debuggee has gone away.  We'll just treat it the
     // same as if we got an EOF.
   }
 }
Exemplo n.º 26
0
    public void run() {
      try {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        if (outputFile != null) {
          bw =
              new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), charset));
        }
        String line;
        while ((line = br.readLine()) != null) {
          filePosition += line.length() + 2;
          line = line.trim();
          if (!line.startsWith("#")) {
            String[] sides = split(line);
            if ((sides != null) && !sides[0].equals("key")) {

              if (searchPHI) {
                // Search the decrypted PHI for the searchText
                sides[0] = decrypt(sides[0]);
                if (sides[0].indexOf(searchText) != -1) {
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              } else {
                // Search the trial ID for the searchText
                if (sides[1].indexOf(searchText) != -1) {
                  sides[0] = decrypt(sides[0]);
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              }
            }
          }
        }
        br.close();
        if (bw != null) {
          bw.flush();
          bw.close();
        }
      } catch (Exception e) {
        append("\n\n" + e.getClass().getName() + ": " + e.getMessage() + "\n");
      }
      append("\nDone.\n");
      setMessage("Ready...");
    }
Exemplo n.º 27
0
 public String next() {
   while (tokenizer == null || !tokenizer.hasMoreTokens()) {
     try {
       tokenizer = new StringTokenizer(reader.readLine());
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   return tokenizer.nextToken();
 }
Exemplo n.º 28
0
  public static void readFile() {

    try {

      FileReader arq = new FileReader(FileManenger.fileName);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha =
          lerArq
              .readLine(); // lê a primeira linha a variável "linha" recebe o valor "null" quando o
                           // processo  de repetição atingir o final do arquivo texto
      while (linha != null) {
        System.out.println(linha);
        linha = lerArq.readLine(); // lê da segunda até a última linha
      }
      arq.close();

    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }
Exemplo n.º 29
0
  public static void loadPermissions(URL url) throws IOException, PermissionParseException {

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    Pattern ignore = Pattern.compile("^\\s*(//.*)?$");
    Pattern valid =
        Pattern.compile("^\\s*permission\\s+(\\S+)" + "(\\s+\"([^\"]*)\"(,\\s+\"([^\"]*)\")?)?;$");

    Set<Permission> perms = new HashSet<Permission>();

    while ((line = in.readLine()) != null) {
      if (ignore.matcher(line).matches()) {
        continue;
      }

      Matcher matcher = valid.matcher(line);
      if (!matcher.matches()) {
        throw new PermissionParseException("invalid syntax: " + line);
      }

      int nGroups = matcher.groupCount();
      String type = matcher.group(1);
      String name = expand(nGroups >= 3 ? matcher.group(3) : null);
      String actions = expand(nGroups >= 5 ? matcher.group(5) : null);

      try {
        Permission perm = getPermission(type, name, actions);
        perms.add(perm);
      } catch (Throwable e) {
        String message =
            String.format(
                "could not instantiate permission: " + "type=%s name=%s actions=",
                type, name, actions);
        throw new PermissionParseException(message, e);
      }
    }

    in.close();

    permSet.addAll(perms);
  }
Exemplo n.º 30
0
 private static List<String> loadAccounts(String fileName) {
   List<String> accounts = new ArrayList<String>();
   try {
     Pattern pattern = Pattern.compile("[\\w]{1,16}");
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) {
       Matcher matcher = pattern.matcher(line);
       if (!matcher.find()) continue;
       String username = matcher.group();
       if (!matcher.find()) continue;
       String password = matcher.group();
       accounts.add(username + ":" + password);
     }
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
   System.out.println("Loaded " + accounts.size() + " accounts.");
   return accounts;
 }