Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • DM/dm-docs
  • hammonds/dm-docs
  • hparraga/dm-docs
3 results
Show changes
Showing
with 1440 additions and 0 deletions
j2ee.server.home=/home/dm/support/opt/glassfish/glassfish
j2ee.server.middleware=/home/dm/support/opt/glassfish
j2ee.server.home=DM_GLASSFISH_DIR/glassfish
j2ee.server.middleware=DM_GLASSFISH_DIR
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
<open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
<group>
<file>file:/home/sveseli/Work/DM/dev/src/java/DmWebPortal/web/views/roleType/private/systemRoleTypeListDataTable.xhtml</file>
<file>file:/home/sveseli/Work/DM/dev/src/java/DmWebPortal/web/views/roleType/private/experimentRoleTypeListDataTable.xhtml</file>
<file>file:/home/sveseli/Work/DM/dev/src/java/DmWebPortal/web/views/experimentStation/private/stationManagerListDataTable.xhtml</file>
<file>file:/home/sveseli/Work/DM/dev/src/java/DmWebPortal/web/views/experiment/private/experimentUserListDataTable.xhtml</file>
</group>
</open-files>
</project-private>
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=true
annotation.processing.processor.options=-Aeclipselink.canonicalmodel.use_static_factory=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
auxiliary.org-netbeans-modules-projectapi.jsf_2e_language=Facelets
auxiliary.org-netbeans-modules-web-clientproject-api.js_2e_libs_2e_folder=js/libs
build.classes.dir=${build.web.dir}/WEB-INF/classes
build.classes.excludes=**/*.java,**/*.form
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
build.web.dir=${build.dir}/web
build.web.excludes=${build.classes.excludes}
client.urlPart=
compile.jsps=false
conf.dir=${source.root}/conf
debug.classpath=${build.classes.dir}:${javac.classpath}
debug.test.classpath=\
${run.test.classpath}
display.browser=true
# Files to be excluded from distribution war
dist.archive.excludes=
dist.dir=dist
dist.ear.war=${dist.dir}/${war.ear.name}
dist.javadoc.dir=${dist.dir}/javadoc
dist.war=${dist.dir}/${war.name}
endorsed.classpath=\
${libs.javaee-endorsed-api-7.0.classpath}
excludes=
file.reference.gson-2.3.1.jar=lib/gson-2.3.1.jar
file.reference.itext-2.1.7.jar=lib/itext-2.1.7.jar
file.reference.log4j-1.2.17.jar=lib/log4j-1.2.17.jar
file.reference.org-netbeans-modules-java-j2seproject-copylibstask.jar=lib/org-netbeans-modules-java-j2seproject-copylibstask.jar
file.reference.poi-3.10.jar=lib/poi-3.10.jar
file.reference.postgresql-9.3-1102.jdbc41.jar=lib/postgresql-9.3-1102.jdbc41.jar
file.reference.primefaces-6.0.jar=lib/primefaces-6.0.jar
includes=**
j2ee.compile.on.save=true
j2ee.copy.static.files.on.save=true
j2ee.deploy.on.save=true
j2ee.platform=1.7-web
j2ee.platform.classpath=${j2ee.server.home}/modules/endorsed/javax.annotation-api.jar:${j2ee.server.home}/modules/endorsed/jaxb-api.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.inject.jar:${j2ee.server.home}/modules/javax.servlet.jsp-api.jar:${j2ee.server.home}/modules/javax.batch-api.jar:${j2ee.server.home}/modules/javax.json.jar:${j2ee.server.home}/modules/javax.security.jacc-api.jar:${j2ee.server.home}/modules/javax.enterprise.concurrent-api.jar:${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/javax.jms-api.jar:${j2ee.server.home}/modules/javax.el.jar:${j2ee.server.home}/modules/javax.ejb-api.jar:${j2ee.server.home}/modules/javax.transaction-api.jar:${j2ee.server.home}/modules/javax.ws.rs-api.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.home}/modules/javax.faces.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl-api.jar:${j2ee.server.home}/modules/javax.servlet-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl.jar:${j2ee.server.home}/modules/javax.resource-api.jar:${j2ee.server.home}/modules/javax.mail.jar:${j2ee.server.home}/modules/javax.enterprise.concurrent.jar:${j2ee.server.home}/modules/javax.xml.registry-api.jar:${j2ee.server.home}/modules/javax.persistence.jar:${j2ee.server.home}/modules/javax.management.j2ee-api.jar:${j2ee.server.home}/modules/javax.websocket-api.jar:${j2ee.server.home}/modules/javax.xml.rpc-api.jar:${j2ee.server.home}/modules/javax.enterprise.deploy-api.jar:${j2ee.server.home}/modules/cdi-api.jar:${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/javax.interceptor-api.jar:${j2ee.server.home}/modules/javax.security.auth.message-api.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.middleware}/mq/lib/jaxm-api.jar
j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar
j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar
j2ee.platform.wsgen.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api.jar
j2ee.platform.wsimport.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api.jar
j2ee.platform.wsit.classpath=
j2ee.server.type=gfv3ee6
jar.compress=false
javac.classpath=\
${file.reference.gson-2.3.1.jar}:\
${file.reference.itext-2.1.7.jar}:\
${file.reference.log4j-1.2.17.jar}:\
${file.reference.postgresql-9.3-1102.jdbc41.jar}:\
${file.reference.org-netbeans-modules-java-j2seproject-copylibstask.jar}:\
${file.reference.poi-3.10.jar}:\
${file.reference.primefaces-6.0.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.debug=true
javac.deprecation=false
javac.processorpath=\
${javac.classpath}:\
${libs.eclipselink.classpath}:\
${libs.eclipselinkmodelgen.classpath}
javac.source=1.8
javac.target=1.8
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.preview=true
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
lib.dir=${web.docbase.dir}/WEB-INF/lib
persistence.xml.dir=${conf.dir}
platform.active=default_platform
resource.dir=setup
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
# Space-separated list of JVM arguments used when running a class with a main method or a unit test
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value):
runmain.jvmargs=
source.encoding=UTF-8
source.root=src
src.dir=${source.root}/java
test.src.dir=test
war.content.additional=
war.ear.name=${war.name}
war.name=DmWebPortal.war
web.docbase.dir=web
webinf.dir=web/WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.web.project</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/web-project/3">
<name>DmWebPortal</name>
<minimum-ant-version>1.6.5</minimum-ant-version>
<web-module-libraries>
<library dirs="200">
<file>${file.reference.gson-2.3.1.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.itext-2.1.7.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.log4j-1.2.17.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.postgresql-9.3-1102.jdbc41.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.org-netbeans-modules-java-j2seproject-copylibstask.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.poi-3.10.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
<library dirs="200">
<file>${file.reference.primefaces-6.0.jar}</file>
<path-in-war>WEB-INF/lib</path-in-war>
</library>
</web-module-libraries>
<web-module-additional-libraries/>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
<definitions>./lib/nblibraries.properties</definitions>
</libraries>
<libraries xmlns="http://www.netbeans.org/ns/cdnjs-libraries/1"/>
</configuration>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="postgresql_dm_DbPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="11136"/>
<property name="databaseName" value="dm"/>
<property name="User" value="dm"/>
<property name="Password" value="DM_DB_PASSWORD"/>
<property name="URL" value="jdbc:postgresql://localhost:11136/dm"/>
<property name="driverClass" value="org.postgresql.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="dm_DataSource" object-type="user" pool-name="postgresql_dm_DbPool"/>
</resources>
Manifest-Version: 1.0
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DmWebPortalPU" transaction-type="JTA">
<jta-data-source>dm_DataSource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
# 'USERNAME' string will be replaced by the actual username
# dm.portal.ldapUrl=ldaps://phoebusldap.aps.anl.gov:636
# dm.portal.ldapDnString=uid=USERNAME,ou=people,o=aps.anl.gov,dc=aps,dc=anl,dc=gov
dm.portal.ldapUrl=ldaps://dmid-vm.xray.aps.anl.gov:636
dm.portal.ldapDnString=uid=USERNAME,ou=DM,ou=People,o=aps.anl.gov,dc=aps,dc=anl,dc=gov
dm.dsWebService.url=https://apsgpfs08:22236/dm
dm.system.user=dm
dm.system.passwordFile=DM_INSTALL_DIR/etc/DM_SYSTEM_USER.system.passwd
package gov.anl.aps.dm.api;
import gov.anl.aps.dm.common.constants.DmHttpHeader;
import gov.anl.aps.dm.common.constants.DmProperty;
import gov.anl.aps.dm.common.constants.DmRole;
import gov.anl.aps.dm.common.constants.DmServiceProtocol;
import gov.anl.aps.dm.common.exceptions.AuthorizationError;
import gov.anl.aps.dm.common.exceptions.CommunicationError;
import gov.anl.aps.dm.common.exceptions.ConfigurationError;
import gov.anl.aps.dm.common.exceptions.InvalidArgument;
import gov.anl.aps.dm.common.exceptions.InvalidSession;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.DmExceptionFactory;
import gov.anl.aps.dm.common.utilities.NoServerVerificationSSLSocketFactory;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.apache.log4j.Logger;
/**
* DM REST Web Service API class.
*
* This class serves as superclass for all DM web service interface classes. It
* handles basic communication with web service (establishing sessions, sending
* requests, receiving responses, generating exceptions, etc.).
*/
public class DmRestApi {
/**
* Relative path for login requests.
*/
public static final String LOGIN_REQUEST_URL = "/login";
private static final String DefaultSessionId = "defaultSession";
private static final boolean httpsInitialized = initializeHttpsConnection();
private static final Logger logger = Logger.getLogger(DmRestApi.class.getName());
private static boolean initializeHttpsConnection() {
HttpsURLConnection.setDefaultSSLSocketFactory(new NoServerVerificationSSLSocketFactory());
return true;
}
private URL serviceUrl;
private DmSession session = new DmSession();
private String loginUsername;
private String loginPassword;
/**
* Constructor.
*
* Initializes web service URL from system properties.
*
* @throws ConfigurationError if web service URL property is malformed or
* null
*/
public DmRestApi() throws ConfigurationError {
configureFromProperties();
}
/**
* Constructor.
*
* @param webServiceUrl web service URL
* @throws ConfigurationError if web service URL is malformed or null
*/
public DmRestApi(String webServiceUrl) throws ConfigurationError {
configureFromString(webServiceUrl);
}
/**
* Constructor.
*
* @param webServiceUrl web service URL
* @param loginUsername login username
* @param loginPassword login password
* @throws ConfigurationError if web service URL is malformed or null
*/
public DmRestApi(String webServiceUrl, String loginUsername, String loginPassword) throws ConfigurationError {
configureFromString(webServiceUrl);
this.loginUsername = loginUsername;
this.loginPassword = loginPassword;
}
/**
* Configure web service URL from Java VM properties.
*
* @throws ConfigurationError if web service URL property is malformed or
* null
*/
public final void configureFromProperties() throws ConfigurationError {
String webServiceUrl = System.getProperty(DmProperty.DS_WEB_SERVICE_URL_PROPERTY_NAME);
configureFromString(webServiceUrl);
}
/**
* Configure web service URL from string.
*
* @param webServiceUrl web service URL
* @throws ConfigurationError if web service URL property is malformed or
* null
*/
public final void configureFromString(String webServiceUrl) throws ConfigurationError {
if (webServiceUrl == null) {
throw new ConfigurationError("DM web service url is not specified.");
}
try {
serviceUrl = new URL(webServiceUrl);
} catch (MalformedURLException ex) {
throw new ConfigurationError("Malformed DM web service url: " + webServiceUrl);
}
DmServiceProtocol protocol = DmServiceProtocol.fromString(serviceUrl.getProtocol());
if (protocol == null) {
throw new ConfigurationError("Unsupported service protocol specified in " + webServiceUrl);
}
}
public void setLoginUsername(String loginUsername) {
this.loginUsername = loginUsername;
}
public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}
public URL getServiceUrl() {
return serviceUrl;
}
public DmSession getSession() {
return session;
}
public void setSession(DmSession session) {
this.session = session;
}
/**
* Check HTTP response for exceptions.
*
* @param connection HTTP connection
* @throws DmException when DM error is detected
*/
public static void checkHttpResponseForDmException(HttpURLConnection connection) throws DmException {
String exceptionType = connection.getHeaderField(DmHttpHeader.DM_EXCEPTION_TYPE_HEADER);
if (exceptionType != null) {
String statusMessage = connection.getHeaderField(DmHttpHeader.DM_STATUS_MESSAGE_HEADER);
String statusCode = connection.getHeaderField(DmHttpHeader.DM_STATUS_CODE_HEADER);
int code = Integer.parseInt(statusCode);
DmExceptionFactory.throwDmException(exceptionType, code, statusMessage);
}
}
/**
* Convert HTTP error for exceptions.
*
* @param httpError HTTP error
* @param connection HTTP connection
* @return generated DM exception
*/
public static DmException convertHttpErrorToDmException(Exception httpError, HttpURLConnection connection) {
String exceptionType = connection.getHeaderField(DmHttpHeader.DM_EXCEPTION_TYPE_HEADER);
if (exceptionType != null) {
String statusMessage = connection.getHeaderField(DmHttpHeader.DM_STATUS_MESSAGE_HEADER);
String statusCode = connection.getHeaderField(DmHttpHeader.DM_STATUS_CODE_HEADER);
int code = Integer.parseInt(statusCode);
return DmExceptionFactory.generateDmException(exceptionType, code, statusMessage);
} else {
return new DmException(httpError);
}
}
/**
* Get full request URL.
*
* @param requestUrl relative request path, e.g. /object
* @return full request URL string, e.g. http://localhost:17524/dm/object
*/
public String getFullRequestUrl(String requestUrl) {
String url = serviceUrl + requestUrl;
return url;
}
/**
* Verify session cookie.
*
* @return session cookie
* @throws InvalidSession if session cookie is expired or null
*/
public String verifySessionCookie() throws InvalidSession {
return session.verifyCookie();
}
/*
* Get all response headers in a single string.
*
* @param connection HTTP connection
* @return string containing response headers
*/
private static String getResponseHeaders(HttpURLConnection connection) {
String headerString = "";
Map<String, List<String>> headerMap = connection.getHeaderFields();
for (String key : headerMap.keySet()) {
List<String> values = headerMap.get(key);
headerString += key + ": " + values + "\n";
}
return headerString;
}
/**
* Prepare post data.
*
* @param data key/value data map
* @return string suitable for HTTP post request
* @throws InvalidArgument in case of invalid input data
*/
public static String preparePostData(Map<String, String> data) throws InvalidArgument {
try {
String postData = "";
String separator = "";
for (String key : data.keySet()) {
postData += separator + key + "=" + URLEncoder.encode(data.get(key), "UTF8");
separator = "&";
}
return postData;
} catch (UnsupportedEncodingException ex) {
logger.error("Invalid argument: " + ex);
throw new InvalidArgument(ex);
}
}
/**
* Update session cookie from connection's HTTP headers.
*
* @param connection HTTP connection
*/
private void updateSessionCookie(HttpURLConnection connection) {
String cookie = connection.getHeaderField(DmHttpHeader.DM_SET_COOKIE_HEADER);
if (cookie != null) {
session.setCookie(cookie);
logger.debug("Updated session cookie: " + cookie);
}
String sessionRole = connection.getHeaderField(DmHttpHeader.DM_SESSION_ROLE_HEADER);
if (sessionRole != null) {
session.setRole(DmRole.fromString(sessionRole));
logger.debug("Updated session role: " + sessionRole);
}
}
/**
* Send post data.
*
* @param data key/value data map
* @param connection HTTP connection
* @throws InvalidArgument in case there is a problem with post data
* @throws DmException in case of any other error
*/
private static void sendPostData(Map<String, String> data, HttpURLConnection connection) throws InvalidArgument, DmException {
String postData = preparePostData(data);
try (DataOutputStream dos = new DataOutputStream(connection.getOutputStream())) {
dos.writeBytes(postData);
dos.flush();
} catch (IOException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Read HTTP response.
*
* @param connection HTTP connection
* @return HTTP response as a string
* @throws DmException in case of any errors
*/
private static String readHttpResponse(HttpURLConnection connection) throws DmException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
sb.append('\n');
}
return sb.toString();
} catch (IOException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Set session cookie in the request headers.
*
* @param connection HTTP connection
* @param sessionCookie session cookie (may be null)
*/
private static void setCookieRequestHeader(HttpURLConnection connection, String sessionCookie) {
if (sessionCookie != null) {
connection.setRequestProperty("Cookie", sessionCookie);
logger.debug("Setting session cookie to: " + sessionCookie);
}
}
/**
* Set common POST request headers plus session cookie.
*
* @param connection HTTP connection
* @param sessionCookie session cookie (may be null)
* @throws DmException in case of any errors
*/
private static void setPostRequestHeaders(HttpURLConnection connection, String sessionCookie) throws DmException {
setPostRequestHeaders(connection);
setCookieRequestHeader(connection, sessionCookie);
}
/**
* Set common POST request headers.
*
* @param connection HTTP connection
* @throws DmException in case of any errors
*/
private static void setPostRequestHeaders(HttpURLConnection connection) throws DmException {
try {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
} catch (ProtocolException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Set common GET request headers plus session cookie.
*
* @param connection HTTP connection
* @param sessionCookie session cookie (may be null)
* @throws DmException in case of any errors
*/
private static void setGetRequestHeaders(HttpURLConnection connection, String sessionCookie) throws DmException {
setGetRequestHeaders(connection);
setCookieRequestHeader(connection, sessionCookie);
}
/**
* Set common GET request headers.
*
* @param connection HTTP connection
* @throws DmException in case of any errors
*/
private static void setGetRequestHeaders(HttpURLConnection connection) throws DmException {
try {
connection.setRequestMethod("GET");
} catch (ProtocolException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Set common PUT request headers plus session cookie.
*
* @param connection HTTP connection
* @param sessionCookie session cookie (may be null)
* @throws DmException in case of any errors
*/
private static void setPutRequestHeaders(HttpURLConnection connection, String sessionCookie) throws DmException {
setPutRequestHeaders(connection);
setCookieRequestHeader(connection, sessionCookie);
}
/**
* Set common PUT request headers.
*
* @param connection HTTP connection
* @throws DmException in case of any errors
*/
private static void setPutRequestHeaders(HttpURLConnection connection) throws DmException {
try {
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
} catch (ProtocolException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Set common DELETE request headers plus session cookie.
*
* @param connection HTTP connection
* @param sessionCookie session cookie (may be null)
* @throws DmException in case of any errors
*/
private static void setDeleteRequestHeaders(HttpURLConnection connection, String sessionCookie) throws DmException {
setDeleteRequestHeaders(connection);
setCookieRequestHeader(connection, sessionCookie);
}
/**
* Set common DELETE request headers.
*
* @param connection HTTP connection
* @throws DmException in case of any errors
*/
private static void setDeleteRequestHeaders(HttpURLConnection connection) throws DmException {
try {
connection.setRequestMethod("DELETE");
} catch (ProtocolException ex) {
logger.error(ex);
throw new DmException(ex);
}
}
/**
* Login with a given username and password, and with specified session id.
*
* @param username username
* @param password password
* @param sessionId session id, can be null
* @throws AuthorizationError in case of incorrect username or password
* @throws CommunicationError in case service cannot be contacted
* @throws DmException in case of any other errors
*/
public void login(String username, String password, String sessionId) throws DmException {
HttpURLConnection connection = null;
try {
String urlString = getFullRequestUrl(LOGIN_REQUEST_URL);
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
setPostRequestHeaders(connection);
HashMap<String, String> loginData = new HashMap<>();
loginData.put("username", username);
loginData.put("password", password);
logger.debug("Establishing session for user: " + username);
logger.debug("Service URL: " + serviceUrl);
sendPostData(loginData, connection);
checkHttpResponseForDmException(connection);
session.setUsername(username);
session.setId(sessionId);
updateSessionCookie(connection);
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (DmException ex) {
logger.error(ex);
throw ex;
} catch (IOException ex) {
logger.error(ex);
throw new DmException(ex);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Login with a given username and password.
*
* @param username username
* @param password password
* @throws AuthorizationError in case of incorrect username or password
* @throws CommunicationError in case service cannot be contacted
* @throws DmException in case of any other errors
*/
public void login(String username, String password) throws DmException {
login(username, password, DefaultSessionId);
}
/**
* Invoke GET request with login.
*
* @param requestUrl relative request path, e.g. /object
* @return service response string
* @throws DmException in case of any errors
*/
public String loginAndInvokeSessionGetRequest(String requestUrl) throws DmException {
try {
// If we have session, simply invoke request.
session.verifyCookie();
return invokeSessionGetRequest(requestUrl);
} catch (InvalidSession ex) {
// Session was invalidated, login and try again
}
login(loginUsername, loginPassword);
return invokeSessionGetRequest(requestUrl);
}
/**
* Invoke GET request.
*
* @param requestUrl relative request path, e.g. /object
* @return service response string
* @throws DmException in case of any errors
*/
public String invokeSessionGetRequest(String requestUrl) throws DmException {
String urlString = getFullRequestUrl(requestUrl);
HttpURLConnection connection = null;
try {
logger.debug("Invoking session get request for URL: " + requestUrl);
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
setGetRequestHeaders(connection, sessionCookie);
updateSessionCookie(connection);
checkHttpResponseForDmException(connection);
logger.debug("Response message:\n" + connection.getResponseMessage());
return readHttpResponse(connection);
} catch (DmException ex) {
throw ex;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (IOException ex) {
DmException dmException = convertHttpErrorToDmException(ex, connection);
logger.error(ex.getMessage());
throw dmException;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Invoke GET request.
*
* @param requestUrl relative request path, e.g. /object
* @return service response string
* @throws DmException in case of any errors
*/
public String invokeGetRequest(String requestUrl) throws DmException {
String urlString = getFullRequestUrl(requestUrl);
HttpURLConnection connection = null;
try {
logger.debug("Invoking get request for URL: " + requestUrl);
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
updateSessionCookie(connection);
checkHttpResponseForDmException(connection);
logger.debug("Response message:\n" + connection.getResponseMessage());
return readHttpResponse(connection);
} catch (DmException ex) {
throw ex;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (IOException ex) {
DmException dmException = convertHttpErrorToDmException(ex, connection);
logger.error(ex.getMessage());
throw dmException;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Invoke POST request with login.
*
* @param requestUrl relative request path, e.g. /object
* @param data request data
* @return service response string
* @throws DmException in case of any errors
*/
public String loginAndInvokeSessionPostRequest(String requestUrl, Map<String, String> data) throws DmException {
try {
// If we have session, simply invoke request.
session.verifyCookie();
return invokeSessionPostRequest(requestUrl, data);
} catch (InvalidSession ex) {
// Session was invalidated, login and try again
}
login(loginUsername, loginPassword);
return invokeSessionPostRequest(requestUrl, data);
}
/**
* Invoke POST request.
*
* @param requestUrl relative request path, e.g. /object
* @param data request data
* @return service response string
* @throws DmException in case of any errors
*/
public String invokeSessionPostRequest(String requestUrl, Map<String, String> data) throws DmException {
String urlString = getFullRequestUrl(requestUrl);
HttpURLConnection connection = null;
try {
logger.debug("Invoking session post request for URL: " + requestUrl);
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
setPostRequestHeaders(connection, sessionCookie);
sendPostData(data, connection);
updateSessionCookie(connection);
checkHttpResponseForDmException(connection);
logger.debug("Response message:\n" + connection.getResponseMessage());
return readHttpResponse(connection);
} catch (DmException ex) {
throw ex;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (IOException ex) {
DmException dmException = convertHttpErrorToDmException(ex, connection);
logger.error(ex.getMessage());
throw dmException;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Invoke PUT request with login.
*
* @param requestUrl relative request path, e.g. /object
* @param data request data
* @return service response string
* @throws DmException in case of any errors
*/
public String loginAndInvokeSessionPutRequest(String requestUrl, Map<String, String> data) throws DmException {
try {
// If we have session, simply invoke request.
session.verifyCookie();
return invokeSessionPutRequest(requestUrl, data);
} catch (InvalidSession ex) {
// Session was invalidated, login and try again
}
login(loginUsername, loginPassword);
return invokeSessionPutRequest(requestUrl, data);
}
/**
* Invoke PUT request.
*
* @param requestUrl relative request path, e.g. /object
* @param data request data
* @return service response string
* @throws DmException in case of any errors
*/
public String invokeSessionPutRequest(String requestUrl, Map<String, String> data) throws DmException {
String urlString = getFullRequestUrl(requestUrl);
HttpURLConnection connection = null;
try {
logger.debug("Invoking session put request for URL: " + requestUrl);
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
setPutRequestHeaders(connection, sessionCookie);
sendPostData(data, connection);
updateSessionCookie(connection);
checkHttpResponseForDmException(connection);
logger.debug("Response message:\n" + connection.getResponseMessage());
return readHttpResponse(connection);
} catch (DmException ex) {
throw ex;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (IOException ex) {
DmException dmException = convertHttpErrorToDmException(ex, connection);
logger.error(ex.getMessage());
throw dmException;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Invoke DELETE request with login.
*
* @param requestUrl relative request path, e.g. /object
* @return service response string
* @throws DmException in case of any errors
*/
public String loginAndInvokeSessionDeleteRequest(String requestUrl) throws DmException {
try {
// If we have session, simply invoke request.
session.verifyCookie();
return invokeSessionDeleteRequest(requestUrl);
} catch (InvalidSession ex) {
// Session was invalidated, login and try again
}
login(loginUsername, loginPassword);
return invokeSessionDeleteRequest(requestUrl);
}
/**
* Invoke DELETE request.
*
* @param requestUrl relative request path, e.g. /dm/object
* @return service response string
* @throws DmException in case of any errors
*/
public String invokeSessionDeleteRequest(String requestUrl) throws DmException {
String urlString = getFullRequestUrl(requestUrl);
HttpURLConnection connection = null;
try {
logger.debug("Invoking session post request for URL: " + requestUrl);
String sessionCookie = session.verifyCookie();
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
setDeleteRequestHeaders(connection, sessionCookie);
updateSessionCookie(connection);
checkHttpResponseForDmException(connection);
logger.debug("Response message:\n" + connection.getResponseMessage());
return readHttpResponse(connection);
} catch (DmException ex) {
throw ex;
} catch (ConnectException ex) {
String errorMsg = "Cannot connect to " + getServiceUrl();
logger.error(errorMsg);
throw new CommunicationError(errorMsg, ex);
} catch (IOException ex) {
DmException dmException = convertHttpErrorToDmException(ex, connection);
logger.error(ex.getMessage());
throw dmException;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/*
* Main method, used for simple testing.
*
* @param args main arguments
*/
public static void main(String[] args) {
try {
DmRestApi client = new DmRestApi("http://zagreb.svdev.net:10232/dm");
//client.login("sveseli", "sveseli");
HashMap<String, String> data = new HashMap<>();
//data.put("parentDirectory", "/");
client.invokeGetRequest("/experiment/e1");
} catch (DmException ex) {
System.out.println("Sorry: " + ex);
}
}
}
package gov.anl.aps.dm.api;
import gov.anl.aps.dm.common.constants.DmRole;
import gov.anl.aps.dm.common.exceptions.InvalidSession;
import java.io.Serializable;
import java.net.HttpCookie;
/**
* DM session class, used for keeping all session-related information (session
* id, username, role, etc.).
*/
public class DmSession implements Serializable {
private static final long serialVersionUID = 1L;
private String id = null;
private String username = null;
private String cookie = null;
private DmRole role = null;
public DmSession() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCookie() {
return cookie;
}
public void setCookie(String cookie) {
this.cookie = cookie;
}
public String verifyCookie() throws InvalidSession {
if (cookie == null) {
throw new InvalidSession("Valid session has not been established.");
} else {
HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
if (httpCookie.hasExpired()) {
throw new InvalidSession("Session id " + id + " has expired.");
}
}
return cookie;
}
public DmRole getRole() {
return role;
}
public void setRole(DmRole role) {
this.role = role;
}
public boolean isAdminRole() {
if (role != null) {
return role.equals(DmRole.ADMIN);
}
return false;
}
public boolean isUserRole() {
if (role != null) {
return role.equals(DmRole.USER);
}
return false;
}
@Override
public String toString() {
String result = "{ ";
String delimiter = "";
if (username != null) {
result += "username :" + username;
delimiter = "; ";
}
if (id != null) {
result += delimiter + "id : " + id;
delimiter = "; ";
}
if (cookie != null) {
result += delimiter + "cookie : " + cookie;
}
result += " }";
return result;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.anl.aps.dm.api;
import gov.anl.aps.dm.common.exceptions.ConfigurationError;
import gov.anl.aps.dm.common.exceptions.DmException;
import gov.anl.aps.dm.common.exceptions.InvalidArgument;
import gov.anl.aps.dm.common.exceptions.ObjectNotFound;
import gov.anl.aps.dm.common.objects.DmObjectFactory;
import gov.anl.aps.dm.common.objects.Experiment;
import gov.anl.aps.dm.common.utilities.ArgumentUtility;
import java.util.HashMap;
/**
*
* @author sveseli
*/
public class ExperimentDsApi extends DmRestApi {
/**
* Constructor.
*
* @throws ConfigurationError if web service URL property is malformed or
* null
*/
public ExperimentDsApi() throws ConfigurationError {
super();
}
/**
* Constructor.
*
* @param webServiceUrl web service URL
* @throws ConfigurationError if web service URL is malformed or null
*/
public ExperimentDsApi(String webServiceUrl) throws ConfigurationError {
super(webServiceUrl);
}
/**
* Constructor.
*
* @param webServiceUrl web service URL
* @param loginUsername login username
* @param loginPassword login password
* @throws ConfigurationError if web service URL is malformed or null
*/
public ExperimentDsApi(String webServiceUrl, String loginUsername, String loginPassword) throws ConfigurationError {
super(webServiceUrl, loginUsername, loginPassword);
}
/**
* Update experiment (group users, etc.).
*
* @param experimentName experiment name
* @return Experiment object
* @throws InvalidArgument if provided name is empty or null
* @throws ObjectNotFound when specified experiment does not exist
* @throws DmException in case of all other errors
*/
public Experiment updateExperiment(String experimentName) throws InvalidArgument, ObjectNotFound, DmException {
ArgumentUtility.verifyNonEmptyString("Experiment name", experimentName);
String requestUrl = "/experiments/update";
HashMap<String, String> requestData = new HashMap<>();
requestData.put("name", ArgumentUtility.encode(experimentName));
String jsonString = loginAndInvokeSessionPutRequest(requestUrl, requestData);
Experiment experiment = (Experiment) DmObjectFactory.createDmObject(jsonString, Experiment.class);
return experiment;
}
/*
* Main method, used for simple testing.
*
* @param args main arguments
*/
public static void main(String[] args) {
try {
ExperimentDsApi client = new ExperimentDsApi("https://dmstorage.svdev.net:22236/dm", "dm", "dm");
Experiment experiment = client.updateExperiment("e1");
System.out.println("Updated experiment: \n" + experiment);
} catch (DmException ex) {
System.out.println("Sorry: " + ex);
}
}
}
package gov.anl.aps.dm.common.constants;
/**
* HTTP headers specific to DM.
*/
public class DmHttpHeader {
public static final String DM_SET_COOKIE_HEADER = "Set-Cookie";
public static final String DM_EXCEPTION_TYPE_HEADER = "Dm-Exception-Type";
public static final String DM_STATUS_CODE_HEADER = "Dm-Status-Code";
public static final String DM_STATUS_MESSAGE_HEADER = "Dm-Status-Message";
public static final String DM_SESSION_ROLE_HEADER = "Dm-Session-Role";
}
package gov.anl.aps.dm.common.constants;
/**
* DM property names.
*/
public class DmProperty {
public static final String DS_WEB_SERVICE_URL_PROPERTY_NAME = "dm.dsWebService.url";
public static final String SYSTEM_USER_PROPERTY_NAME = "dm.system.user";
public static final String SYSTEM_PASSWORD_FILE_PROPERTY_NAME = "dm.system.passwordFile";
}
package gov.anl.aps.dm.common.constants;
/**
* DM role enum.
*/
public enum DmRole {
USER("user"),
ADMIN("admin");
private final String type;
private DmRole(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
public static DmRole fromString(String type) {
DmRole role = null;
switch (type) {
case "user":
role = USER;
break;
case "admin":
role = ADMIN;
break;
}
return role;
}
}
package gov.anl.aps.dm.common.constants;
/**
* DM service protocol enum.
*/
public enum DmServiceProtocol {
HTTP("http"),
HTTPS("https");
private final String type;
private DmServiceProtocol(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
public static DmServiceProtocol fromString(String type) {
DmServiceProtocol protocol = null;
switch (type) {
case "http":
protocol = HTTP;
break;
case "https":
protocol = HTTPS;
break;
}
return protocol;
}
}
package gov.anl.aps.dm.common.constants;
/**
* DM status codes.
*/
public class DmStatus {
public static final int DM_OK = 0;
public static final int DM_ERROR = 1;
public static final int DM_INTERNAL_ERROR = 2;
public static final int DM_COMMUNICATION_ERROR = 3;
public static final int DM_CONFIGURATION_ERROR = 4;
public static final int DM_AUTHORIZATION_ERROR = 5;
public static final int DM_AUTHENTICATION_ERROR = 6;
public static final int DM_DB_ERROR = 7;
public static final int DM_URL_ERROR = 8;
public static final int DM_TIMEOUT_ERROR = 9;
public static final int DM_INVALID_ARGUMENT = 10;
public static final int DM_INVALID_REQUEST = 11;
public static final int DM_INVALID_SESSION = 12;
public static final int DM_COMMAND_FAILED = 13;
public static final int DM_OBJECT_NOT_FOUND = 14;
public static final int DM_OBJECT_ALREADY_EXISTS = 15;
public static final int DM_INVALID_OBJECT_STATE = 16;
public static final int DM_FILE_PROCESSING_ERROR = 17;
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Authentication error exception.
*/
public class AuthenticationError extends DmException {
/**
* Default constructor.
*/
public AuthenticationError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public AuthenticationError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public AuthenticationError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public AuthenticationError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_AUTHENTICATION_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Authorization error exception.
*/
public class AuthorizationError extends DmException {
/**
* Default constructor.
*/
public AuthorizationError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public AuthorizationError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public AuthorizationError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public AuthorizationError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_AUTHORIZATION_ERROR;
}
}
package gov.anl.aps.dm.common.exceptions;
import gov.anl.aps.dm.common.constants.DmStatus;
/**
* Communication error exception.
*/
public class CommunicationError extends DmException {
/**
* Default constructor.
*/
public CommunicationError() {
super();
}
/**
* Constructor using error message.
*
* @param message error message
*/
public CommunicationError(String message) {
super(message);
}
/**
* Constructor using throwable object.
*
* @param throwable throwable object
*/
public CommunicationError(Throwable throwable) {
super(throwable);
}
/**
* Constructor using error message and throwable object.
*
* @param message error message
* @param throwable throwable object
*/
public CommunicationError(String message, Throwable throwable) {
super(message, throwable);
}
@Override
public int getErrorCode() {
return DmStatus.DM_COMMUNICATION_ERROR;
}
}