Examples of FreenetURI


Examples of freenet.keys.FreenetURI

      // PUSH N+1 BLOCKS
      for (int i = 0; i <= MAX_N; i++) {
          RandomAccessBucket data = randomData(node);
        HighLevelSimpleClient client = node.clientCore.makeClient((short) 0, false, false);
        FreenetURI uri = new FreenetURI("KSK@" + uid + "-" + dateFormat.format(today.getTime()) + "-" + i);
        System.out.println("PUSHING " + uri);
        client.addEventHook(new ClientEventListener() {

          @Override
          public void receive(ClientEvent ce, ClientContext context) {
            System.out.println(ce.getDescription());
          }
         
        });

        try {
          InsertBlock block = new InsertBlock(data, new ClientMetadata(), uri);
          t1 = System.currentTimeMillis();
          client.insert(block, false, null);
          t2 = System.currentTimeMillis();

          System.out.println("PUSH-TIME-" + i + ":" + (t2 - t1));
          csvLine.add(String.valueOf(t2 - t1));
        } catch (InsertException e) {
          e.printStackTrace();
          csvLine.add("N/A");
        }

        data.free();
      }

      node.park();

      // Node 2
      File innerDir2 = new File(dir, Integer.toString(DARKNET_PORT2));
      innerDir2.mkdir();
      fis = new FileInputStream(seednodes);
      FileUtil.writeTo(fis, new File(innerDir2, "seednodes.fref"));
      fis.close();
      node2 = NodeStarter.createTestNode(DARKNET_PORT2, OPENNET_PORT2, dir.getPath(), false,
              Node.DEFAULT_MAX_HTL, 0, random, new PooledExecutor(), 1000, 5 * 1024 * 1024, true, true, true,
              true, true, true, true, 12 * 1024, false, true, false, false, null);
      node2.start(true);

      t1 = System.currentTimeMillis();
      if (!TestUtil.waitForNodes(node2)) {
        exitCode = EXIT_FAILED_TARGET;
        return;
      }
      t2 = System.currentTimeMillis();
      System.out.println("SEED-TIME:" + (t2 - t1));
      csvLine.add(String.valueOf(t2 - t1));

      // PULL N+1 BLOCKS
      for (int i = 0; i <= MAX_N; i++) {
        HighLevelSimpleClient client = node2.clientCore.makeClient((short) 0, false, false);
        Calendar targetDate = (Calendar) today.clone();
        targetDate.add(Calendar.DAY_OF_MONTH, -((1 << i) - 1));

        FreenetURI uri = new FreenetURI("KSK@" + uid + "-" + dateFormat.format(targetDate.getTime()) + "-" + i);
        System.out.println("PULLING " + uri);

        try {
          t1 = System.currentTimeMillis();
          client.fetch(uri);
View Full Code Here

Examples of freenet.keys.FreenetURI

   * affects whether we do multiple inserts of the same block. */
  private ClientPutState createInserter(BaseClientPutter parent, Bucket data, short compressionCodec,
      InsertContext ctx, PutCompletionCallback cb, boolean isMetadata, int sourceLength, int token,
      boolean addToParent, ClientContext context, boolean freeData, boolean forSplitfile) throws InsertException {
   
    FreenetURI uri = block.desiredURI;
    uri.checkInsertURI(); // will throw an exception if needed
   
    if(uri.getKeyType().equals("USK")) {
      try {
        return new USKInserter(parent, data, compressionCodec, uri, ctx, cb, isMetadata, sourceLength, token,
          addToParent, this.token, context, freeData, persistent, realTimeFlag, forSplitfile ? ctx.extraInsertsSplitfileHeaderBlock : ctx.extraInsertsSingleBlock, cryptoAlgorithm, forceCryptoKey);
      } catch (MalformedURLException e) {
        throw new InsertException(InsertExceptionMode.INVALID_URI, e, null);
View Full Code Here

Examples of freenet.keys.FreenetURI

    try {
      // Browse... button on upload page
      if (request.isPartSet("insert-local")) {
       
        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;
        }
        MultiValueTable<String, String> responseHeaders = new MultiValueTable<String, String>();
        responseHeaders.put("Location", LocalFileInsertToadlet.PATH+"?key="+insertURI.toASCIIString()+
                "&compress="+String.valueOf(request.getPartAsStringFailsafe("compress", 128).length() > 0)+
                "&compatibilityMode="+request.getPartAsStringFailsafe("compatibilityMode", 100)+
                "&overrideSplitfileKey="+request.getPartAsStringFailsafe("overrideSplitfileKey", 65));
        ctx.sendReplyHeaders(302, "Found", responseHeaders, null, 0);
        return;
      } else if (request.isPartSet("select-location")) {
        try {
          throw new RedirectException(LocalDirectoryConfigToadlet.basePath()+"/downloads/");
        } catch (URISyntaxException e) {
          //Shouldn't happen, path is defined as such.
        }
      }

      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")});

        this.writeHTMLReply(ctx, 200, "OK", pageNode.generate());
        return;
      } else if(request.isPartSet("recommend_uri") && request.isPartSet("URI")) {
        String description = request.getPartAsStringFailsafe("description", 32768);
        ArrayList<FreenetURI> uris = new ArrayList<FreenetURI>();
        for(String part : request.getParts()) {
          if(!part.startsWith("key-")) continue;
          String key = request.getPartAsStringFailsafe(part, MAX_KEY_LENGTH);
          try {
            FreenetURI furi = new FreenetURI(key);
            uris.add(furi);
          } catch (MalformedURLException e) {
            writeError(l10n("errorInvalidURI"), l10n("errorInvalidURIToU"), ctx);
            return;
          }
View Full Code Here

Examples of freenet.keys.FreenetURI

    StringBuffer sb = new StringBuffer();

    for(RequestStatus req: reqs) {
      if(req instanceof DownloadRequestStatus) {
        DownloadRequestStatus get = (DownloadRequestStatus)req;
        FreenetURI uri = get.getURI();
        sb.append(uri.toString());
        sb.append("\n");
      }
    }
    return sb.toString();
  }
View Full Code Here

Examples of freenet.keys.FreenetURI

  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) });
View Full Code Here

Examples of freenet.keys.FreenetURI

      if(logMINOR)
        Logger.minor(this, "Request hasn't finished: "+req+" for "+identifier, new Exception("debug"));
      return;
    }
    if(req instanceof ClientGet) {
      FreenetURI uri = ((ClientGet)req).getURI();
      if(uri == null) {
        Logger.error(this, "No URI for supposedly finished request "+req);
        return;
      }
      long size = ((ClientGet)req).getDataSize();
      GetCompletedEvent event = new GetCompletedEvent(identifier, uri, size);
      synchronized(completedGets) {
        completedGets.put(identifier, event);
      }
      core.alerts.register(event);
    } else if(req instanceof ClientPut) {
      FreenetURI uri = ((ClientPut)req).getFinalURI();
      if(uri == null) {
        Logger.error(this, "No URI for supposedly finished request "+req);
        return;
      }
      long size = ((ClientPut)req).getDataSize();
      PutCompletedEvent event = new PutCompletedEvent(identifier, uri, size);
      synchronized(completedPuts) {
        completedPuts.put(identifier, event);
      }
      core.alerts.register(event);
    } else if(req instanceof ClientPutDir) {
      FreenetURI uri = ((ClientPutDir)req).getFinalURI();
      if(uri == null) {
        Logger.error(this, "No URI for supposedly finished request "+req);
        return;
      }
      long size = ((ClientPutDir)req).getTotalDataSize();
View Full Code Here

Examples of freenet.keys.FreenetURI

        if("edit".equals(action)) {
          bookmarkManager.renameBookmark(bookmarkPath, name);
          boolean hasAnActivelink = req.isPartSet("hasAnActivelink");
          if(bookmark instanceof BookmarkItem) {
            BookmarkItem item = (BookmarkItem) bookmark;
            item.update(new FreenetURI(req.getPartAsStringFailsafe("key", MAX_KEY_LENGTH)), hasAnActivelink, req.getPartAsStringFailsafe("descB", MAX_KEY_LENGTH), req.getPartAsStringFailsafe("explain", MAX_EXPLANATION_LENGTH));
            sendBookmarkFeeds(req, item, req.getPartAsStringFailsafe("publicDescB", MAX_KEY_LENGTH));
          }
          bookmarkManager.storeBookmarks();

          pageMaker.getInfobox("infobox-success", NodeL10n.getBase().getString("BookmarkEditorToadlet.changesSavedTitle"), content, "bookmark-error", false).
            addChild("p", NodeL10n.getBase().getString("BookmarkEditorToadlet.changesSaved"));

        } else if("addItem".equals(action) || "addCat".equals(action)) {

          Bookmark newBookmark = null;
          if("addItem".equals(action)) {
            FreenetURI key = new FreenetURI(req.getPartAsStringFailsafe("key", MAX_KEY_LENGTH));
            /* TODO:
             * <nextgens> I suggest you implement a HTTPRequest.getBoolean(String name) using Fields.stringtobool
             * <nextgens> HTTPRequest.getBoolean(String name, boolean default) even
             *
             * - values as "on", "true", "yes" should be accepted.
View Full Code Here

Examples of freenet.keys.FreenetURI

    }
        System.err.println("Inserting test data.");
        HighLevelSimpleClient client = node.clientCore.makeClient((short)0, false, false);
        InsertBlock block = new InsertBlock(data, new ClientMetadata(), FreenetURI.EMPTY_CHK_URI);
        long startInsertTime = System.currentTimeMillis();
        FreenetURI uri;
        try {
      uri = client.insert(block, false, null);
    } catch (InsertException e) {
      System.err.println("INSERT FAILED: "+e);
      e.printStackTrace();
View Full Code Here

Examples of freenet.keys.FreenetURI

  @Override
  public synchronized void onSuccess(ClientPutState state, ClientContext context) {
    USK newEdition = pubUSK.copy(edition);
    finished = true;
    sbi = null;
    FreenetURI targetURI = pubUSK.getSSK(edition).getURI();
    FreenetURI realURI = ((SingleBlockInserter)state).getURI(context);
    if(!targetURI.equals(realURI))
      Logger.error(this, "URI should be "+targetURI+" actually is "+realURI);
    else {
      if(logMINOR)
        Logger.minor(this, "URI should be "+targetURI+" actually is "+realURI);
View Full Code Here

Examples of freenet.keys.FreenetURI

          } catch (NumberFormatException e) {
            insertTimes[i] = -1;
          }
          token++;
          try {
            insertedURIs[i] = new FreenetURI(split[token]);
          } catch (MalformedURLException e) {
            insertedURIs[i] = null;
          }
          token++;
          System.out.println("Key insert "+i+" : "+insertedURIs[i]+" in "+insertTimes[i]);
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.