Search in sources :

Example 11 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project gocd by gocd.

the class FakeArtifactPublisherServlet method doPost.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    MultipartHttpServletRequest httpServletRequest = multipartResolver.resolveMultipart(request);
    Map<String, MultipartFile> map = httpServletRequest.getFileMap();
    MultipartFile multipartFile = map.values().iterator().next();
    receivedFiles.add(multipartFile.getOriginalFilename());
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) CommonsMultipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest)

Example 12 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project gocd by gocd.

the class ArtifactsController method updateChecksumFile.

private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier, String filePath) throws IOException, IllegalArtifactLocationException {
    MultipartFile checksumMultipartFile = getChecksumFile(request);
    if (checksumMultipartFile != null) {
        String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier), ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME);
        File checksumFile = artifactsService.getArtifactLocation(checksumFilePath);
        synchronized (checksumFilePath.intern()) {
            return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream());
        }
    } else {
        LOGGER.warn(String.format("[Artifacts Upload] Checksum file not uploaded for artifact at path '%s'", filePath));
    }
    return true;
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile)

Example 13 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project gocd by gocd.

the class ArtifactsController method postArtifact.

@RequestMapping("/repository/restful/artifact/POST/*")
public ModelAndView postArtifact(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam(value = "buildId", required = false) Long buildId, @RequestParam("filePath") String filePath, @RequestParam(value = "attempt", required = false) Integer attempt, MultipartHttpServletRequest request) throws Exception {
    JobIdentifier jobIdentifier;
    if (!headerConstraint.isSatisfied(request)) {
        return ResponseCodeView.create(HttpServletResponse.SC_BAD_REQUEST, "Missing required header 'Confirm'");
    }
    try {
        jobIdentifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName, buildId);
    } catch (Exception e) {
        return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName);
    }
    int convertedAttempt = attempt == null ? 1 : attempt;
    try {
        File artifact = artifactsService.findArtifact(jobIdentifier, filePath);
        if (artifact.exists() && artifact.isFile()) {
            return FileModelAndView.fileAlreadyExists(filePath);
        }
        MultipartFile multipartFile = multipartFile(request);
        if (multipartFile == null) {
            return FileModelAndView.invalidUploadRequest();
        }
        boolean success = saveFile(convertedAttempt, artifact, multipartFile, shouldUnzipStream(multipartFile));
        if (!success) {
            return FileModelAndView.errorSavingFile(filePath);
        }
        success = updateChecksumFile(request, jobIdentifier, filePath);
        if (!success) {
            return FileModelAndView.errorSavingChecksumFile(filePath);
        }
        return FileModelAndView.fileCreated(filePath);
    } catch (IllegalArtifactLocationException e) {
        return FileModelAndView.forbiddenUrl(filePath);
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) IllegalArtifactLocationException(com.thoughtworks.go.domain.exception.IllegalArtifactLocationException) JobIdentifier(com.thoughtworks.go.domain.JobIdentifier) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) IllegalArtifactLocationException(com.thoughtworks.go.domain.exception.IllegalArtifactLocationException) HeaderConstraint(com.thoughtworks.go.server.security.HeaderConstraint) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 14 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project nhin-d by DirectProject.

the class PoliciesController method checkLexiconFile.

/*********************************
     *
     * Check Lexicon File Method
     *
     *********************************/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkLexiconFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkLexiconFile(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, Object command, @RequestHeader(value = "lexicon", required = false) String lexicon, MultipartHttpServletRequest request) throws FileUploadException, IOException, Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String uploadToString = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking uploaded lexicon file for format and validation");
    }
    // Grab uploaded file from the post submission
    UploadedFile ufile = new UploadedFile();
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = request.getFile(itr.next());
    try {
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();
    } catch (IOException e) {
    }
    // Convert upload content to string
    uploadToString = new String(ufile.bytes);
    uploadToString = JSONObject.escape(uploadToString);
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(ufile.bytes);
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy file " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"File was not a valid file.\",\"Content\":\"" + uploadToString + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\",\"Content\":\"" + uploadToString + "\"}";
    }
    return jsonResponse;
}
Also used : PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 15 with MultipartFile

use of org.springframework.web.multipart.MultipartFile in project Settler by EmhyrVarEmreis.

the class ImportService method importTransactions.

public void importTransactions(MultipartFile file) throws IOException {
    List<Category> categoryList = categoryRepository.findAll();
    Map<String, Category> categoryMap = categoryList == null ? new HashMap<>() : categoryList.stream().collect(Collectors.toMap(Category::getCode, category -> category));
    List<Transaction> transactionList = new ArrayList<>();
    ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());
    String content = IOUtils.toString(stream, "UTF-8");
    String[] lines = content.split("\\r?\\n");
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd.MM.yyyy");
    User o = userRepository.findOneByLogin(splitLine(lines[0])[26]);
    User c = userRepository.findOneByLogin(splitLine(lines[0])[27]);
    int ln = 0;
    for (String line : lines) {
        ln++;
        if (ln < 3) {
            continue;
        }
        try {
            String[] cells = splitLine(line);
            String name = cells[0];
            String mark = cells[4].trim();
            Double value;
            Double sharedAValue;
            Double sharedBValue;
            Integer sharedA;
            Integer sharedB;
            LocalDateTime date;
            Boolean normal;
            Transaction transaction = new Transaction();
            List<Redistribution> owners = new ArrayList<>();
            List<Redistribution> contractors = new ArrayList<>();
            value = Double.valueOf(cells[2].replaceAll("[^0-9^,-]+", "").replace(",", "."));
            date = dateTimeFormatter.parseLocalDateTime(cells[1]);
            sharedA = cells.length < 7 || cells[5].trim().isEmpty() ? -1 : Integer.valueOf(cells[5].trim());
            sharedB = cells.length < 7 || cells[6].trim().isEmpty() ? -1 : Integer.valueOf(cells[6].trim());
            normal = value > 0;
            value = Math.abs(value);
            if (mark.equalsIgnoreCase("x")) {
                if (sharedA < 0 || sharedB < 0) {
                    sharedA = 1;
                    sharedB = 2;
                }
            } else if (mark.equalsIgnoreCase("b") || mark.equalsIgnoreCase("z")) {
                sharedA = 1;
                sharedB = 1;
            } else {
                continue;
            }
            sharedAValue = value;
            value = (value / (sharedA)) * sharedB;
            value = (double) Math.round(value * 100) / 100;
            sharedBValue = value - sharedAValue;
            sharedBValue = (double) Math.round(sharedBValue * 100) / 100;
            if (normal) {
                owners.add(new Redistribution(RedistributionType.O, transaction, o, value));
                if (sharedBValue > 0) {
                    contractors.add(new Redistribution(RedistributionType.C, transaction, o, sharedBValue));
                }
                contractors.add(new Redistribution(RedistributionType.C, transaction, c, sharedAValue));
            } else {
                owners.add(new Redistribution(RedistributionType.O, transaction, c, value));
                contractors.add(new Redistribution(RedistributionType.C, transaction, o, sharedAValue));
                if (sharedBValue > 0) {
                    contractors.add(new Redistribution(RedistributionType.C, transaction, c, sharedBValue));
                }
            }
            transaction.setValue(value);
            owners.forEach(redistribution -> redistribution.setPercentage(redistribution.getPercentage() / 1.0 / transaction.getValue()));
            contractors.forEach(redistribution -> redistribution.setPercentage(redistribution.getPercentage() / 1.0 / transaction.getValue()));
            transaction.setOwners(owners);
            transaction.setContractors(contractors);
            date = date.withHourOfDay(12).withMinuteOfHour(0).withSecondOfMinute(0);
            transaction.setCreator(Security.currentUser());
            transaction.setType(TransactionType.NOR);
            transaction.setDescription(name);
            transaction.setEvaluated(date);
            List<Category> cl = checkCategories(transaction.getDescription()).stream().map(categoryMap::get).filter(Objects::nonNull).collect(Collectors.toList());
            transaction.setCategories(cl.isEmpty() ? null : cl);
            transaction.setReference(sequenceManager.getNextReferenceForTransaction(transaction));
            transactionList.add(transaction);
        } catch (Exception e) {
            log.warn("Unable to convert line No{}: {}", ln, line, e);
        }
    }
    transactionList.sort((o1, o2) -> o1.getEvaluated().compareTo(o2.getCreated()));
    transactionList.forEach(t -> {
        t.setCreated(new LocalDateTime());
        log.info(t.getEvaluated() + " " + t.getReference() + " " + t.getValue() + " [" + t.getDescription() + "]" + " [" + t.getOwners().stream().map(r -> r.getId().getUser().getLogin() + "/" + r.getPercentage()).collect(Collectors.joining(", ")) + "]" + " [" + t.getContractors().stream().map(r -> r.getId().getUser().getLogin() + "/" + r.getPercentage()).collect(Collectors.joining(", ")) + "]" + " [" + (t.getCategories() == null ? "" : t.getCategories().stream().map(Category::getCode).collect(Collectors.joining(", "))) + "]");
        transactionRepository.save(t);
    });
}
Also used : LocalDateTime(org.joda.time.LocalDateTime) TransactionType(pl.morecraft.dev.settler.domain.dictionaries.TransactionType) java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Category(pl.morecraft.dev.settler.domain.Category) ByteArrayInputStream(java.io.ByteArrayInputStream) Transaction(pl.morecraft.dev.settler.domain.Transaction) Gson(com.google.gson.Gson) Service(org.springframework.stereotype.Service) UserRepository(pl.morecraft.dev.settler.dao.repository.UserRepository) Qualifier(org.springframework.beans.factory.annotation.Qualifier) CategoryRepository(pl.morecraft.dev.settler.dao.repository.CategoryRepository) RedistributionType(pl.morecraft.dev.settler.domain.dictionaries.RedistributionType) DateTimeFormat(org.joda.time.format.DateTimeFormat) User(pl.morecraft.dev.settler.domain.User) Logger(org.slf4j.Logger) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) Security(pl.morecraft.dev.settler.security.util.Security) IOException(java.io.IOException) LocalDateTime(org.joda.time.LocalDateTime) Collectors(java.util.stream.Collectors) TransactionRepository(pl.morecraft.dev.settler.dao.repository.TransactionRepository) IOUtils(org.apache.commons.io.IOUtils) MultipartFile(org.springframework.web.multipart.MultipartFile) Redistribution(pl.morecraft.dev.settler.domain.Redistribution) Transactional(org.springframework.transaction.annotation.Transactional) Category(pl.morecraft.dev.settler.domain.Category) User(pl.morecraft.dev.settler.domain.User) IOException(java.io.IOException) Redistribution(pl.morecraft.dev.settler.domain.Redistribution) Transaction(pl.morecraft.dev.settler.domain.Transaction) ByteArrayInputStream(java.io.ByteArrayInputStream) DateTimeFormatter(org.joda.time.format.DateTimeFormatter)

Aggregations

MultipartFile (org.springframework.web.multipart.MultipartFile)53 Test (org.junit.Test)18 File (java.io.File)16 MockMultipartFile (org.springframework.mock.web.test.MockMultipartFile)14 IOException (java.io.IOException)13 MockMultipartHttpServletRequest (org.springframework.mock.web.test.MockMultipartHttpServletRequest)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)10 MultipartHttpServletRequest (org.springframework.web.multipart.MultipartHttpServletRequest)10 MethodParameter (org.springframework.core.MethodParameter)8 List (java.util.List)6 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)6 FileOutputStream (java.io.FileOutputStream)5 ActivitiException (org.activiti.engine.ActivitiException)5 RequestParam (org.springframework.web.bind.annotation.RequestParam)5 ArrayList (java.util.ArrayList)4 Optional (java.util.Optional)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 Part (javax.servlet.http.Part)3