Exemple #1
0
 protected RequestConfig configureRequest(RequestConfig.Builder rcb, Settings settings)
     throws HTTPException {
   // Configure the RequestConfig
   for (Prop key : settings.getKeys()) {
     Object value = settings.getParameter(key);
     boolean tf = (value instanceof Boolean ? (Boolean) value : false);
     if (key == Prop.ALLOW_CIRCULAR_REDIRECTS) {
       rcb.setCircularRedirectsAllowed(tf);
     } else if (key == Prop.HANDLE_REDIRECTS) {
       rcb.setRedirectsEnabled(tf);
       rcb.setRelativeRedirectsAllowed(tf);
     } else if (key == Prop.MAX_REDIRECTS) {
       rcb.setMaxRedirects((Integer) value);
     } else if (key == Prop.SO_TIMEOUT) {
       rcb.setSocketTimeout((Integer) value);
     } else if (key == Prop.CONN_TIMEOUT) {
       rcb.setConnectTimeout((Integer) value);
     } else if (key == Prop.CONN_REQ_TIMEOUT) {
       rcb.setConnectionRequestTimeout((Integer) value);
     } else if (key == Prop.MAX_THREADS) {
       connmgr.setMaxTotal((Integer) value);
       connmgr.setDefaultMaxPerRoute((Integer) value);
     } /* else ignore */
   }
   RequestConfig cfg = rcb.build();
   return cfg;
 }
  public static String getMetadataApplicationId(Context context) {
    Validate.notNull(context, "context");

    Settings.loadDefaultsFromMetadata(context);

    return Settings.getApplicationId();
  }
Exemple #3
0
 public HTTPSession setConnectionTimeout(int timeout) {
   if (timeout <= 0) throw new IllegalArgumentException("setConnectionTImeout");
   localsettings.setParameter(Prop.CONN_TIMEOUT, timeout);
   localsettings.setParameter(Prop.CONN_REQ_TIMEOUT, timeout);
   this.cachevalid = false;
   return this;
 }
 private static Settings settings(DateMapping mapDate, String namespace) {
   final Settings settings = new Settings();
   settings.jsonLibrary = JsonLibrary.jackson2;
   settings.namespace = namespace;
   settings.mapDate = mapDate;
   return settings;
 }
 public void changeLocalFolder(File folder) {
   try {
     File oldFolder = settings.getLocalFolder();
     Files.move(oldFolder.toPath(), folder.toPath(), StandardCopyOption.REPLACE_EXISTING);
     settings.setLocalFolder(folder);
   } catch (IOException ex) {
     model.addErrorMessage("Verzeichnis konnte nicht geändert werden");
   }
   model.fireChange();
 }
Exemple #6
0
  public GalaxyViewer(Settings settings, boolean animatorFrame) throws Exception {
    super("Stars GalaxyViewer");
    this.settings = settings;
    this.animatorFrame = animatorFrame;
    if (settings.gameName.equals("")) throw new Exception("GameName not defined in settings.");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    File dir = new File(settings.directory);
    File map = new File(dir, settings.getGameName() + ".MAP");
    if (map.exists() == false) {
      File f = new File(dir.getParentFile(), settings.getGameName() + ".MAP");
      if (f.exists()) map = f;
      else {
        String error = "Could not find " + map.getAbsolutePath() + "\n";
        error += "Export this file from Stars! (Only needs to be done one time pr game)";
        throw new Exception(error);
      }
    }
    Vector<File> mFiles = new Vector<File>();
    Vector<File> hFiles = new Vector<File>();
    for (File f : dir.listFiles()) {
      if (f.getName().toUpperCase().endsWith("MAP")) continue;
      if (f.getName().toUpperCase().endsWith("HST")) continue;
      if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".M")) mFiles.addElement(f);
      else if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".H"))
        hFiles.addElement(f);
    }
    if (mFiles.size() == 0) throw new Exception("No M-files found matching game name.");
    if (hFiles.size() == 0) throw new Exception("No H-files found matching game name.");
    parseMapFile(map);
    Vector<File> files = new Vector<File>();
    files.addAll(mFiles);
    files.addAll(hFiles);
    p = new Parser(files);
    calculateColors();

    // UI:
    JPanel cp = (JPanel) getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(universe, BorderLayout.CENTER);
    JPanel south = createPanel(0, hw, new JLabel("Search: "), search, names, zoom, colorize);
    search.setPreferredSize(new Dimension(100, -1));
    cp.add(south, BorderLayout.SOUTH);
    hw.addActionListener(this);
    names.addActionListener(this);
    zoom.addChangeListener(this);
    search.addKeyListener(this);
    colorize.addActionListener(this);
    setSize(800, 600);
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((screen.width - getWidth()) / 2, (screen.height - getHeight()) / 2);
    setVisible(animatorFrame == false);
    if (animatorFrame) names.setSelected(false);
  }
Exemple #7
0
 protected void configClient(HttpClientBuilder cb, Settings settings) throws HTTPException {
   cb.useSystemProperties();
   String agent = (String) settings.get(Prop.USER_AGENT);
   if (agent != null) cb.setUserAgent(agent);
   setInterceptors(cb);
   cb.setContentDecoderRegistry(contentDecoderMap);
 }
 public void exit() {
   settings.save();
   saveServers();
   logger.info("Client beendet");
   logDate();
   System.exit(0);
 }
 public void removeThread(WorkerThread thread) {
   threads.remove(thread);
   Logger.log(Level.DEBUG, Messages.getString("connection_closed", Settings.getLocale()));
   if (FancyFileServer.getGUI() != null) {
     FancyFileServer.getGUI().updateConnectionsCounter();
   }
 }
Exemple #10
0
 /**
  * Set the max number of redirects to follow
  *
  * @param n
  */
 public HTTPSession setMaxRedirects(int n) {
   if (n < 0) // validate
   throw new IllegalArgumentException("setMaxRedirects");
   localsettings.setParameter(Prop.MAX_REDIRECTS, n);
   this.cachevalid = false;
   return this;
 }
Exemple #11
0
 public static synchronized void setGlobalCompression(String compressors) {
   if (globalsettings.getParameter(Prop.COMPRESSION) != null) removeGlobalCompression();
   String compresslist = checkCompressors(compressors);
   if (HTTPUtil.nullify(compresslist) == null)
     throw new IllegalArgumentException("Bad compressors: " + compressors);
   globalsettings.setParameter(Prop.COMPRESSION, compresslist);
   HttpResponseInterceptor hrsi;
   if (compresslist.contains("gzip")) {
     hrsi = new GZIPResponseInterceptor();
     rspintercepts.add(hrsi);
   }
   if (compresslist.contains("deflate")) {
     hrsi = new DeflateResponseInterceptor();
     rspintercepts.add(hrsi);
   }
 }
Exemple #12
0
    public static boolean sendTracking(String category, String action, String label) {
        String url = "http://www.google-analytics.com/collect";
        try {
            URL urlObj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
            con.setRequestMethod("POST");

            String urlParameters = "v=1&tid=UA-30896795-3&cid=" + Settings.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label;

            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("Analytics Response [" + category + "]: " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();


            return true;
        } catch (IOException e) {
            return false;
        }
    }
 public void changeSettingsAutoupdate(boolean autoupdate) {
   settings.setAutoupdate(autoupdate);
   if (!autoupdate) {
     updateAllInBackground.interrupt();
   } else {
     startBackgroundThread();
   }
 }
 public void openLocalFolder() {
   try {
     File localFolder = settings.getLocalFolder();
     Desktop.getDesktop().open(localFolder);
   } catch (IOException ex) {
     model.addErrorMessage("Verzeichnis konnte nicht geöffnet werden");
   }
 }
Exemple #15
0
 public static void removeGlobalCompression() {
   if (globalsettings.removeParameter(Prop.COMPRESSION) != null) {
     for (int i = rspintercepts.size() - 1; i >= 0; i--) { // walk backwards
       HttpResponseInterceptor hrsi = rspintercepts.get(i);
       if (hrsi instanceof GZIPResponseInterceptor || hrsi instanceof DeflateResponseInterceptor)
         rspintercepts.remove(i);
     }
   }
 }
 public void changeAutoupdateInterval(String interval) {
   try {
     int newInterval = Integer.parseInt(interval);
     settings.setAutoupdateInterval(newInterval);
   } catch (NumberFormatException ex) {
     model.addErrorMessage("Du musst eine Zahl als Wert angeben!");
   }
   model.fireChange();
 }
Exemple #17
0
 // Provide defaults for a settings map
 protected static void setDefaults(Settings props) {
   if (false) { // turn off for now
     props.setParameter(Prop.HANDLE_AUTHENTICATION, Boolean.TRUE);
   }
   props.setParameter(Prop.HANDLE_REDIRECTS, Boolean.TRUE);
   props.setParameter(Prop.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
   props.setParameter(Prop.MAX_REDIRECTS, (Integer) DFALTREDIRECTS);
   props.setParameter(Prop.SO_TIMEOUT, (Integer) DFALTSOTIMEOUT);
   props.setParameter(Prop.CONN_TIMEOUT, (Integer) DFALTCONNTIMEOUT);
   props.setParameter(Prop.CONN_REQ_TIMEOUT, (Integer) DFALTCONNREQTIMEOUT);
   props.setParameter(Prop.USER_AGENT, DFALTUSERAGENT);
 }
Exemple #18
0
    public static Settings init() throws Exception {
      File f = new File("galaxyviewer.ini");
      if (f.getAbsoluteFile().getParentFile().getName().equals("bin"))
        f = new File("..", "galaxyviewer.ini");
      Settings settings;
      if (f.exists()) {
        settings = new Settings();
        BufferedReader in = new BufferedReader(new FileReader(f));
        while (true) {
          String s = in.readLine();
          if (s == null) break;
          if (s.contains("=") == false) continue;
          String[] el = s.split("=", -1);
          if (el[0].equalsIgnoreCase("PlayerNr"))
            settings.playerNr = Integer.parseInt(el[1].trim()) - 1;
          if (el[0].equalsIgnoreCase("GameName")) settings.gameName = el[1].trim();
          if (el[0].equalsIgnoreCase("GameDir")) settings.directory = el[1].trim();
        }
        in.close();
      } else settings = new Settings();

      JTextField pNr = new JTextField("" + (settings.playerNr + 1));
      JTextField gName = new JTextField(settings.gameName);
      JTextField dir = new JTextField("" + settings.directory);

      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3, 2));
      p.add(new JLabel("Player nr"));
      p.add(pNr);
      p.add(new JLabel("Game name"));
      p.add(gName);
      p.add(new JLabel("Game directory"));
      p.add(dir);
      gName.setToolTipText("Do not include file extensions");
      String[] el = {"Ok", "Cancel"};
      int ok =
          JOptionPane.showOptionDialog(
              null,
              p,
              "Choose settings",
              JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              el,
              el[0]);
      if (ok != 0) System.exit(0);
      settings.playerNr = Integer.parseInt(pNr.getText().trim()) - 1;
      settings.directory = dir.getText().trim();
      settings.gameName = gName.getText().trim();
      BufferedWriter out = new BufferedWriter(new FileWriter(f));
      out.write("PlayerNr=" + (settings.playerNr + 1) + "\n");
      out.write("GameName=" + settings.gameName + "\n");
      out.write("GameDir=" + settings.directory + "\n");
      out.flush();
      out.close();
      return settings;
    }
Exemple #19
0
 public static void main(String[] args) throws Exception {
   try {
     Settings settings = Settings.init();
     new GalaxyViewer(settings, false);
   } catch (Exception ex) {
     ex.printStackTrace();
     System.err.println(ex.toString());
     JOptionPane.showMessageDialog(null, ex.toString());
     System.exit(0);
   }
 }
Exemple #20
0
 public void init(InputStream oldStdin, PipeOutputStream stdin, PipeInputStream stdout)
     throws IOException {
   this.stdoutPipe = stdout;
   this.stdinPipe = stdin;
   this.oldStdin = oldStdin;
   settings.load();
   updater = new Updater();
   UserRegistry.REGISTRY.load();
   manager = new XMPPChatManager();
   copier = new StreamCopier(oldStdin, stdinPipe);
   parser = new LogParser(stdoutPipe);
 }
  @Override
  public void parse(InputStream in, OutputStream out) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
    CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
    Date startTime = Settings.getInstance().getStartTime();
    Date endTime = Settings.getInstance().getEndTime();
    long startTimeVal = startTime == null ? -1 : startTime.getTime();
    long endTimeVal = endTime == null ? -1 : endTime.getTime();

    String line;
    while ((line = reader.readLine()) != null) {
      String[] fields = line.split(",");
      long timestamp = Long.parseLong(fields[0]);
      if (timestamp == 0) {
        LOGGER.warning("Skip invalid data row: " + line);
        continue;
      }
      int rt = Integer.parseInt(fields[1]);
      if (startTimeVal > 0 && timestamp + rt < startTimeVal
          || endTimeVal > 0 && timestamp + rt > endTimeVal) continue;
      String label = fields[2];
      int skip = 0;
      if (fields[4].startsWith("\"")) ++skip;
      if (fields[skip + 5].startsWith("\"")) ++skip;
      int latency = Integer.parseInt(fields[skip + 9]);
      int threads = 0;
      int bytes = Integer.parseInt(fields[skip + 8]);
      boolean error = !Boolean.parseBoolean(fields[skip + 7]);
      csvPrinter.printRecord(
          "TX-" + label + (error ? "-F" : "-S"),
          timestamp,
          threads,
          error ? '1' : '0',
          latency,
          rt,
          bytes);
    }
    writer.flush();
  }
 private void saveServers() {
   File serverDir = new File(settings.getLocalFolder(), "servers");
   if (!serverDir.exists()) {
     serverDir.mkdirs();
   }
   for (Server s : model.getAllServers()) {
     try {
       File serverFile = new File(serverDir, s.getName() + ".server");
       s.writeToFile(serverFile);
     } catch (IOException ex) {
       logger.log(Level.SEVERE, null, ex);
     }
   }
 }
 private Logfile createLogfile() {
   File folder = new File(settings.getLocalFolder(), "logs");
   DateFormat format = new SimpleDateFormat("dd_mm_yyyy");
   Date date = new Date();
   String folderName = format.format(date);
   File logFileFolder = new File(folder, folderName);
   if (!logFileFolder.exists()) {
     logFileFolder.mkdirs();
   }
   int numFiles = logFileFolder.listFiles().length;
   File file = new File(logFileFolder, "log_" + numFiles + ".txt");
   Logfile logfile = new Logfile(file);
   return logfile;
 }
 public void deleteKnownServer() {
   Server currentServer = model.getCurrentServer();
   if (currentServer != null) {
     try {
       model.removeServer(currentServer);
       File serverDir = new File(settings.getLocalFolder(), "servers");
       File serverFile = new File(serverDir, currentServer.getName() + ".server");
       Files.delete(serverFile.toPath());
     } catch (IOException ex) {
       model.addErrorMessage("Server-Datei konnte nicht gelöscht werden");
       logger.log(Level.SEVERE, null, ex);
     }
     model.fireChange();
   }
 }
 public RemoteClientController(RemoteClientModel model) {
   this.model = model;
   settings = new Settings();
   model.setSettings(settings);
   log = createLogfile();
   LogfileHandler handler = new LogfileHandler(log);
   handler.setLevel(Level.ALL);
   logger.addHandler(handler);
   startQueue();
   if (settings.isAutoupdate()) {
     startBackgroundThread();
   }
   logger.info("Client initialisiert");
   logDate();
 }
  public void updateConsole(final boolean fireChange) {
    if (!settings.isUseConsole()) {
      return;
    }
    Runnable r =
        new Runnable() {

          @Override
          public void run() {
            try {
              String[] updates = model.getCurrentServer().updateConsole();
              model.addToConsole(updates);
              if (fireChange) {
                model.fireChange();
              }
            } catch (IOException ex) {
              instantLogout();
              logger.log(Level.SEVERE, null, ex);
            }
          }
        };
    queue.addTask(r);
  }
 public void loadServers() {
   File serverDir = new File(settings.getLocalFolder(), "servers");
   if (serverDir.exists()) {
     for (File f : serverDir.listFiles()) {
       ObjectInputStream oIn = null;
       try {
         oIn = new ObjectInputStream(new FileInputStream(f));
         Server server = (Server) oIn.readObject();
         model.addServer(server);
         oIn.close();
       } catch (IOException | ClassNotFoundException ex) {
         logger.log(Level.SEVERE, null, ex);
       } finally {
         try {
           oIn.close();
         } catch (IOException ex) {
           logger.log(Level.SEVERE, null, ex);
         }
       }
     }
     model.fireChange();
   }
 }
 public void changeSettingsUseConsole(boolean useConsole) {
   settings.setUseConsole(useConsole);
 }
  public void deinit(Appendable out, boolean force) throws Exception {
    Settings settings = new Settings(platform.getConfigFile());

    if (!force) {
      Justif justify = new Justif(80, 40);
      StringBuilder sb = new StringBuilder();
      Formatter f = new Formatter(sb);

      try {
        String list = listFiles(platform.getGlobal());
        if (list != null) {
          f.format("In global default environment:%n");
          f.format(list);
        }

        list = listFiles(platform.getLocal());
        if (list != null) {
          f.format("In local default environment:%n");
          f.format(list);
        }

        if (settings.containsKey(JPM_CACHE_GLOBAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL)));
          if (list != null) {
            f.format("In global configured environment:%n");
            f.format(list);
          }
        }

        if (settings.containsKey(JPM_CACHE_LOCAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL)));
          if (list != null) {
            f.format("In local configured environment:%n");
            f.format(list);
          }
        }

        list = listSupportFiles();
        if (list != null) {
          f.format("jpm support files:%n");
          f.format(list);
        }

        f.format("%n%n");

        f.format(
            "All files listed above will be deleted if deinit is run with the force flag set"
                + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n");
        f.flush();

        justify.wrap(sb);
        out.append(sb.toString());
      } finally {
        f.close();
      }
    } else { // i.e. if(force)
      int count = 0;
      File[] caches = {platform.getGlobal(), platform.getLocal(), null, null};
      if (settings.containsKey(JPM_CACHE_LOCAL)) {
        caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL));
      }
      if (settings.containsKey(JPM_CACHE_GLOBAL)) {
        caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL));
      }
      ArrayList<File> toDelete = new ArrayList<File>();

      for (File cache : caches) {
        if (cache == null || !cache.exists()) {
          continue;
        }
        listFiles(cache, toDelete);
        if (toDelete.size() > count) {
          count = toDelete.size();
          if (!cache.canWrite()) {
            reporter.error(PERMISSION_ERROR + " (" + cache + ")");
            return;
          }
          toDelete.add(cache);
        }
      }
      listSupportFiles(toDelete);

      for (File f : toDelete) {
        if (f.exists() && !f.canWrite()) {
          reporter.error(PERMISSION_ERROR + " (" + f + ")");
        }
      }
      if (reporter.getErrors().size() > 0) {
        return;
      }

      for (File f : toDelete) {
        if (f.exists()) {
          IO.deleteWithException(f);
        }
      }
    }
  }
  public void run() {
    try {
      this.serverSocket = new ServerSocket(Settings.getPropertyInteger("server_port"));
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_open_port_", Settings.getLocale())
              + Settings.getPropertyInteger("server_port"));
      if (FancyFileServer.getGUI() != null) {
        FancyFileServer.getGUI().updateServerStatus();
      }
      return;
    }

    running = true;

    this.parameters = new BasicHttpParams();
    this.parameters.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000);
    this.parameters.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    this.parameters.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    this.parameters.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true);
    this.parameters.setParameter(
        HttpProtocolParams.ORIGIN_SERVER,
        FancyFileServer.NAME.replaceAll("\\s", "-") + "/" + FancyFileServer.VERSION);

    Logger.log(Level.INFO, Messages.getString("server_started", Settings.getLocale()));

    try {
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) interfaces.nextElement();
        if (i.isLoopback() || i.isVirtual()) {
          continue;
        }
        Enumeration<InetAddress> addresses = i.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress a = (InetAddress) addresses.nextElement();
          if (a instanceof Inet4Address) {
            Logger.log(
                Level.INFO,
                Messages.getString("server_address_", Settings.getLocale())
                    + "http://"
                    + a.getHostAddress()
                    + ":"
                    + serverSocket.getLocalPort()
                    + "/");
          }
        }
      }
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_get_server_address_", Settings.getLocale()) + e.getMessage());
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }

    while (running) {
      try {
        /** Set up HTTP connection */
        Socket socket = this.serverSocket.accept();
        DefaultHttpServerConnection connection = new DefaultHttpServerConnection();
        Logger.log(
            Level.DEBUG,
            Messages.getString("incoming_connection_from_", Settings.getLocale())
                + socket.getInetAddress().getHostAddress());
        connection.bind(socket, this.parameters);

        /** Set up HTTP protocol processor */
        BasicHttpProcessor processor = new BasicHttpProcessor();
        processor.addInterceptor(new ResponseDate());
        processor.addInterceptor(new ResponseServer());
        processor.addInterceptor(new ResponseContent());
        processor.addInterceptor(new ResponseConnControl());

        /** Set up HTTP request handlers */
        HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
        registry.register("*", new FileHandler());

        /** Set up HTTP service */
        HttpService service =
            new HttpService(
                processor,
                new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory(),
                registry,
                this.parameters);

        /** Start worker thread */
        WorkerThread t = new WorkerThread(this, service, connection);
        t.setDaemon(true);
        t.start();
      } catch (IOException e) {
        if (running) {
          running = false;
          Logger.log(
              Level.SEVERE,
              Messages.getString("i_o_error_", Settings.getLocale()) + e.getMessage());
          break;
        }
      }
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }
    Logger.log(Level.INFO, Messages.getString("server_stopped", Settings.getLocale()));
  }