Skip to content

Commit

Permalink
Merge pull request #105 from Open-MBEE/bugfix/MAGICDRAW-696
Browse files Browse the repository at this point in the history
MAGICDRAW-696 #comment Merged pull request. #resolve
  • Loading branch information
ivan-gomes authored May 3, 2017
2 parents 50d33a3 + 9a72c0f commit 02e4afc
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 122 deletions.
18 changes: 16 additions & 2 deletions src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,25 @@ public static void generateAllDocuments(Project project) {
}

/**
* Executes "Validate Model" on specified element
* Executes "Validate Element" on specified element
*
* @param validateTarget element that the validation is to be performed upon
*/
public static void manualValidateElement(Element validateTarget) {
Collection<Element> sync = new ArrayList<>();
sync.add(validateTarget);
ManualSyncRunner manualSyncRunner = new ManualSyncRunner(sync, Application.getInstance().getProject(), 0);
ProgressStatusRunner.runWithProgressStatus(manualSyncRunner, "Manual Sync", true, 0);
Application.getInstance().getGUILog().log("Validated");
validationWindow = new MDKValidationWindow(manualSyncRunner.getValidationSuite());
}

/**
* Executes "Validate Model" on specified element
*
* @param validateTarget element that the validation is to be performed upon
*/
public static void manualValidateModel(Element validateTarget) {
Collection<Element> sync = new ArrayList<>();
sync.add(validateTarget);
ManualSyncRunner manualSyncRunner = new ManualSyncRunner(sync, Application.getInstance().getProject(), -1);
Expand All @@ -320,7 +334,7 @@ public static void manualValidateElement(Element validateTarget) {
* Executes "Validate Model" on model root
*/
public static void manualValidateModel() {
manualValidateElement(ElementFinder.getModelRoot());
manualValidateModel(ElementFinder.getModelRoot());
}

/**********************************************************************************
Expand Down
181 changes: 70 additions & 111 deletions src/main/java/gov/nasa/jpl/mbee/mdk/mms/MMSUtils.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package gov.nasa.jpl.mbee.mdk.mms;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
Expand All @@ -23,10 +20,10 @@
import gov.nasa.jpl.mbee.mdk.http.HttpDeleteWithBody;
import gov.nasa.jpl.mbee.mdk.http.ServerException;
import gov.nasa.jpl.mbee.mdk.json.JacksonUtils;
import gov.nasa.jpl.mbee.mdk.mms.actions.MMSLogoutAction;
import gov.nasa.jpl.mbee.mdk.util.MDUtils;
import gov.nasa.jpl.mbee.mdk.util.TicketUtils;
import gov.nasa.jpl.mbee.mdk.util.Utils;
import gov.nasa.jpl.mbee.mdk.mms.actions.MMSLogoutAction;
import gov.nasa.jpl.mbee.mdk.options.MDKOptionsGroup;

import org.apache.commons.io.IOUtils;
Expand Down Expand Up @@ -287,67 +284,32 @@ public static File sendMMSRequest(Project project, HttpRequestBase request)
logBody = logBody && httpEntityEnclosingRequest.getEntity().isRepeatable();
System.out.println("MMS Request [" + request.getMethod() + "] " + request.getURI().toString());

// flag for later server exceptions; they will be thrown after printing any available server messages to the gui log
boolean throwServerException = false;
int responseCode;

// create client, execute request, parse response, store in thread safe buffer to return as string later
// client, response, and reader are all auto closed after block
try (CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(request);
InputStream inputStream = response.getEntity().getContent();
OutputStream outputStream = new FileOutputStream(targetFile)) {
// get data out of the response
responseCode = response.getStatusLine().getStatusCode();
String responseType = ((response.getEntity().getContentType() != null) ? response.getEntity().getContentType().getValue() : "");

// debug / logging output from response
responseCode = response.getStatusLine().getStatusCode();
System.out.println("MMS Response [" + request.getMethod() + "] " + request.getURI().toString() + " - Code: " + responseCode);
System.out.println("Response Body: " + targetFile.getPath());

// assume that a GET that returns 404 with json response bodies is a "missing resource" 404, which are expected for some cases and should not break normal execution flow
if (responseCode == HttpURLConnection.HTTP_OK || (request.getMethod().equals("GET") && responseCode == HttpURLConnection.HTTP_NOT_FOUND && responseType.equals("application/json;charset=UTF-8"))) {
// continue
}
// allow re-attempt of request if credentials have expired or are invalid
else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
Utils.guilog("[ERROR] MMS authentication is missing or invalid. Closing connections. Please log in again and your request will be retried. Server code: " + responseCode);
MMSLogoutAction.logoutAction(project);
throwServerException = true;
}
// if it's anything else, assume failure and break normal flow
else {
Utils.guilog("[ERROR] Operation failed due to server error. Server code: " + responseCode);
throwServerException = true;
}

// dump to temp response file, build jsonParser and print server message if possible
if (inputStream != null && responseType.equals("application/json;charset=UTF-8")) {
// get data out of the response, dump to temp file
System.out.println("Response Body: " + targetFile.getPath());
if (inputStream != null) {
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}

JsonFactory jsonFactory = JacksonUtils.getJsonFactory();
try (JsonParser jsonParser = jsonFactory.createParser(targetFile)) {
while (jsonParser.nextFieldName() != null && !jsonParser.nextFieldName().equals("message")) {
// spin until we find message
}
if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME) {
jsonParser.nextToken();
Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + jsonParser.getText());
try (FileInputStream fileInputStream = new FileInputStream(targetFile)) {
if (!processResponse(responseCode, fileInputStream, project)) {
throw new ServerException(targetFile.getAbsolutePath(), responseCode);
}
}

if (throwServerException) {
// big flashing red letters that the action failed, or as close as we're going to get
Utils.showPopupMessage("Action failed. See notification window for details.");
// throw is done last, after printing the error and any messages that might have been returned
throw new ServerException(targetFile.getAbsolutePath(), responseCode);
}
return targetFile;
}

Expand Down Expand Up @@ -442,53 +404,24 @@ public static String sendCredentials(Project project, String username, String pa

// do request
System.out.println("MMS Request [POST] " + requestUri.toString());
ObjectNode responseJson = null;
String responseBody;
int responseCode;
try (CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(request);
InputStream inputStream = response.getEntity().getContent()) {
// get data out of the response
int responseCode = response.getStatusLine().getStatusCode();
String responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : "");
String responseType = ((response.getEntity().getContentType() != null) ? response.getEntity().getContentType().getValue() : "");

// debug / logging output from response
responseCode = response.getStatusLine().getStatusCode();
System.out.println("MMS Response [POST] " + requestUri.toString() + " - Code: " + responseCode);

// flag for later server exceptions; they will be thrown after printing any available server messages to the gui log
boolean throwServerException = false;

// if it's not 200, failure and break normal flow
if (responseCode != HttpURLConnection.HTTP_OK) {
Application.getInstance().getGUILog().log("[ERROR] Operation failed due to server error. Server code: " + responseCode);
throwServerException = true;
}

// print server message if possible
if (!responseBody.isEmpty() && responseType.equals("application/json;charset=UTF-8")) {
responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class);
JsonNode value;
// display single response message
if (responseJson != null && (value = responseJson.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) {
Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText());
}
// display multiple response messages
if (responseJson != null && (value = responseJson.get("messages")) != null && value.isArray()) {
ArrayNode msgs = (ArrayNode) value;
for (JsonNode msg : msgs) {
if (msg != null && (value = msg.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) {
Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText());
}
}
}
}

if (throwServerException) {
// big flashing red letters that the action failed, or as close as we're going to get
Utils.showPopupMessage("Action failed. See notification window for details.");
// throw is done last, after printing the error and any messages that might have been returned
throw new ServerException(responseBody, responseCode);
// get data out of the response
responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : "");
}
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBody.getBytes())) {
if (!processResponse(responseCode, byteArrayInputStream, project)) {
throw new ServerException("Credential acquisition could not be completed.", responseCode);
}
}

ObjectNode responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class);
// parse response
JsonNode value;
if (responseJson != null && (value = responseJson.get("data")) != null && (value = value.get("ticket")) != null && value.isTextual()) {
Expand All @@ -512,39 +445,65 @@ public static String validateCredentials(Project project, String ticket)

// do request
System.out.println("MMS Request [GET] " + requestUri.toString());
ObjectNode responseJson;
JsonNode value;
String responseBody;
int responseCode;
try (CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(request);
InputStream inputStream = response.getEntity().getContent()) {
// get data out of the response
int responseCode = response.getStatusLine().getStatusCode();
String responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : "");
String responseType = ((response.getEntity().getContentType() != null) ? response.getEntity().getContentType().getValue() : "");

// debug / logging output from response
responseCode = response.getStatusLine().getStatusCode();
System.out.println("MMS Response [GET] " + requestUri.toString() + " - Code: " + responseCode);
// get data out of the response
responseBody = ((inputStream != null) ? IOUtils.toString(inputStream) : "");
}
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBody.getBytes())) {
if (!processResponse(responseCode, byteArrayInputStream, project)) {
throw new ServerException("Credential validation could not be completed.", responseCode);
}
}

if (responseCode == 200) {
if (!responseBody.isEmpty() && responseType.equals("application/json;charset=UTF-8")) {
responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class);
if (responseJson != null && (value = responseJson.get("message")) != null && value.isTextual() && !value.asText().isEmpty()) {
Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + value.asText());
}
if (responseJson != null && (value = responseJson.get("username")) != null && value.isTextual() && !value.asText().isEmpty()) {
return value.asText();
}
}
return "";
ObjectNode responseJson = JacksonUtils.getObjectMapper().readValue(responseBody, ObjectNode.class);
// parse response
JsonNode value;
if (responseJson != null && (value = responseJson.get("username")) != null && value.isTextual() && !value.asText().isEmpty()) {
return value.asText();
}
return "";
}

private static boolean processResponse(int responseCode, InputStream responseStream, Project project) {
boolean throwServerException = false;
JsonFactory jsonFactory = JacksonUtils.getJsonFactory();
try (JsonParser jsonParser = jsonFactory.createParser(responseStream)) {
while (jsonParser.nextFieldName() != null && !jsonParser.nextFieldName().equals("message")) {
// spin until we find message
}
else {
Application.getInstance().getGUILog().log("[ERROR] Operation failed due to server error. Server code: " + responseCode);
// big flashing red letters that the action failed, or as close as we're going to get
Utils.showPopupMessage("Action failed. See notification window for details.");
// throw is done last, after printing the error and any messages that might have been returned
throw new ServerException(responseBody, responseCode);
if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME) {
jsonParser.nextToken();
Application.getInstance().getGUILog().log("[SERVER MESSAGE] " + jsonParser.getText());
}
} catch (IOException e) {
Application.getInstance().getGUILog().log("[WARNING] Unable to retrieve messages from server response.");
throwServerException = true;
}

if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
Application.getInstance().getGUILog().log("[ERROR] MMS authentication is missing or invalid. Closing connections. Please log in again and your request will be retried.");
MMSLogoutAction.logoutAction(project);
throwServerException = true;
}
// if we got messages out, we hit a valid endpoint and got a valid response and either a 200 or a 404 is an acceptable response code. If not, throw is already true.
else if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NOT_FOUND) {
throwServerException = true;
}

if (throwServerException) {
// big flashing red letters that the action failed, or as close as we're going to get
Application.getInstance().getGUILog().log("<span style=\"color:#FF0000; font-weight:bold\">[ERROR] Operation failed due to server error. Server code: " + responseCode + "</span>" +
"<span style=\"color:#FFFFFF; font-weight:bold\"> !!!!!</span>"); // hidden characters for easy search
// Utils.showPopupMessage("Action failed. See notification window for details.");
}
return !throwServerException;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,12 @@ public void update() {

@Override
public void actionPerformed(final ActionEvent event) {
outputQueueDetailWindow.setVisible(!outputQueueDetailWindow.isVisible());
if (outputQueueDetailWindow.isVisible()) {
if (!outputQueueDetailWindow.isVisible()) {
outputQueueDetailWindow.setVisible(true);
}
else {
outputQueueDetailWindow.update();
outputQueueDetailWindow.toFront();
}
}

Expand Down Expand Up @@ -137,7 +140,7 @@ public void update() {
((AbstractTableModel) table.getModel()).fireTableStructureChanged();
}*/
table.repaint();
this.setAlwaysOnTop(true);
// this.setAlwaysOnTop(true);
//tableModel.fireTableDataChanged();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,12 @@ public SyncStatusFrame getSyncStatusFrame() {

@Override
public void actionPerformed(@CheckForNull ActionEvent actionEvent) {
getSyncStatusFrame().setVisible(!getSyncStatusFrame().isVisible());
if (getSyncStatusFrame().isVisible()) {
if (!getSyncStatusFrame().isVisible()) {
getSyncStatusFrame().setVisible(true);
}
else {
update();
getSyncStatusFrame().toFront();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public SyncStatusFrame() {
pack();
setMinimumSize(getSize());
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setAlwaysOnTop(true);
// setAlwaysOnTop(true);
detailsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public ViewEditorLinkForm(String label, List<JButton> buttons) {
setMinimumSize(getSize());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setAlwaysOnTop(true);
// setAlwaysOnTop(true);
}

{
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/gov/nasa/jpl/mbee/mdk/util/TicketUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class TicketUtils {

private static String username = "";
private static String password = "";
private static final int TICKET_RENEWAL_INTERVAL = 1800; //seconds
private static final int TICKET_RENEWAL_INTERVAL = 15 * 60; //seconds
private static final HashMap<Project, TicketMapping> ticketMappings = new HashMap<>();

/**
Expand All @@ -52,7 +52,8 @@ public static boolean isTicketValid(Project project) throws ServerException, IOE
if (!isTicketSet(project)) {
return false;
}
return MMSUtils.validateCredentials(project, ticketMappings.get(project).getTicket()).equals(username);
String ticket = ticketMappings.get(project).getTicket();
return MMSUtils.validateCredentials(project, ticket).equals(username);
}

/**
Expand Down

0 comments on commit 02e4afc

Please sign in to comment.