TransferController.java 14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
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<String, String> params)
            throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();

        for (Map.Entry<String, String> 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(
                "(?<!\\d|\\d\\.)" +
                        "(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                        "(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])" +
                        "(?!\\d|\\.\\d)").matcher(s);
        return m.find() ? m.group() : null;
    }


    public static String reAssembleURL(String url){

        String url_canon_init = "http://";

        if(extractIP(url) != null){

            if(url.length() < 7 || !url.substring(0,7).equals(url_canon_init)){

                url = url_canon_init + url;
            }
        }else{

            if(url.length() < 11 || !url.substring(0,11).equals(url_canon_init+"www.")){

                url = url_canon_init +"www."+ url;
            }
        }

        return url;

    }

    public static boolean token_caducity(Date token_receipt){

        Date token_receipt_date = token_receipt;

        long diff = new Date().getTime() - token_receipt_date.getTime();

        if(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS) >= 7){

            return true;
        }

        return false;

    }

}