Esempio n. 1
0
 public void run() {
   try {
     InputStream in;
     OutputStream out;
     try {
       in = sk.getInputStream();
       out = sk.getOutputStream();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
     while (true) {
       try {
         int len = Utils.int32d(read(in, 4), 0);
         if (!auth && (len > 256)) return;
         Message msg = new MessageBuf(read(in, len));
         String cmd = msg.string();
         Object[] args = msg.list();
         Object[] reply;
         if (auth) {
           Command cc = commands.get(cmd);
           if (cc != null) reply = cc.run(this, args);
           else reply = new Object[] {"nocmd"};
         } else {
           if (cmd.equals("nonce")) {
             reply = new Object[] {nonce};
           } else if (cmd.equals("auth")) {
             if (Arrays.equals((byte[]) args[0], ckey)) {
               reply = new Object[] {"ok"};
               auth = true;
             } else {
               reply = new Object[] {"no"};
             }
           } else {
             return;
           }
         }
         MessageBuf rb = new MessageBuf();
         rb.addlist(reply);
         byte[] rbuf = new byte[4 + rb.size()];
         Utils.uint32e(rb.size(), rbuf, 0);
         rb.fin(rbuf, 4);
         out.write(rbuf);
       } catch (IOException e) {
         return;
       }
     }
   } catch (InterruptedException e) {
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
Esempio n. 2
0
  @Override
  public List<FeedValue> getFeed(final int count, final String relationshipEntityKey)
      throws NimbitsException {

    final User loggedInUser = getUser();
    final User feedUser = getFeedUser(relationshipEntityKey, loggedInUser);

    if (feedUser != null) {

      final Point point = getFeedPoint(feedUser);
      if (point == null) {
        return new ArrayList<FeedValue>(0);
      } else {
        final List<Value> values =
            RecordedValueServiceFactory.getInstance().getTopDataSeries(point, count, new Date());
        final List<FeedValue> retObj = new ArrayList<FeedValue>(values.size());

        for (final Value v : values) {
          if (!Utils.isEmptyString(v.getData())) {
            try {
              retObj.add(GsonFactory.getInstance().fromJson(v.getData(), FeedValueModel.class));
            } catch (JsonSyntaxException ignored) {

            }
          }
        }
        return retObj;
      }
    } else {
      return new ArrayList<FeedValue>(0);
    }
  }
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
Esempio n. 4
0
  /** execute method之后,取返回的inputstream */
  private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception {
    int statusCode = client.getResponseCode();
    if (statusCode != HttpURLConnection.HTTP_OK) {
      throw new EnvException("Method failed: " + statusCode);
    }
    InputStream in = client.getResponseStream();
    if (in == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      Utils.copyBinaryTo(in, out);

      // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception
      byte[] bytes = out.toByteArray();
      // carl:格式一致传中文
      String message = new String(bytes, EncodeConstants.ENCODING_UTF_8);
      if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) {
        return null;
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) {
        throw new EnvException(RemoteDeziConstants.INVALID_USER);
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) {
        JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked"));
        return null;
      } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) {
      }
      return new ByteArrayInputStream(bytes);
    } finally {
      in.close();
      out.close();
      client.release();
    }
  }
  public Process(String name, int pid, int n) {

    this.name = name;
    this.port = Utils.REGISTRAR_PORT + pid;

    this.host = "UNKNOWN";
    try {
      this.host = (InetAddress.getLocalHost()).getHostName();

    } catch (UnknownHostException e) {
      String msg = String.format("Error: getHostName() failed at %s.", this.getInfo());
      System.err.println(msg);
      System.err.println(e.getMessage());
      System.exit(1);
    }

    this.pid = pid;
    this.n = n;

    random = new Random();

    /* Accepts connections from one of Registrar's worker threads */
    new Thread(new Listener(this)).start();
    /* Connect to registrar */
    socket = connect();
    init();
    Utils.out(pid, "Connected.");
  }
Esempio n. 6
0
 private void tick(Info info) {
   if (Utils.shouldDefer(info)) return;
   // else
   if (OFFSET == -1) {
     info.sendMessage(
         "Tick not sychronized yet. Wait for the next tick and execute /msg "
             + info.getBot().getName()
             + " !setTickor find out how long until the next tick and execute /msg "
             + info.getBot().getName()
             + " !setTick <mins>");
     return;
   }
   int timeRemaining = 15 - ((15 + Utils.getRealMinutes(info) - OFFSET) % 15);
   long daysSinceSet = (System.currentTimeMillis() - tickTime) / (1000 * 60 * 60 * 24);
   info.sendMessage(
       timeRemaining + " minutes until the next tick (last set " + daysSinceSet + " days ago)");
 }
 /**
  * Get commits
  *
  * @throws IOException
  */
 @Test
 public void getCommits() throws IOException {
   RepositoryId repo = new RepositoryId("bzhang93", "Spoon-Knife");
   service.getCommits(repo);
   GitHubRequest request = new GitHubRequest();
   request.setUri(Utils.page("/repos/bzhang93/Spoon-Knife/commits"));
   verify(client).get(request);
 }
Esempio n. 8
0
  /**
   * 访问服务器环境
   *
   * @param names 参数名字
   * @param values 参数值
   */
  public static void visitEnvServerByParameters(String[] names, String[] values) {
    int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values));
    String[] segs = new String[len];
    for (int i = 0; i < len; i++) {
      try {
        // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\
        // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心.
        String value = values[i].replaceAll("\\\\", "/");
        segs[i] =
            URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8)
                + "="
                + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
    String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY);

    if (FRContext.getCurrentEnv() instanceof RemoteEnv) {
      try {
        if (Utils.isEmbeddedParameter(postfixOfUri)) {
          String time = Calendar.getInstance().getTime().toString().replaceAll(" ", "");
          boolean isUserPrivilege =
              ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri);
          postfixOfUri =
              isUserPrivilege
                  ? postfixOfUri
                      + "&fr_check_url="
                      + time
                      + "&id="
                      + FRContext.getCurrentEnv().getUserID()
                  : postfixOfUri;
        }

        String urlPath = getWebBrowserPath();
        Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri));
      } catch (Exception e) {
        FRContext.getLogger().error("cannot open the url Successful", e);
      }
    } else {
      try {
        String web = GeneralContext.getCurrentAppNameOfEnv();
        String url =
            "http://localhost:"
                + DesignerEnvManager.getEnvManager().getJettyServerPort()
                + "/"
                + web
                + "/"
                + ConfigManager.getProviderInstance().getServletMapping()
                + postfixOfUri;
        StartServer.browerURLWithLocalEnv(url);
      } catch (Throwable e) {
        //
      }
    }
  }
 public boolean registeR() {
   String payload;
   Message m;
   boolean result;
   payload = String.format("%s:%s:%d", name, host, port);
   m = new Message(pid, 0, "NULL", payload);
   result = await(m.pack());
   if (result) Utils.out(pid, "Registered.");
   return result;
 }
Esempio n. 10
0
 private void setTick(Info info, String time) {
   int addon = 0;
   try {
     addon = Integer.parseInt(time);
   } catch (NumberFormatException e) {
     info.sendMessage(
         "Format exception.  Command should be !setTick # where # is the number of minutes till the next tick.");
   }
   tickSetter = info.getSender();
   tickTime = System.currentTimeMillis();
   OFFSET = (Utils.getRealMinutes(info) + addon) % 15;
   info.sendMessage("Tick set to " + OFFSET + " minutes off.");
 }
Esempio n. 11
0
  /**
   * Creates the url that we use to announce to the tracker.
   *
   * @param announceURL the announce url
   * @return appended URL with our updated information
   */
  public URL createURL(URL announceURL) {
    String newURL = announceURL.toString();
    newURL +=
        "?info_hash="
            + Utils.toHexString(this.infohash)
            + "&peer_id="
            + Utils.toHexString(this.peerid)
            + "&port="
            + this.port
            + "&uploaded="
            + this.uploaded
            + "&downloaded="
            + this.downloaded
            + "&left="
            + this.left;
    if (this.event != null) newURL += "&event=" + this.event;

    try {
      return new URL(newURL);
    } catch (MalformedURLException e) {
      log.severe("Error: " + e);
      return null;
    }
  }
Esempio n. 12
0
  @Override
  public void render(Parameters blockParameters, Writer w, RenderHints hints)
      throws FrameworkException {

    if (decorate) {
      try {
        decorateIntro(hints, w, null);
      } catch (IOException ioe) {
        throw new FrameworkException(ioe);
      }
    }
    String name = getResource();
    ResourceLoader loader = ResourceLoader.Type.valueOf(resourceType.toUpperCase()).get();
    try {
      InputStream is = loader.getResourceAsStream(name);
      if (is == null)
        throw new FrameworkException(
            "No such resource " + loader.getResource(name) + " in " + loader);
      if (xsl == null) {
        Reader r = loader.getReader(is, name);
        char[] buf = new char[1000];
        int c;
        while ((c = r.read(buf, 0, 1000)) > 0) {
          w.write(buf, 0, c);
        }
      } else {
        /// convert using the xsl and spit out that.
        URL x = ResourceLoader.getConfigurationRoot().getResource(xsl);
        Utils.xslTransform(blockParameters, loader.getResource(name), is, w, x);
      }
    } catch (IOException ioe) {
      throw new FrameworkException(ioe);
    } catch (javax.xml.transform.TransformerException te) {
      throw new FrameworkException(te.getMessage(), te);
    } catch (RuntimeException e) {
      log.debug(e.getMessage(), e);
      throw e;
    } finally {
      if (decorate) {
        try {
          decorateOutro(hints, w);
        } catch (IOException ioe) {
          throw new FrameworkException(ioe);
        }
      }
    }
  }
Esempio n. 13
0
  private String valueToHtml(final Entity entity, final Entity point, final Value value) {
    final StringBuilder sb = new StringBuilder(SIZE);
    if (!(Double.compare(value.getDoubleValue(), Const.CONST_IGNORED_NUMBER_VALUE) == 0)) {
      sb.append("<img style=\"float:left\" src=\"")
          .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()));

      switch (value.getAlertState()) {
        case LowAlert:
          sb.append("/resources/images/point_low.png\">");
          break;
        case HighAlert:
          sb.append("/resources/images/point_high.png\">");
          break;
        case IdleAlert:
          sb.append("/resources/images/point_idle.png\">");
          break;
        case OK:
          sb.append("/resources/images/point_ok.png\">");
          break;
      }
    }

    if (entity != null && point != null) {

      sb.append("&nbsp;");

      if (!(Double.compare(value.getDoubleValue(), Const.CONST_IGNORED_NUMBER_VALUE) == 0)) {
        sb.append("Alert&nbsp;Status:").append(value.getAlertState().name());
        sb.append("<br>Value:").append(value.getDoubleValue());
      }

      if (!Utils.isEmptyString(value.getNote())) {
        sb.append("<br>Note:").append(value.getNote());
      }

      sb.append("<a href=\"#\" onclick=\"window.open('report.html?uuid=")
          .append(point.getKey())
          .append("', 'Report',")
          .append("'height=800,width=800,toolbar=0,status=0,location=0' );\" >")
          .append("&nbsp;[more]</a>");
    }

    return sb.toString();
  }
Esempio n. 14
0
 private void tickAlarm(Info info) {
   if (OFFSET == -1) {
     info.sendMessage(
         "Tick not sychronized yet. Wait for the next tick and execute /msg "
             + info.getBot().getName()
             + " !setTick or find out how long until the next tick and execute /msg "
             + info.getBot().getName()
             + " !setTick <mins>");
     return;
   }
   int timeRemaining = 15 - ((15 + Utils.getRealMinutes(info) - OFFSET) % 15);
   if (timeRemaining < 2) {
     info.sendMessage(Colors.BLUE + Colors.BOLD + "The tick is in " + timeRemaining + " minutes.");
   } else {
     PingTask ptask = new PingTask(info, "the tick is in one minute.");
     timer.schedule(ptask, (int) ((timeRemaining - 1) * 60 * 1000));
     info.sendMessage("I'll alert you.");
   }
 }
Esempio n. 15
0
  private void nextRaid(Info info) {
    GregorianCalendar nextRaid = raids.get(info.getChannel());
    GregorianCalendar now = Utils.getRealDate(info);
    int diffMins = (int) ((nextRaid.getTimeInMillis() - now.getTimeInMillis()) / 1000 / 60);
    if (nextRaid.compareTo(now) < 0) {
      info.sendMessage("There is no future raid set.");
      return;
    }
    String tz = info.getMessage().substring(9).trim();
    tz = substituteTimeZone(tz);
    TimeZone timeZone;
    if (tz.length() == 0) timeZone = tZF("GMT");
    else timeZone = tZF(tz);
    formatter.setTimeZone(timeZone);

    String ret = "The next raid is scheduled for " + formatter.format(nextRaid.getTime());
    ret = ret + getTimeDifference(diffMins);
    info.sendMessage(ret);
  }
Esempio n. 16
0
    protected authDialog(
        AESemaphore _sem, Display display, String realm, String tracker, String torrent_name) {
      sem = _sem;

      if (display.isDisposed()) {

        sem.release();

        return;
      }

      shell = new Shell(display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

      Utils.setShellIcon(shell);
      Messages.setLanguageText(shell, "authenticator.title");

      GridLayout layout = new GridLayout();
      layout.numColumns = 3;

      shell.setLayout(layout);

      GridData gridData;

      // realm

      Label realm_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(realm_label, "authenticator.realm");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      realm_label.setLayoutData(gridData);

      Label realm_value = new Label(shell, SWT.NULL);
      realm_value.setText(realm.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      realm_value.setLayoutData(gridData);

      // tracker

      Label tracker_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(tracker_label, "authenticator.tracker");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      tracker_label.setLayoutData(gridData);

      Label tracker_value = new Label(shell, SWT.NULL);
      tracker_value.setText(tracker.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      tracker_value.setLayoutData(gridData);

      if (torrent_name != null) {

        Label torrent_label = new Label(shell, SWT.NULL);
        Messages.setLanguageText(torrent_label, "authenticator.torrent");
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 1;
        torrent_label.setLayoutData(gridData);

        Label torrent_value = new Label(shell, SWT.NULL);
        torrent_value.setText(torrent_name.replaceAll("&", "&&"));
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 2;
        torrent_value.setLayoutData(gridData);
      }
      // user

      Label user_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(user_label, "authenticator.user");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      user_label.setLayoutData(gridData);

      final Text user_value = new Text(shell, SWT.BORDER);
      user_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      user_value.setLayoutData(gridData);

      user_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              username = user_value.getText();
            }
          });

      // password

      Label password_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(password_label, "authenticator.password");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      password_label.setLayoutData(gridData);

      final Text password_value = new Text(shell, SWT.BORDER);
      password_value.setEchoChar('*');
      password_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      password_value.setLayoutData(gridData);

      password_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              password = password_value.getText();
            }
          });

      // persist

      Label blank_label = new Label(shell, SWT.NULL);
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      blank_label.setLayoutData(gridData);

      final Button checkBox = new Button(shell, SWT.CHECK);
      checkBox.setText(MessageText.getString("authenticator.savepassword"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      checkBox.setLayoutData(gridData);
      checkBox.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              persist = checkBox.getSelection();
            }
          });

      // line

      Label labelSeparator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
      gridData = new GridData(GridData.FILL_HORIZONTAL);
      gridData.horizontalSpan = 3;
      labelSeparator.setLayoutData(gridData);

      // buttons

      new Label(shell, SWT.NULL);

      Button bOk = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bOk, "Button.ok");
      gridData =
          new GridData(
              GridData.FILL_HORIZONTAL
                  | GridData.HORIZONTAL_ALIGN_END
                  | GridData.HORIZONTAL_ALIGN_FILL);
      gridData.grabExcessHorizontalSpace = true;
      gridData.widthHint = 70;
      bOk.setLayoutData(gridData);
      bOk.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(true);
            }
          });

      Button bCancel = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bCancel, "Button.cancel");
      gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
      gridData.grabExcessHorizontalSpace = false;
      gridData.widthHint = 70;
      bCancel.setLayoutData(gridData);
      bCancel.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(false);
            }
          });

      shell.setDefaultButton(bOk);

      shell.addListener(
          SWT.Traverse,
          new Listener() {
            public void handleEvent(Event e) {
              if (e.character == SWT.ESC) {
                close(false);
              }
            }
          });

      shell.pack();

      Utils.centreWindow(shell);

      shell.open();

      shell.forceActive();
    }
Esempio n. 17
0
 public static void main(String[] args) throws Exception {
   new Server(Integer.parseInt(args[0]), Utils.base64dec(System.getenv("AUTHKEY")));
 }
  @Override
  public void run() {
    if (getMainFrame().getUI_btnDownload() != null)
      getMainFrame().getUI_btnDownload().setEnabled(false);

    String DIR_NAME = "";
    String textInfo = "";

    try {
      DIR_NAME = getMainFrame().getUI_WorkDir();

      Utils.makeDir(DIR_NAME);
      DIR_NAME += Utils.getDirSlash();

      String tileURL = getMainFrame().getUI_ProductName();

      int start_pos_part_base_url = tileURL.lastIndexOf("#tiles") + 7;

      String baseURL =
          "http://sentinel-s2-l1c.s3.amazonaws.com/tiles/"
              + tileURL.substring(start_pos_part_base_url, tileURL.length());

      if (baseURL.charAt(baseURL.length() - 1) != '/') baseURL += "/";

      textInfo =
          "Processing for link:\n"
              + getMainFrame().getUI_ProductName()
              + "\n"
              + "Download information of product...\n";

      FileDownload.doDownload(
          new URL(baseURL + "productInfo.json"),
          DIR_NAME + "productInfo.json",
          getProgressBar(),
          textInfo,
          getTextInfoArea(),
          false);

      String productMetadataURL =
          "http://sentinel-s2-l1c.s3.amazonaws.com/"
              + getProductPath(DIR_NAME + "productInfo.json")
              + "/metadata.xml";

      textInfo = "Download product metadata...\n";
      FileDownload.doDownload(
          new URL(productMetadataURL),
          DIR_NAME + "product_metadata.xml",
          getProgressBar(),
          textInfo,
          getTextInfoArea(),
          false);

      textInfo = "Download tile metadata...\n";

      FileDownload.doDownload(
          new URL(baseURL + "metadata.xml"),
          DIR_NAME + "tile_metadata.xml",
          getProgressBar(),
          textInfo,
          getTextInfoArea(),
          false);

      textInfo = "Download tile preview...\n";

      FileDownload.doDownload(
          new URL(baseURL + "preview.jpg"),
          DIR_NAME + "preview.jpg",
          getProgressBar(),
          textInfo,
          getTextInfoArea(),
          false);

      int[] band_indexes = getMainFrame().getDownloadBandsIndexes();
      if (null == band_indexes) {
        for (int i = 1; i <= 13; i++) {
          String bandFileName = "";
          if (i == 13) bandFileName = "B8A";
          else if (i < 10) bandFileName = "B0" + Integer.toString(i);
          else bandFileName = "B" + Integer.toString(i);

          textInfo = "Download " + bandFileName + "...\n";

          FileDownload.doDownload(
              new URL(baseURL + bandFileName + ".jp2"),
              DIR_NAME + bandFileName + ".jp2",
              getProgressBar(),
              textInfo,
              getTextInfoArea(),
              false);

          postDownloading(
              DIR_NAME + bandFileName + ".jp2",
              getTextInfoArea(),
              Utils.getSpatialResolution(Utils.SENTINEL2_MSI, i));
        }
      } else {
        for (int i : band_indexes) {
          String bandFileName = "";
          if (i == 13) bandFileName = "B8A";
          else if (i < 10) bandFileName = "B0" + Integer.toString(i);
          else bandFileName = "B" + Integer.toString(i);

          textInfo = "Download " + bandFileName + "...\n";

          FileDownload.doDownload(
              new URL(baseURL + bandFileName + ".jp2"),
              DIR_NAME + bandFileName + ".jp2",
              getProgressBar(),
              textInfo,
              getTextInfoArea(),
              false);

          postDownloading(
              DIR_NAME + bandFileName + ".jp2",
              getTextInfoArea(),
              Utils.getSpatialResolution(Utils.SENTINEL2_MSI, i));
        }
      }

      if (m_optionGdalMerge) {
        if (null != band_indexes) {
          String bandNames = "";
          String mergeFileName =
              DIR_NAME
                  + Integer.toString(
                      Utils.getSpatialResolution(Utils.SENTINEL2_MSI, band_indexes[0]))
                  + "M.tif";

          for (int i : band_indexes) {
            String bandFileName = "";
            if (i == 13) bandFileName = "B8A";
            else if (i < 10) bandFileName = "B0" + Integer.toString(i);
            else bandFileName = "B" + Integer.toString(i);

            bandNames += DIR_NAME + bandFileName + ".tif ";
          }

          Utils.printInfo(getTextInfoArea(), "Execute GDAL_MERGE for " + mergeFileName + "...\n");
          if (Utils.getOSType() == Utils.OS_UNIX)
            Utils.runExternProgram("gdal_merge.py -separate -o " + mergeFileName + " " + bandNames);
          else Utils.runExternProgram("cmd /c create_stack.cmd " + mergeFileName + " " + bandNames);
        }
      }

      Utils.printInfo(getTextInfoArea(), "Process COMPLETE.\n");

    } catch (Exception ex) {
    }

    if (getMainFrame().getUI_btnDownload() != null)
      getMainFrame().getUI_btnDownload().setEnabled(true);
  }
  private void postDownloading(String fileName, JTextArea txtInfo, int resolution) {
    if (m_optionDecompress) {
      String name = fileName.substring(0, fileName.lastIndexOf(".jp2"));
      String DirName = name.substring(0, name.lastIndexOf(Utils.getDirSlash()) + 1);
      String outputFileName = name + "_tmp.tif";
      String outputRefFileName = "";

      if (false == m_optionCheckReflectance) outputRefFileName = name + ".tif";
      else outputRefFileName = name + "_tmp2.tif";

      String outputCorrRefFileName = name + ".tif";

      Utils.printInfo(txtInfo, "Decompress " + fileName + "...\n");
      if (Utils.getOSType() == Utils.OS_UNIX)
        Utils.runExternProgram("opj_decompress_jp2 " + fileName + " " + outputFileName);
      else
        Utils.runExternProgram(
            "cmd.exe /C opj_decompress_jp2.cmd " + fileName + " " + outputFileName);

      Utils.printInfo(txtInfo, "Set projection " + outputRefFileName + "...\n");
      if (Utils.getOSType() == Utils.OS_UNIX)
        Utils.runExternProgram(
            "s2_set_projection "
                + outputFileName
                + " "
                + DirName
                + "product_metadata.xml "
                + DirName
                + "tile_metadata.xml "
                + Integer.toString(resolution)
                + " "
                + outputRefFileName
                + " 0");
      else
        Utils.runExternProgram(
            "cmd /c s2_set_projection "
                + outputFileName
                + " "
                + DirName
                + "product_metadata.xml "
                + DirName
                + "tile_metadata.xml "
                + Integer.toString(resolution)
                + " "
                + outputRefFileName
                + " 0");

      if (Utils.getOSType() == Utils.OS_UNIX) Utils.runExternProgram("rm -f " + outputFileName);
      else Utils.runExternProgram("cmd /c del " + outputFileName);

      if (m_optionCheckReflectance) {
        Utils.printInfo(
            txtInfo,
            "Check and correction TOA spectral reflectance " + outputCorrRefFileName + "...\n");
        if (Utils.getOSType() == Utils.OS_UNIX)
          Utils.runExternProgram(
              "check_reflectance " + outputRefFileName + " 1 " + outputCorrRefFileName);
        else
          Utils.runExternProgram(
              "cmd /c check_reflectance " + outputRefFileName + " 1 " + outputCorrRefFileName);

        if (Utils.getOSType() == Utils.OS_UNIX)
          Utils.runExternProgram("rm -f " + outputRefFileName);
        else Utils.runExternProgram("cmd /c del " + outputRefFileName);
      }
    }
  }
    protected authDialog(
        AESemaphore _sem,
        Display display,
        String realm,
        boolean is_tracker,
        String target,
        String details) {
      sem = _sem;

      if (display.isDisposed()) {

        sem.releaseForever();

        return;
      }

      final String ignore_key = "IgnoreAuth:" + realm + ":" + target + ":" + details;

      if (RememberedDecisionsManager.getRememberedDecision(ignore_key) == 1) {

        Debug.out(
            "Authentication for "
                + realm
                + "/"
                + target
                + "/"
                + details
                + " ignored as told not to ask again");

        sem.releaseForever();

        return;
      }

      shell = ShellFactory.createMainShell(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);

      Utils.setShellIcon(shell);
      Messages.setLanguageText(shell, "authenticator.title");

      GridLayout layout = new GridLayout();
      layout.numColumns = 3;

      shell.setLayout(layout);

      GridData gridData;

      // realm

      Label realm_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(realm_label, "authenticator.realm");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      realm_label.setLayoutData(gridData);

      Label realm_value = new Label(shell, SWT.NULL);
      realm_value.setText(realm.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      realm_value.setLayoutData(gridData);

      // target

      Label target_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(
          target_label, is_tracker ? "authenticator.tracker" : "authenticator.location");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      target_label.setLayoutData(gridData);

      Label target_value = new Label(shell, SWT.NULL);
      target_value.setText(target.replaceAll("&", "&&"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      target_value.setLayoutData(gridData);

      if (details != null) {

        Label details_label = new Label(shell, SWT.NULL);
        Messages.setLanguageText(
            details_label, is_tracker ? "authenticator.torrent" : "authenticator.details");
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 1;
        details_label.setLayoutData(gridData);

        Label details_value = new Label(shell, SWT.NULL);
        details_value.setText(details.replaceAll("&", "&&"));
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalSpan = 2;
        details_value.setLayoutData(gridData);
      }
      // user

      Label user_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(user_label, "authenticator.user");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      user_label.setLayoutData(gridData);

      final Text user_value = new Text(shell, SWT.BORDER);
      user_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      user_value.setLayoutData(gridData);

      user_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              username = user_value.getText();
            }
          });

      // password

      Label password_label = new Label(shell, SWT.NULL);
      Messages.setLanguageText(password_label, "authenticator.password");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      password_label.setLayoutData(gridData);

      final Text password_value = new Text(shell, SWT.BORDER);
      password_value.setEchoChar('*');
      password_value.setText("");
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 2;
      password_value.setLayoutData(gridData);

      password_value.addListener(
          SWT.Modify,
          new Listener() {
            public void handleEvent(Event event) {
              password = password_value.getText();
            }
          });

      // persist

      Label blank_label = new Label(shell, SWT.NULL);
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      blank_label.setLayoutData(gridData);

      final Button checkBox = new Button(shell, SWT.CHECK);
      checkBox.setText(MessageText.getString("authenticator.savepassword"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      checkBox.setLayoutData(gridData);
      checkBox.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              persist = checkBox.getSelection();
            }
          });

      final Button dontAsk = new Button(shell, SWT.CHECK);
      dontAsk.setText(MessageText.getString("general.dont.ask.again"));
      gridData = new GridData(GridData.FILL_BOTH);
      gridData.horizontalSpan = 1;
      dontAsk.setLayoutData(gridData);
      dontAsk.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              RememberedDecisionsManager.setRemembered(ignore_key, dontAsk.getSelection() ? 1 : 0);
            }
          });

      // line

      Label labelSeparator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
      gridData = new GridData(GridData.FILL_HORIZONTAL);
      gridData.horizontalSpan = 3;
      labelSeparator.setLayoutData(gridData);

      // buttons

      new Label(shell, SWT.NULL);

      Button bOk = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bOk, "Button.ok");
      gridData =
          new GridData(
              GridData.FILL_HORIZONTAL
                  | GridData.HORIZONTAL_ALIGN_END
                  | GridData.HORIZONTAL_ALIGN_FILL);
      gridData.grabExcessHorizontalSpace = true;
      gridData.widthHint = 70;
      bOk.setLayoutData(gridData);
      bOk.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(true);
            }
          });

      Button bCancel = new Button(shell, SWT.PUSH);
      Messages.setLanguageText(bCancel, "Button.cancel");
      gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
      gridData.grabExcessHorizontalSpace = false;
      gridData.widthHint = 70;
      bCancel.setLayoutData(gridData);
      bCancel.addListener(
          SWT.Selection,
          new Listener() {
            public void handleEvent(Event e) {
              close(false);
            }
          });

      shell.setDefaultButton(bOk);

      shell.addListener(
          SWT.Traverse,
          new Listener() {
            public void handleEvent(Event e) {
              if (e.character == SWT.ESC) {
                close(false);
              }
            }
          });

      shell.pack();

      Utils.centreWindow(shell);

      shell.open();
    }
  public synchronized void receive(Message m) {

    Utils.out(pid, m.toString()); /* The default action. */
  }
Esempio n. 22
0
 private void setTick(Info info) {
   tickSetter = info.getSender();
   tickTime = System.currentTimeMillis();
   OFFSET = Utils.getRealMinutes(info) % 15;
   info.sendMessage("Tick set to " + OFFSET + " minutes off.");
 }
Esempio n. 23
0
 public Session run(HavenPanel hp) throws InterruptedException {
   ui = hp.newui(null);
   ui.setreceiver(this);
   ui.bind(new LoginScreen(ui.root), 1);
   String username;
   boolean savepw = false;
   Utils.setpref("password", "");
   byte[] token = null;
   if (Utils.getpref("savedtoken", "").length() == 64)
     token = Utils.hex2byte(Utils.getpref("savedtoken", null));
   username = Utils.getpref("username", "");
   String authserver = (Config.authserv == null) ? address : Config.authserv;
   retry:
   do {
     byte[] cookie;
     if (initcookie != null) {
       username = inituser;
       cookie = initcookie;
       initcookie = null;
     } else if (token != null) {
       savepw = true;
       ui.uimsg(1, "token", username);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             break;
           } else if (msg.name == "forget") {
             token = null;
             Utils.setpref("savedtoken", "");
             continue retry;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         auth = new AuthClient(authserver, username);
         if (!auth.trytoken(token)) {
           auth.close();
           token = null;
           Utils.setpref("savedtoken", "");
           ui.uimsg(1, "error", "Invalid save");
           continue retry;
         }
         cookie = auth.cookie;
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     } else {
       String password;
       ui.uimsg(1, "passwd", username, savepw);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             username = (String) msg.args[0];
             password = (String) msg.args[1];
             savepw = (Boolean) msg.args[2];
             break;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         try {
           auth = new AuthClient(authserver, username);
         } catch (UnknownHostException e) {
           ui.uimsg(1, "error", "Could not locate server");
           continue retry;
         }
         if (!auth.trypasswd(password)) {
           auth.close();
           password = "";
           ui.uimsg(1, "error", "Username or password incorrect");
           continue retry;
         }
         cookie = auth.cookie;
         if (savepw) {
           if (auth.gettoken()) Utils.setpref("savedtoken", Utils.byte2hex(auth.token));
         }
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     }
     ui.uimsg(1, "prg", "Connecting...");
     try {
       sess = new Session(InetAddress.getByName(address), username, cookie);
     } catch (UnknownHostException e) {
       ui.uimsg(1, "error", "Could not locate server");
       continue retry;
     }
     Thread.sleep(100);
     while (true) {
       if (sess.state == "") {
         Utils.setpref("username", username);
         ui.destroy(1);
         break retry;
       } else if (sess.connfailed != 0) {
         String error;
         switch (sess.connfailed) {
           case 1:
             error = "Invalid authentication token";
             break;
           case 2:
             error = "Already logged in";
             break;
           case 3:
             error = "Could not connect to server";
             break;
           case 4:
             error = "This client is too old";
             break;
           case 5:
             error = "Authentication token expired";
             break;
           default:
             error = "Connection failed";
             break;
         }
         ui.uimsg(1, "error", error);
         sess = null;
         continue retry;
       }
       synchronized (sess) {
         sess.wait();
       }
     }
   } while (true);
   haven.error.ErrorHandler.setprop("usr", sess.username);
   return (sess);
   // (new RemoteUI(sess, ui)).start();
 }