Mengubah file extension secara otomatis pada java

File Service Java :

package com.emerio.surveysystem.service;

import ch.qos.logback.core.util.ContentTypeUtil; import ch.qos.logback.core.util.FileUtil; import io.minio.MinioClient; import io.minio.errors.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.xmlpull.v1.XmlPullParserException; import org.springframework.web.multipart.MultipartFile;

@Service public class FileService {

@Value("${app.minio.host}") private String minioHost; // @Value("${app.minio.ip}") private String minioIp;

@Value("${app.minio.access.key}") private String minioAccessKey;

@Value("${app.minio.secret.key}") private String minioSecretKey;

private MinioClient client;

public InputStream getFile(String bucket, String filename) { try { try { this.client = new MinioClient(this.minioHost, this.minioAccessKey, this.minioSecretKey); } catch (InvalidEndpointException e) { e.printStackTrace(); } catch (InvalidPortException e) { e.printStackTrace(); } return client.getObject(bucket, filename); } catch (InvalidKeyException | InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException | NoResponseException | ErrorResponseException | InternalException | InvalidArgumentException | InvalidResponseException | IOException | XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }

public void uploadFile(MultipartFile file, String objectName) { try { try { this.client = new MinioClient(this.minioHost, this.minioAccessKey, this.minioSecretKey); } catch (InvalidEndpointException e) { e.printStackTrace(); } catch (InvalidPortException e) { e.printStackTrace(); }

} catch (InvalidBucketNameException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoResponseException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (ErrorResponseException e) { e.printStackTrace(); } catch (InternalException e) { e.printStackTrace(); } catch (InvalidArgumentException e) { e.printStackTrace(); } catch (InsufficientDataException e) { e.printStackTrace(); } catch (InvalidResponseException e) { e.printStackTrace(); } } }

File controller :

package com.emerio.surveysystem;

import com.emerio.surveysystem.model.*; import com.emerio.surveysystem.service.FileService; import com.emerio.surveysystem.service.SurveyService; import com.google.gson.Gson; import org.bson.Document; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile;

import java.io.IOException; import java.sql.SQLException; import java.util.*;

@RequestMapping("api/survey") @RestController()

public class Controller {

@Value("${app.kong.host}") private String kongHost;

@Value("${app.kong.port}") private int kongPort;

@Autowired FileService minioService;

@Autowired UserDao userDao;

@Autowired SurveyService surveyService;

@Autowired SurveyDao surveyDao;

@GetMapping("/generate-id-survey") public ResponseEntity generateIdSurvey() throws SQLException { return new ResponseEntity(surveyService.getnerateId(), HttpStatus.OK); }

@PostMapping("/add-survey") public ResponseEntity addSurvey(@RequestBody Survey survey) {

boolean exists = surveyService.checkIdSurvey(survey.getIdSurvey()); if (exists == true) {

if (survey.getImgHeader() != null) { String[] headerData = survey.getImgHeader().split(",", 2); List list1 = Arrays.asList(headerData); String headerEncode = list1.get(1); byte[] headerImage = Base64.getDecoder().decode(headerEncode); String nameHeaderImage = "imageHeader-" + survey.getIdSurvey() + ".jpeg"; minioService.uploadFile(headerImage, nameHeaderImage); survey.setImgHeader(kongHost + ":" + kongPort + "/api/survey/file/survey-system/" + nameHeaderImage); }

if (survey.getImgIcon() != null) { String[] logoData = survey.getImgIcon().split(",", 2); List list2 = Arrays.asList(logoData); String logoEncode = list2.get(1); byte[] logoImage = Base64.getDecoder().decode(logoEncode); String namelogoImage = "imageLogo-" + survey.getIdSurvey() + ".png"; minioService.uploadFile(logoImage, namelogoImage); survey.setImgIcon(kongHost + ":" + kongPort + "/api/survey/file/survey-system/" + namelogoImage); } for (Page page : survey.getPages()) { for (Question question : page.getQuestions()) { if (question.getImgPage() != null) { String[] imageData = question.getImgPage().split(",", 2); List list = Arrays.asList(imageData); String encode = list.get(1);

byte[] imageByte = Base64.getDecoder().decode(encode); String namePicture = "picturepages" + survey.getIdSurvey() + "-" + page.getId() + "-" + question.getId() + ".jpeg"; minioService.uploadFile(imageByte, namePicture); question.setImgPage( kongHost + ":" + kongPort + "/api/survey/file/survey-system/" + namePicture); }

}

} surveyService.updateSurvey(survey); return new ResponseEntity<>(HttpStatus.CREATED); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping("/load-all-survey") public ResponseEntity&gt; getAllSurvey() { try { return new ResponseEntity>(surveyService.loadAlSurveys(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } }

@RequestMapping(method = RequestMethod.GET, value = "/load-survey-by-id/{survey_id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getSurveyById(@PathVariable(name = "survey_id") int idSurvey) {

boolean exists = surveyService.checkIdSurvey(idSurvey); if (exists == true) { return new ResponseEntity(surveyService.loadSurveyById(idSurvey), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping("/load-survey-by-id-page-one/{survey_id}") public ResponseEntity getSurveyPageOneById(@PathVariable(name = "survey_id") int idSurvey) {

boolean exists = surveyService.checkIdSurvey(idSurvey); if (exists == true) { return new ResponseEntity(surveyService.loadSurveyByIdPageOne(idSurvey), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping("/load-survey-by-survey-id-and-page-id/{user_id}/{survey_id}/{page_id}") public ResponseEntity getSurveyByUserIdSurveyIdandPageId(@PathVariable(name = "user_id") String idUser, @PathVariable(name = "survey_id") int idSurvey, @PathVariable(name = "page_id") int page_id) {

Survey newSurvey = surveyService.loadSurveyBySurveyIdandPageId(idSurvey, idUser, page_id); Page newPage = surveyService.loadPageBySurveyIdandPageId(idSurvey, idUser, page_id); int totalpage = surveyService.totalCountPage(idSurvey) - 1; // Response newResponse = surveyService.loadResponseBySurveyIdPageIdQuestionIdUserId(idSurvey, user_id); // String userId = newResponse.getUserId(); String user_id = surveyService.loadUserId(idSurvey, idUser);

for (Question question : newPage.getQuestions()) {

//Response newResponse = surveyService.loadResponseBySurveyIdPageIdQuestionIdUserId(idSurvey, page_id, question.getId(), user_id); //String userId = surveyService.loadUserId(idSurvey, page_id, question.getId()); boolean answerExist = surveyService.checkAnswerBySurveyIdPageIdQuestionId(idSurvey, page_id, question.getId(), idUser);

if (answerExist == false) { question.setAnswer(null);

} else {

if (question.getQuestionType().equalsIgnoreCase("checkbox")) { List values = surveyService.loadOptionAnswerbySurveyIdPageIdandQuestionId(idSurvey, page_id, question.getId(), idUser); question.setValues(values); question.setAnswer(null); } else { // question.setValues(null); String answer = surveyService.loadAnswerbySurveyIdPageIdandQuestionId(idSurvey, page_id, question.getId(), idUser);

question.setAnswer(answer); } }

}

Document doc = new Document();

doc.put("idSurvey", newSurvey.getIdSurvey()); doc.put("idUser", user_id ); doc.put("colorHeader", newSurvey.getColorHeader()); doc.put("colorBg", newSurvey.getColorBg()); doc.put("icon", newSurvey.getIcon()); doc.put("imgHeader", newSurvey.getImgHeader()); doc.put("imgLogo", newSurvey.getImgIcon()); doc.put("totalpages", totalpage); doc.put("id", newPage.getId()); doc.put("title", newPage.getTitle()); doc.put("desc", newPage.getDesc()); doc.put("questions", newPage.getQuestions());

return new ResponseEntity(doc, HttpStatus.OK);

}

@RequestMapping(value = "/find-all-survey-pagination/{pageNo}", method = RequestMethod.GET) public ResponseEntity&gt; surveyPagination(@PathVariable(name = "pageNo") int pageNo) throws SQLException {

try {

int totalRecords = surveyService.totalCount();

int p = 0; if (totalRecords % 12 == 0) { p = totalRecords / 12; } else { p = totalRecords / 12 + 1; }

if (pageNo <= p) { List surveyViews = surveyService.surveyPagination(12, pageNo); Map response = new HashMap<>(); response.put("surveyView", surveyViews); response.put("totalPages", p);

return new ResponseEntity>(response, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@PostMapping(value = "/update-response") public List updateResponse(@RequestBody Document response) throws ParseException {

List f = new ArrayList<>();

List responses = new ArrayList<>(); List questions = (List) response.get("questions"); Gson gson = new Gson(); for (Object question : questions) { String json = gson.toJson(question);

Document doc = Document.parse(json); Response response1 = new Response();

response1.setPageId(response.getInteger("id")); response1.setSurveyId(response.getInteger("idSurvey")); response1.setQuestionId(doc.getInteger("id")); response1.setUserId(response.getString("idUser"));

if (doc.getString("questionType").equalsIgnoreCase("checkbox")) { List values = (List) doc.get("values"); List optionAnswers = new ArrayList<>(); for (Document value : values) { OptionAnswer optionAnswer = new OptionAnswer(); optionAnswer.setId(value.getInteger("id")); optionAnswer.setValues(value.getString("values")); optionAnswer.setChecked(value.getBoolean("checked")); optionAnswers.add(optionAnswer);

}

response1.setQuestionType(doc.getString("questionType")); response1.setOptionAnswers(optionAnswers); response1.setAnswer(doc.getString("answer")); surveyDao.updateResponseCheckbox(response1);

} else { OptionAnswer answer = new OptionAnswer(); answer.setId(0); answer.setValues(doc.getString("answer"));

response1.setAnswer(doc.getString("answer")); surveyDao.updateResponseBesideCheckbox(response1);

}

}

}

@RequestMapping(value = "/file/{bucket}/{filename}", method = RequestMethod.GET) public ResponseEntity download(@PathVariable(name = "bucket") String bucket, @PathVariable(name = "filename") String filename) { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "image/jpeg+xml"); headers.add("Connection", "keep-alive"); headers.add("Accept-Ranges", "bytes"); // headers.add("Content-Disposition", "attachment; filename=\""+filename+"\""); return new ResponseEntity( new InputStreamResource(this.minioService.getFile(bucket, filename)), headers, HttpStatus.OK); // return Mono.just(ResponseEntity.ok().headers(headers).body(new // InputStreamResource(this.minioService.getFile(bucket, filename)))); }

@RequestMapping(value = "/coba", method = RequestMethod.POST) public ResponseEntity getFileByte(@RequestBody Document image) throws Exception {

String[] imageData = image.getString("image").split(",", 2);

List list = Arrays.asList(imageData); String encode = list.get(1);

byte[] imageByte = Base64.getDecoder().decode(encode); minioService.uploadFile(imageByte, "photo100076769.jpeg"); // return list.get(1); return new ResponseEntity("done", HttpStatus.OK); // return Mono.just(ResponseEntity.ok().body("done"));

}

@DeleteMapping("/delete-survey/{surveyId}") public ResponseEntity deleteSurveyById(@PathVariable int surveyId) {

surveyService.deleteSurveyById(surveyId); return new ResponseEntity<>(HttpStatus.OK); }

@RequestMapping(value = "/find-all-survey-pagination-save-status/{pageNo}", method = RequestMethod.GET) public ResponseEntity&gt; surveyPaginationSubmitStatus(@PathVariable(name = "pageNo") int pageNo) throws SQLException {

try {

int totalRecords = surveyService.totalCount();

int p = 0; if (totalRecords % 12 == 0) { p = totalRecords / 12; } else { p = totalRecords / 12 + 1; }

if (pageNo <= p) { List surveyViews = surveyService.surveyPaginationSubmitStatus(12, pageNo); Map response = new HashMap<>(); response.put("surveyView", surveyViews); response.put("totalPages", p);

return new ResponseEntity>(response, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@RequestMapping(value = "/find-all-survey-pagination-publish-status/{pageNo}", method = RequestMethod.GET) public ResponseEntity&gt; surveyPaginationPublishStatus(@PathVariable(name = "pageNo") int pageNo) throws SQLException {

try {

int totalRecords = surveyService.totalCount();

int p = 0; if (totalRecords % 12 == 0) { p = totalRecords / 12; } else { p = totalRecords / 12 + 1; }

if (pageNo <= p) { List surveyViews = surveyService.surveyPaginationPublishStatus(12, pageNo); Map response = new HashMap<>(); response.put("surveyView", surveyViews); response.put("totalPages", p);

return new ResponseEntity>(response, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@RequestMapping(value = "/find-all-survey-pagination-private-status/{pageNo}", method = RequestMethod.GET) public ResponseEntity&gt; surveyPaginationPrivateStatus(@PathVariable(name = "pageNo") int pageNo) throws SQLException {

try {

int totalRecords = surveyService.totalCount();

int p = 0; if (totalRecords % 12 == 0) { p = totalRecords / 12; } else { p = totalRecords / 12 + 1; }

if (pageNo <= p) { List surveyViews = surveyService.surveyPaginationPrivateStatus(12, pageNo); Map response = new HashMap<>(); response.put("surveyView", surveyViews); response.put("totalPages", p);

return new ResponseEntity>(response, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@RequestMapping(value = "/find-all-survey-pagination-public-status/{pageNo}", method = RequestMethod.GET) public ResponseEntity&gt; surveyPaginationActiveStatus(@PathVariable(name = "pageNo") int pageNo) throws SQLException {

try {

int totalRecords = surveyService.totalCount();

int p = 0; if (totalRecords % 12 == 0) { p = totalRecords / 12; } else { p = totalRecords / 12 + 1; }

if (pageNo <= p) { List surveyViews = surveyService.surveyPaginationPublicStatus(12, pageNo); Map response = new HashMap<>(); response.put("surveyView", surveyViews); response.put("totalPages", p);

return new ResponseEntity>(response, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping(value = "/find-all-user") public ResponseEntity&gt; selectAllUser() {

try { return new ResponseEntity<>(userDao.selectAllUser(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping(value = "/get-email-list") public ResponseEntity&gt; getEmailList() {

try { return new ResponseEntity<>(userDao.getEmailList(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@GetMapping(value = "/get-user-list") public ResponseEntity&gt; getUserList() {

try { return new ResponseEntity<>(userDao.getUserList(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) public Document createNewObjectWithImage( @RequestPart String name, @RequestPart MultipartFile image) throws IOException {

byte[] images = image.getBytes(); String imageName = name+".jpeg"; minioService.uploadFile(images, imageName);

Document doc = new Document(); doc.append("bucketName", "survey-system"); doc.append("imageName", "name.jpeg"); doc.append("path", "http://localhost:9090/api/survey/file/survey-system/"+imageName);

return doc;

}

@PostMapping(value = "/assign-survey") public void assignSurvey(@RequestBody Document payload){ List userId = (List) payload.get("userList"); int survey_id = payload.getInteger("idSurvey"); //surveyDao.assignSurvey(survey_id, userId);

surveyDao.assignSurvey(survey_id,userId); Survey survey = surveyService.loadSurveyById(survey_id);

if(surveyService.checkResponse(survey_id) == false) { List responses = new ArrayList<>();

for (Page page : survey.getPages()) { Gson gson = new Gson(); for (Question question : page.getQuestions()) { String json = gson.toJson(question);

Response response1 = new Response();

response1.setPageId(page.getId()); response1.setSurveyId(survey.getIdSurvey()); response1.setQuestionId(question.getId()); List listOptionAnswer = new ArrayList<>(); for (Values value : question.getValues()) { OptionAnswer optionAnswer = new OptionAnswer(); optionAnswer.setId(value.getId()); optionAnswer.setValues(value.getValues()); optionAnswer.setChecked(value.getChecked()); listOptionAnswer.add(optionAnswer); } response1.setAnswer(question.getAnswer()); response1.setOptionAnswers(listOptionAnswer); response1.setQuestionType(question.getQuestionType()); // responses.add(response1); surveyService.insertResponse(response1, userId); } } } }

}

avatar cakrahamka
@cakrahamka

1 Kontribusi 0 Poin

Dipost 5 tahun yang lalu

Tanggapan

tolong di share bagian error nya saja ya

Belum ada Jawaban. Jadi yang pertama Jawaban

Login untuk ikut Jawaban