package adt.mainnode.controller; import adt.mainnode.entity.Credentials; import adt.mainnode.entity.ScanConfig; import adt.mainnode.entity.Node; import adt.mainnode.entity.Vlan; import adt.mainnode.repository.CredentialsRepository; import adt.mainnode.repository.ScanConfigRepository; import adt.mainnode.repository.NodeRepository; import adt.mainnode.repository.VlanRepository; import adt.mainnode.service.InitializeService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.concurrent.Executors; import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.core.JsonProcessingException; import java.io.FileWriter; import java.io.IOException; import java.io.*; import java.util.Arrays; import java.util.ArrayList; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response.Status; import java.io.IOException; import java.util.*; import java.net.*; import java.util.Date; import java.util.concurrent.TimeUnit; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.entity.mime.*; import org.apache.http.entity.*; import org.apache.http.*; import org.apache.http.util.*; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.JSONArray; import java.io.*; @RestController @RequestMapping("event") @Api( value = "/event", produces = MediaType.APPLICATION_JSON_VALUE, tags = {"(Event) Transfer Service"} ) @Slf4j public class TransferController { private final InitializeService initializeService; private final CredentialsRepository credentialsRepository; @Autowired public TransferController(InitializeService initializeService, CredentialsRepository credentialsRepository) { this.initializeService = initializeService; this.credentialsRepository = credentialsRepository; } @CrossOrigin @ApiOperation(value = "Transfer a JSON object.", response = Node.class) @ResponseStatus(HttpStatus.CREATED) @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) String processEvent(HttpServletResponse response, HttpServletRequest httpServletRequest, @RequestParam(value = "token") String token, @RequestBody String item) { Credentials credential = credentialsRepository.findByToken(token); String petition_user = initializeService.getTransferUser(); String petition_password = initializeService.getTransferPassword(); String petition_url = initializeService.getPetitionUrl(); String transfer_url = initializeService.getTransferUrl(); String transfer_token = initializeService.getTransferToken(); Date token_receipt = initializeService.getTransferTokenReceipt(); if(credential != null && credential.getStatus().equals("OPERATIVE")) { if (credential.getAvailableEndpoint().contains("(POST) event/")) { if ( petition_user != null || petition_password != null || petition_url != null || transfer_url != null) { if (transfer_token == null || transfer_token.length() == 0 || token_caducity(token_receipt)){ try { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(petition_url);//"http://83.212.116.5:8000/api/v1/login/access-token"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", petition_user);//"adt@curex-project.eu"); builder.addTextBody("password", petition_password);//"upm-adt"); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); HttpResponse response_client = client.execute(httpPost); HttpEntity entity = response_client.getEntity(); String response_body = EntityUtils.toString(entity); log.info("[Event Service] Token obtention - Response Code: {}", response_client); client.close(); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(response_body); transfer_token = (String) json.get("access_token"); String token_failure = null; if(transfer_token == null){ token_failure = (String) json.get("detail"); if(token_failure.contains("Not Found")){ try { response.sendError(404, "URL Not Found."); }catch(IOException ioe){ } return null; }else if(token_failure.contains("Incorrect email or password")) { try { response.sendError(401, "The credentials set for the Token Obtention process (username or password) are invalid."); } catch (IOException ioe) { // } return null; }else{ try { response.sendError(500, "Something went wrong. You may check your Token Obtention credentials and/or the provided URL."); } catch (IOException ioe) { // } return null; } } initializeService.setTransferToken(transfer_token); initializeService.setTransferTokenReceipt(new Date()); log.info("[Event Service] Token obtention - Received Token: {}", transfer_token); } catch (Exception e) { log.error("[Event Service] Token obtention - Something went wrong:\n", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exc = sw.toString(); if(exc.contains("UnknownHostException")) { try { response.sendError(404, "URL Not Found."); } catch (IOException ioe) { // } return null; }else{ try { response.sendError(500, "Something went wrong. You may check your Token Obtention credentials and/or the provided URL."); } catch (IOException ioe) { // } return null; } } } try { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(transfer_url);//"http://83.212.116.5:8000/api/v1/adt/"); String request_body = item; HttpEntity request_entity = new StringEntity(request_body); log.info("[Event Service] Event Transfer - Sending request with entity:\n {}", EntityUtils.toString(request_entity)); log.info("[Event Service] Event Transfer - Sending request with token:\n {}", transfer_token); httpPost.setHeader("Authorization", "Bearer " + transfer_token);//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJleHAiOjE1Nzk2ODIxMjEsInN1YiI6ImFjY2VzcyJ9.rJGhvYBqP-USUvzazwrDDB0hivGrvobN1YCty42hgG4"); //+ transfer_token); httpPost.setEntity(request_entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse response_client = client.execute(httpPost); log.info("[Event Service] Event Transfer - Response Code: {}", response_client); HttpEntity entity = response_client.getEntity(); String response_body = EntityUtils.toString(entity); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(response_body); response_body = (String) json.get("msg"); JSONArray response_body_fail = null; if(response_body == null){ //// VERIFICAR QUE SEA ARRAY O NO response_body_fail = (JSONArray) json.get("detail"); json = (JSONObject) response_body_fail.get(0); response_body = (String) json.get("msg"); try { response.sendError(422, "The provided Events information is not valid (unprocessable JSON format)."); }catch(IOException ioe){ // } return null; } log.info("[Event Service] Event Transfer - Response Body: {}", response_body); client.close(); }catch(Exception e){ log.error("[Event Service] Something went wrong:\n", e); try { response.sendError(500, "Something went wrong. You may check your Token Obtention credentials and/or the provided URL."); } catch (IOException ioe) { // } return null; } return item; }else{ try { response.sendError(400, "Unset Event Transfer Variables."); }catch(IOException ioe){ // } return null; } } } try { response.sendError(400, "Unrecognized token. Access denied."); }catch(IOException ioe){ // } return null; } public static String getParamsString(Map params) throws UnsupportedEncodingException{ StringBuilder result = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); result.append("&"); } String resultString = result.toString(); return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; } public static String extractIP(String s) { java.util.regex.Matcher m = java.util.regex.Pattern.compile( "(?= 7){ return true; } return false; } }