@Before
  public void before() throws Exception {

    when(resourceMock1.getPathWithinContext()).thenReturn(resourceName1);
    when(resourceMock1.getFile()).thenReturn(fileMock1);

    when(resourceMock2.getDescription()).thenReturn(resourceName2);
    when(resourceMock2.getFile()).thenReturn(fileMock2);

    when(resourceMock3.getFile()).thenReturn(fileMock3);
    when(fileMock3.getAbsolutePath()).thenReturn(resourceName3);

    when(resourceMock4.getFile()).thenReturn(fileMock4);
    when(fileMock4.getAbsolutePath()).thenReturn(resourceName4);

    when(resourceMock5.getFile()).thenReturn(fileMock5);
    when(fileMock5.getAbsolutePath()).thenReturn(resourceName5);

    when(resourceMock1.getInputStream()).thenReturn(inputStreamMock);
    when(resourceMock2.getInputStream()).thenReturn(inputStreamMock);
    when(resourceMock3.getInputStream()).thenReturn(inputStreamMock);
    when(resourceMock4.getInputStream()).thenReturn(inputStreamMock);
    when(resourceMock5.getInputStream()).thenReturn(inputStreamMock);

    when(repositoryServiceMock.createDeployment()).thenReturn(deploymentBuilderMock);
    when(deploymentBuilderMock.enableDuplicateFiltering()).thenReturn(deploymentBuilderMock);
    when(deploymentBuilderMock.name(isA(String.class))).thenReturn(deploymentBuilderMock);

    when(deploymentBuilderMock.deploy()).thenReturn(deploymentMock);
  }
 /**
  * Set the temporary directory where uploaded files get stored. Default is the servlet container's
  * temporary directory for the web application.
  *
  * @see org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE
  */
 public void setUploadTempDir(Resource uploadTempDir) throws IOException {
   if (!uploadTempDir.exists() && !uploadTempDir.getFile().mkdirs()) {
     throw new IllegalArgumentException(
         "Given uploadTempDir [" + uploadTempDir + "] could not be created");
   }
   this.fileItemFactory.setRepository(uploadTempDir.getFile());
   this.uploadTempDirSpecified = true;
 }
  private PdfPTable buildHeader(String date) throws BadElementException, IOException {
    PdfPCell cell;
    PdfPTable table = new PdfPTable(3);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);

    Resource r = appContex.getResource("/img/logo_mairie.png");
    Image img = Image.getInstance(r.getFile().getAbsolutePath());
    cell = new PdfPCell();
    cell.addElement(new Chunk(img, 60, 0));
    cell.setFixedHeight(70);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setPaddingTop(23);
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setRowspan(2);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("FICHE EVENEMENTIELLE", FONT_TITLE));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    Resource r2 = appContex.getResource("/img/logo_police_nc.jpg");
    Image img2 = Image.getInstance(r2.getFile().getAbsolutePath());
    cell = new PdfPCell();
    cell.addElement(new Chunk(img2, 130, 0));
    cell.setFixedHeight(70);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setPaddingTop(23);
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setRowspan(2);
    table.addCell(cell);

    cell =
        new PdfPCell(
            new Phrase(
                "Fiche éditée le "
                    + date
                    + "\npar "
                    + authHelper.getCurrentUser().getAgent().getNom()
                    + " "
                    + authHelper.getCurrentUser().getAgent().getPrenom(),
                FONT_TITLE_LIGHT));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    table.setSpacingBefore(5);
    table.setSpacingAfter(5);

    return table;
  }
 protected void reload(final boolean forceReload) throws IOException {
   boolean reload = forceReload;
   for (int i = 0; i < locations.length; i++) {
     final Resource location = locations[i];
     final File file;
     try {
       file = location.getFile();
     } catch (final IOException e) {
       // not a file resource
       continue;
     }
     try {
       final long l = file.lastModified();
       if (l > lastModified[i]) {
         lastModified[i] = l;
         reload = true;
       }
     } catch (final Exception e) {
       // cannot access file. assume unchanged.
       if (log.isDebugEnabled())
         log.debug("can't determine modification time of " + file + " for " + location, e);
     }
   }
   if (reload) doReload();
 }
Beispiel #5
0
  /**
   * Loads nested schema type definitions from wsdl.
   *
   * @throws IOException
   * @throws WSDLException
   * @throws TransformerFactoryConfigurationError
   * @throws TransformerException
   * @throws TransformerConfigurationException
   */
  private void loadSchemas()
      throws WSDLException, IOException, TransformerConfigurationException, TransformerException,
          TransformerFactoryConfigurationError {
    Definition definition =
        WSDLFactory.newInstance().newWSDLReader().readWSDL(wsdl.getFile().getAbsolutePath());

    Types types = definition.getTypes();
    List<?> schemaTypes = types.getExtensibilityElements();

    for (Object schemaObject : schemaTypes) {
      if (schemaObject instanceof SchemaImpl) {
        SchemaImpl schema = (SchemaImpl) schemaObject;

        inheritNamespaces(schema, definition);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Source source = new DOMSource(schema.getElement());
        Result result = new StreamResult(bos);

        TransformerFactory.newInstance().newTransformer().transform(source, result);
        Resource schemaResource = new ByteArrayResource(bos.toByteArray());

        schemas.add(schemaResource);

        if (definition
            .getTargetNamespace()
            .equals(schema.getElement().getAttribute("targetNamespace"))) {
          setXsd(schemaResource);
        }
      } else {
        log.warn("Found unsupported schema type implementation " + schemaObject.getClass());
      }
    }
  }
Beispiel #6
0
 public static Configuration buildConfiguration(String directory) throws IOException {
   Configuration cfg = new Configuration();
   Resource path = new DefaultResourceLoader().getResource(directory);
   cfg.setDirectoryForTemplateLoading(path.getFile());
   cfg.setDefaultEncoding("utf-8");
   return cfg;
 }
  /**
   * Setup for the tests.
   *
   * @throws IOException on error
   */
  @Before
  public void setup() throws IOException {
    final Calendar cal = Calendar.getInstance(JobConstants.UTC);
    cal.add(Calendar.DAY_OF_YEAR, 1);
    this.tomorrow = cal.getTime();
    this.jobSearchService = Mockito.mock(JobSearchService.class);
    this.jobSubmitterService = Mockito.mock(JobSubmitterService.class);
    final Executor executor = Mockito.mock(Executor.class);
    this.scheduler = Mockito.mock(TaskScheduler.class);
    this.eventMulticaster = Mockito.mock(ApplicationEventMulticaster.class);
    final Registry registry = Mockito.mock(Registry.class);
    this.unableToCancel = Mockito.mock(Counter.class);
    Mockito.when(registry.counter(Mockito.anyString())).thenReturn(this.unableToCancel);

    final File jobsFile = this.folder.newFolder();
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.getFile()).thenReturn(jobsFile);

    this.coordinator =
        new JobMonitoringCoordinator(
            HOSTNAME,
            this.jobSearchService,
            Mockito.mock(ApplicationEventPublisher.class),
            this.eventMulticaster,
            this.scheduler,
            executor,
            registry,
            jobsDir,
            new JobsProperties(),
            jobSubmitterService);
  }
  @Test
  public void testDAO() throws IOException {

    Resource resource = context.getResource("data");
    File dir = resource.getFile();
    assertTrue(dir.exists());

    File file = new File(dir, "flow1.xml");
    assertTrue(file.exists());

    XStreamFlowConfigurationDAO dao =
        new XStreamFlowConfigurationDAO(dir.getAbsolutePath(), createAlias());
    FileBasedFlowConfiguration fbfc = dao.find("flow1", false);

    assertNotNull(fbfc);

    assertEquals(fbfc.getId(), "flow1");
    assertEquals(fbfc.getName(), "flow1name");
    assertEquals(fbfc.getDescription(), "flow1desc");

    FileBasedEventGeneratorConfiguration fbegc =
        (FileBasedEventGeneratorConfiguration) fbfc.getEventGeneratorConfiguration();
    assertNotNull(fbegc);

    FileBasedEventConsumerConfiguration fbecc =
        (FileBasedEventConsumerConfiguration) fbfc.getEventConsumerConfiguration();
    assertNotNull(fbecc);

    List<? extends ActionConfiguration> lac = fbecc.getActions();
    assertNull(lac);
  }
  private void addDummyData() throws IOException, EntityExistsException, EntityNotFoundException {
    LOGGER.warn("Add dummy data to database, which could overwrite existing data");

    final DummyData dummyData =
        objectMapper.readValue(dummyDataResource.getFile(), DummyData.class);

    // User
    final List<User> users = dummyData.getUsers();
    for (User user : users) {
      userService.save(user);
      LOGGER.info("User '{}' created", user.getUsername());
    }

    // Gateway
    final List<Gateway> gateways = dummyData.getGateways();
    for (Gateway gateway : gateways) {
      gatewayService.save(gateway);
      LOGGER.info("Gateway '{}' with id '{}' created", gateway.getName(), gateway.getId());
    }

    // Cluster
    final List<Cluster> clusters = dummyData.getClusters();
    for (Cluster cluster : clusters) {
      clusterService.save(cluster);
      LOGGER.info("Cluster '{}' with id '{}' created", cluster.getName(), cluster.getId());
    }

    // Sensor
    final List<Sensor> sensors = dummyData.getSensors();
    for (Sensor sensor : sensors) {
      sensorService.save(sensor);
      LOGGER.info("Sensor '{}' with id '{}' created", sensor.getName(), sensor.getId());
    }
  }
Beispiel #10
0
 public void testClasspathResourceByDefaultClassLoader() throws IOException {
   Resource resource = new ClassPathResource("com/iss/expense/demo/chapter4/test1.properties");
   if (resource.exists()) {
     dumpStream(resource);
   }
   System.out.println("path:--->" + resource.getFile().getAbsolutePath());
   Assert.assertEquals(false, resource.isOpen());
 }
 /* (non-Javadoc)
  * @see org.springframework.batch.core.step.tasklet.Tasklet#execute(org.springframework.batch.core.StepContribution, org.springframework.batch.core.scope.context.ChunkContext)
  */
 @Override
 public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)
     throws Exception {
   log.info("initialize dsp_struct");
   String initScriptContent = new String(Files.readAllBytes(initScript.getFile().toPath()));
   jdbcTemplate.update(initScriptContent);
   return RepeatStatus.FINISHED;
 }
 /**
  * Gets the class name of the specified Grails resource
  *
  * @param resource The Spring Resource
  * @return The class name or null if the resource is not a Grails class
  */
 public static String getClassName(Resource resource) {
   try {
     return getClassName(resource.getFile().getAbsolutePath());
   } catch (IOException e) {
     throw new GrailsConfigurationException(
         "I/O error reading class name from resource [" + resource + "]: " + e.getMessage(), e);
   }
 }
 @Override
 protected boolean shouldConsider(Resource r) {
   try {
     return r.getFile().isDirectory();
   } catch (IOException e) {
     return false;
   }
 }
Beispiel #14
0
 public static File getFile(Resource resource) {
   File file = null;
   try {
     file = resource.getFile();
   } catch (IOException e) {
     log.warn(String.format("WebdavUtil.getFile fail... path : %s", resource.getFilename()));
   }
   return file;
 }
 @Override
 public List<AbstractValidator> resolveValidator() throws Exception {
   File file = validatorsConfig.getFile();
   if (!file.exists()) {
     throw new FileNotFoundException(ErrorMsg.VALIDATOR_CONFIG_FILE_DOES_NOT_EXIST);
   }
   Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
   return parseValidators(doc);
 }
 @Test(expected = ConstraintViolationException.class)
 @Transactional
 @Rollback(true)
 public void testSaveInvalidArviointi2FromJson() throws IOException {
   Resource resource = new ClassPathResource("material/invalid_arviointi2.json");
   ArviointiDto dto = objectMapper.readValue(resource.getFile(), ArviointiDto.class);
   arviointiService.add(dto);
   em.flush();
 }
 private Set<File> getEndToEndFilesFromResources() throws IOException {
   PathMatchingResourcePatternResolver res = new PathMatchingResourcePatternResolver();
   Resource[] resources = res.getResources("classpath*:" + FILE_PREFIX + ".*.*." + FILE_POSTFIX);
   HashSet<File> files = new HashSet<File>();
   for (Resource r : resources) {
     files.add(r.getFile());
   }
   return files;
 }
 public String getRealPath(String path) {
   Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
   try {
     return resource.getFile().getAbsolutePath();
   } catch (IOException ex) {
     logger.warn("Couldn't determine real path of resource " + resource, ex);
     return null;
   }
 }
 public JarDataAndPath(String jarPath, Class<?> anchor, Object... namesAndValues) {
   this.data = Maps.<String, Object>makeMap(namesAndValues);
   this.jar = new ClassPathResource(jarPath, anchor);
   try {
     Assert.assertTrue(jar.getFile().exists());
   } catch (IOException e) {
     throw WrappedException.wrap(e);
   }
 }
  public void afterPropertiesSet() throws Exception {
    Resource[] resources = getResources();

    for (Resource r : resources) {
      String filePath = r.getFile().getAbsolutePath();
      if (StringUtils.indexOf(filePath, "_") == -1)
        this.resourceBundleHolder.loadMessageResource(filePath, this.order);
    }
  }
Beispiel #21
0
 public String getFontFilePath(String classpathRelativePath) {
   try {
     Resource rsrc = new ClassPathResource(classpathRelativePath);
     return rsrc.getFile().getAbsolutePath();
   } catch (Exception e) {
     LOG.error("Error : while accessing font file " + e);
   }
   return null;
 }
 /** 获取classpath中的附件. */
 private File generateAttachment() throws MessagingException {
   try {
     Resource resource = new ClassPathResource("/email/mailAttachment.txt");
     return resource.getFile();
   } catch (IOException e) {
     logger.error("构造邮件失败,附件文件不存在", e);
     throw new MessagingException("附件文件不存在", e);
   }
 }
 public HashtagCounterAnalysis(String input, Resource output, Configuration config) {
   this.inputPath = input;
   try {
     this.outputPath = output.getFile().getAbsolutePath();
   } catch (IOException e) {
     throw new IllegalArgumentException("failed to determine output path", e);
   }
   this.hadoopConfiguration = config;
 }
  @Override
  public FileManager getObject() throws Exception {

    XmlFileManagerFactory fileAdapterFactory = getFileManagerFactoryClass().newInstance();

    fileAdapterFactory.setRootPath(rootPath);
    fileAdapterFactory.setSchemaFile(schema.getFile());

    return fileAdapterFactory.build();
  }
 private File targetModuleLocation(ModuleDefinition definition) throws IOException {
   Resource resource = getResources(definition.getType().name(), definition.getName(), ".jar")[0];
   File result = resource.getFile();
   File parent = result.getParentFile();
   Assert.isTrue(
       parent.exists() && parent.isDirectory() || parent.mkdirs(),
       String.format(
           "Could not ensure that '%s' exists and is a directory", parent.getAbsolutePath()));
   return result.getAbsoluteFile();
 }
 /**
  * saveXml
  *
  * @param xml a {@link java.lang.String} object.
  * @throws java.io.IOException if any.
  */
 protected void saveXml(final String xml) throws IOException {
   if (xml != null) {
     final Writer fileWriter =
         new OutputStreamWriter(
             new FileOutputStream(m_monitoringLocationConfigResource.getFile()), "UTF-8");
     fileWriter.write(xml);
     fileWriter.flush();
     fileWriter.close();
   }
 }
  @PostConstruct
  public void setup() throws Throwable {
    File file = itemFilesMount.getFile();

    if (!file.exists()) {
      file.mkdirs();
    }

    System.out.println("file system is setup at " + file.getAbsolutePath());
  }
  @Test
  public void testValidRun() {
    try {
      JobExecution jobExecution = this.launchStep("step1");

      // Ensure job completed successfully.
      Assert.isTrue(
          jobExecution.getExitStatus().equals(ExitStatus.COMPLETED),
          "Step Execution did not complete normally: " + jobExecution.getExitStatus());

      // Check output.
      Assert.isTrue(actual.exists(), "Actual does not exist.");
      AssertFile.assertFileEquals(expected.getFile(), actual.getFile());

    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
  private Resource copyFileToPictures(MultipartFile file) throws IOException {
    String fileExtension = getFileExtension(file.getOriginalFilename());
    File tempFile = File.createTempFile("pic", fileExtension, picturesDir.getFile());
    try (InputStream in = file.getInputStream();
        OutputStream out = new FileOutputStream(tempFile)) {

      IOUtils.copy(in, out);
    }
    return new FileSystemResource(tempFile);
  }
Beispiel #30
0
 @Override
 public void afterPropertiesSet() throws IOException {
   toolBoxConfigurationPath = toolBoxConfigLocation.getFile().getAbsolutePath();
   if (logger.isInfoEnabled()) {
     logger.info(
         "Resource loader path '{}' resolved to file '{}'",
         toolBoxConfigLocation.getURI(),
         toolBoxConfigurationPath);
   }
 }