Beispiel #1
0
 private void extractInfo(File filename) {
   checkpoint = false;
   String line;
   try {
     ArrayList<String> order = new ArrayList<String>();
     BufferedReader input =
         new BufferedReader(new InputStreamReader(new FileInputStream(filename), "iso-8859-1"));
     while ((line = input.readLine()) != null) {
       if (line.equalsIgnoreCase("hämtas")) checkpoint = true;
       if (checkpoint) order.add(new String(line));
     }
     //	printList(order);
     int quant = Integer.parseInt(order.get(2));
     int rows = 9;
     int outer = (quant * rows);
     double price;
     double total;
     // DecimalFormat decimal = (DecimalFormat) format;
     Number number;
     for (int i = 4; i <= outer; i += 9) {
       Data d =
           new Data(
               order.get(i + 1),
               order.get(i + 3),
               order.get(i + 4),
               order.get(i + 5),
               order.get(i + 7));
       dataList.add(d);
       /*	try {
       System.out.println(order.get(i+5));
       number = format.parse(order.get(i+5));
       System.out.println("Number is " + number);
       price = number.doubleValue();
       System.out.println("Price is " + price);
       number = format.parse(order.get(i+7));
       total = number.doubleValue();
       Data d = new Data(order.get(i), Integer.parseInt(order.get(i+1)), Integer.parseInt(order.get(i+2)), order.get(i+3), order.get(i+4), price, total);
       dataList.add(d);
       } catch (ParseException numExcep) {
       numExcep.printStackTrace();
       System.exit(1);
       }
       **/
     }
     //	printDataList(dataList);
   } catch (FileNotFoundException found) {
     found.printStackTrace();
     System.exit(1);
   } catch (UnsupportedEncodingException encode) {
     encode.printStackTrace();
     System.exit(1);
   } catch (IOException ioexcep) {
     ioexcep.printStackTrace();
     System.exit(1);
   }
 }
Beispiel #2
0
  public void createExcel(String file) {

    String filename = createPath(file);
    System.out.println(filename);

    /*
       try {
       WorkbookSettings ws = new WorkbookSettings();
       ws.setLocale(new Locale("sv", "SE"));
       WritableWorkbook workbook = Workbook.createWorkbook(new File(filename), ws);
       WritableSheet s = workbook.createSheet("Sheet1", 0);
    //writeDataSheet(s);
    workbook.write();
    workbook.close();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (WriteException e) {
    e.printStackTrace();
    }**/

    try {

      File newFile = new File(filename);
      Writer out =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF8"));
      //	BufferedWrite output = new BufferedWriter(new OutputStreamReader(new
      // FileInputS§tream(filename), "iso-8859-1"));
      // FileWriter fw = new FileWriter(newFile.getAbsoluteFile());
      // BufferedWriter bw = new BufferedWriter(fw);
      // bw.write("Artikel;Antal/st;Pris/st;Total\n");
      out.append("Artikel;Antal/st;Pris/st;Total\n");
      for (Data d : dataList) {
        out.append(d.toString());
        out.append("\n");
        // bw.write(d.toString());
        // bw.write("\n");
      }
      // bw.close();
      out.flush();
      out.close();
    } catch (UnsupportedEncodingException unsuppEn) {
      unsuppEn.printStackTrace();
    } catch (IOException ioE) {
      ioE.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #3
0
  public static String getAddressByIP(String ip) {
    try {
      String js = visitWeb("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip);
      JsonParser jsonParser = new JsonParser();
      js = js.trim();
      JsonObject jo = jsonParser.parse(js.substring(21, js.length() - 1)).getAsJsonObject();
      String province = "";
      String city = "";
      try {
        // 获取 省、市
        province =
            jo.get("province") == null
                ? ""
                : URLDecoder.decode(jo.get("province").toString(), "UTF-8");
        city = jo.get("city") == null ? "" : URLDecoder.decode(jo.get("city").toString(), "UTF-8");
        // 省为空用国家代替
        if (StringUtils.isEmpty(province)) {
          province =
              jo.get("country") == null
                  ? ""
                  : URLDecoder.decode(jo.get("country").toString(), "UTF-8");
        }

      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      return (province.equals("") || province.equals(city)) ? city : province + " " + city;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }
Beispiel #4
0
  public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException {

    String realm = "/";
    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "policynames="
              + URLEncoder.encode(polname, "UTF-8")
              + "&realm="
              + URLEncoder.encode(realm, "UTF-8")
              + "&submit="
              + URLEncoder.encode("Submit", "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + ssoadm_list));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\"");
      r.Send(urlc, data);

      String answer = null;
      int status = 0;
      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
Beispiel #5
0
  public ErrorInfo doLogin() throws IOException, RestException {

    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "username="******"UTF-8")
              + "&password="******"UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + authenticate));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      r.Send(urlc, data);

      String answer = null;
      int status = 0;

      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
Beispiel #6
0
  private static void createFile(List<String> palabras, String pathToWords) {
    PrintWriter writer = null;
    try {
      writer = new PrintWriter(pathToWords, "UTF-8");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    for (String temp : palabras) {
      writer.println(temp);
    }
    writer.close();
  }
 public void printString(String output) {
   PrintWriter printer;
   try {
     printer = new PrintWriter("botOutput.txt", "UTF-8");
     printer.write(output);
     printer.close();
     /*                for (String word : individual.toString().split(" ")) {
         printer.write(word);
     }*/
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
 }
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
Beispiel #9
0
  public String getBody(String url, String text, LinkedHashMap header) {
    if (text != null && text.length() > 0) {
      File tmpFile = new File("/tmp/aa");
      OutputStreamWriter out = null;
      try {
        // write the input
        out = new OutputStreamWriter(new FileOutputStream(tmpFile), "UTF8");
        out.write(text);
        out.close();

        // run TextPro
        String[] CONFIG = {"TEXTPRO=" + TEXTPRO_PATH, "PATH=" + "/usr/bin/" + ":."};
        String[] cmd = {
          "/bin/tcsh",
          "-c",
          "perl " + TEXTPRO_PATH + "/textpro.pl -l eng -c token+pos+lemma+sentence -y " + tmpFile
        };
        Process process = run(cmd, CONFIG);
        process.waitFor();

        // read the TextPro's output
        BufferedReader txpFile =
            new BufferedReader(
                new InputStreamReader(new FileInputStream(tmpFile.getCanonicalPath() + ".txp")));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = txpFile.readLine()) != null) {
          if (!line.startsWith("# FILE:")) {
            result.append(line).append("\n");
          }
        }
        txpFile.close();

        return result.toString();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    return "";
  }
Beispiel #10
0
  public static Pair<String, List<String>> decodeKeyValues(String str) {
    int index = str.indexOf("=");
    if (index == -1) {
      return null;
    }
    String k = str.substring(0, index);
    LinkedList<String> vlist = new LinkedList<String>();
    try {
      String vstr = URLDecoder.decode(str.substring(index + 1, str.length()), "UTF-8");
      String[] array = vstr.split(",");
      for (int i = 0; i < array.length; i++) {
        vlist.addLast(array[i]);
      }
      return new Pair<String, List<String>>(k, vlist);

    } catch (UnsupportedEncodingException e) {
      System.err.println("BAD STRING " + str);
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      System.err.println("BAD STRING " + str);
      return null;
    }
  }