Examples of HTMLNode


Examples of freenet.support.HTMLNode

      }

      if(request.isPartSet("delete_request") && (request.getPartAsStringFailsafe("delete_request", 128).length() > 0)) {
        // Confirm box
        PageNode page = ctx.getPageMaker().getPageNode(l10n("confirmDeleteTitle"), ctx);
        HTMLNode inner = page.content;
        HTMLNode content = ctx.getPageMaker().getInfobox("infobox-warning", l10n("confirmDeleteTitle"), inner, "confirm-delete-title", true);
       
        HTMLNode deleteNode = new HTMLNode("p");
        HTMLNode deleteForm = ctx.addFormChild(deleteNode, path(), "queueDeleteForm");
        HTMLNode infoList = deleteForm.addChild("ul");
       
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          part = part.substring("identifier-".length());
          if(part.length() > 50) continue; // It's just a number
         
          String identifier = request.getPartAsStringFailsafe("identifier-"+part, MAX_IDENTIFIER_LENGTH);
          if(identifier == null) continue;
          String filename = request.getPartAsStringFailsafe("filename-"+part, MAX_FILENAME_LENGTH);
          String keyString = request.getPartAsStringFailsafe("key-"+part, MAX_KEY_LENGTH);
          String type = request.getPartAsStringFailsafe("type-"+part, MAX_TYPE_LENGTH);
          String size = request.getPartAsStringFailsafe("size-"+part, 50);
          if(filename != null) {
            HTMLNode line = infoList.addChild("li");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet.filenameLabel")+" ");
            if(keyString != null) {
              line.addChild("a", "href", "/"+keyString, filename);
            } else {
              line.addChild("#", filename);
            }
          }
          if(type != null && !type.equals("")) {
            HTMLNode line = infoList.addChild("li");
            boolean finalized = request.isPartSet("finalizedType");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet."+(finalized ? "mimeType" : "expectedMimeType"), new String[] { "mime" }, new String[] { type }));
          }
          if(size != null) {
            HTMLNode line = infoList.addChild("li");
            line.addChild("#", NodeL10n.getBase().getString("FProxyToadlet.sizeLabel") + " " + size);
          }
          infoList.addChild("#", l10n("deleteFileFromTemp"));
          infoList.addChild("input", new String[] { "type", "name", "value", "checked" },
                  new String[] { "checkbox", "identifier-"+part, identifier, "checked" });
        }
       
        content.addChild("p", l10n("confirmDelete"));
        content.addChild(deleteNode);

        deleteForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "submit", "remove_request", NodeL10n.getBase().getString("Toadlet.yes") });
        deleteForm.addChild("input",
                new String[] { "type", "name", "value" },
                new String[] { "submit", "cancel", NodeL10n.getBase().getString("Toadlet.no") });

        this.writeHTMLReply(ctx, 200, "OK", page.outer.generate());
        return;
      } else if(request.isPartSet("remove_request") && (request.getPartAsStringFailsafe("remove_request", 128).length() > 0)) {
       
        // FIXME optimise into a single database job.
       
        String identifier = "";
        try {
          for(String part : request.getParts()) {
            if(!part.startsWith("identifier-")) continue;
            identifier = part.substring("identifier-".length());
            if(identifier.length() > 50) continue;
            identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
            if(logMINOR) Logger.minor(this, "Removing "+identifier);
            fcp.removeGlobalRequestBlocking(identifier);
          }
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("remove_finished_uploads_request") && (request.getPartAsStringFailsafe("remove_finished_uploads_request", 128).length() > 0)) {
        String identifier = "";
        try {
          RequestStatus[] reqs;
          reqs = fcp.getGlobalRequests();
                                        for(RequestStatus r : reqs) {
            if(r instanceof UploadFileRequestStatus) {
              UploadFileRequestStatus upload = (UploadFileRequestStatus)r;
              if(upload.hasSucceeded()) {
                identifier = upload.getIdentifier();
                fcp.removeGlobalRequestBlocking(identifier);
              }
            }
          } 
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
       
      } else if(request.isPartSet("remove_finished_downloads_request") && (request.getPartAsStringFailsafe("remove_finished_downloads_request", 128).length() > 0)) {
        String identifier = "";
        try {
          RequestStatus[] reqs;
          reqs = fcp.getGlobalRequests();
         
          boolean hasIdentifier = false;
          for(String part : request.getParts()) {
            if(!part.startsWith("identifier-")) continue;
            hasIdentifier = true;
            identifier = part.substring("identifier-".length());
            if(identifier.length() > 50) continue;
            identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
            if(logMINOR) Logger.minor(this, "Removing "+identifier);
            fcp.removeGlobalRequestBlocking(identifier);
          }
         
          if(!hasIdentifier) { // delete all, because no identifier is given
            for(RequestStatus r : reqs) {
              if(r instanceof DownloadRequestStatus) {
                DownloadRequestStatus download = (DownloadRequestStatus)r;
                if(download.isPersistent() && download.hasSucceeded() && download.isTotalFinalized() && !download.toTempSpace()) {
                  identifier = download.getIdentifier();
                  fcp.removeGlobalRequestBlocking(identifier);
                }
              }
            }
          }
        } catch (MessageInvalidException e) {
          this.sendErrorPage(ctx, 200,
              l10n("failedToRemoveRequest"),
              l10n("failedToRemove",
                      new String[]{ "id", "message" },
                      new String[]{ identifier, e.getMessage()}
              ));
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      }
      else if(request.isPartSet("restart_request") && (request.getPartAsStringFailsafe("restart_request", 128).length() > 0)) {
        boolean disableFilterData = request.isPartSet("disableFilterData");
       
       
        String identifier = "";
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          identifier = part.substring("identifier-".length());
          if(identifier.length() > 50) continue;
          identifier = request.getPartAsStringFailsafe(part, MAX_IDENTIFIER_LENGTH);
          if(logMINOR) Logger.minor(this, "Restarting "+identifier);
          try {
            fcp.restartBlocking(identifier, disableFilterData);
          } catch (PersistenceDisabledException e) {
            sendPersistenceDisabledError(ctx);
            return;
          }
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("panic") && (request.getPartAsStringFailsafe("panic", 128).length() > 0)) {
        if(SimpleToadletServer.noConfirmPanic) {
          core.node.killMasterKeysFile();
          core.node.panic();
          sendPanicingPage(ctx);
          core.node.finishPanic();
          return;
        } else {
          sendConfirmPanicPage(ctx);
          return;
        }
      } else if(request.isPartSet("confirmpanic") && (request.getPartAsStringFailsafe("confirmpanic", 128).length() > 0)) {
        core.node.killMasterKeysFile();
        core.node.panic();
        sendPanicingPage(ctx);
        core.node.finishPanic();
        return;
      } else if(request.isPartSet("download")) {
        // Queue a download
        if(!request.isPartSet("key")) {
          writeError(l10n("errorNoKey"), l10n("errorNoKeyToD"), ctx);
          return;
        }
        String expectedMIMEType = null;
        if(request.isPartSet("type")) {
          expectedMIMEType = request.getPartAsStringFailsafe("type", MAX_TYPE_LENGTH);
        }
        FreenetURI fetchURI;
        try {
          fetchURI = new FreenetURI(request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH));
        } catch (MalformedURLException e) {
          writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToD"), ctx);
          return;
        }
        String persistence = request.getPartAsStringFailsafe("persistence", 32);
        String returnType = request.getPartAsStringFailsafe("return-type", 32);
        boolean filterData = request.isPartSet("filterData");
        String downloadPath;
        File downloadsDir = null;
        //Download to disk disabled and initialized.
        if (request.isPartSet("path") && !core.isDownloadDisabled()) {
          downloadPath = request.getPartAsStringFailsafe("path", MAX_FILENAME_LENGTH);
          try {
            downloadsDir = getDownloadsDir(downloadPath);
          } catch (NotAllowedException e) {
            downloadDisallowedPage(e, downloadPath, ctx);
            return;
          }
        //Downloading to disk not initialized and/or disabled.
        } else returnType = "direct";
        try {
          fcp.makePersistentGlobalRequestBlocking(fetchURI, filterData, expectedMIMEType, persistence, returnType, false, downloadsDir);
        } catch (NotAllowedException e) {
          this.writeError(l10n("errorDToDisk"), l10n("errorDToDiskConfig"), ctx);
          return;
        } catch (PersistenceDisabledException e) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        writePermanentRedirect(ctx, "Done", path());
        return;
      } else if(request.isPartSet("bulkDownloads")) {
        String bulkDownloadsAsString = request.getPartAsStringFailsafe("bulkDownloads", 262144);
        String[] keys = bulkDownloadsAsString.split("\n");
        if(("".equals(bulkDownloadsAsString)) || (keys.length < 1)) {
          writePermanentRedirect(ctx, "Done", path());
          return;
        }
        LinkedList<String> success = new LinkedList<String>(), failure = new LinkedList<String>();
        boolean filterData = request.isPartSet("filterData");
        String target = request.getPartAsStringFailsafe("target", 128);
        if(target == null) target = "direct";
        String downloadPath;
        File downloadsDir = null;
        if (request.isPartSet("path") && !core.isDownloadDisabled()) {
          downloadPath = request.getPartAsStringFailsafe("path", MAX_FILENAME_LENGTH);
          try {
            downloadsDir = getDownloadsDir(downloadPath);
          } catch (NotAllowedException e) {
            downloadDisallowedPage(e, downloadPath, ctx);
            return;
          }
        } else target = "direct";

        for(int i=0; i<keys.length; i++) {
          String currentKey = keys[i];

          // trim leading/trailing space
          currentKey = currentKey.trim();
          if (currentKey.length() == 0)
            continue;

          try {
            FreenetURI fetchURI = new FreenetURI(currentKey);
            fcp.makePersistentGlobalRequestBlocking(fetchURI, filterData, null,
                    "forever", target, false, downloadsDir);
            success.add(fetchURI.toString(true, false));
          } catch (Exception e) {
            failure.add(currentKey);
            Logger.error(this,
                    "An error occured while attempting to download key("+i+") : "+
                    currentKey+ " : "+e.getMessage());
          }
        }

        boolean displayFailureBox = failure.size() > 0;
        boolean displaySuccessBox = success.size() > 0;

        PageNode page = ctx.getPageMaker().getPageNode(l10n("downloadFiles"), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;

        HTMLNode alertContent = ctx.getPageMaker().getInfobox(
                (displayFailureBox ? "infobox-warning" : "infobox-info"),
                l10n("downloadFiles"), contentNode, "grouped-downloads", true);
        if(displaySuccessBox) {
          HTMLNode successDiv = alertContent.addChild("ul");
          successDiv.addChild("#", l10n("enqueuedSuccessfully", "number",
                  String.valueOf(success.size())));
          for(String s: success) {
            HTMLNode line = successDiv.addChild("li");
            line.addChild("#", s);
          }
          successDiv.addChild("br");
        }
        if(displayFailureBox) {
          HTMLNode failureDiv = alertContent.addChild("ul");
          if(displayFailureBox) {
            failureDiv.addChild("#", l10n("enqueuedFailure", "number",
                    String.valueOf(failure.size())));
            for(String f: failure) {
              HTMLNode line = failureDiv.addChild("li");
              line.addChild("#", f);
            }
          }
          failureDiv.addChild("br");
        }
        alertContent.addChild("a", "href", path(),
                NodeL10n.getBase().getString("Toadlet.returnToQueuepage"));
        writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      } else if (request.isPartSet("change_priority_top")) {
        handleChangePriority(request, ctx, "_top");
        return;
      } else if (request.isPartSet("change_priority_bottom")) {
        handleChangePriority(request, ctx, "_bottom");
        return;
        // FIXME factor out the next 3 items, they are very messy!
      } else if (request.getPartAsStringFailsafe("insert", 128).length() > 0) {
        final FreenetURI insertURI;
        String keyType = request.getPartAsStringFailsafe("keytype", 10);
        if ("CHK".equals(keyType)) {
          insertURI = new FreenetURI("CHK@");
          if(fiw != null)
            fiw.reportCanonicalInsert();
        } else if("SSK".equals(keyType)) {
          insertURI = new FreenetURI("SSK@");
          if(fiw != null)
            fiw.reportRandomInsert();
        } else if("specify".equals(keyType)) {
          try {
            String u = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
            insertURI = new FreenetURI(u);
            if(logMINOR)
              Logger.minor(this, "Inserting key: "+insertURI+" ("+u+")");
          } catch (MalformedURLException mue1) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx, false, true);
            return;
          }
        } else {
          writeError(l10n("errorMustSpecifyKeyTypeTitle"),
                     l10n("errorMustSpecifyKeyType"), ctx, false, true);
          return;
        }
        final HTTPUploadedFile file = request.getUploadedFile("filename");
        if (file == null || file.getFilename().trim().length() == 0) {
          writeError(l10n("errorNoFileSelected"), l10n("errorNoFileSelectedU"), ctx, false, true);
          return;
        }
        final boolean compress = request.getPartAsStringFailsafe("compress", 128).length() > 0;
        final String identifier = file.getFilename() + "-fred-" + System.currentTimeMillis();
        final String compatibilityMode = request.getPartAsStringFailsafe("compatibilityMode", 100);
        final CompatibilityMode cmode;
        if(compatibilityMode.equals(""))
          cmode = CompatibilityMode.COMPAT_DEFAULT.intern();
        else
          cmode = CompatibilityMode.valueOf(compatibilityMode).intern();
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        final String fnam;
        if(insertURI.getKeyType().equals("CHK") || keyType.equals("SSK"))
          fnam = file.getFilename();
        else
          fnam = null;
        /* copy bucket data */
        final RandomAccessBucket copiedBucket = core.persistentTempBucketFactory.makeBucket(file.getData().size());
        BucketTools.copy(file.getData(), copiedBucket);
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              try {
              final ClientPut clientPut;
              try {
                clientPut = new ClientPut(fcp.getGlobalForeverClient(), insertURI, identifier, Integer.MAX_VALUE, null, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, UploadFrom.DIRECT, null, file.getContentType(), copiedBucket, null, fnam, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, cmode, overrideSplitfileKey, false, fcp.core);
                if(clientPut != null)
                  try {
                    fcp.startBlocking(clientPut, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same file twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (NotAllowedException e) {
                writeError(l10n("errorAccessDenied"), l10n("errorAccessDeniedFile", "file", file.getFilename()), ctx, false, true);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", file.getFilename()), ctx, false, true);
                return false;
              } catch (MalformedURLException mue1) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx, false, true);
                return false;
              } catch (MetadataUnresolvedException e) {
                Logger.error(this, "Unresolved metadata in starting insert from data uploaded from browser: "+e, e);
                writePermanentRedirect(ctx, "Done", path());
                return false;
                // FIXME should this be a proper localised message? It shouldn't happen... but we'd like to get reports if it does.
              } catch (Throwable t) {
                writeInternalError(t, ctx);
                return false;
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet(LocalFileBrowserToadlet.selectFile)) {
        final String filename = request.getPartAsStringFailsafe("filename", MAX_FILENAME_LENGTH);
        if(logMINOR) Logger.minor(this, "Inserting local file: "+filename);
        final File file = new File(filename);
        final String identifier = file.getName() + "-fred-" + System.currentTimeMillis();
        final String contentType = DefaultMIMETypes.guessMIMEType(filename, false);
        final FreenetURI furi;
        final String key = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
        final boolean compress = request.isPartSet("compress");
        final String compatibilityMode = request.getPartAsStringFailsafe("compatibilityMode", 100);
        final CompatibilityMode cmode;
        if(compatibilityMode.equals(""))
          cmode = CompatibilityMode.COMPAT_DEFAULT;
        else
          cmode = CompatibilityMode.valueOf(compatibilityMode);
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        if(key != null) {
          try {
            furi = new FreenetURI(key);
          } catch (MalformedURLException e) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
            return;
          }
        } else {
          furi = new FreenetURI("CHK@");
        }
        final String target;
        if(furi.getDocName() != null)
          target = null;
        else
          target = file.getName();
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartLocalFileInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              final ClientPut clientPut;
              try {
              try {
                clientPut = new ClientPut(fcp.getGlobalForeverClient(), furi, identifier, Integer.MAX_VALUE, null, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, UploadFrom.DISK, file, contentType, new FileBucket(file, true, false, false, false), null, target, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, cmode, overrideSplitfileKey, false, fcp.core);
                if(logMINOR) Logger.minor(this, "Started global request to insert "+file+" to CHK@ as "+identifier);
                if(clientPut != null)
                  try {
                    fcp.startBlocking(clientPut, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  } catch (PersistenceDisabledException e) {
                    // Impossible???
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same file twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (MalformedURLException e) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", target), ctx);
                return false;
              } catch (NotAllowedException e) {
                writeError(l10n("errorAccessDenied"), l10n("errorAccessDeniedFile", new String[]{ "file" }, new String[]{ file.getName() }), ctx);
                return false;
              } catch (MetadataUnresolvedException e) {
                Logger.error(this, "Unresolved metadata in starting insert from data from file: "+e, e);
                writePermanentRedirect(ctx, "Done", path());
                return false;
                // FIXME should this be a proper localised message? It shouldn't happen... but we'd like to get reports if it does.
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet(LocalFileBrowserToadlet.selectDir)) {
        final String filename = request.getPartAsStringFailsafe("filename", MAX_FILENAME_LENGTH);
        if(logMINOR) Logger.minor(this, "Inserting local directory: "+filename);
        final File file = new File(filename);
        final String identifier = file.getName() + "-fred-" + System.currentTimeMillis();
        final FreenetURI furi;
        final String key = request.getPartAsStringFailsafe("key", MAX_KEY_LENGTH);
        final boolean compress = request.isPartSet("compress");
        String s = request.getPartAsStringFailsafe("overrideSplitfileKey", 65);
        final byte[] overrideSplitfileKey;
        if(s != null && !s.equals(""))
          overrideSplitfileKey = HexUtil.hexToBytes(s);
        else
          overrideSplitfileKey = null;
        if(key != null) {
          try {
            furi = new FreenetURI(key);
          } catch (MalformedURLException e) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
            return;
          }
        } else {
          furi = new FreenetURI("CHK@");
        }
        final CountDownLatch done = new CountDownLatch(1);
        try {
          core.clientLayerPersister.queue(new PersistentJob() {

            @Override
            public String toString() {
              return "QueueToadlet StartLocalDirInsert";
            }

            @Override
            public boolean run(ClientContext context) {
              ClientPutDir clientPutDir;
              try {
              try {
                clientPutDir = new ClientPutDir(fcp.getGlobalForeverClient(), furi, identifier, Integer.MAX_VALUE, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, Persistence.FOREVER, null, false, !compress, -1, file, null, false, /* make include hidden files configurable? FIXME */ false, true, false, false, Node.FORK_ON_CACHEABLE_DEFAULT, HighLevelSimpleClientImpl.EXTRA_INSERTS_SINGLE_BLOCK, HighLevelSimpleClientImpl.EXTRA_INSERTS_SPLITFILE_HEADER, false, overrideSplitfileKey, fcp.core);
                if(logMINOR) Logger.minor(this, "Started global request to insert dir "+file+" to "+furi+" as "+identifier);
                if(clientPutDir != null)
                  try {
                    fcp.startBlocking(clientPutDir, context);
                  } catch (IdentifierCollisionException e) {
                    Logger.error(this, "Cannot put same file twice in same millisecond");
                    writePermanentRedirect(ctx, "Done", path());
                    return false;
                  } catch (PersistenceDisabledException e) {
                    sendPersistenceDisabledError(ctx);
                    return false;
                  }
                writePermanentRedirect(ctx, "Done", path());
                return true;
              } catch (IdentifierCollisionException e) {
                Logger.error(this, "Cannot put same directory twice in same millisecond");
                writePermanentRedirect(ctx, "Done", path());
                return false;
              } catch (MalformedURLException e) {
                writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
                return false;
              } catch (FileNotFoundException e) {
                writeError(l10n("errorNoFileOrCannotRead"), l10n("errorAccessDeniedFile", "file", file.toString()), ctx);
                return false;
              } catch (TooManyFilesInsertException e) {
                writeError(l10n("tooManyFilesInOneFolder"), l10n("tooManyFilesInOneFolder"), ctx);
                return false;
              } finally {
                done.countDown();
              }
              } catch (IOException e) {
                // Ignore
                return false;
              } catch (ToadletContextClosedException e) {
                // Ignore
                return false;
              }
            }

          }, NativeThread.HIGH_PRIORITY+1);
        } catch (PersistenceDisabledException e1) {
          sendPersistenceDisabledError(ctx);
          return;
        }
        while (done.getCount() > 0) {
          try {
            done.await();
          } catch (InterruptedException e) {
            // Ignore
          }
        }
        return;
      } else if (request.isPartSet("recommend_request")) {
        PageNode page = ctx.getPageMaker().getPageNode(l10n("recommendAFileToFriends"), ctx);
        HTMLNode pageNode = page.outer;
        HTMLNode contentNode = page.content;
        HTMLNode infoboxContent = ctx.getPageMaker().getInfobox("#", l10n("recommendAFileToFriends"), contentNode, "recommend-file", true);
        HTMLNode form = ctx.addFormChild(infoboxContent, path(), "recommendForm2");
       
        int x = 0;
        for(String part : request.getParts()) {
          if(!part.startsWith("identifier-")) continue;
          String key = request.getPartAsStringFailsafe("key-"+part.substring("identifier-".length()), MAX_KEY_LENGTH);
          if(key == null || key.equals("")) continue;
          form.addChild("#", l10n("key") + ":");
          form.addChild("br");
          form.addChild("#", key);
          form.addChild("br");
          form.addChild("input", new String[] { "type", "name", "value" },
              new String[] { "hidden", "key-"+x, key });
        }
        form.addChild("label", "for", "descB", (l10n("recommendDescription") + ' '));
        form.addChild("br");
        form.addChild("textarea",
                new String[]{"id", "name", "row", "cols"},
                new String[]{"descB", "description", "3", "70"});
        form.addChild("br");

        HTMLNode peerTable = form.addChild("table", "class", "darknet_connections");
        peerTable.addChild("th", "colspan", "2", l10n("recommendToFriends"));
        for(DarknetPeerNode peer : core.node.getDarknetConnections()) {
          HTMLNode peerRow = peerTable.addChild("tr", "class", "darknet_connections_normal");
          peerRow.addChild("td", "class", "peer-marker").addChild("input",
                  new String[] { "type", "name" },
                  new String[] { "checkbox", "node_" + peer.hashCode() });
          peerRow.addChild("td", "class", "peer-name").addChild("#", peer.getName());
        }

        form.addChild("input",
                new String[]{"type", "name", "value"},
                new String[]{"submit", "recommend_uri", l10n("recommend")});
View Full Code Here

Examples of freenet.support.HTMLNode

    if(!(isFailed || isCompleted))
      form.addChild(createPriorityControl(pageMaker, ctx, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS, priorityClasses, advancedModeEnabled, isUpload, top ? "_top" : "_bottom"));
  }

  private HTMLNode createCheckboxCell(RequestStatus clientRequest, int counter) {
    HTMLNode cell = new HTMLNode("td", "class", "checkbox-cell");
    String identifier = clientRequest.getIdentifier();
    cell.addChild("input", new String[] { "type", "name", "value" },
        new String[] { "checkbox", "identifier-"+counter, identifier } );
    FreenetURI uri;
    long size = -1;
    String filename = null;
    if(clientRequest instanceof DownloadRequestStatus) {
      uri = clientRequest.getURI();
      size = clientRequest.getDataSize();
    } else if(clientRequest instanceof UploadRequestStatus) {
      uri = ((UploadRequestStatus)clientRequest).getFinalURI();
      size = clientRequest.getDataSize();
    } else {
      uri = null;
    }
    if(uri != null) {
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "key-"+counter, uri.toASCIIString() });
    }
    filename = clientRequest.getPreferredFilenameSafe();
    if(size != -1)
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "size-"+counter, Long.toString(size) });
    if(filename != null)
      cell.addChild("input", new String[] { "type", "name", "value" },
          new String[] { "hidden", "filename-"+counter, filename });
    return cell;
  }
View Full Code Here

Examples of freenet.support.HTMLNode

          new String[] { "hidden", "filename-"+counter, filename });
    return cell;
  }

  private HTMLNode createCompatModeCell(DownloadRequestStatus get) {
    HTMLNode compatCell = new HTMLNode("td", "class", "request-compat-mode");
    InsertContext.CompatibilityMode[] compat = get.getCompatibilityMode();
    if(!(compat[0] == InsertContext.CompatibilityMode.COMPAT_UNKNOWN && compat[1] == InsertContext.CompatibilityMode.COMPAT_UNKNOWN)) {
      if(compat[0] == compat[1])
        compatCell.addChild("#", NodeL10n.getBase().getString("InsertContext.CompatibilityMode."+compat[0].name())); // FIXME l10n
      else
        compatCell.addChild("#", NodeL10n.getBase().getString("InsertContext.CompatibilityMode."+compat[0].name())+" - "+NodeL10n.getBase().getString("InsertContext.CompatibilityMode."+compat[1].name())); // FIXME l10n
      byte[] overrideCryptoKey = get.getOverriddenSplitfileCryptoKey();
      if(overrideCryptoKey != null)
        compatCell.addChild("#", " - "+l10n("overriddenCryptoKeyInCompatCell")+": "+HexUtil.bytesToHex(overrideCryptoKey));
      if(get.detectedDontCompress())
        compatCell.addChild("#", " ("+l10n("dontCompressInCompatCell")+")");
    }
    return compatCell;
  }
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

         System.out.print(text + " " + node);
   }

   public void testParser() throws Exception
   {
      HTMLNode node =
         HTMLParser.createDocument(new File("C:\\Documents and Settings\\exo\\Desktop\\130033.htm"), "utf-8").getRoot();
      //System.out.println(node.getTextValue());
      //print("", node);
      assertEquals(node.getTextValue(), node.getTextValue());
   }
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

      //Gets the NodePath object locating the path of a TAG in the HTML file.
      NodePath path = NodePathParser.toPath("html.body.h2");

      //Looks for the Node coresponding to the NodePath object of the HTML document.
      //and checks the existing of this TAG.
      HTMLNode node = NodePathUtil.lookFor(document.getRoot(), path);
      assertEquals(node.getName(), Name.H2);
      assertEquals(node.getName().toString(), "H2");

      //Similar as above.
      path = NodePathParser.toPath("html.body.font[1]");
      node = NodePathUtil.lookFor(document.getRoot(), path);
      assertNotNull(node);

      //Gets all the attributes of the Node object in the HTML document.
      //simultaneously checks the existing of an Attribute of this Node.
      Attributes attributes = AttributeParser.getAttributes(node);
      assertEquals(attributes.get("size").getValue(), "4");

      //Removes an Attribute of a Node.
      //and then checks the existing of this Attribute in the attribute collection of the Node.
      attributes.remove("size");
      System.out.println(node.getTextValue());
      //assertNotNull(attributes.get("size"));  
   }
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

   public void testRoot() throws Exception
   {
      HTMLDocument document = HTMLParser.createDocument(this.file_, null);
      assertNotNull(document);
      //HTMLNode root = NodePathUtil.lookFor(document.getRoot(),NodePathParser.toPath("html"));
      HTMLNode root = document.getRoot();
      assertNotNull(root);
      System.out.println("ROOT-NAME: " + root.getName());
      System.out.println("ROOT-VALUE: " + root.getValue().toString());
      System.out.println("ROOT-TEXTVALUE: " + root.getTextValue());
   }
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

   public void testHead() throws Exception
   {
      HTMLDocument document = HTMLParser.createDocument(this.file_, null);
      String pathStr = "html.head";
      NodePath path = NodePathParser.toPath(pathStr);
      HTMLNode node = NodePathUtil.lookFor(document.getRoot(), path);
      assertNotNull(node);
      assertEquals(node.getName(), Name.HEAD);
      assertEquals(node.getName().toString(), "HEAD");
      List<HTMLNode> children = node.getChildrenNode();
      assertNotNull(children);
      int i = 0;
      for (HTMLNode child : children)
      {
         assertNotNull(child);
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

   public void testBody() throws Exception
   {
      HTMLDocument document = HTMLParser.createDocument(this.file_, null);
      String pathStr = "html.body";
      NodePath path = NodePathParser.toPath(pathStr);
      HTMLNode node = NodePathUtil.lookFor(document.getRoot(), path);
      assertNotNull(node);
      assertEquals(node.getName(), Name.BODY);
      assertEquals(node.getName().toString(), "BODY");
   }
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

      NodePath tablePath = NodePathParser.toPath("html.body.table[1]");
      assertNotNull(tablePath);
      System.out.println(tablePath.toString());

      //HTMLNode.
      HTMLNode node = NodePathUtil.lookFor(htmlDocument.getRoot(), tablePath);
      assertNotNull(node);
      assertEquals(node.getName(), Name.TABLE);
      assertEquals(node.getName().toString(), "TABLE");
      System.out.println("NODE-NAME: " + node.getName());
      System.out.println("NODE-VALUE: " + new String(node.getValue()));
      System.out.println("NODE-TEXT VALUE: " + node.getTextValue());

      //Attributes.
      Attributes attrs = AttributeParser.getAttributes(node);
      for (Attribute attr : attrs)
      {
View Full Code Here

Examples of org.exoplatform.services.html.HTMLNode

      NodePath path = NodePathParser.toPath(pathStr);
      assertNotNull(path);
      assertEquals(path.toString(), "HTML[0].HEAD[0].TITLE[0]");
      System.out.println("PATH: " + path.toString());

      HTMLNode node = NodePathUtil.lookFor(document.getRoot(), path);
      assertNotNull(node);
      assertEquals(node.getName(), Name.TITLE);

      //Add a Tag to HTMLDocument.
      NodeImpl impl = new NodeImpl("h2 id = \"dds\"".toCharArray(), Name.H2);
      node.addChild(impl);
      assertNotNull(node.getChildrenNode().get(1));
      assertEquals(node.getChildren().get(1).getName(), Name.H2);
      System.out.println("THE NEW NODE-NAME: " + node.getChildrenNode().get(1).getName().toString());
      System.out.println("THE NEW NODE-VALUE: " + new String(node.getChildren().get(1).getValue()));

      //Add a Table to HTMLDocument.
      HTMLDocument doc = HTMLParser.createDocument("<table border='1'><tr></tr></table>");
      HTMLNode table = NodePathUtil.lookFor(doc.getRoot(), NodePathParser.toPath("html.body.table"));
      node.addChild(table);

      //Remove a Node which is text in format from HTMLDocument.
      System.out.println("\n\nRemove:");
      HTMLNode contentNode = NodePathUtil.lookFor(document.getRoot(), NodePathParser.toPath("html.head.title.content"));
      assertNotNull(contentNode);
      assertEquals(Name.CONTENT, contentNode.getName());
      assertEquals("CONTENT", contentNode.getName().toString());
      assertEquals(new String(contentNode.getValue()), contentNode.getTextValue());

      System.out.println("NODE-VALUE: " + new String(contentNode.getValue()));
      System.out.println("NODE-TEXTVALUE: " + contentNode.getTextValue());

      assertEquals(true, node.getChildren().remove(contentNode));

      //Pass the Node which has removed from HTMLDocument into the <h2> TAG.
      HTMLNode h2Node = NodePathUtil.lookFor(document.getRoot(), NodePathParser.toPath("html.head.title.h2"));
      assertNotNull(h2Node);
      assertEquals(Name.H2, h2Node.getName());
      assertEquals("H2", h2Node.getName().toString());
      h2Node.addChild(contentNode);

      //Show all.
      System.out.println("\n\nShow all the content of HTML file:");
      System.out.println(node.getTextValue());
   }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.