/** Initialize the (java.bean) PropertyDescriptors for the properties */
 private void initPropertyDescriptor() {
   for (Iterator<String> it = orderedExportedProperties.iterator(); it.hasNext(); ) {
     String propertyName = it.next();
     try {
       // we're using this specialized constructor since we want to allow properties that are
       // read-only (such as creationDate).
       // with the simpler constructor (String,Class) that would result in an Exception.
       // also note that we're using "is"+propertyName rather than get - that's the way the
       // PropertyDescriptor itself
       // does it in the constructor (String,Class) - resulting in a lookup of an is Method first
       // and then the get Method
       // this seems to be the correct standard here.
       PropertyDescriptor pd =
           new PropertyDescriptor(
               propertyName, LoggingObject.class, "is" + capitalize(propertyName), null);
       orderedExportedPropertyDescriptors.add(pd);
     } catch (IntrospectionException e) {
       log_.error(
           "initPropertyDescriptor: Could not retrieve property "
               + propertyName
               + " from LoggingObject, configuration error?",
           e);
     }
   }
 }
  private Versions readVersions(VFSLeaf leaf, VFSLeaf fVersions) {
    if (fVersions == null) {
      return new NotVersioned();
    }

    try {
      VFSContainer fVersionContainer = fVersions.getParentContainer();
      VersionsFileImpl versions = (VersionsFileImpl) XStreamHelper.readObject(mystream, fVersions);
      versions.setVersionFile(fVersions);
      versions.setCurrentVersion((Versionable) leaf);
      if (versions.getRevisionNr() == null || versions.getRevisionNr().length() == 0) {
        versions.setRevisionNr(getNextRevisionNr(versions));
      }

      for (VFSRevision revision : versions.getRevisions()) {
        RevisionFileImpl revisionImpl = (RevisionFileImpl) revision;
        revisionImpl.setContainer(fVersionContainer);
      }
      return versions;
    } catch (Exception e) {
      log.warn("This file is not a versions XML file: " + fVersions, e);
      fVersions.delete();
      VersionsFileImpl versions = new VersionsFileImpl();
      versions.setCurrentVersion((Versionable) leaf);
      versions.setVersioned(isVersioned(leaf));
      versions.setRevisionNr(getNextRevisionNr(versions));
      log.warn("Deleted corrupt version XML file and created new version XML file: " + versions);
      // the old revisions can not be restored automatically. They are still on disk, you could
      // recover them
      // manually. This is not a perfect solution, but at least the user does not get an RS
      return versions;
    }
  }
Example #3
0
  /** Used by to task executor, without any GUI */
  @Override
  public void run() {
    final List<BulkAssessmentFeedback> feedbacks = new ArrayList<>();
    try {
      log.audit("Start process bulk assessment");

      LoggingResourceable[] infos = new LoggingResourceable[2];
      if (task != null && task.getCreator() != null) {
        UserSession session = new UserSession();
        session.setIdentity(task.getCreator());
        session.setSessionInfo(
            new SessionInfo(task.getCreator().getKey(), task.getCreator().getName()));
        ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(session);
        infos[0] = LoggingResourceable.wrap(courseRes, OlatResourceableType.course);
        ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[0]);
        infos[1] = LoggingResourceable.wrap(getCourseNode());
        ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[1]);
      }

      doProcess(feedbacks);
      log.audit("End process bulk assessment");
      cleanup();

      ThreadLocalUserActivityLogger.log(AssessmentLoggingAction.ASSESSMENT_BULK, getClass(), infos);
    } catch (Exception e) {
      log.error("", e);
      feedbacks.add(new BulkAssessmentFeedback("", "bulk.assessment.error"));
      throw e;
    } finally {
      cleanupUnzip();
      sendFeedback(feedbacks);
    }
  }
  /**
   * Copy an InputStream to an OutputStream.
   *
   * @param source InputStream, left open.
   * @param target OutputStream, left open.
   * @param length how many bytes to copy.
   * @return true if the copy was successful.
   */
  public static boolean copy(InputStream source, OutputStream target, long length) {
    if (length == 0) return true;
    try {
      int chunkSize = (int) Math.min(buffSize, length);
      long chunks = length / chunkSize;
      int lastChunkSize = (int) (length % chunkSize);
      // code will work even when chunkSize = 0 or chunks = 0;
      byte[] ba = new byte[chunkSize];

      for (long i = 0; i < chunks; i++) {
        int bytesRead = readBlocking(source, ba, 0, chunkSize);
        if (bytesRead != chunkSize) {
          throw new IOException();
        }
        target.write(ba);
      } // end for
      // R E A D / W R I T E last chunk, if any
      if (lastChunkSize > 0) {
        int bytesRead = readBlocking(source, ba, 0, lastChunkSize);
        if (bytesRead != lastChunkSize) {
          throw new IOException();
        }
        target.write(ba, 0, lastChunkSize);
      } // end if
    } catch (IOException e) {
      // don't log as error - happens all the time (ClientAbortException)
      if (log.isDebug())
        log.debug("Could not copy stream::" + e.getMessage() + " with length::" + length);
      return false;
    }
    return true;
  } // end copy
  /**
   * Copy an InputStream to an OutputStream, until EOF. Use only when you don't know the length.
   *
   * @param source InputStream, left open.
   * @param target OutputStream, left open.
   * @return true if the copy was successful.
   */
  @Deprecated
  public static boolean copy(InputStream source, OutputStream target) {
    try {

      int chunkSize = buffSize;
      // code will work even when chunkSize = 0 or chunks = 0;
      // Even for small files, we allocate a big buffer, since we
      // don't know the size ahead of time.
      byte[] ba = new byte[chunkSize];

      while (true) {
        int bytesRead = readBlocking(source, ba, 0, chunkSize);
        if (bytesRead > 0) {
          target.write(ba, 0, bytesRead);
        } else {
          break;
        } // hit eof
      } // end while
    } catch (MalformedStreamException e) {
      throw new OLATRuntimeException("Could not read stream", e);
    } catch (IOException e) {
      // don't log as error - happens all the time (ClientAbortException)
      if (log.isDebug()) log.debug("Could not copy stream::" + e.getMessage());
      return false;
    }
    return true;
  } // end copy
 @Override
 public boolean isSafelyAllowed(HttpServletRequest request, String safeExamBrowserKeys) {
   boolean safe = false;
   boolean debug = log.isDebug();
   if (StringHelper.containsNonWhitespace(safeExamBrowserKeys)) {
     String safeExamHash = request.getHeader("x-safeexambrowser-requesthash");
     String url = request.getRequestURL().toString();
     for (StringTokenizer tokenizer = new StringTokenizer(safeExamBrowserKeys);
         tokenizer.hasMoreTokens() && !safe; ) {
       String safeExamBrowserKey = tokenizer.nextToken();
       String hash = Encoder.sha256Exam(url + safeExamBrowserKey);
       if (safeExamHash != null && safeExamHash.equals(hash)) {
         safe = true;
       }
       if (debug) {
         log.debug(
             (safeExamHash.equals(hash) ? "Success" : "Failed")
                 + " : "
                 + safeExamHash
                 + " (Header) "
                 + hash
                 + " (Calculated)");
       }
     }
   } else {
     safe = true;
   }
   return safe;
 }
  @Override
  public void extract(VFSLeaf document, File bufferFile)
      throws IOException, DocumentAccessException {
    if (!(document instanceof LocalFileImpl)) {
      log.warn("Can only index local file");
      return;
    }

    List<String> cmds = new ArrayList<String>();
    cmds.add(searchModule.getPdfExternalIndexerCmd());
    cmds.add(((LocalFileImpl) document).getBasefile().getAbsolutePath());
    cmds.add(bufferFile.getAbsolutePath());

    CountDownLatch doneSignal = new CountDownLatch(1);

    ProcessWorker worker = new ProcessWorker(cmds, doneSignal);
    worker.start();

    try {
      doneSignal.await(3000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      log.error("", e);
    }

    worker.destroyProcess();
  }
  /**
   * @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest,
   *     org.olat.core.gui.components.Component, org.olat.core.gui.control.Event)
   */
  @Override
  public void event(UserRequest ureq, Component source, Event event) {
    if (STATISTICS_FULL_RECALCULATION_TRIGGER_BUTTON.equals(event.getCommand())) {
      StatisticUpdateManager statisticUpdateManager = getStatisticUpdateManager();
      if (statisticUpdateManager == null) {
        log_.info("event: UpdateStatisticsJob configured, but no StatisticManager available");
      } else {

        String title = getTranslator().translate("statistics.fullrecalculation.really.title");
        String text = getTranslator().translate("statistics.fullrecalculation.really.text");
        dialogCtr_ = DialogBoxUIFactory.createYesNoDialog(ureq, getWindowControl(), title, text);
        listenTo(dialogCtr_);
        dialogCtr_.activate();
      }
    } else if (STATISTICS_UPDATE_TRIGGER_BUTTON.equals(event.getCommand())) {
      StatisticUpdateManager statisticUpdateManager = getStatisticUpdateManager();
      if (statisticUpdateManager == null) {
        log_.info("event: UpdateStatisticsJob configured, but no StatisticManager available");
      } else {
        statisticUpdateManager.updateStatistics(false, getUpdateFinishedCallback());
        refreshUIState();
        getInitialComponent().setDirty(true);
      }
    }
  }
 /**
  * Delete all ResultSet for certain identity.
  *
  * @param identity
  */
 public void deleteUserData(Identity identity, String newDeletedUserName) {
   List<QTIResultSet> qtiResults = findQtiResultSets(identity);
   for (QTIResultSet set : qtiResults) {
     deleteResultSet(set);
   }
   if (log.isDebug()) {
     log.debug("Delete all QTI result data in db for identity=" + identity);
   }
 }
Example #10
0
  /**
   * Resolves a file path in the base container or creates this file under the given path. The
   * method creates any missing directories.
   *
   * @param baseContainer The base directory. User must have write permissions on this container
   * @param relFilePath The path relative to the base container. Must start with a '/'. To separate
   *     sub directories use '/'
   * @return The resolved or created leaf or NULL if a problem happened
   */
  public static VFSLeaf resolveOrCreateLeafFromPath(
      VFSContainer baseContainer, String relFilePath) {
    if (StringHelper.containsNonWhitespace(relFilePath)) {
      int lastSlash = relFilePath.lastIndexOf("/");
      String relDirPath = relFilePath;
      String fileName = null;
      if (lastSlash == -1) {
        // relFilePath is the file name - no directories involved
        relDirPath = null;
        fileName = relFilePath;
      } else if (lastSlash == 0) {
        // Remove start slash from file name
        relDirPath = null;
        fileName = relFilePath.substring(1, relFilePath.length());
      } else {
        relDirPath = relFilePath.substring(0, lastSlash);
        fileName = relFilePath.substring(lastSlash);
      }

      // Create missing directories and set parent dir for later file creation
      VFSContainer parent = baseContainer;
      if (StringHelper.containsNonWhitespace(relDirPath)) {
        parent = resolveOrCreateContainerFromPath(baseContainer, relDirPath);
      }
      // Now create file in that dir
      if (StringHelper.containsNonWhitespace(fileName)) {
        VFSLeaf leaf = null;
        VFSItem resolvedFile = parent.resolve(fileName);
        if (resolvedFile == null) {
          leaf = parent.createChildLeaf(fileName);
          if (leaf == null) {
            log.error(
                "Could not create leaf with relPath::"
                    + relFilePath
                    + " in base container::"
                    + getRealPath(baseContainer),
                null);
          }
        } else {
          if (resolvedFile instanceof VFSLeaf) {
            leaf = (VFSLeaf) resolvedFile;
          } else {
            leaf = null;
            log.error(
                "Could not create relPath::"
                    + relFilePath
                    + ", a directory with this name exists (but not a file) in base container::"
                    + getRealPath(baseContainer),
                null);
          }
        }
        return leaf;
      }
    }
    return null;
  }
 private void checkPublisher(Publisher p) {
   try {
     if (!NotificationsUpgradeHelper.checkCourse(p)) {
       log.info("deactivating publisher with key; " + p.getKey(), null);
       NotificationsManager.getInstance().deactivate(p);
     }
   } catch (Exception e) {
     log.error("", e);
   }
 }
  public MediaResource handle(String relPath, HttpServletRequest request) {
    if (log.isDebug()) log.debug("CPComponent Mapper relPath=" + relPath);

    VFSItem currentItem = mapperRootContainer.resolve(relPath);
    if (currentItem == null || (currentItem instanceof VFSContainer)) {
      return new NotFoundMediaResource(relPath);
    }
    VFSMediaResource vmr = new VFSMediaResource((VFSLeaf) currentItem);
    String encoding = SimpleHtmlParser.extractHTMLCharset(((VFSLeaf) currentItem));
    if (log.isDebug()) log.debug("CPComponent Mapper set encoding=" + encoding);
    vmr.setEncoding(encoding); //
    return vmr;
  }
Example #13
0
  public OAuthUser parseInfos(String body) {
    OAuthUser infos = new OAuthUser();
    try {
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(new InputSource(new StringReader(body)));

      NodeList nodes = doc.getElementsByTagName("person");
      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
          String localName = node.getNodeName();
          if ("first-name".equals(localName)) {
            infos.setFirstName(getCharacterDataFromElement(node));
          } else if ("last-name".equals(localName)) {
            infos.setLastName(getCharacterDataFromElement(node));
          } else if ("email-address".equals(localName)) {
            infos.setEmail(getCharacterDataFromElement(node));
          } else if ("id".equals(localName)) {
            infos.setId(getCharacterDataFromElement(node));
          }
        }
      }
    } catch (ParserConfigurationException | SAXException | IOException e) {
      log.error("", e);
    }
    return infos;
  }
Example #14
0
  /**
   * Copy method to copy a file to another file
   *
   * @param sourceFile
   * @param targetFile
   * @param move true: move file; false: copy file
   * @return true: success; false: failure
   */
  public static boolean copyFileToFile(File sourceFile, File targetFile, boolean move) {
    try {
      if (sourceFile.isDirectory() || targetFile.isDirectory()) {
        return false;
      }

      // create target directories
      targetFile.getParentFile().mkdirs(); // don't check for success... would return false on

      // catch move/copy of "same" file -> buggy under Windows.
      if (sourceFile.getCanonicalPath().equals(targetFile.getCanonicalPath())) return true;
      if (move) {
        // try to rename it first - operation might only be successful on a local filesystem!
        if (sourceFile.renameTo(targetFile)) return true;
        // it failed, so continue with copy code!
      }

      bcopy(sourceFile, targetFile, "copyFileToFile");

      if (move) {
        // to finish the move accross different filesystems we need to delete the source file
        sourceFile.delete();
      }
    } catch (IOException e) {
      log.error(
          "Could not copy file::"
              + sourceFile.getAbsolutePath()
              + " to file::"
              + targetFile.getAbsolutePath(),
          e);
      return false;
    }
    return true;
  } // end copy
Example #15
0
  private boolean isSameFile(VFSLeaf currentFile, VersionsFileImpl versions) {
    boolean same = false;
    if (versions.getRevisions() != null && !versions.getRevisions().isEmpty()) {
      VFSRevision lastRevision = versions.getRevisions().get(versions.getRevisions().size() - 1);

      long lastSize = lastRevision.getSize();
      long currentSize = currentFile.getSize();
      if (currentSize == lastSize
          && currentSize > 0
          && lastRevision instanceof RevisionFileImpl
          && currentFile instanceof LocalFileImpl) {
        RevisionFileImpl lastRev = ((RevisionFileImpl) lastRevision);
        LocalFileImpl current = (LocalFileImpl) currentFile;
        // can be the same file
        try {
          Checksum cm1 =
              FileUtils.checksum(((LocalFileImpl) lastRev.getFile()).getBasefile(), new Adler32());
          Checksum cm2 = FileUtils.checksum(current.getBasefile(), new Adler32());
          same = cm1.getValue() == cm2.getValue();
        } catch (IOException e) {
          log.debug("Error calculating the checksum of files");
        }
      }
    }
    return same;
  }
 /** Helper to create XSLT transformer for this instance */
 private void initTransformer() {
   // build new transformer
   final InputStream xslin =
       getClass().getResourceAsStream("/org/olat/ims/resources/xsl/" + XSLFILENAME);
   // translate xsl with velocity
   final Context vcContext = new VelocityContext();
   vcContext.put("t", pT);
   vcContext.put("staticPath", StaticMediaDispatcher.createStaticURIFor(""));
   String xslAsString = "";
   try {
     xslAsString = slurp(xslin);
   } catch (final IOException e) {
     log.error("Could not convert xsl to string!", e);
   }
   final String replacedOutput = evaluateValue(xslAsString, vcContext);
   final TransformerFactory tfactory = TransformerFactory.newInstance();
   XMLReader reader;
   try {
     reader = XMLReaderFactory.createXMLReader();
     reader.setEntityResolver(er);
     final Source xsltsource =
         new SAXSource(reader, new InputSource(new StringReader(replacedOutput)));
     this.transformer = tfactory.newTransformer(xsltsource);
   } catch (final SAXException e) {
     throw new OLATRuntimeException("Could not initialize transformer!", e);
   } catch (final TransformerConfigurationException e) {
     throw new OLATRuntimeException("Could not initialize transformer (wrong config)!", e);
   }
 }
Example #17
0
  private void loadSelectionKeysFromConfig() {
    Map<String, String> handlerConfig = cfgFactory.loadConfigForHandler(this);

    // now "calculate" available year-values for dropdown, according to
    // handler config
    if (handlerConfig.containsKey(PROP_FROM) && handlerConfig.containsKey(PROP_TO)) {
      // we have a valid config
      int nowYear = Calendar.getInstance().get(Calendar.YEAR);

      String from = handlerConfig.get(PROP_FROM);
      String to = handlerConfig.get(PROP_TO);
      int i_from = 1900;
      int i_to = 1900;

      if (from.startsWith("+")) i_from = nowYear + Integer.parseInt(from.substring(1));
      else if (from.startsWith("-")) i_from = nowYear - Integer.parseInt(from.substring(1));
      else i_from = Integer.parseInt(from);

      if (to.startsWith("+")) i_to = nowYear + Integer.parseInt(to.substring(1));
      else if (to.startsWith("-")) i_to = nowYear - Integer.parseInt(to.substring(1));
      else i_to = Integer.parseInt(to);

      if (i_to < i_from) {
        logger.warn("wrong config in YearPropertyHandler : to is smaller than from...");
        // leave selectionKeys to default
        selectionKeys = getDefaultYears();
      } else {
        // now fill the array
        int span = i_to - i_from;
        if (span > 1000) span = 1000; // just prevent toooooo long dropdown-list ^
        selectionKeys = new String[span + 1];
        for (int j = 0; j <= span; j++) selectionKeys[j] = String.valueOf(i_from + j);
      }
    }
  }
Example #18
0
  private void processReturnFile(
      AssessableCourseNode courseNode,
      BulkAssessmentRow row,
      UserCourseEnvironment uce,
      File assessedFolder) {
    String assessedId = row.getAssessedId();
    Identity identity = uce.getIdentityEnvironment().getIdentity();
    VFSContainer returnBox = getReturnBox(uce, courseNode, identity);
    if (returnBox != null) {
      for (String returnFilename : row.getReturnFiles()) {
        File returnFile = new File(assessedFolder, returnFilename);
        VFSItem currentReturnLeaf = returnBox.resolve(returnFilename);
        if (currentReturnLeaf != null) {
          // remove the current file (delete make a version if it is enabled)
          currentReturnLeaf.delete();
        }

        VFSLeaf returnLeaf = returnBox.createChildLeaf(returnFilename);
        if (returnFile.exists()) {
          try {
            InputStream inStream = new FileInputStream(returnFile);
            VFSManager.copyContent(inStream, returnLeaf);
          } catch (FileNotFoundException e) {
            log.error("Cannot copy return file " + returnFilename + " from " + assessedId, e);
          }
        }
      }
    }
  }
Example #19
0
  public OAuthUser parseInfos(String body) {
    OAuthUser user = new OAuthUser();

    try {
      JSONObject obj = new JSONObject(body);
      user.setId(getValue(obj, "id_str"));

      String name = getValue(obj, "name");
      if (name != null) {
        name = name.trim();
        int lastSpaceIndex = name.lastIndexOf(' ');
        if (lastSpaceIndex > 0) {
          user.setFirstName(name.substring(0, lastSpaceIndex));
          user.setLastName(name.substring(lastSpaceIndex + 1));
        } else {
          user.setLastName(name);
        }
      }

      user.setLang(getValue(obj, "lang"));
    } catch (JSONException e) {
      log.error("", e);
    }

    return user;
  }
  private static String getContent(final WikiPage wikiPage) {
    try {
      final ParserInput input = new ParserInput();
      input.setWikiUser(null);
      input.setAllowSectionEdit(false);
      input.setDepth(2);
      input.setContext("");
      input.setLocale(Locale.ENGLISH);
      input.setTopicName("dummy");
      input.setUserIpAddress("0.0.0.0");
      input.setDataHandler(DUMMY_DATA_HANDLER);
      input.setVirtualWiki("/olat");

      final AbstractParser parser = new JFlexParser(input);
      final ParserDocument parsedDoc = parser.parseHTML(wikiPage.getContent());
      final String parsedContent = parsedDoc.getContent();
      final String filteredContent =
          FilterFactory.getHtmlTagAndDescapingFilter().filter(parsedContent);
      return filteredContent;
    } catch (final Exception e) {
      e.printStackTrace();
      log.error("", e);
      return wikiPage.getContent();
    }
  }
Example #21
0
 /**
  * Copy the content of the file in the target leaf.
  *
  * @param source A file
  * @param target The target leaf
  * @return
  */
 public static boolean copyContent(File source, VFSLeaf target) {
   try (InputStream inStream = new FileInputStream(source)) {
     return copyContent(inStream, target, true);
   } catch (IOException ex) {
     log.error("", ex);
     return false;
   }
 }
 private void updateStatisticUpdateOngoingFlag() {
   StatisticUpdateManager statisticUpdateManager = getStatisticUpdateManager();
   if (statisticUpdateManager == null) {
     log_.info("event: UpdateStatisticsJob configured, but no StatisticManager available");
     content.contextPut("statisticUpdateOngoing", Boolean.TRUE);
   } else {
     content.contextPut("statisticUpdateOngoing", statisticUpdateManager.updateOngoing());
   }
 }
Example #23
0
 private void cleanupUnzip() {
   try {
     if (unzipped != null && unzipped.exists()) {
       FileUtils.deleteDirsAndFiles(unzipped, true, true);
     }
   } catch (Exception e) {
     log.error("Cannot cleanup unzipped datas after bulk assessment", e);
   }
 }
 /**
  * @see org.olat.core.gui.components.Component#doDispatchRequest(org.olat.core.gui.UserRequest)
  */
 @Override
 protected void doDispatchRequest(UserRequest ureq) {
   setDirty(true);
   String cmd = ureq.getParameter(VelocityContainer.COMMAND_ID);
   if (log.isDebug()) {
     log.debug("***RATING_CLICKED*** dispatchID::" + ureq.getComponentID() + " rating::" + cmd);
   }
   try {
     float rating = Float.parseFloat(cmd);
     // update GUI
     this.setCurrentRating(rating);
     // notify listeners
     Event event = new RatingEvent(rating);
     fireEvent(ureq, event);
   } catch (NumberFormatException e) {
     log.error("Error while parsing rating value::" + cmd);
   }
 }
Example #25
0
 /**
  * Copies the stream to the target leaf.
  *
  * @param source
  * @param target
  * @param closeInput set to false if it's a ZipInputStream
  * @return True on success, false on failure
  */
 public static boolean copyContent(InputStream inStream, VFSLeaf target, boolean closeInput) {
   boolean successful;
   if (inStream != null && target != null) {
     InputStream in = new BufferedInputStream(inStream);
     OutputStream out = new BufferedOutputStream(target.getOutputStream(false));
     // write the input to the output
     try {
       byte[] buf = new byte[FileUtils.BSIZE];
       int i = 0;
       while ((i = in.read(buf)) != -1) {
         out.write(buf, 0, i);
       }
       successful = true;
     } catch (IOException e) {
       // something went wrong.
       successful = false;
       log.error(
           "Error while copying content from source: "
               + inStream
               + " to target: "
               + target.getName(),
           e);
     } finally {
       // Close streams
       try {
         if (out != null) {
           out.flush();
           out.close();
         }
         if (closeInput && in != null) {
           in.close();
         }
       } catch (IOException ex) {
         log.error("Error while closing/cleaning up in- and output streams", ex);
       }
     }
   } else {
     // source or target is null
     successful = false;
     if (log.isDebug())
       log.debug("Either the source or the target is null. Content of leaf cannot be copied.");
   }
   return successful;
 }
Example #26
0
 private void doNoLockingEnrol(Identity i, SecurityGroup group) {
   // check that below max
   try {
     StringBuilder sb = new StringBuilder();
     int cnt = BaseSecurityManager.getInstance().countIdentitiesOfSecurityGroup(group);
     sb.append("enrol:cnt:" + cnt);
     if (cnt < MAX_COUNT) {
       // now sleep a while to allow others to think also that there is still space left in the
       // group
       sleep(100);
       // now add the user to the security group
       sb.append(" adding " + i.getName() + ": current.. " + cnt + ", max = " + MAX_COUNT);
       BaseSecurityManager.getInstance().addIdentityToSecurityGroup(i, group);
     }
     log.info(sb.toString());
   } catch (Exception e) {
     log.error("", e);
   }
 }
Example #27
0
  @Override
  public void run() {
    long start = System.nanoTime();
    log.info("Start scanning for QTI resources");

    List<String> types = new ArrayList<>(2);
    types.add(TestFileResource.TYPE_NAME);
    types.add(SurveyFileResource.TYPE_NAME);
    List<OLATResource> qtiResources =
        CoreSpringFactory.getImpl(OLATResourceManager.class).findResourceByTypes(types);
    DBFactory.getInstance().commitAndCloseSession();
    for (OLATResource qtiResource : qtiResources) {
      OnyxModule.isOnyxTest(qtiResource);
    }
    log.info(
        qtiResources.size()
            + " QTI Resources scanned in (ms): "
            + CodeHelper.nanoToMilliTime(start));
  }
  private final void executeProcess(Process proc) {
    StringBuilder errors = new StringBuilder();
    StringBuilder output = new StringBuilder();

    InputStream stderr = proc.getErrorStream();
    InputStreamReader iserr = new InputStreamReader(stderr);
    BufferedReader berr = new BufferedReader(iserr);
    String line = null;
    try {
      while ((line = berr.readLine()) != null) {
        errors.append(line);
      }
    } catch (IOException e) {
      //
    }

    InputStream stdout = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdout);
    BufferedReader br = new BufferedReader(isr);
    line = null;
    try {
      while ((line = br.readLine()) != null) {
        output.append(line);
      }
    } catch (IOException e) {
      //
    }

    try {
      int exitValue = proc.waitFor();
      if (log.isDebug()) {
        log.info("PDF extracted: " + exitValue);
      }
    } catch (InterruptedException e) {
      //
    }

    if (log.isDebug()) {
      log.error(errors.toString());
      log.info(output.toString());
    }
  }
Example #29
0
  /**
   * Copy the contents of the specified input stream to the specified output stream, and ensure that
   * both streams are closed before returning (even in the face of an exception).
   *
   * @param istream The input stream to read from
   * @param ostream The output stream to write to
   * @param start Start of the range which will be copied
   * @param end End of the range which will be copied
   * @return Exception which occurred during processing
   */
  protected IOException copyRange(
      InputStream istream, ServletOutputStream ostream, long start, long end) {

    if (log.isDebug()) {
      log.debug("Serving bytes:" + start + "-" + end);
    }

    long skipped = 0;
    try {
      skipped = istream.skip(start);
    } catch (IOException e) {
      return e;
    }
    if (skipped < start) {
      return new IOException(
          "defaultservlet.skipfail" + Long.valueOf(skipped) + Long.valueOf(start));
    }

    IOException exception = null;
    long bytesToRead = end - start + 1;

    byte buffer[] = new byte[input];
    int len = buffer.length;
    while ((bytesToRead > 0) && (len >= buffer.length)) {
      try {
        len = istream.read(buffer);
        if (bytesToRead >= len) {
          ostream.write(buffer, 0, len);
          bytesToRead -= len;
        } else {
          ostream.write(buffer, 0, (int) bytesToRead);
          bytesToRead = 0;
        }
      } catch (IOException e) {
        exception = e;
        len = -1;
      }
      if (len < buffer.length) break;
    }

    return exception;
  }
 /**
  * Takes String with template and fills values from Translator in Context
  *
  * @param valToEval String with variables to replace
  * @param vcContext velocity context containing a translator in this case
  * @return input String where values from context were replaced
  */
 private String evaluateValue(final String valToEval, final Context vcContext) {
   final StringWriter evaluatedValue = new StringWriter();
   // evaluate inputFieldValue to get a concatenated string
   try {
     velocityEngine.evaluate(vcContext, evaluatedValue, "vcUservalue", valToEval);
   } catch (final ParseErrorException e) {
     log.error("parsing of values in xsl-file of LocalizedXSLTransformer not possible!", e);
     return "ERROR";
   } catch (final MethodInvocationException e) {
     log.error("evaluating of values in xsl-file of LocalizedXSLTransformer not possible!", e);
     return "ERROR";
   } catch (final ResourceNotFoundException e) {
     log.error("xsl-file of LocalizedXSLTransformer not found!", e);
     return "ERROR";
   } catch (final IOException e) {
     log.error("could not read xsl-file of LocalizedXSLTransformer!", e);
     return "ERROR";
   }
   return evaluatedValue.toString();
 }