Ejemplo n.º 1
0
 public Enumeration getChildrenInfo() {
   if (nrNeededParams >= 0) {
     return Utils.arrayEnumeration(Utils.arrayConcat(new Object[] {funcOrVal}, getBoundParams()));
   } else {
     return Utils.oneEnumeration(funcOrVal);
   }
 }
Ejemplo n.º 2
0
 public void reloadScript() {
   onDisable();
   try {
     ScriptEngine engine = ((ScriptLoader) loader).getScriptEngine(file);
     engine.put(Utils.getStringOrDefault(engine, "HELPER_VARIABLE_NAME", "helper"), helper);
     engine.put(Utils.getStringOrDefault(engine, "PLUGIN_VARIABLE_NAME", "plugin"), this);
     engine.put(Utils.getStringOrDefault(engine, "SERVER_VARIABLE_NAME", "server"), server);
     sEngine = (Invocable) engine;
   } catch (FileNotFoundException fnfe) {
     log(
         Level.SEVERE,
         String.format(
             "Not reloading script \"%s\"; file not found. Was the script file moved or deleted?",
             file.getName()),
         fnfe);
   } catch (ScriptException sex) {
     log(
         Level.SEVERE,
         String.format("Not reloading script \"%s\"; error while parsing script.", file.getName()),
         sex);
   } catch (InvalidPluginException ipe) {
     log(
         Level.SEVERE,
         String.format(
             "Not reloading script \"%s\"; someone broke jxpl via reflection.", file.getName()),
         ipe);
   } finally {
     onEnable();
   }
 }
Ejemplo n.º 3
0
 private void deflate(String tmpDir, String path) {
   String tmpFile = "tmp-" + Utils.timestamp() + ".zip";
   try {
     ZipFile zipFile = new ZipFile(tmpFile);
     ZipParameters parameters = new ZipParameters();
     parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
     parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
     parameters.setIncludeRootFolder(false);
     zipFile.addFolder(tmpDir, parameters);
   } catch (Exception e) {
     e.printStackTrace();
     return;
   }
   File from = null;
   File to = null;
   try {
     File target = new File(path);
     if (target.exists()) FileUtils.forceDelete(target);
     from = new File(tmpFile);
     to = new File(path);
     FileUtils.moveFile(from, to);
   } catch (IOException e) {
     Utils.onError(new Error.FileMove(tmpFile, path));
   }
   try {
     FileUtils.deleteDirectory(new File(tmpDir));
   } catch (IOException e) {
     Utils.log("can't delete temporary folder");
   }
 }
 /**
  * Received when a peer request a piece. If the piece is available (which should always be the
  * case according to Bittorrent protocol) and we are able and willing to upload, the send the
  * piece to the peer
  *
  * @param peerID String
  * @param piece int
  * @param begin int
  * @param length int
  */
 public synchronized void peerRequest(String peerID, int piece, int begin, int length) {
   if (this.isPieceComplete(piece)) {
     DownloadTask dt = this.task.get(peerID);
     if (dt != null) {
       dt.ms.addMessageToQueue(
           new Message_PP(
               PeerProtocol.PIECE,
               Utils.concat(
                   Utils.intToByteArray(piece),
                   Utils.concat(
                       Utils.intToByteArray(begin), this.getPieceBlock(piece, begin, length)))));
       dt.peer.setULRate(length);
     }
     dt = null;
     this.pu.updateParameters(0, length, "");
   } else {
     try {
       this.task.get(peerID).end();
     } catch (Exception e) {
     }
     this.task.remove(peerID);
     this.peerList.remove(peerID);
     this.unchoken.remove(peerID);
   }
 }
Ejemplo n.º 5
0
 private File initialiseDataFolder() {
   if (Utils.getOrDefault(rdescription, "jxpl.hasdatafolder", false)) {
     File tempFolder = new File(file.getParentFile(), description.getName());
     if (Utils.dirExistOrCreate(tempFolder)) return tempFolder;
   }
   return null;
 }
 public static void generateNativeMethodStubs(
     AnnotationProcessorEnvironment env,
     TypeMap type_map,
     PrintWriter writer,
     InterfaceDeclaration d,
     boolean generate_error_checks,
     boolean context_specific) {
   for (MethodDeclaration method : d.getMethods()) {
     Alternate alt_annotation = method.getAnnotation(Alternate.class);
     if (alt_annotation != null && !alt_annotation.nativeAlt()) continue;
     generateMethodStub(
         env,
         type_map,
         writer,
         Utils.getQualifiedClassName(d),
         method,
         Mode.NORMAL,
         generate_error_checks,
         context_specific);
     if (Utils.hasMethodBufferObjectParameter(method))
       generateMethodStub(
           env,
           type_map,
           writer,
           Utils.getQualifiedClassName(d),
           method,
           Mode.BUFFEROBJECT,
           generate_error_checks,
           context_specific);
   }
 }
  /**
   * Save the downloaded files into the corresponding directories
   *
   * @deprecated
   */
  public synchronized void save() {
    synchronized (this) {
      synchronized (this.isComplete) {
        byte[] data = new byte[0];
        for (int i = 0; i < this.nbPieces; i++) {
          if (this.pieceList[i] == null) {

          } else {
            data = Utils.concat(data, this.pieceList[i].data());
          }
        }
        String saveAs = Constants.SAVEPATH;
        int offset = 0;
        if (this.nbOfFiles > 1) saveAs += this.torrent.saveAs + "/";
        for (int i = 0; i < this.nbOfFiles; i++) {
          try {
            new File(saveAs).mkdirs();
            FileOutputStream fos =
                new FileOutputStream(saveAs + ((String) (this.torrent.name.get(i))));
            fos.write(
                Utils.subArray(data, offset, ((Integer) (this.torrent.length.get(i))).intValue()));
            fos.flush();
            fos.close();
            offset += ((Integer) (this.torrent.length.get(i))).intValue();
          } catch (IOException ioe) {
            ioe.printStackTrace();
            System.err.println(
                "Error when saving the file " + ((String) (this.torrent.name.get(i))));
          }
        }
      }
    }
  }
  /** Initialize all the data structures relevant to the domain */
  private void _initializeDataStructures() {
    this.possibleOperators = new Operator[this.numCakes];
    // Initialize the operators (according to the updated position of the pancake)
    for (int i = 0; i < this.numCakes; ++i) {
      this.possibleOperators[i] = new PancakeOperator(i + 1);
    }
    // Set the maximum index (if it is not already defined)
    if (Pancakes.MAX_PANCAKE_FOR_PDB == -1) {
      this.maxPancakeForPDB = this.numCakes - 1;
    } else {
      this.maxPancakeForPDB = Pancakes.MAX_PANCAKE_FOR_PDB;
    }
    // calculate the bits and bitmask to store single pancake
    this.bitsForSinglePancake = Utils.bits(this.numCakes);
    this.maskForSinglePancake = Utils.mask(this.bitsForSinglePancake);
    // System.out.println("mask: " + this.maskForSinglePancake);
    this.packedCakesInSingleLong =
        Math.min(this.numCakes, (int) Math.floor(64.0d / this.bitsForSinglePancake));
    // System.out.println("packedCakesInSingleLong: " + this.packedCakesInSingleLong);
    this.packedLongsCount = (int) Math.ceil(this.numCakes * this.bitsForSinglePancake / 64.0d);
    // System.out.println("packedLongsCount: " + this.packedLongsCount);

    // Current debugs ..
    // assert(this.bitsForSinglePancake == 5);
    // assert this.packedLongsCount == 2;
  }
Ejemplo n.º 9
0
 private synchronized void doOptions(String url)
     throws NotFoundException, java.net.ConnectException, NotAuthorizedException,
         java.net.UnknownHostException, SocketTimeoutException, IOException,
         com.ettrema.httpclient.HttpException {
   notifyStartRequest();
   String uri = url;
   log.trace("doOptions: {}", url);
   HttpOptions m = new HttpOptions(uri);
   InputStream in = null;
   try {
     int res = Utils.executeHttpWithStatus(client, m, null);
     log.trace("result code: " + res);
     if (res == 301 || res == 302) {
       return;
     }
     Utils.processResultCode(res, url);
   } catch (ConflictException ex) {
     throw new RuntimeException(ex);
   } catch (BadRequestException ex) {
     throw new RuntimeException(ex);
   } finally {
     Utils.close(in);
     notifyFinishRequest();
   }
 }
  public static void main(String[] args) throws Exception {
    // create the keys
    KeyPair pair = Utils.generateRSAKeyPair();

    // create the input stream
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    if (outputFormat.equals(DER)) {
      bOut.write(X509V1CreateExample.generateV1Certificate(pair).getEncoded());
    } else if (outputFormat.equals(PEM)) {
      PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(bOut));
      pemWriter.writeObject(X509V1CreateExample.generateV1Certificate(pair));
      pemWriter.close();
    }

    bOut.close();

    // Print the contents of bOut

    System.out.println(outputFormat.equals(DER) ? "DER-format:" : "PEM-format:");

    System.out.println(Utils.toString(bOut.toByteArray()));

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    // create the certificate factory
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    // read the certificate
    X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in);

    System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
  }
Ejemplo n.º 11
0
 /**
  * 从文件中拿图片
  *
  * @return
  */
 private static Bitmap getBitmapFromFile(Context con, String url, boolean blean) {
   String imageName = "";
   if (!url.startsWith("http")) {
     imageName = url.substring(url.lastIndexOf("/") + 1);
   } else {
     imageName = Utils.getMD5Str(url);
   }
   if (url.contains("ba57b8e1463b63cb01463b7a18eb0083")) {
     MyLogger.commLog().e(imageName);
   }
   Bitmap bitmap = null;
   File file = null;
   String cacheDir = Utils.getCacheDir(con, "picture");
   if (imageName != null) {
     try {
       file = new File(cacheDir, imageName);
       if (file.exists()) {
         // DisplayMetrics dm = context.getResources().getDisplayMetrics();
         // int hh = dm.heightPixels;// 这里设置高度为800f
         // int ww = dm.widthPixels;// 这里设置宽度为480f
         bitmap = decodeSampledBitmapFromFile(cacheDir + "/" + imageName, 100, 100);
       }
     } catch (Exception e) {
       e.printStackTrace();
       bitmap = null;
     }
   }
   if (bitmap != null) {
     addBitmapToMemoryCache(url, bitmap);
     MyLogger.commLog().d(url);
   }
   return bitmap;
 }
Ejemplo n.º 12
0
  /*
   ** calculate, given the examine/ignore and save/refuse values, whether
   ** to examine and/or save s.
   */
  private boolean[] EISR(
      String s, String which, String examine[], String ignore[], String save[], String refuse[]) {
    if (s == null) return (null);

    logger.fine(s);
    logger.fine(which);
    logger.fine(java.util.Arrays.toString(examine));
    logger.fine(java.util.Arrays.toString(ignore));
    logger.fine(java.util.Arrays.toString(save));
    logger.fine(java.util.Arrays.toString(refuse));

    boolean E = Utils.blurf(examine, ignore, s, false);
    boolean S = Utils.blurf(save, refuse, s, false);

    if (args.PrintExamine && E) logger.info("Examining " + which + ": " + s);
    if (args.PrintIgnore && !E) logger.info("Ignoring " + which + ": " + s);

    if (args.PrintSave && S) logger.info("Saving " + which + ": " + s);
    if (args.PrintRefuse && !S) logger.info("Refusing " + which + ": " + s);

    boolean ret[] = new boolean[2];
    ret[0] = E;
    ret[1] = S;
    return (ret);
  }
Ejemplo n.º 13
0
  /**
   * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally the entire
   * buffer must be read, it may be more efficient to read the packed-stream to a file and pass the
   * File object, in the alternate method described below.
   *
   * <p>Closes its input but not its output. (The output can accumulate more elements.)
   *
   * @param in an InputStream.
   * @param out a JarOutputStream.
   * @exception IOException if an error is encountered.
   */
  public void unpack(InputStream in0, JarOutputStream out) throws IOException {
    assert (Utils.currentInstance.get() == null);
    TimeZone tz = (_props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null : TimeZone.getDefault();

    try {
      Utils.currentInstance.set(this);
      if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
      final int verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
      BufferedInputStream in = new BufferedInputStream(in0);
      if (Utils.isJarMagic(Utils.readMagic(in))) {
        if (verbose > 0) Utils.log.info("Copying unpacked JAR file...");
        Utils.copyJarFile(new JarInputStream(in), out);
      } else if (_props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
        (new DoUnpack()).run(in, out);
        in.close();
        Utils.markJarFile(out);
      } else {
        (new NativeUnpack(this)).run(in, out);
        in.close();
        Utils.markJarFile(out);
      }
    } finally {
      _nunp = null;
      Utils.currentInstance.set(null);
      if (tz != null) TimeZone.setDefault(tz);
    }
  }
Ejemplo n.º 14
0
 /**
  * POSTs the variables and returns the body
  *
  * @param url - fully qualified and encoded URL to post to
  * @param params
  * @return
  */
 public String doPost(String url, Map<String, String> params)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException {
   notifyStartRequest();
   HttpPost m = new HttpPost(url);
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   for (Entry<String, String> entry : params.entrySet()) {
     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
   }
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams);
   } catch (UnsupportedEncodingException ex) {
     throw new RuntimeException(ex);
   }
   m.setEntity(entity);
   try {
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
     int res = Utils.executeHttpWithStatus(client, m, bout);
     Utils.processResultCode(res, url);
     return bout.toString();
   } catch (HttpException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 15
0
  public boolean load(String filepath) throws FileNotFoundException {
    fileType = "OBJ"; // Set the file type to OBJ in case we ever want to later identify its source
    filePath =
        Utils.dirFromPath(
            filepath); // The fileName is the ENTIRE path to the file (including the filename)
    objName = Utils.fileFromPath(filepath); // The objName is strictly the filename to begin with
    readVerts(filepath); // Read all of the vertices from the file
    // readTexVerts(filepath);	// Read all of the texture vertices (if any) from the file)

    // Read any materials from the file
    // If no materials are loaded, a default one will be assigned
    if (readMaterials(filepath) == -1) {
      System.out.println("Not all materials could be loaded for: " + filepath);
      System.out.println("Surfaces with no materials will be assigned a default material");
    } // end if

    readSurfaces(filepath); // Read all surface information
    countPolyVerts(); // Calculates how many vertices are in each polygon
    calcPolyNorms(); // Calculate all polygon normals (never rely on the file itself)
    calcVertNorms(); // Calculate all vertex normals based on polygon normals
    boundingSphere = calcBoundingSphere(); // Calculate the bounding sphere for raytracing

    active = true; // We've just created an object...so make it active!
    next = null; // Next object in the linked list is null

    // This simply loads the modelMat with an identity matrix.
    modelMat = MatrixOps.newIdentity();

    // System.out.println("\nObject loaded!\n");
    loadBuffers();
    return true;
  } // end method load
Ejemplo n.º 16
0
  private String getSingleLineOfChildren(final List children) {
    final StringBuilder result = new StringBuilder();
    final Iterator childrenIt = children.iterator();
    boolean isFirst = true;

    while (childrenIt.hasNext()) {
      final Object child = childrenIt.next();

      if (!(child instanceof ContentNode)) {
        return null;
      } else {
        String content = child.toString();

        // if first item trims it from left
        if (isFirst) {
          content = Utils.ltrim(content);
        }

        // if last item trims it from right
        if (!childrenIt.hasNext()) {
          content = Utils.rtrim(content);
        }

        if (content.indexOf('\n') >= 0 || content.indexOf('\r') >= 0) {
          return null;
        }
        result.append(content);
      }

      isFirst = false;
    }

    return result.toString();
  }
Ejemplo n.º 17
0
 public Enumeration getSuccessors() {
   Object[] params = getBoundParams();
   Object[] succ = params;
   if (funcOrVal instanceof Eval) {
     succ = Utils.arrayCons(funcOrVal, params);
   }
   return Utils.arrayEnumeration(succ);
 }
Ejemplo n.º 18
0
  private int printThreadGroup(OutputSink out, ThreadGroupReference tg, int iThread) {
    out.println("Group " + tg.name() + ":");
    List<ThreadReference> tlist = tg.threads();
    int maxId = 0;
    int maxName = 0;
    for (int i = 0; i < tlist.size(); i++) {
      ThreadReference thr = tlist.get(i);
      int len = Utils.description(thr).length();
      if (len > maxId) {
        maxId = len;
      }
      String name = thr.name();
      int iDot = name.lastIndexOf('.');
      if (iDot >= 0 && name.length() > iDot) {
        name = name.substring(iDot + 1);
      }
      if (name.length() > maxName) {
        maxName = name.length();
      }
    }
    String maxNumString = String.valueOf(iThread + tlist.size());
    int maxNumDigits = maxNumString.length();
    for (int i = 0; i < tlist.size(); i++) {
      ThreadReference thr = tlist.get(i);
      char buf[] = new char[80];
      for (int j = 0; j < 79; j++) {
        buf[j] = ' ';
      }
      buf[79] = '\0';
      StringBuffer sbOut = new StringBuffer();
      sbOut.append(buf);

      // Right-justify the thread number at start of output string
      String numString = String.valueOf(iThread + i + 1);
      sbOut.insert(maxNumDigits - numString.length(), numString);
      sbOut.insert(maxNumDigits, ".");

      int iBuf = maxNumDigits + 2;
      sbOut.insert(iBuf, Utils.description(thr));
      iBuf += maxId + 1;
      String name = thr.name();
      int iDot = name.lastIndexOf('.');
      if (iDot >= 0 && name.length() > iDot) {
        name = name.substring(iDot + 1);
      }
      sbOut.insert(iBuf, name);
      iBuf += maxName + 1;
      sbOut.insert(iBuf, Utils.getStatus(thr));
      sbOut.setLength(79);
      out.println(sbOut.toString());
    }
    for (ThreadGroupReference tg0 : tg.threadGroups()) {
      if (!tg.equals(tg0)) { // TODO ref mgt
        iThread += printThreadGroup(out, tg0, iThread + tlist.size());
      }
    }
    return tlist.size();
  }
Ejemplo n.º 19
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));
     }
   }
 }
Ejemplo n.º 20
0
    public void run(BufferedInputStream in, JarOutputStream out) throws IOException {
      if (verbose > 0) {
        _props.list(System.out);
      }
      for (int seg = 1; ; seg++) {
        unpackSegment(in, out);

        // Try to get another segment.
        if (!Utils.isPackMagic(Utils.readMagic(in))) break;
        if (verbose > 0) Utils.log.info("Finished segment #" + seg);
      }
    }
Ejemplo n.º 21
0
 /**
  * @param sourceUrl - encoded source url
  * @param newUri - encoded destination url
  * @return
  * @throws IOException
  * @throws com.ettrema.httpclient.HttpException
  */
 public synchronized int doMove(String sourceUrl, String newUri)
     throws IOException, com.ettrema.httpclient.HttpException, NotAuthorizedException,
         ConflictException, BadRequestException, NotFoundException, URISyntaxException {
   notifyStartRequest();
   MoveMethod m = new MoveMethod(sourceUrl, newUri);
   try {
     int res = Utils.executeHttpWithStatus(client, m, null);
     Utils.processResultCode(res, sourceUrl);
     return res;
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 22
0
 private YamlConfiguration getDefaultConfig() {
   try {
     Map<String, Object> defmap =
         (Map<String, Object>) Utils.getOrExcept((ScriptEngine) sEngine, "DEFAULT_CONFIG");
     YamlConfiguration yamldef = new YamlConfiguration();
     Utils.callMethodHelper(yamldef, "deserializeValues", defmap, yamldef);
     return yamldef;
   } catch (IllegalArgumentException e) {
   } catch (Throwable t) {
     log(Level.SEVERE, "Failed to get default config!", t);
   }
   return null;
 }
Ejemplo n.º 23
0
 private void call(Node operation)
     throws ParserConfigurationException, TransformerConfigurationException {
   String opName = operation.getNodeName();
   if (opName.equals("call")) {
     String script =
         Utils.combine(Utils.getParentDir(this.currentScript), operation.getTextContent());
     call(script);
   } else if (opName.equals("apply")) processApply(operation);
   else if (opName.equals("xml")) processXml(operation);
   else if (opName.equals("txt")) processTxt(operation);
   else if (opName.equals("copy")) processCopy(operation);
   else if (opName.equals("delete")) processDelete(operation);
 }
Ejemplo n.º 24
0
  /**
   * Parses a given list of options.
   *
   * @param options the list of options as an array of strings
   * @exception Exception if an option is not supported
   */
  public void setOptions(String[] options) throws Exception {

    String optionString = Utils.getOption('N', options);

    if (optionString.length() != 0) {
      setNumClusters(Integer.parseInt(optionString));
    }

    optionString = Utils.getOption('S', options);

    if (optionString.length() != 0) {
      setSeed(Integer.parseInt(optionString));
    }
  }
Ejemplo n.º 25
0
 /**
  * @param url - encoded url
  * @return
  * @throws IOException
  * @throws com.ettrema.httpclient.HttpException
  */
 public synchronized int doDelete(String url)
     throws IOException, com.ettrema.httpclient.HttpException, NotAuthorizedException,
         ConflictException, BadRequestException, NotFoundException {
   notifyStartRequest();
   HttpDelete m = new HttpDelete(url);
   try {
     int res = Utils.executeHttpWithStatus(client, m, null);
     Utils.processResultCode(res, url);
     return res;
   } catch (HttpException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 26
0
 /**
  * @param uri - must be encoded
  * @param lockToken
  * @return
  * @throws com.ettrema.httpclient.HttpException
  */
 public synchronized int doUnLock(String uri, String lockToken)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException, URISyntaxException {
   notifyStartRequest();
   UnLockMethod p = new UnLockMethod(uri, lockToken);
   try {
     int result = Utils.executeHttpWithStatus(client, p, null);
     Utils.processResultCode(result, uri);
     return result;
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Ejemplo n.º 27
0
 private String inflate(String path) {
   if (!new File(path).canRead()) {
     Utils.onError(new Error.FileRead(path));
     return null;
   }
   String tmpDir = "tmp-" + Utils.timestamp();
   try {
     ZipFile zipFile = new ZipFile(path);
     zipFile.extractAll(tmpDir);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
   return tmpDir;
 }
Ejemplo n.º 28
0
 private void savewndstate() {
   if (prefs == null) {
     if (getExtendedState() == NORMAL)
     /* Apparent, getSize attempts to return the "outer
      * size" of the window, including WM decorations, even
      * though setSize sets the "inner size" of the
      * window. Therefore, use the Panel's size instead; it
      * ought to correspond to the inner size at all
      * times. */ {
       Dimension dim = p.getSize();
       Utils.setprefc("wndsz", new Coord(dim.width, dim.height));
     }
     Utils.setprefb("wndmax", (getExtendedState() & MAXIMIZED_BOTH) != 0);
   }
 }
  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.");
  }
Ejemplo n.º 30
0
 private static void main2(String[] args) {
   Config.cmdline(args);
   try {
     javabughack();
   } catch (InterruptedException e) {
     return;
   }
   setupres();
   MainFrame f = new MainFrame(null);
   if (Utils.getprefb("fullscreen", false)) f.setfs();
   f.mt.start();
   try {
     f.mt.join();
   } catch (InterruptedException e) {
     f.g.interrupt();
     return;
   }
   dumplist(Resource.remote().loadwaited(), Config.loadwaited);
   dumplist(Resource.remote().cached(), Config.allused);
   if (ResCache.global != null) {
     try {
       Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8");
       try {
         Resource.dumplist(Resource.remote().used(), w);
       } finally {
         w.close();
       }
     } catch (IOException e) {
     }
   }
   System.exit(0);
 }