Ejemplo n.º 1
1
  private HtmlRequest readRequest(Socket socket) throws IOException {

    BufferedReader requestBufferedReader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder requestStringBuilder = new StringBuilder();
    try {
      String line = requestBufferedReader.readLine();

      while (!line.isEmpty()) {
        requestStringBuilder.append(line + NEWLINE);
        line = requestBufferedReader.readLine();
      }

    } catch (IOException e) {
      System.out.println("An error occured while reading from the socket: " + e.toString());
    }
    if (requestStringBuilder.toString().isEmpty()) {
      return null;
    }
    HtmlRequest htmlRequest = new HtmlRequest(requestStringBuilder.toString());
    if (htmlRequest.type.equals("POST") || htmlRequest.type.equals("TRACE")) {
      htmlRequest.getParametersFromBody(requestBufferedReader);
    }
    return htmlRequest;
  }
Ejemplo n.º 2
1
  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  @Nullable
  public static String getFileText(String parentDir, String fileName, boolean wrapHTML) {

    File inputFile = parentDir != null ? new File(parentDir, fileName) : new File(fileName);
    if (!inputFile.exists()) return null;
    StringBuilder taskText = new StringBuilder();
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
      String line;
      while ((line = reader.readLine()) != null) {
        taskText.append(line).append("\n");
        if (wrapHTML) {
          taskText.append("<br>");
        }
      }
      return wrapHTML ? UIUtil.toHtml(taskText.toString()) : taskText.toString();
    } catch (IOException e) {
      LOG.info("Failed to get file text from file " + fileName, e);
    } finally {
      closeSilently(reader);
    }
    return null;
  }
Ejemplo n.º 3
1
 /**
  * Given a string, return an array of tokens. The separator can be escaped with the '\' character.
  * The '\' character may also be escaped by the '\' character.
  *
  * @param s the string to tokenize.
  * @param separator the separator char.
  * @param maxTokens the maxmimum number of tokens returned. If the max is reached, the remaining
  *     part of s is appended to the end of the last token.
  * @return an array of tokens.
  */
 public static String[] tokenize(String s, char separator, int maxTokens) {
   List tokens = new ArrayList();
   StringBuilder token = new StringBuilder();
   boolean prevIsEscapeChar = false;
   for (int i = 0; i < s.length(); i += Character.charCount(i)) {
     int currentChar = s.codePointAt(i);
     if (prevIsEscapeChar) {
       // Case 1:  escaped character
       token.appendCodePoint(currentChar);
       prevIsEscapeChar = false;
     } else if (currentChar == separator && tokens.size() < maxTokens - 1) {
       // Case 2:  separator
       tokens.add(token.toString());
       token = new StringBuilder();
     } else if (currentChar == '\\') {
       // Case 3:  escape character
       prevIsEscapeChar = true;
     } else {
       // Case 4:  regular character
       token.appendCodePoint(currentChar);
     }
   }
   if (token.length() > 0) {
     tokens.add(token.toString());
   }
   return (String[]) tokens.toArray(new String[] {});
 }
Ejemplo n.º 4
1
  /**
   * If the outbound level is BINARY, convert the string field to binary, then pad to the left with
   * the appropriate number of zero bits to reach a number of bits specified by the bitLength
   * attribute of the TDT definition file.
   */
  private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
    String fieldname = tdtfield.getName();
    int reqbitlength = tdtfield.getBitLength();
    String value;

    String binaryValue = fieldToBinary(tdtfield, extraparams);
    if (binaryValue.length() < reqbitlength) {
      int extraBitLength = reqbitlength - binaryValue.length();

      StringBuilder zeroPaddedBinaryValue = new StringBuilder("");
      for (int i = 0; i < extraBitLength; i++) {
        zeroPaddedBinaryValue.append("0");
      }
      zeroPaddedBinaryValue.append(binaryValue);
      value = zeroPaddedBinaryValue.toString();
    } else {
      if (binaryValue.length() > reqbitlength)
        throw new TDTException(
            "Binary value ["
                + binaryValue
                + "] for field "
                + fieldname
                + " exceeds maximum allowed "
                + reqbitlength
                + " bits.  Decimal value was "
                + extraparams.get(fieldname));

      value = binaryValue;
    }
    extraparams.put(fieldname, value);
  }
Ejemplo n.º 5
1
    // create from a dataset
    public VariableBean(Variable vs) {
      this.vs = vs;
      // vs = (v instanceof VariableEnhanced) ? (VariableEnhanced) v : new VariableStandardized( v);

      setName(vs.getShortName());
      setDescription(vs.getDescription());
      setUnits(vs.getUnitsString());
      setDataType(vs.getDataType().toString());

      // Attribute csAtt = vs.findAttribute("_coordSystems");
      // if (csAtt != null)
      //  setCoordSys( csAtt.getStringValue());

      // collect dimensions
      StringBuilder lens = new StringBuilder();
      StringBuilder names = new StringBuilder();
      java.util.List dims = vs.getDimensions();
      for (int j = 0; j < dims.size(); j++) {
        ucar.nc2.Dimension dim = (ucar.nc2.Dimension) dims.get(j);
        if (j > 0) {
          lens.append(",");
          names.append(",");
        }
        String name = dim.isShared() ? dim.getName() : "anon";
        names.append(name);
        lens.append(dim.getLength());
      }
      setDimensions(names.toString());
      setShape(lens.toString());
    }
Ejemplo n.º 6
1
  private void sendResourceFile(HttpExchange exchange) {
    StringBuilder response = new StringBuilder();

    String path = exchange.getRequestURI().getPath();
    if (path.contains("resources")) {
      path = path.substring(path.indexOf("resources") + 9);
    }
    InputStream is = MyBaseHandler.class.getResourceAsStream(path);
    if (is == null) {
      writeResponse(exchange, "File not found", 404);
      return;
    }
    InputStreamReader reader = new InputStreamReader(is);

    try {
      BufferedReader bufferedReader = new BufferedReader(reader);

      String tmp;
      while ((tmp = bufferedReader.readLine()) != null) {
        response.append(tmp);
        response.append("\n");
      }
    } catch (NullPointerException e) {
      response.append("Resource file not found");
      writeResponse(exchange, response.toString(), 404);
    } catch (IOException e) {
      response.append("Error while reading from file");
      writeResponse(exchange, response.toString(), 400);
    }
    writeResponse(exchange, response.toString(), 200);
  }
  public String getUrl() {
    StringBuilder sb = new StringBuilder();
    StringBuilder ori = getOut();
    this.setOut(sb);
    TreeMap<Integer, cn.bran.japid.template.ActionRunner> parentActionRunners = actionRunners;
    actionRunners = new TreeMap<Integer, cn.bran.japid.template.ActionRunner>();
    // line 48, japidviews\AdminController\flashPurchaseList.html
    p("            	"); // line 48, japidviews\AdminController\flashPurchaseList.html
    p(
        lookup(
            "AdminController.flashPurchaseList",
            new Object[] {})); // line 49, japidviews\AdminController\flashPurchaseList.html
    p("            "); // line 49, japidviews\AdminController\flashPurchaseList.html

    this.setOut(ori);
    if (actionRunners.size() > 0) {
      StringBuilder _sb2 = new StringBuilder();
      int segStart = 0;
      for (Map.Entry<Integer, cn.bran.japid.template.ActionRunner> _arEntry :
          actionRunners.entrySet()) {
        int pos = _arEntry.getKey();
        _sb2.append(sb.substring(segStart, pos));
        segStart = pos;
        cn.bran.japid.template.ActionRunner _a_ = _arEntry.getValue();
        _sb2.append(_a_.run().getContent().toString());
      }
      _sb2.append(sb.substring(segStart));
      actionRunners = parentActionRunners;
      return _sb2.toString();
    } else {
      actionRunners = parentActionRunners;
      return sb.toString();
    }
  }
Ejemplo n.º 8
1
 /**
  * Returns a map with variable bindings.
  *
  * @param opts main options
  * @return bindings
  */
 public static HashMap<String, String> bindings(final MainOptions opts) {
   final HashMap<String, String> bindings = new HashMap<>();
   final String bind = opts.get(MainOptions.BINDINGS).trim();
   final StringBuilder key = new StringBuilder();
   final StringBuilder val = new StringBuilder();
   boolean first = true;
   final int sl = bind.length();
   for (int s = 0; s < sl; s++) {
     final char ch = bind.charAt(s);
     if (first) {
       if (ch == '=') {
         first = false;
       } else {
         key.append(ch);
       }
     } else {
       if (ch == ',') {
         if (s + 1 == sl || bind.charAt(s + 1) != ',') {
           bindings.put(key.toString().trim(), val.toString());
           key.setLength(0);
           val.setLength(0);
           first = true;
           continue;
         }
         // literal commas are escaped by a second comma
         s++;
       }
       val.append(ch);
     }
   }
   if (key.length() != 0) bindings.put(key.toString().trim(), val.toString());
   return bindings;
 }
Ejemplo n.º 9
1
Archivo: Macro.java Proyecto: bramk/bnd
  public String _range(String args[]) {
    verifyCommand(args, _rangeHelp, _rangePattern, 2, 3);
    Version version = null;
    if (args.length >= 3) version = new Version(args[2]);
    else {
      String v = domain.getProperty("@");
      if (v == null) return null;
      version = new Version(v);
    }
    String spec = args[1];

    Matcher m = RANGE_MASK.matcher(spec);
    m.matches();
    String floor = m.group(1);
    String floorMask = m.group(2);
    String ceilingMask = m.group(3);
    String ceiling = m.group(4);

    String left = version(version, floorMask);
    String right = version(version, ceilingMask);
    StringBuilder sb = new StringBuilder();
    sb.append(floor);
    sb.append(left);
    sb.append(",");
    sb.append(right);
    sb.append(ceiling);

    String s = sb.toString();
    VersionRange vr = new VersionRange(s);
    if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) {
      domain.error(
          "${range} macro created an invalid range %s from %s and mask %s", s, version, spec);
    }
    return sb.toString();
  }
Ejemplo n.º 10
1
  /**
   * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf");
   * No special handling implemented for escaped (\") quotes.
   */
  private static StringList breakCommas(String contents) {
    StringList outgoing = new StringList();

    boolean insideQuote = false;
    // The current word being read
    StringBuilder current = new StringBuilder();
    char[] chars = contents.toCharArray();
    for (int i = 0; i < chars.length; i++) {
      char c = chars[i];
      if (insideQuote) {
        current.append(c);
        if (c == '\"') {
          insideQuote = false;
        }
      } else {
        if (c == ',') {
          if (current.length() != 0) {
            outgoing.append(current.toString());
            current.setLength(0);
          }
        } else {
          current.append(c);
          if (c == '\"') {
            insideQuote = true;
          }
        }
      }
    }
    if (current.length() != 0) {
      outgoing.append(current.toString());
    }
    return outgoing;
  }
Ejemplo n.º 11
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

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

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
  public String getHtmlReport() {
    StringBuilder generationReport = new StringBuilder();

    Enumeration<String> e = myElecInputs.keys();

    while (e.hasMoreElements()) {
      String elecInputName = e.nextElement();

      StimulationSettings s = project.elecInputInfo.getStim(elecInputName);

      generationReport.append(
          "<b>"
              + ClickProjectHelper.getElecInputLink(elecInputName)
              + "</b> ("
              + s.getElectricalInput().toLinkedString()
              + " on "
              + s.getCellChooser().toNiceString()
              + " of "
              + ClickProjectHelper.getCellGroupLink(s.getCellGroup())
              + ", segs: "
              + s.getSegChooser()
              + ")<br>");

      generationReport.append(
          "Number of individual inputs: <b>"
              + project.generatedElecInputs.getNumberSingleInputs(elecInputName)
              + "</b><br><br>");
    }

    if (generationReport.toString().length() == 0) {
      generationReport.append("No Electrical Inputs generated<br><br>");
    }

    return generationReport.toString();
  }
  private static String makeRequest(String pfamAccession) throws IOException {
    StringBuilder urlBuilder = new StringBuilder();

    urlBuilder.append(MUTATION_ALIGNER_API);
    urlBuilder.append(pfamAccession);
    urlBuilder.append(MUTATION_ALIGNER_API_SUFFIX);

    String url = urlBuilder.toString();

    URL aligner = new URL(url);
    URLConnection alignerCxn = aligner.openConnection();

    StringBuilder sb = new StringBuilder();

    // not found!
    if (((HttpURLConnection) alignerCxn).getResponseCode() != HttpURLConnection.HTTP_OK) {
      sb.append("");
    } else {
      BufferedReader in = new BufferedReader(new InputStreamReader(alignerCxn.getInputStream()));
      String line;

      // Read all
      while ((line = in.readLine()) != null) {
        sb.append(line);
      }

      in.close();
    }

    return sb.toString();
  }
Ejemplo n.º 14
0
  /** Convert the HTML document back to a string. */
  @Override
  public String toString() {
    try {
      StringBuilder result = new StringBuilder();

      int ch = 0;
      StringBuilder text = new StringBuilder();
      do {
        ch = read();
        if (ch == 0) {
          if (text.length() > 0) {
            System.out.println("Text:" + text.toString());
            text.setLength(0);
          }
          System.out.println("Tag:" + getTag());
        } else if (ch != -1) {
          text.append((char) ch);
        }
      } while (ch != -1);
      if (text.length() > 0) {
        System.out.println("Text:" + text.toString().trim());
      }
      return result.toString();
    } catch (IOException e) {
      return "[IO Error]";
    }
  }
Ejemplo n.º 15
0
 public void listIgnores(IgnorePlayer player) {
   if (player.isAllIgnored()) {
     player
         .getPlayer()
         .sendMessage(plugin.getStringFromConfig("ignorecraft.messages.info.ignoreall"));
   } else {
     ArrayList<UUID> ignores = (ArrayList<UUID>) player.getIgnoreList();
     if (ignores.size() <= 0) {
       player
           .getPlayer()
           .sendMessage(plugin.getStringFromConfig("ignorecraft.messages.errors.noignores"));
     } else {
       StringBuilder s = new StringBuilder();
       s.append("&2Ignoring: ");
       for (int i = 0; i < ignores.size(); i++) {
         Player p = plugin.getServer().getPlayer(ignores.get(i));
         s.append("&e");
         s.append(p.getName());
         s.append(", ");
         if (i % 8 == 0 && i != 0) {
           player.getPlayer().sendMessage(PickleCraftPlugin.Colorize(s.toString()));
           s = new StringBuilder();
         }
       }
       String d = s.toString();
       if (!d.isEmpty()) {
         // incase not enough indexs to fire the sendmessage in le loop :c
         player.getPlayer().sendMessage(PickleCraftPlugin.Colorize(d));
       }
     }
   }
 }
Ejemplo n.º 16
0
    public void map(
        Object key, Text value, OutputCollector<IntWritable, Text> output, Reporter reporter)
        throws IOException {

      // vid neighbors_num n1 n2 ...
      // vid color 1/0 "COLOR"
      String str = value.toString();
      if (str.endsWith(COLOR)) {
        // color table
        String[] tokens = str.substring(0, str.length() - 5).split("\\s+");
        int change = Integer.parseInt(tokens[2]);
        if (change == 1) {
          IntWritable SourceId = new IntWritable(Integer.parseInt(tokens[0]));
          StringBuilder sb = new StringBuilder();
          sb.append(tokens[1]);
          sb.append(" ");
          sb.append(tokens[2]);
          sb.append(COLOR);
          output.collect(SourceId, new Text(sb.toString()));
        }
      } else {
        // edge table
        String[] tokens = value.toString().split("\\s+");
        IntWritable SourceId = new IntWritable(Integer.parseInt(tokens[0]));
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < tokens.length; i++) {
          if (sb.length() != 0) sb.append(" ");
          sb.append(tokens[i]);
        }
        output.collect(SourceId, new Text(sb.toString()));
      }
    }
Ejemplo n.º 17
0
  private String readResult(HttpURLConnection urlConnection) throws WeiboException {
    InputStream is = null;
    BufferedReader buffer = null;
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      is = urlConnection.getInputStream();

      String content_encode = urlConnection.getContentEncoding();

      if (null != content_encode && !"".equals(content_encode) && content_encode.equals("gzip")) {
        is = new GZIPInputStream(is);
      }

      buffer = new BufferedReader(new InputStreamReader(is));
      StringBuilder strBuilder = new StringBuilder();
      String line;
      while ((line = buffer.readLine()) != null) {
        strBuilder.append(line);
      }
      AppLogger.d("result=" + strBuilder.toString());
      return strBuilder.toString();
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    } finally {
      Utility.closeSilently(is);
      Utility.closeSilently(buffer);
      urlConnection.disconnect();
    }
  }
 /**
  * Reads a line of text form the current position in this file. A line is represented by zero or
  * more characters followed by {@code '\n'}, {@code '\r'}, {@code "\r\n"} or the end of file
  * marker. The string does not include the line terminating sequence.
  *
  * <p>Blocks until a line terminating sequence has been read, the end of the file is reached or an
  * exception is thrown.
  *
  * @return the contents of the line or {@code null} if no characters have been read before the end
  *     of the file has been reached.
  * @throws IOException if this file is closed or another I/O error occurs.
  */
 public final String readLine() throws IOException {
   StringBuilder line = new StringBuilder(80); // Typical line length
   boolean foundTerminator = false;
   long unreadPosition = -1;
   while (true) {
     int nextByte = read();
     switch (nextByte) {
       case -1:
         return line.length() != 0 ? line.toString() : null;
       case (byte) '\r':
         if (foundTerminator) {
           seek(unreadPosition);
           return line.toString();
         }
         foundTerminator = true;
         /* Have to be able to peek ahead one byte */
         unreadPosition = getPosition();
         break;
       case (byte) '\n':
         return line.toString();
       default:
         if (foundTerminator) {
           seek(unreadPosition);
           return line.toString();
         }
         line.append((char) nextByte);
     }
   }
 }
Ejemplo n.º 19
0
 private static Element parseElement(XMLStreamReader xsr) throws XMLStreamException {
   // xsr points to a START_ELEMENT event. Create the element and read all its attributes
   // Then read all its children events
   Element element = new Element(xsr.getLocalName());
   // text that will be added to the element. Text can come in different events, so we add it here
   // and add it to the element at the end
   StringBuilder elementText = new StringBuilder();
   int attributeCount = xsr.getAttributeCount();
   for (int i = 0; i < attributeCount; i++) {
     element.putAttribute(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
   }
   while (xsr.hasNext()) {
     xsr.next();
     if (xsr.getEventType() == XMLStreamConstants.END_ELEMENT) {
       // element is closed. Move the cursor and return it
       // check if there is some text to add before (empty text is not added, but added text is not
       // trimmed)
       // we set empty text also if the element has no children
       if (!elementText.toString().trim().isEmpty() || !element.hasChildren()) {
         element.setText(elementText.toString());
       }
       //                xsr.next();
       return element;
     } else if (xsr.getEventType() == XMLStreamConstants.CHARACTERS) {
       // an attribute of the current element
       elementText.append(xsr.getText());
     } else if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
       // new element begins -> read it recursively and add it to the current element
       element.addChild(parseElement(xsr));
     }
   }
   // we reached the end of the document without the tag end -> error parsing
   throw new XMLStreamException(
       "End of the document unexpectedly reached. Element " + element.getName() + " not closed");
 }
Ejemplo n.º 20
0
  /**
   * @param clazz the class to be handled (read from and wrote to)
   * @param file the file to be processed
   */
  public void handleConfig(Class<?> clazz, File file) {
    if (!hasRun) {
      hasRun = true;
      for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
          if (annotation.annotationType() == Config.String.class)
            handleString(clazz, field, (Config.String) annotation);
          else if (annotation.annotationType() == Config.Integer.class)
            handleInteger(clazz, field, (Config.Integer) annotation);
          else if (annotation.annotationType() == Config.Boolean.class)
            handleBoolean(clazz, field, (Config.Boolean) annotation);
          else if (annotation.annotationType() == Config.List.class)
            handleList(clazz, field, (Config.List) annotation);
          else if (annotation.annotationType() == Config.Map.class)
            handleMap(clazz, field, (Config.Map) annotation);
          else if (annotation.annotationType() == Config.Long.class)
            handleLong(clazz, field, (Config.Long) annotation);
          else if (annotation.annotationType() == Config.Float.class)
            handleFloat(clazz, field, (Config.Float) annotation);
          else if (annotation.annotationType() == Config.Double.class)
            handleDouble(clazz, field, (Config.Double) annotation);
          else if (annotation.annotationType() == Config.Character.class)
            handleCharacter(clazz, field, (Config.Character) annotation);
        }
      }
    }

    try (BufferedReader reader =
        new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.contains("{")) {
          char[] chars = line.toCharArray();
          boolean hasNotEncounteredText = true;
          StringBuilder stringBuilder = new StringBuilder();
          for (Character character : chars) {
            if ((!character.equals(' ') && !character.equals('\t')) || hasNotEncounteredText) {
              hasNotEncounteredText = false;
              stringBuilder.append(character);
            } else if (character.equals(' ')) break;
          }
          categories
              .getOrDefault(stringBuilder.toString(), categories.get("General"))
              .read(clazz, reader);
        }
      }
    } catch (IOException ignored) {
    }

    StringBuilder stringBuilder = new StringBuilder();
    categories.values().forEach(category -> category.write(stringBuilder));
    String fileString = stringBuilder.toString();

    try (BufferedWriter writer =
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
      writer.append(fileString);
    } catch (IOException ignored) {
    }
  }
Ejemplo n.º 21
0
  private void handleAuthorization(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    PrintWriter writer = resp.getWriter();
    if (req.getParameter("error") != null) {
      writer.append(req.getParameter("error"));
      return;
    }

    String code = req.getParameter("code");

    String redir = (String) req.getSession().getAttribute("redir");
    req.getSession().setAttribute("redir", null);

    if (code == null || redir == null) {
      resp.sendRedirect("/");
      return;
    }

    StringBuilder postParameters = new StringBuilder();
    postParameters.append(para("code", code)).append("&");
    postParameters.append(para("client_id", Configuration.googleClientId())).append("&");
    postParameters.append(para("client_secret", Configuration.googleClientSecret())).append("&");
    postParameters.append(para("redirect_uri", redir)).append("&");
    postParameters.append(para("grant_type", "authorization_code"));
    URL url = new URL("https://accounts.google.com/o/oauth2/token");
    URLConnection urlConnection = url.openConnection();

    ((HttpURLConnection) urlConnection).setRequestMethod("POST");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-Length", "" + postParameters.toString().length());

    // Create I/O streams
    DataOutputStream outStream = new DataOutputStream(urlConnection.getOutputStream());
    // Send request
    outStream.writeBytes(postParameters.toString());
    outStream.flush();
    outStream.close();

    String googleJson = toString(urlConnection.getInputStream());

    JsonObject jsonObject = (JsonObject) JsonParser.parse(googleJson);
    String accessToken = jsonObject.requiredString("access_token");

    // get some info about the user with the access token
    String getStr =
        "https://www.googleapis.com/oauth2/v1/userinfo?" + para("access_token", accessToken);
    URLConnection inconn = new URL(getStr).openConnection();
    String gsstr;
    try (InputStream is = inconn.getInputStream()) {
      gsstr = toString(is);
    }

    updateUserLogin(req, gsstr);
    redirToLandingPage(req, resp);
  }
Ejemplo n.º 22
0
  private String genOptions() {
    /*
     * For multiplechoice
     * <input id="radio1" name="" value="" type="radio" />
     *     <label for="radio1">
     *      Streeful
     *     </label>
     * For checkBox:
     * <input id="checkbox1" name="" type="checkbox" />
     *      <label for="checkbox1">
     *       Apple
     *      </label>
     *
     * For chooselist:
     *
     * <option value="option1">
     *   Option 1
     * </option>
     */
    StringBuilder optHtml = new StringBuilder();
    String optMFormat = "<input id=\"radio%d\" name=\"ans\" value=\"%s\" type=\"radio\" />\n";
    String optMLableFormat = "<label for=\"radio%d\"> %s </label> \n";

    if (this.options.isEmpty()) {
      return optHtml.toString();
    }
    if (this.style.equals(this.MULTIPLECHOICE) || this.style.equals(this.YESNO)) {
      int i = 1;
      for (String option : this.options) {
        optHtml.append(String.format(optMFormat, i, option));
        optHtml.append(String.format(optMLableFormat, i, option));
        i++;
      }
    }

    String optCFormat = "<input id=\"checkbox%d\" name=\"ans\" value=\"%s\" type=\"checkbox\" />\n";
    String optCLableFormat = "<label for=\"checkbox%d\"> %s </label> \n";
    Log.i(TAG, "before entering checkbox");
    if (this.style.equals(this.CHECKBOX)) {
      int j = 1;
      for (String option : this.options) {
        optHtml.append(String.format(optCFormat, j, option));
        optHtml.append(String.format(optCLableFormat, j, option));
        j++;
      }
    }
    String optLFormt = "<option value=\"option%d\"> %s </option>";
    if (this.style.equals(this.CHOOSELIST)) {
      int k = 1;
      for (String option : this.options) {
        optHtml.append(String.format(optLFormt, k, option));

        k++;
      }
    }
    Log.i(TAG, "gen options for:(" + this.style + ")" + optHtml.toString());
    return optHtml.toString();
  }
  // save log to file and return warning messages
  private String logToFile() {
    if (getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS, getPackageName())
        != 0) {
      return null;
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH'h'mm'm'ss's'");
    String logfilename =
        AdPreviewer.ADPREVIEWER_DIR
            + this.getIntent().getExtras().getString("originalFilename")
            + "."
            + dateFormat.format(new Date());
    File logfile = new File(logfilename + ".log");
    File warningsLogfile = new File(logfilename + ".WARNING.log");
    String pidString = null;
    try {
      Log.i(CLASSTAG, "creating log file: " + logfilename);
      logfile.createNewFile();

      Process process = Runtime.getRuntime().exec("logcat -v time -d");
      BufferedReader bufferedReader =
          new BufferedReader(new InputStreamReader(process.getInputStream()));
      StringBuilder log = new StringBuilder();
      StringBuilder warningsLog = new StringBuilder();
      String line;
      int warningsCount = 0;
      while ((line = bufferedReader.readLine()) != null) {
        if (pidString == null && line.indexOf("AdContext") > 0) {
          pidString = line.substring(line.indexOf("("), line.indexOf(")") + 1);
        }
        if (pidString != null && line.indexOf(pidString) > 0) {
          log.append(line + "\n");
          if (line.indexOf("W/") >= 0 || line.indexOf("E/") >= 0) {
            warningsLog.append(line + "\n");
            warningsCount++;
          }
        }
      }

      BufferedWriter out = new BufferedWriter(new FileWriter(logfile));
      out.write(log.toString());
      out.close();

      if (warningsCount > 0) {
        warningsLogfile.createNewFile();
        BufferedWriter out2 = new BufferedWriter(new FileWriter(warningsLogfile));
        out2.write(warningsLog.toString());
        out2.close();
        return warningsLog.toString();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 24
0
 /**
  * Converts a binary string input into a character string output, assuming that 5-bit compaction
  * was used
  */
 private String bin2uppercasefive(String binary) {
   String uppercasefive;
   StringBuilder buffer = new StringBuilder("");
   int len = binary.length();
   for (int i = 0; i < len; i += 5) {
     int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 5), 8)));
     buffer.append((char) (j + 64));
   }
   uppercasefive = buffer.toString();
   return uppercasefive;
 }
Ejemplo n.º 25
0
 public static InputStream getFlexNoPrivStream() {
   try {
     flexNoPrivStream =
         new ByteArrayInputStream(
             sbFlex.toString().getBytes("UTF-8"), 0, sbFlex.toString().getBytes("UTF-8").length);
     flexNoPrivStream.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return flexNoPrivStream;
 }
Ejemplo n.º 26
0
 /** Converts a binary string input into a byte string, using 8-bits per character byte */
 private String bytestring2bin(String bytestring) {
   String binary;
   StringBuilder buffer = new StringBuilder("");
   int len = bytestring.length();
   byte[] bytes = bytestring.getBytes();
   for (int i = 0; i < len; i++) {
     buffer.append(padBinary(dec2bin(Integer.toString(bytes[i])), 8));
   }
   binary = buffer.toString();
   return binary;
 }
Ejemplo n.º 27
0
 /** Converts a byte string input into a binary string, using 8-bits per character byte */
 private String bin2bytestring(String binary) {
   String bytestring;
   StringBuilder buffer = new StringBuilder("");
   int len = binary.length();
   for (int i = 0; i < len; i += 8) {
     int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 8), 8)));
     buffer.append((char) j);
   }
   bytestring = buffer.toString();
   return bytestring;
 }
Ejemplo n.º 28
0
 /**
  * Converts an ASCII string input into a binary string, using 7-bit compaction of each ASCII byte
  */
 private String asciiseven2bin(String asciiseven) {
   String binary;
   StringBuilder buffer = new StringBuilder("");
   int len = asciiseven.length();
   byte[] bytes = asciiseven.getBytes();
   for (int i = 0; i < len; i++) {
     buffer.append(padBinary(dec2bin(Integer.toString(bytes[i] % 128)), 8).substring(1, 8));
   }
   binary = buffer.toString();
   return binary;
 }
Ejemplo n.º 29
0
 /**
  * Converts a binary string input into an ASCII string output, assuming that 7-bit compaction was
  * used
  */
 private String bin2asciiseven(String binary) {
   String asciiseven;
   StringBuilder buffer = new StringBuilder("");
   int len = binary.length();
   for (int i = 0; i < len; i += 7) {
     int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 7), 8)));
     buffer.append((char) j);
   }
   asciiseven = buffer.toString();
   return asciiseven;
 }
Ejemplo n.º 30
0
 /**
  * Converts an alphanumeric string input into a binary string, using 6-bit compaction of each
  * ASCII byte
  */
 private String alphanumsix2bin(String alphanumsix) {
   String binary;
   StringBuilder buffer = new StringBuilder("");
   int len = alphanumsix.length();
   byte[] bytes = alphanumsix.getBytes();
   for (int i = 0; i < len; i++) {
     buffer.append(padBinary(dec2bin(Integer.toString(bytes[i] % 64)), 8).substring(2, 8));
   }
   binary = buffer.toString();
   return binary;
 }