private void saveCurrent() {
    PrintWriter writer = null;

    try {
      writer = new PrintWriter("config.txt", "UTF-8");
      writer.println("PhoneNumbers:");

      for (String s : Main.getEmails()) {
        writer.println(s);
      }

      writer.println("Items:");

      for (Item s : Main.getItems()) {
        writer.println(s.getName() + "," + s.getWebsite());
      }

      results.setText("Current settings have been saved sucessfully.");
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }

    writer.close();
  }
Example #2
0
 /**
  * Get请求
  *
  * @param url
  * @param params
  * @return
  */
 public static String get(String url, List<NameValuePair> params) {
   String body = null;
   try {
     // Get请求
     HttpGet httpget = new HttpGet(url);
     // 设置参数
     String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
     httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
     // 发送请求
     HttpResponse httpresponse = httpClient.execute(httpget);
     // 获取返回数据
     HttpEntity entity = httpresponse.getEntity();
     body = EntityUtils.toString(entity);
     if (entity != null) {
       entity.consumeContent();
     }
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return body;
 }
Example #3
0
  /** @param args */
  public static void main(String[] args) {
    if (args.length != 1) {
      System.err.println("Usage: java " + ATBCorrector.class.getName() + " filename\n");
      System.exit(-1);
    }

    TreeTransformer tt = new ATBCorrector();

    File f = new File(args[0]);
    try {

      BufferedReader br =
          new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
      TreeReaderFactory trf = new ArabicTreeReaderFactory.ArabicRawTreeReaderFactory();
      TreeReader tr = trf.newTreeReader(br);

      int nTrees = 0;
      for (Tree t; (t = tr.readTree()) != null; nTrees++) {
        Tree fixedT = tt.transformTree(t);
        System.out.println(fixedT.toString());
      }

      tr.close();

      System.err.printf("Wrote %d trees%n", nTrees);

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

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #4
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 "";
    }
  }
 public SummaryResultsParser(String path) {
   this();
   try {
     parseSummaryFile(path);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
 }
  static void uIDfill(String file, OptionsFiller filler) {

    InputStream assetsDB = null;
    try {
      assetsDB = getContext().getAssets().open(file);
    } catch (IOException e) {
      e.printStackTrace();
      return;
    }

    BufferedReader buf = null;
    try {
      buf = new BufferedReader(new InputStreamReader(assetsDB, "UTF-8"));
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
    }

    try {
      while (buf.ready()) {
        String str = buf.readLine();
        /*
         * Test for BOM
         */
        if (str.length() > 0 && (int) str.charAt(0) == 65279) {
          str = str.substring(1);
        }

        int spaceIndex = str.indexOf(' ');

        if (spaceIndex < 0) {
          break;
        }

        int index1 = str.indexOf(':');
        int index2 = str.lastIndexOf(':', spaceIndex);

        if (index2 == index1) {
          filler.fill(
              new UniqueID(str.substring(0, spaceIndex)).hashCode(),
              str.substring(spaceIndex + 1),
              null);
        } else {
          filler.fill(
              new UniqueID(str.substring(0, index2)).hashCode(),
              str.substring(spaceIndex + 1),
              str.substring(index2 + 1, spaceIndex));
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    try {
      assetsDB.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public void flush() {
   try {
     m_txtArea.append(new String(buffer.toByteArray(), encoding));
   } catch (UnsupportedEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   buffer.reset();
 }
 /**
  * This method will set the content-string to be the content of this Information object.
  * Internally, the content will be written into a newly created ByteArrayOutputStream. Calling
  * this method will erase previously set content on this object. The content-string will be read
  * as UTF8.
  *
  * @param content The content to be set.
  */
 @Override
 public void setContent(String content) {
   try {
     setContent(content.getBytes(KEPMessage.ENCODING));
   } catch (UnsupportedEncodingException e) {
     // FIXME: Catch unknown encoding exception?!
     e.printStackTrace();
   }
 }
Example #9
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);
   }
 }
Example #10
0
 public FileConfiguration getMensagensConfig() {
   if (mensagens == null) {
     try {
       reloadMensagensConfig();
     } catch (UnsupportedEncodingException e) {
       e.printStackTrace();
     }
   }
   return mensagens;
 }
Example #11
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;
  }
 public static byte[] func_75895_a(String p_75895_0_, PublicKey p_75895_1_, SecretKey p_75895_2_) {
   try {
     return func_75893_a(
         "SHA-1",
         new byte[][] {
           p_75895_0_.getBytes("ISO_8859_1"), p_75895_2_.getEncoded(), p_75895_1_.getEncoded()
         });
   } catch (UnsupportedEncodingException unsupportedencodingexception) {
     unsupportedencodingexception.printStackTrace();
   }
   return null;
 }
Example #13
0
  public static ResourceBundle loadLocale(String localeString) {

    JarFile jarFile;
    try {
      jarFile = new JarFile(MyPetPlugin.getPlugin().getFile());
    } catch (IOException ignored) {
      return null;
    }

    ResourceBundle newLocale = null;
    try {
      JarEntry jarEntry = jarFile.getJarEntry("locale/MyPet_" + localeString + ".properties");
      if (jarEntry != null) {
        java.util.ResourceBundle defaultBundle =
            new PropertyResourceBundle(
                new InputStreamReader(jarFile.getInputStream(jarEntry), "UTF-8"));
        newLocale = new ResourceBundle(defaultBundle);
      } else {
        throw new IOException();
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      DebugLogger.printThrowable(e);
    } catch (IOException ignored) {
    }

    File localeFile =
        new File(
            MyPetPlugin.getPlugin().getDataFolder()
                + File.separator
                + "locale"
                + File.separator
                + "MyPet_"
                + localeString
                + ".properties");
    if (localeFile.exists()) {
      if (newLocale == null) {
        newLocale = new ResourceBundle();
      }
      try {
        java.util.ResourceBundle optionalBundle =
            new PropertyResourceBundle(
                new InputStreamReader(new FileInputStream(localeFile), "UTF-8"));
        newLocale.addExtensionBundle(optionalBundle);
      } catch (IOException e) {
        e.printStackTrace();
        DebugLogger.printThrowable(e);
      }
    }
    return newLocale;
  }
Example #14
0
 public static void save_file(File file) {
   try {
     save_sifp(file);
   } catch (UnsupportedEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #15
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;
  }
 public String encodeQingcloud(String data) {
   data = data.replace("+", "-");
   data = data.replace("/", "_");
   while (data.endsWith("=")) {
     data = data.substring(0, data.length() - 1);
   }
   String encodeData = null;
   try {
     encodeData = new String(Base64.encodeBase64(encodeData.getBytes("UTF-8")), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   return encodeData;
 }
  @Override
  protected PaymentType doInBackground(String... params) {
    PaymentType paymentType = null;

    InputStream inputStream = null;
    HttpEntity httpEntity = null;

    try {
      httpEntity = Response.getResponse(params[0]).getEntity();

      inputStream = httpEntity.getContent();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
      StringBuilder builder = new StringBuilder();
      String line = null;

      while ((line = reader.readLine()) != null) {
        builder.append(line + "\n");
      }

      inputStream.close();
      result = builder.toString();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      JSONObject jsonObject = new JSONObject(result);

      JSONObject paymentTypeObject = jsonObject.getJSONObject("paymentType");

      int id = paymentTypeObject.getInt("id");
      int informationTypeId = paymentTypeObject.getInt("informationTypeId");
      String time = paymentTypeObject.getString("time");
      double price = paymentTypeObject.getDouble("price");

      paymentType = new PaymentType(id, informationTypeId, time, price);

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

    return paymentType;
  }
 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();
   }
 }
Example #19
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();
  }
Example #20
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();
    }
  }
Example #21
0
  // добавить продукт в базу 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");
    }
  }
 public String decodeQingcloud(String data) {
   int len = 4 - data.length() % 4 == 0 ? 4 : data.length() % 4;
   data = data.replace("-", "+");
   data = data.replace("_", "/");
   for (int i = 0; i < len; i++) {
     data += "=";
   }
   String decodeSignature = null;
   try {
     decodeSignature =
         new String(org.apache.commons.codec.binary.Base64.decodeBase64(data), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   return decodeSignature;
 }
Example #23
0
 public void printList(Node[] nodes) {
   PrintWriter pw;
   try {
     pw = new PrintWriter("wordCount_Output_HP.txt", "UTF-8");
     for (int i = 0; i < nodes.length; i++) {
       pw.println("(" + nodes[i].data + ", " + nodes[i].count + ")");
     }
     pw.close();
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     System.out.println(e.getMessage());
     e.printStackTrace();
   }
 }
Example #24
0
  static void fill(String file, Filler filler) {
    InputStream assetsDB = null;
    try {
      assetsDB = getContext().getAssets().open(file);
    } catch (IOException e) {
      e.printStackTrace();
      return;
    }

    BufferedReader buf = null;
    try {
      buf = new BufferedReader(new InputStreamReader(assetsDB, "UTF-8"));
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
    }

    try {
      while (buf.ready()) {
        String str = buf.readLine();
        /*
         * Test for BOM
         */
        if (str == null) {
          break;
        }
        if (str.length() > 0 && (int) str.charAt(0) == 65279) {
          str = str.substring(1);
        }

        int spaceIndex = str.indexOf(' ');

        if (spaceIndex < 0) {
          break;
        }

        filler.fill(Integer.parseInt(str.substring(0, spaceIndex)), str.substring(spaceIndex + 1));
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    try {
      assetsDB.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #25
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 "";
  }
 public void store(String cacheEntryName, InputStream inputStream, long expirationDate) {
   try {
     PreparedStatement stmt =
         connection.prepareStatement(
             "INSERT INTO " + tableName + " (id, expiration_date, response) VALUES(?, ?, ?)");
     stmt.setString(1, cacheEntryName);
     stmt.setTimestamp(2, new Timestamp(expirationDate));
     stmt.setCharacterStream(3, new InputStreamReader(inputStream, "UTF-8"), -1);
     stmt.execute();
     stmt.close();
   } catch (SQLException e) {
     e.printStackTrace();
     // ignore
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     //			won't happen
   }
 }
  @POST
  @Path("/setParticipant")
  @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
  public Participant setParticipant(String data) {
    Participant participant = null;
    try {
      // String ecodedValue1 = URLEncoder.encode(data, "UTF-8");
      String decodedValue1 = URLDecoder.decode(data, "UTF-8");
      String[] splitStr = decodedValue1.split("[=&]");
      participant = new Participant();
      participant.setLastName(splitStr[1]);
      participant.setFirstName(splitStr[3]);
      participant.setPatronymic(splitStr[5]);
      participant.setPost(splitStr[7]);

    } catch (UnsupportedEncodingException uee) {
      uee.printStackTrace();
    } finally {
      return participant;
    }
  }
Example #28
0
  public String getDLURL(String path) throws IOException {

    KuaipanCommonString KPString = new KuaipanCommonString();
    KPAuthorization KPAuth = new KPAuthorization();

    KPString.KP_TIMESTAMP = KPAuth.set_timestamp();
    KPString.KP_OAUTH_NONCE = KPAuth.set_nonce();

    String signature;
    try {
      signature = set_KPDL_signature(path);
      KPString.KP_DOWNLOAD_SIGNATURE =
          KPAuth.hmacsha1(signature, KPString.KP_COMSUMER_SECRET + "&" + KPString.KP_OAUTH_TOKEN);
    } catch (UnsupportedEncodingException ex) {
      ex.printStackTrace();
    }

    String url =
        KPString.KP_DOWNLOAD_URL
            + "?"
            + "oauth_version="
            + KPString.KP_OAUTH_VERSION
            + "&oauth_consumer_key="
            + KPString.KP_COMSUMER_KEY
            // + "&oauth_signature_method=" + KPString.KP_OAUTH_SIGNATURE_METHOD
            + "&oauth_token="
            + KPString.KP_OAUTH_TOKEN
            + "&oauth_signature="
            + KPString.KP_DOWNLOAD_SIGNATURE
            + "&oauth_nonce="
            + KPString.KP_OAUTH_NONCE
            + "&oauth_timestamp="
            + KPString.KP_TIMESTAMP
            + "&root="
            + KPString.KP_CLOUDROOT
            + "&path="
            + path;

    return url;
  }
 /**
  * This method finds the default mail template of loan membership message and extract it's content
  * for velocity engine to fill with user membership info
  *
  * @param stepExecution
  */
 public void beforeStep(StepExecution stepExecution) {
   List mailDefinitions =
       mailService.getDefaultSubject(null, Sections.LOAN_MEMBERSHIP_EXPIRATION_SECTION, null);
   if (mailDefinitions != null && mailDefinitions.size() != 0) {
     MailDefinition mailDefinition = (MailDefinition) mailDefinitions.get(0);
     subject = mailDefinition.getSubject();
     MailAttachmentResourceItem attachment = null;
     String content = "";
     char[] temp = new char[200];
     BufferedReader reader;
     int size;
     InputStream inputStream = null;
     List resources =
         resourceService.getResourceItemByMasterId(
             MailAttachmentResourceItem.class, mailDefinition.getId());
     if (resources != null && resources.size() != 0) {
       List attachments =
           resourceService.getResourceItemByMasterId(
               MailAttachmentResourceItem.class, mailDefinition.getId());
       if (attachments != null && attachments.size() > 0) {
         attachment = (MailAttachmentResourceItem) attachments.get(0);
         try {
           inputStream = attachment.getResourceBlob().getBinaryStream();
           reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
           while ((size = reader.read(temp)) > 0) {
             content += String.copyValueOf(temp, 0, size);
           }
         } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
         } catch (SQLException e) {
           e.printStackTrace();
         } catch (IOException e) {
           e.printStackTrace();
         }
         contentFields = content;
       }
     }
   }
 }
Example #30
0
 /**
  * Post a note that contains only a message.
  *
  * @param noteTo The recipient(s) of the note. Options are public, all, friend_x, or set_x.
  *     Available options for the authenticated user can be found from the Send To List endpoint.
  * @param noteBody The main text body of the note.
  */
 public void sendMessage(String noteTo, String noteBody) {
   String messageData = "";
   if (!noteTo.equals("public")
       && !noteTo.equals("all")
       && !noteTo.startsWith("friend")
       && !noteTo.startsWith("set")) return; // bail
   try {
     messageData =
         URLEncoder.encode("note_to", "UTF-8") + "=" + URLEncoder.encode(noteTo, "UTF-8");
     messageData +=
         "&"
             + URLEncoder.encode("note_body", "UTF-8")
             + "="
             + URLEncoder.encode(noteBody, "UTF-8");
   } catch (UnsupportedEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   apiUrl =
       apiBase
           + "/send/"
           + "message."
           + format
           + "?"
           + "app_key="
           + appKey; // + "&" + messageData;
   method = new PostMethod(apiUrl);
   System.out.println("url used in method:" + apiUrl);
   /*HttpMethodParams appParams = new HttpMethodParams();
   appParams.setParameter("app_key", appKey);
   NameValuePair[] data = { new NameValuePair("note_to", noteTo), new NameValuePair("app_key", appKey), new NameValuePair("note_body", URLEncoder.encode(noteBody)) };
   method.setQueryString(data);
   method.setParams(appParams);
   */
   //		method.setQueryString(data);
   //		method.setRequestHeader(data);
 }